From 14ab9310ac0549514532da7bfd10b9e669749dd1 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 3 May 2021 13:22:12 +0200 Subject: [PATCH 001/390] Add python threading workout --- python/python-core/python-threading/README.md | 15 ++ .../python-threading/creating-threads.md | 88 ++++++++ .../python-threading/threading-with-join-2.md | 185 +++++++++++++++++ .../python-threading/threading-with-join.md | 189 ++++++++++++++++++ .../python-threading/threads-and-gil.md | 43 ++++ .../python-threading/what-are-threads.md | 39 ++++ 6 files changed, 559 insertions(+) create mode 100644 python/python-core/python-threading/README.md create mode 100644 python/python-core/python-threading/creating-threads.md create mode 100644 python/python-core/python-threading/threading-with-join-2.md create mode 100644 python/python-core/python-threading/threading-with-join.md create mode 100644 python/python-core/python-threading/threads-and-gil.md create mode 100644 python/python-core/python-threading/what-are-threads.md diff --git a/python/python-core/python-threading/README.md b/python/python-core/python-threading/README.md new file mode 100644 index 0000000000..da53e40a40 --- /dev/null +++ b/python/python-core/python-threading/README.md @@ -0,0 +1,15 @@ +name: Introduction + +description: Intro to Threading. + +insights: + - what-are-threads + - threads-and-gil + - creating-threads + - threading-with-join + - threading-with-join-2 + +aspects: + - new + - obscura + - workout diff --git a/python/python-core/python-threading/creating-threads.md b/python/python-core/python-threading/creating-threads.md new file mode 100644 index 0000000000..df6c83906d --- /dev/null +++ b/python/python-core/python-threading/creating-threads.md @@ -0,0 +1,88 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Creating Threads + +--- + +## Content + +To use threads we can import the standard built-in python `threading` module. + +```python +import threading +``` + +To create a new thread, we will instantiate it with a function. + +```python +# Some Function +def someFunction(): + for x in range(5): + print("I am a thread!!!") + +# First Thread +firstThread = + threading.Thread( + target=someFunction + ) +``` + +After creating it, we need to start it using the built-in `start()` method: +```python +firstThread.start() +``` + +Which gives us this output: +```plain-text +I am a thread!!! + +I am a thread!!! +I am a thread!!! +I am a thread!!! +I am a thread!!! +``` + +We can use some built-in methods to see how many threads we have or if there are any that are stil active: + +```python +# Check number of threads +threading.active_count() + +# This gives the output +2 +``` + +```python +# Check current thread +threading.current_thread() + +# This gives the output +<_MainThread(MainThread, started 3828)> +``` + +Although we have only created a single thread, there are two of them. + +The reason behind this is that the first `MainThread` was created when we launched the interpreter. + +--- + +## Revision + +Create a function with a `print` statement. Then, using the `threading` module, create a thread with that function. Finally, start the thread. + diff --git a/python/python-core/python-threading/threading-with-join-2.md b/python/python-core/python-threading/threading-with-join-2.md new file mode 100644 index 0000000000..15266705f3 --- /dev/null +++ b/python/python-core/python-threading/threading-with-join-2.md @@ -0,0 +1,185 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +--- + +# Threading With .join() Continued + +--- + +## Content + +Previoulsy, we did this[1] and got this result: + +```python +Greetings friend +Third Message + +# Then 5 seconds later we get this: +Why are you ignoring me +``` + +Now let's do the same thing, but instead of only starting it, we will also join it with the main thread. + +```python +import time, threading + +def someFunction(): + # Print a message + print("Greetings friend") + # Wait time in seconds + time.sleep(5) + # Print a message + print("Why are you ignoring me?") + +# Thread +thread1 = threading.Thread(target=someFunction) + +# Start thread +thread1.start() +# Join thread +thread1.join() + +# Outside of the function we will also print a message +print("Third Message") +``` + +This time, the output looks like this: +```python +Greetings friend + +# 5 sec wait time here then: + +Why are you ignoring me +Third Message +``` + +As you can see, when we join the thread with the main one, the main one waits until the joined thread has executed. + +This feature allows you to control when the main thread should wait. Essentially, you can create multiple threads and until all of those threads have executed, the main thread will just wait. + +--- + +## Practice + +Complete the missing code to initiate a thread on the `s()` function. Don't forget to join it. + +```python +import threading, time + +def x(): + # Print a message + print("Hello!") + + # Wait time in seconds + time.sleep(5) + + # Print a message + print("Why are you ignoring me?") + +myThread = + ???.???( + ???=??? + ) +print("I'm not!") + +thread1.start() +thread1.??? +``` + +- threading +- Thread +- target +- s +- join() +- Join() + +--- + +## Revision + +Complete the missing code to initiate a thread on the `x()` function. Don't forget to join and start it. + +```python +import threading, time + +def x(): + # Print a message + print("Hello") + + # Wait time in seconds + time.sleep(4) + + print("I'm angry!") + # Print a message + +myThread = + ???.???( + ???=??? + ) +print("Why are you angry?") + +myThread.??? +myThread.??? +``` + +- threading +- Thread +- target +- x +- start() +- join() +- start +- join +- thread +--- + +## Footnotes + +[1: Previous Insight] + +```python +import threading, time + +def someFunction(): + # Print a message + print("Greetings friend") + + # Wait time in seconds + time.sleep(10) + + # Print a message + print("Why are you ignoring me") + + +# Outside of the function we will also print a message +print("Third Message") +``` + +Output: +```plain-text +Third Message +``` + +Then we added: +```python +thread1.start() +# -----> HERE <------ +print("Third Message") +``` + +When we ran this code we got this: +```python +Greetings friend +Third Message + +# Then 5 seconds later we got this: +Why are you ignoring me +``` diff --git a/python/python-core/python-threading/threading-with-join.md b/python/python-core/python-threading/threading-with-join.md new file mode 100644 index 0000000000..818f637ccb --- /dev/null +++ b/python/python-core/python-threading/threading-with-join.md @@ -0,0 +1,189 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + +type: normal + +category: must-know + +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone +--- + +# Threading With join() + +--- + +## Content + +Previoulsy, we created a thread using `someFunction`[1]: + +```python +firstThread = + threading.Thread( + target=someFunction + ) +``` + +Now, let's import the `time` module and use a different function to create one. + +> Using the `time` module we can easily see how `threading` works by implemeting the `time.sleep(NUM_OF_SECOND)` method. + +```python +import threading, time + +def someFunction(): + # Print a message + print("Greetings friend") + + # Wait time in seconds + time.sleep(5) + + # Print a message + print("Why are you ignoring me") + + +# Outside of the function we will also print a message +print("Third Message") +``` + +If we run the above code, we would get this output: +```plain-text +Third Message +``` + +The reason we are creating a thread on a different function is to showcase what the `.join()` method does. + +This method is used to join a thread with the main thread. + +What this means is, when we join a thread, the main thread stops executing until the joined thread has finished. + +Let's create it: +```python +thread1 = + threading.Thread( + target=someFunction + ) +``` + +First, we will start the thread without `.join()`. + +```python +thread1.start() +``` + +Add this code above the last print but outside of the function: +```python +# -----> HERE <------ +print("Third Message") +``` + +When we run this code we get this: +```python +Greetings friend +Third Message + +# Then 5 seconds later we get this: +Why are you ignoring me +``` + +> Let's continue in the next insight. + + +--- + +## Practice + +Complete the missing code to initiate a thread on the `x()` function. Don't forget to start it. + +```python +import threading, time + +def x(): + # Print a message + print("Hello") + + # Wait time in seconds (4) + ??? + + # Print a message + print("Why are you ignoring me") + +myThread = + ???.???( + ???=??? + ) + +myThread.??? +``` + +- time.sleep(4) +- threading +- Thread +- target +- x +- start() +- sleep.time(4000) + +--- + +## Revision + +Complete the missing code to initiate a thread on the `f()` function. Don't forget to start it. + +```python +import threading, time + +def f(): + # Print a message + print("Hello") + + # Wait time 1 second + ???.???(???) + + # Print a message + print("Why are you ignoring me") + +print("Heyyyy") + +??? = + threading.???( + ???=??? + ) + +myThread.??? +``` + +- time +- sleep +- 1 +- myThread +- Thread +- target +- f +- 1000 + +--- + +## Footnotes + +[1: Some Function] + +The function used to instantiate a thread in the previous insight: + +```python +# Some Function +def someFunction(): + for x in range(5): + print("I am a thread!!!") +``` \ No newline at end of file diff --git a/python/python-core/python-threading/threads-and-gil.md b/python/python-core/python-threading/threads-and-gil.md new file mode 100644 index 0000000000..e4b5f9e4d9 --- /dev/null +++ b/python/python-core/python-threading/threads-and-gil.md @@ -0,0 +1,43 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +links: + - >- + [Hyper-Threading Technology](https://en.wikipedia.org/wiki/Simultaneous_multithreading#:~:text=The%20Intel%20Pentium%204%20was,a%20number%20of%20their%20processors.) + +--- + +# Threads and GIL + +--- + +## Content + +Threads are used when you want to execute multiple tasks within the same program, at once. + +> Although it appears you have multiple things working at once, for Python 3, threads will still execute one at a time, just at a really fast rate, appearing as if they happen simultaneously. + +The reason behind it is the Python Global Interpreter Lock, or `GIL`. + +`GIL` is a mutex that protects access to Python objects. A mutex is a sort of gate keeper. It allows only one thread to use a specific piece of code at a time. + +If a thread starts using some code, the `GIL` will lock that code to that thread until it has finished using it. + +The reason behind this, is that Python is written in `C`, which is called `CPython`. + +And the reason `CPython` has `GIL` is because its memory management is not `thread-safe`. + +Prior to modern computing, when it was first created, processes had only 1 thread. + +`CPython` was first published in 1991. Whereas the first modern desktop multi-threaded procesor was published in 2002. + +> Even though the `GIL` still exists, there are multiple ways you can work around it to allow `multiprocessing`. + +> Let's create a thread in the next insight. diff --git a/python/python-core/python-threading/what-are-threads.md b/python/python-core/python-threading/what-are-threads.md new file mode 100644 index 0000000000..51ddf8e3ad --- /dev/null +++ b/python/python-core/python-threading/what-are-threads.md @@ -0,0 +1,39 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +--- + +# What are Threads? + +--- + +## Content + +In computing, there are `processes` and `threads`. + +A `process` is an instance of a program being executed. They have an assigned memory space that holds instructions for running the program. They may also have additional data stored required for execution. + +`Threads` are separate sequential flows of control within a program. They are more lightweight than `processes`. + +They are components of a `process`. A single `process` can have one or multiple `threads`. + +All `threads` within a `process` share the same memory space (the memory space of their parent `process`.) + +Along side the memory that is being shared, any code, including variables is shared between them. + +--- +## Revision + +??? are separate sequential flows of control within a program. They are components of a ???. + +- Threads +- process +- Processes +- thread \ No newline at end of file From 6e43630d8d8b4ac1355612d55133f18612c16927 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 3 May 2021 13:22:50 +0200 Subject: [PATCH 002/390] Update README.md --- python/python-core/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/python/python-core/README.md b/python/python-core/README.md index 915f0a0d30..bdf57f5060 100644 --- a/python/python-core/README.md +++ b/python/python-core/README.md @@ -34,6 +34,7 @@ sections: - more-on-dictionaries - python-recipes - deep-into-collections + - python-threading - advanced-queues '3': - classes-iii From 287027881866708b429f5bf837c22aac1bd55d38 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 3 May 2021 13:23:27 +0200 Subject: [PATCH 003/390] Update creating-threads.md --- .../python-threading/creating-threads.md | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/python/python-core/python-threading/creating-threads.md b/python/python-core/python-threading/creating-threads.md index df6c83906d..b86daf5d68 100644 --- a/python/python-core/python-threading/creating-threads.md +++ b/python/python-core/python-threading/creating-threads.md @@ -2,7 +2,7 @@ author: Stefan-Stojanovic tags: - - coding + - must-know type: normal @@ -11,7 +11,6 @@ category: coding revisionQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone --- @@ -84,5 +83,24 @@ The reason behind this is that the first `MainThread` was created when we launch ## Revision -Create a function with a `print` statement. Then, using the `threading` module, create a thread with that function. Finally, start the thread. +Using the `threading` module, create and start a thread with the provided function. +```python +# Some Function +def f(): + for x in range(3): + print("I am a thread!!!") + +# Thread +myThread = + ???.???( + ???=f + ) + +myThread.??? +``` + +- threading +- Thread +- target +- start() From 25e6eaf6dbde8f14ec20d637a46ccdbd7807855d Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 3 May 2021 13:23:48 +0200 Subject: [PATCH 004/390] Update threads-and-gil.md --- python/python-core/python-threading/threads-and-gil.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/python/python-core/python-threading/threads-and-gil.md b/python/python-core/python-threading/threads-and-gil.md index e4b5f9e4d9..eadabb5780 100644 --- a/python/python-core/python-threading/threads-and-gil.md +++ b/python/python-core/python-threading/threads-and-gil.md @@ -9,9 +9,8 @@ type: normal category: coding links: - - >- - [Hyper-Threading Technology](https://en.wikipedia.org/wiki/Simultaneous_multithreading#:~:text=The%20Intel%20Pentium%204%20was,a%20number%20of%20their%20processors.) - + - >- + [Hyper-Threading Technology](https://en.wikipedia.org/wiki/Simultaneous_multithreading#:~:text=The%20Intel%20Pentium%204%20was,a%20number%20of%20their%20processors.){website} --- # Threads and GIL From f933a3f8aa769b229272de250e562e0691822ed4 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 3 May 2021 13:26:25 +0200 Subject: [PATCH 005/390] Update threading-with-join-2.md --- .../python-threading/threading-with-join-2.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/python/python-core/python-threading/threading-with-join-2.md b/python/python-core/python-threading/threading-with-join-2.md index 15266705f3..ce8887820b 100644 --- a/python/python-core/python-threading/threading-with-join-2.md +++ b/python/python-core/python-threading/threading-with-join-2.md @@ -2,11 +2,21 @@ author: Stefan-Stojanovic tags: - - coding + - introduction type: normal -category: coding +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- From 8d6e96afd2a333ae375ede8189573db7818247e6 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 3 May 2021 13:26:49 +0200 Subject: [PATCH 006/390] Update what-are-threads.md --- .../python-core/python-threading/what-are-threads.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/python/python-core/python-threading/what-are-threads.md b/python/python-core/python-threading/what-are-threads.md index 51ddf8e3ad..15ce104fd2 100644 --- a/python/python-core/python-threading/what-are-threads.md +++ b/python/python-core/python-threading/what-are-threads.md @@ -2,11 +2,16 @@ author: Stefan-Stojanovic tags: - - coding + - introduction type: normal -category: coding +category: must-know + +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- @@ -36,4 +41,4 @@ Along side the memory that is being shared, any code, including variables is sha - Threads - process - Processes -- thread \ No newline at end of file +- thread From e2ae5494e3387abc121c0e5527fecc0c486f4f97 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 3 May 2021 13:27:39 +0200 Subject: [PATCH 007/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d98731d530..ba088e93cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## May 3rd 2021 + +### Added +- [Python - Threading - Add workout](https://github.com/enkidevs/curriculum/pull/2689) + ## April 27th 2021 ### Added From 009db7a400acd448abb9246c5e269743911ea86a Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Thu, 13 May 2021 17:34:14 +0200 Subject: [PATCH 008/390] remove word "easily" --- python/python-core/python-threading/threading-with-join.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/python-core/python-threading/threading-with-join.md b/python/python-core/python-threading/threading-with-join.md index 818f637ccb..936f818a4b 100644 --- a/python/python-core/python-threading/threading-with-join.md +++ b/python/python-core/python-threading/threading-with-join.md @@ -37,7 +37,7 @@ firstThread = Now, let's import the `time` module and use a different function to create one. -> Using the `time` module we can easily see how `threading` works by implemeting the `time.sleep(NUM_OF_SECOND)` method. +> Using the `time` module we can see how `threading` works by implemeting the `time.sleep(NUM_OF_SECOND)` method. ```python import threading, time @@ -186,4 +186,4 @@ The function used to instantiate a thread in the previous insight: def someFunction(): for x in range(5): print("I am a thread!!!") -``` \ No newline at end of file +``` From d3a5b1401bbafad833f3486b4fd4548a946022db Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Wed, 9 Jun 2021 15:54:29 +0200 Subject: [PATCH 009/390] Apply suggestions from code review Co-authored-by: Nemanja Stojanovic --- python/python-core/python-threading/creating-threads.md | 2 +- python/python-core/python-threading/threading-with-join-2.md | 4 ++-- python/python-core/python-threading/threading-with-join.md | 4 ++-- python/python-core/python-threading/threads-and-gil.md | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/python/python-core/python-threading/creating-threads.md b/python/python-core/python-threading/creating-threads.md index b86daf5d68..420ebbdf51 100644 --- a/python/python-core/python-threading/creating-threads.md +++ b/python/python-core/python-threading/creating-threads.md @@ -57,7 +57,7 @@ I am a thread!!! I am a thread!!! ``` -We can use some built-in methods to see how many threads we have or if there are any that are stil active: +We can use some built-in methods to see how many threads we have or if there're any that are still active: ```python # Check number of threads diff --git a/python/python-core/python-threading/threading-with-join-2.md b/python/python-core/python-threading/threading-with-join-2.md index ce8887820b..7b46661613 100644 --- a/python/python-core/python-threading/threading-with-join-2.md +++ b/python/python-core/python-threading/threading-with-join-2.md @@ -26,7 +26,7 @@ revisionQuestion: ## Content -Previoulsy, we did this[1] and got this result: +Previously, we did this[1] and got this result: ```python Greetings friend @@ -36,7 +36,7 @@ Third Message Why are you ignoring me ``` -Now let's do the same thing, but instead of only starting it, we will also join it with the main thread. +Now let's do the same thing, but instead of only starting it, we'll also join it with the main thread. ```python import time, threading diff --git a/python/python-core/python-threading/threading-with-join.md b/python/python-core/python-threading/threading-with-join.md index 936f818a4b..134c040c16 100644 --- a/python/python-core/python-threading/threading-with-join.md +++ b/python/python-core/python-threading/threading-with-join.md @@ -26,7 +26,7 @@ revisionQuestion: ## Content -Previoulsy, we created a thread using `someFunction`[1]: +Previously, we created a thread using `someFunction`[1]: ```python firstThread = @@ -37,7 +37,7 @@ firstThread = Now, let's import the `time` module and use a different function to create one. -> Using the `time` module we can see how `threading` works by implemeting the `time.sleep(NUM_OF_SECOND)` method. +> Using the `time` module we can see how **threading** works by implementing the `time.sleep(NUM_OF_SECOND)` method. ```python import threading, time diff --git a/python/python-core/python-threading/threads-and-gil.md b/python/python-core/python-threading/threads-and-gil.md index eadabb5780..50eeed6925 100644 --- a/python/python-core/python-threading/threads-and-gil.md +++ b/python/python-core/python-threading/threads-and-gil.md @@ -31,7 +31,7 @@ If a thread starts using some code, the `GIL` will lock that code to that thread The reason behind this, is that Python is written in `C`, which is called `CPython`. -And the reason `CPython` has `GIL` is because its memory management is not `thread-safe`. +And the reason `CPython` has `GIL` is because its memory management is not **thread-safe**. Prior to modern computing, when it was first created, processes had only 1 thread. From ac4737090bbba1badaa274064797083c9d8bddb6 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Wed, 29 Dec 2021 13:20:29 +0100 Subject: [PATCH 010/390] Rename git/essentials/remote-repository/tracking-and-staging-files.md to .archived/git/essentials/remote-repository/tracking-and-staging-files.md --- .../essentials/remote-repository/tracking-and-staging-files.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {git => .archived/git}/essentials/remote-repository/tracking-and-staging-files.md (100%) diff --git a/git/essentials/remote-repository/tracking-and-staging-files.md b/.archived/git/essentials/remote-repository/tracking-and-staging-files.md similarity index 100% rename from git/essentials/remote-repository/tracking-and-staging-files.md rename to .archived/git/essentials/remote-repository/tracking-and-staging-files.md From 7ccd77b73a35f4b5d5c3a8f43bc6f79ef3c631b7 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Wed, 5 Jan 2022 14:38:32 +0100 Subject: [PATCH 011/390] Update image-base.md add missing example for tag using OpenGraph meta tag links --- web/html/html-images/image-base.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/web/html/html-images/image-base.md b/web/html/html-images/image-base.md index 358b20de95..9d5c72fdaa 100755 --- a/web/html/html-images/image-base.md +++ b/web/html/html-images/image-base.md @@ -6,6 +6,8 @@ links: - >- [HTML Element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base){documentation} + - >- + [The Open Graph Protocol](https://ogp.me/){documentation} practiceQuestion: formats: - fill-in-the-gap @@ -54,7 +56,16 @@ All links in the web page or document will lead to the `https://www.enki.com` li ``` -**Note**: In HTML5, the `` end tag has to be omitted. On the other hand, in XHTML it has to be closed. +> 💡 In HTML5, the `` end tag has to be omitted. On the other hand, in XHTML it has to be closed. + +> ❗ OpenGraph meta tag links ignore the `` tag and need to have absolute URL paths: +```html + + + + +``` --- @@ -113,7 +124,6 @@ Complete the code if a `` URL is assigned and an image is used within an O ### What code assigns the default of every link within the web page to open a new page? - ??? - `` From 361814e8c7a855b05f672745532f6df84e0f499b Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Wed, 5 Jan 2022 14:39:13 +0100 Subject: [PATCH 012/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4dcdf02ab..d77fb7c266 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## January 5th 2022 + +### Fixed +- [HTML - Image Base - Add mising example using OpenGraph meta tag](https://github.com/enkidevs/curriculum/pull/2984) + ## January 4th 2022 ### Fixed From 2546f25c34463c1c59cbdcee35d862f9f2b161c5 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 10 Jan 2022 11:32:27 +0100 Subject: [PATCH 013/390] Update set-comprehension.md move the correct answer: ``` - {1,3,5,9} ``` to the first place --- .../functional-programming/comprehension/set-comprehension.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index f9b40726e7..3d648e4c8b 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -95,8 +95,8 @@ odd_set = {x for x in l if x % 2} ??? -- {1,3,3,5,5,9} - {1,3,5,9} +- {1,3,3,5,5,9} - {1,2,3,4,5,8,9} - {2,4,8} From 13ed71a4bc77d8599d8a3b035e77383fc3c53a80 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 10 Jan 2022 11:33:30 +0100 Subject: [PATCH 014/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e97fcca15..202ff0c672 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## January 10th 2022 + +### Fixed +- [Python - Set Comprehension - More corrent answer to appropriate place in RQ](https://github.com/enkidevs/curriculum/pull/2987) + ## January 9th 2022 ### Changed From af009c07161023f27551babd86d9efe36ec048de Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:21:49 +0100 Subject: [PATCH 015/390] undo changes to all folders but advanced referencing --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 478 insertions(+), 369 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 52bfb6f8b0ca83724f82d8108e43f56fe98bd9f8 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:23:12 +0100 Subject: [PATCH 016/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..d4b998ef04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Advanced Referencing - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2989) ## January 4th 2022 From 5784a814947f724eeaa2fb601135386edc01b5f9 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:37:56 +0100 Subject: [PATCH 017/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 79 files changed, 469 insertions(+), 362 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From d5a973ff646c3695f2225f04ff13fe67db103b06 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:38:31 +0100 Subject: [PATCH 018/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..e091b033db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Classes I - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2992) ## January 4th 2022 From b4ae6f2dea7ae505322ceade584b645fb37e7a24 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:42:29 +0100 Subject: [PATCH 019/390] update changelog --- CHANGELOG.md | 2 +- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 84 files changed, 490 insertions(+), 380 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..d78408c6bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Classes II - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2993) ## January 4th 2022 diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From ef6661e7e7592b3b38947066ab4ba8b034ed0e00 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:45:17 +0100 Subject: [PATCH 020/390] update spacing --- .../classes-ii/class-vs-instance-variables.md | 8 ++++---- .../python-core/classes-ii/instance-objects.md | 2 +- python/python-core/classes-ii/method-objects.md | 8 ++++---- .../python-core/classes-ii/private-variables.md | 16 ++++++++-------- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/python/python-core/classes-ii/class-vs-instance-variables.md b/python/python-core/classes-ii/class-vs-instance-variables.md index 2e45663877..112ae4fd09 100644 --- a/python/python-core/classes-ii/class-vs-instance-variables.md +++ b/python/python-core/classes-ii/class-vs-instance-variables.md @@ -27,10 +27,10 @@ Suppose we have the class definition: ```python class Enki: - class_var = 'python' # class var + class_var = 'python' # class var - def __init__(self, inst): - self.inst = inst # instance var + def __init__(self, inst): + self.inst = inst # instance var ``` The difference between the types of variables can be easily seen: @@ -59,7 +59,7 @@ Is `my_var` a class or instance variable? ```python class Test: - my_var = ‘enki’ + my_var = ‘enki’ ``` - `class` diff --git a/python/python-core/classes-ii/instance-objects.md b/python/python-core/classes-ii/instance-objects.md index b23bc8c15d..83ff66165a 100644 --- a/python/python-core/classes-ii/instance-objects.md +++ b/python/python-core/classes-ii/instance-objects.md @@ -55,7 +55,7 @@ print(c1.quadrant) # "first" ``` -Methods are different. Basically a **method** is a function that belongs to a `class`. +Methods are different. A **method** is a function that belongs to a `class`. Theoretically, all attributes of a class that are function objects define corresponding instance methods. diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index fda41bb480..3a35d31499 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() @@ -126,8 +126,8 @@ Store in variable `x` a method object from the `Test` class: ```python class Test: - def p(self): - return “p method” + def p(self): + return “p method” ??? = Test() x = test.??? ``` diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index 663e5674df..452ae1c0fa 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? @@ -106,9 +106,9 @@ We've defined a pythonic private variable in this class. Is it really private? ```python class Secret: - def __init__(self): - self.__supersecret = "the earth is not flat" - print(self.__supersecret) + def __init__(self): + self.__supersecret = "the earth is not flat" + print(self.__supersecret) topsecret = Secret() ``` From 907206dacb799709bd7f547687f1be514cc2344b Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:47:08 +0100 Subject: [PATCH 021/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 481 insertions(+), 374 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 0a38dee2661b054ea21e9742eb34de2ef0c8ad9e Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:47:41 +0100 Subject: [PATCH 022/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..bca09f787c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Classes III - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2994) ## January 4th 2022 From c0d397584c9445c07210b7a60828d7018d679fdd Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:50:42 +0100 Subject: [PATCH 023/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 78 files changed, 455 insertions(+), 345 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 601d9a9f5441102c08343f0e8f5f6e69f023a9b7 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:51:22 +0100 Subject: [PATCH 024/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..9e99e12d11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Control Flow I - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2995) ## January 4th 2022 From 88f698cebd0b3b5223d3278d02eac80293781d0d Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:54:12 +0100 Subject: [PATCH 025/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 484 insertions(+), 374 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 80b65480a344ae46725a254fe51a4a55918cad85 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:54:23 +0100 Subject: [PATCH 026/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..a9c7716ef5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Control Flow II - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2996) ## January 4th 2022 From a496a668469e5fec0d288ce747cf53fcad694ecb Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:56:48 +0100 Subject: [PATCH 027/390] update grammar in the not operator --- python/python-core/control-flow-ii/the-not-operator.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..d022d1ea81 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -43,7 +43,7 @@ not (x < y) We use this approach in our daily lives a lot! -When we make grocery lists, we don't usually go through everything in the fridge. We just check each item straight away. Like this: If milk is `not` there, buy milk! +When we make grocery lists, we don't usually go through everything in the fridge. Instead, we check each item straight away. Like this: If milk is `not` there, buy milk! > 🤔 Can you think of a real-life example where you use the not approach to save your time? > From 891a5f5a81afb52a84f56a91a5ba645fc5ed313e Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:59:26 +0100 Subject: [PATCH 028/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 80 files changed, 483 insertions(+), 375 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 38b62bca5598a1a49f4e96da786c30898c475196 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:59:31 +0100 Subject: [PATCH 029/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..40e994e6b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Deep Into Collections - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2997) ## January 4th 2022 From 6f2f61e7d1073dbe6cf8bbcad74a2b80a2b6985c Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:02:55 +0100 Subject: [PATCH 030/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 472 insertions(+), 364 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 0d6786a8e105464ba52bab9e0d0ab38b7163ac81 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:04:34 +0100 Subject: [PATCH 031/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..f8f4adefff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Intro To Modules - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2998) ## January 4th 2022 From 637d0ccc1286173e0d6bf3dddaa701b6b60812a5 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:08:52 +0100 Subject: [PATCH 032/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 80 files changed, 459 insertions(+), 350 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From b64b9a95659e8ba308c3838a49b35ff1bd35f4a4 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:09:20 +0100 Subject: [PATCH 033/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..5472763ae8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Is Your Python Healthy - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2999) ## January 4th 2022 From 9602d2bf187620638cfe3130b92d89fe97cb8c55 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:11:34 +0100 Subject: [PATCH 034/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 78 files changed, 448 insertions(+), 338 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From eee64e083c3e9a89c133a468ca2ffb00363d820c Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:12:57 +0100 Subject: [PATCH 035/390] update gramar --- python/python-core/looping/break-and-continue-statements.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..4559ef31be 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -50,7 +50,7 @@ Broken away! Python's `continue` statement is used to skip only one iteration[1] of a loop. -The code execution will proceed to the beginning of next loop iteration. +The code execution will proceed to the beginning of the next loop iteration. For example, here's how we can print only odd numbers by skipping every even loop iteration: From a243c04ea04b6d17b6a9ad081b09c71959b52506 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:13:47 +0100 Subject: [PATCH 036/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..b13cdaf352 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Looping - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3000) ## January 4th 2022 From 0e7b9b1a14fbdfcaf4cc2c1239f8e2313d521a69 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:19:40 +0100 Subject: [PATCH 037/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 83 files changed, 489 insertions(+), 379 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 65fd346a90e9a535f19c2c34e62dd6ae2a7a4473 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:20:00 +0100 Subject: [PATCH 038/390] remove extra space from opening paragraph --- python/python-core/math-recipes/python-s-fractions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/python-core/math-recipes/python-s-fractions.md b/python/python-core/math-recipes/python-s-fractions.md index 8c751b725b..5768c88d2e 100644 --- a/python/python-core/math-recipes/python-s-fractions.md +++ b/python/python-core/math-recipes/python-s-fractions.md @@ -23,7 +23,7 @@ revisionQuestion: ## Content -Support for rational number arithmetic can be achieved using Python's `fractions` module. +Support for rational number arithmetic can be achieved using Python's `fractions` module. Import the module: @@ -49,7 +49,7 @@ print(fractions.gcd(25,75)) # 25 ``` -Keep in mind that with the release of Python 3.5, this method is deprecated and `math.gcd()` should be used. +Keep in mind that with the release of Python 3.5, this method is deprecated, and `math.gcd()` should be used. --- From 7a35f364138ab1331a7c2a410926c0391fa135f3 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:20:37 +0100 Subject: [PATCH 039/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..01cb401801 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Math Recipies - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3001) ## January 4th 2022 From 17022c1a92e31cf50709a833e533df36fe662457 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 10 Jan 2022 17:21:27 +0100 Subject: [PATCH 040/390] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01cb401801..9bdc4aa7a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - Math Recipies - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3001) +- [Python - Math Recipies - Minor grammar improvement](https://github.com/enkidevs/curriculum/pull/3001) ## January 4th 2022 From e8fb6c3af97dbde54b6ce5e19a45a7cf4196433c Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:28:39 +0100 Subject: [PATCH 041/390] revert previous folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 83 files changed, 489 insertions(+), 379 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 1494348e6a8a913cc46dc7162c3451cb7aa84e0a Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:28:49 +0100 Subject: [PATCH 042/390] minor grammar improvements --- python/python-core/memory-allocation/copy-vs-deepcopy.md | 2 +- python/python-core/memory-allocation/memory-leaks.md | 4 ++-- .../memory-allocation/pointers-and-references-python.md | 2 +- .../python-core/memory-allocation/python-garbage-collector.md | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/python/python-core/memory-allocation/copy-vs-deepcopy.md b/python/python-core/memory-allocation/copy-vs-deepcopy.md index b71e93b109..73af4d26b0 100644 --- a/python/python-core/memory-allocation/copy-vs-deepcopy.md +++ b/python/python-core/memory-allocation/copy-vs-deepcopy.md @@ -44,7 +44,7 @@ print(n) # [1, 2] ``` -A shallow copy is a first-layer only copy of the container: any reference to a mutable object contained is kept. +A shallow copy is a first-layer-only copy of the container: any reference to a mutable object contained is kept. ```python m = [1, []] diff --git a/python/python-core/memory-allocation/memory-leaks.md b/python/python-core/memory-allocation/memory-leaks.md index f1e007ba60..c9a2f54da1 100644 --- a/python/python-core/memory-allocation/memory-leaks.md +++ b/python/python-core/memory-allocation/memory-leaks.md @@ -32,9 +32,9 @@ A **memory leak** occurs when a program manages *memory allocation* incorrectly: 0MB 512MB 1024MB ``` -Instead of reusing memory already allocated , the program requests more and more memory, hence eating up memory other background programs/processes might be using. This can slow the whole system down due to *thrashing*[1] making the OS to force kill `A` to free up memory. +Instead of reusing memory already allocated, the program requests more and more memory, hence eating up memory other background programs/processes might be using. This can slow the whole system down due to *thrashing*[1] making the OS force kill `A` to free up memory. -You can usually assume your Python application has a memory leak if its memory usage grows steadily over time. This is not necessarily a reason for concern, as there are a number of tools that can help you identify and solve the problem. To name a few: +You can usually assume your Python application has a memory leak if its memory usage grows steadily over time. This is not necessarily a reason for concern, as several tools can help you identify and solve the problem. To name a few: - Python's debugger, `pdb` - memory monitors and analyzers, `pympler` and `memory_profiler` diff --git a/python/python-core/memory-allocation/pointers-and-references-python.md b/python/python-core/memory-allocation/pointers-and-references-python.md index 23ebea6f9a..a857af7783 100644 --- a/python/python-core/memory-allocation/pointers-and-references-python.md +++ b/python/python-core/memory-allocation/pointers-and-references-python.md @@ -45,7 +45,7 @@ They both **reference** the same place in memory. Strange, right? In Python, basic types are usually *immutable*. This means you can't change their value without them changing their identity (you can already represent an integer in binary; if you are to modify any bit, its value would also change). The same is true for *strings*, *floats*, *tuples* and *bytes*. -It then comes down to the variables' name: what do they represent? In this case, the `=` operator is better described by **"binding"** than *"assignment"*. In other words, both `a` and `b` reference the same object (as seen above with regard to their memory addresses). Incrementing either of them means binding their name to a new value: +It then comes down to the variables name: what do they represent? In this case, the `=` operator is better described by **"binding"** than *"assignment"*. In other words, both `a` and `b` reference the same object (as seen above with regard to their memory addresses). Incrementing either of them means binding their name to a new value: ```python a = a + 1 diff --git a/python/python-core/memory-allocation/python-garbage-collector.md b/python/python-core/memory-allocation/python-garbage-collector.md index f6115b8c4b..501d05cd84 100644 --- a/python/python-core/memory-allocation/python-garbage-collector.md +++ b/python/python-core/memory-allocation/python-garbage-collector.md @@ -70,7 +70,7 @@ What does the garbage collector actually do? ??? - steps in and marks the memory address as free -- delets variables +- deletes variables - removes values from variables From ef9b1b0406e26b6d1663d8244448120d417786a4 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:30:01 +0100 Subject: [PATCH 043/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..486fd94eb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Memory Allocation - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces, grammar improvements](https://github.com/enkidevs/curriculum/pull/3002) ## January 4th 2022 From c8f33435e763802a1c7f4a12f48e9dc18034a0c5 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:32:56 +0100 Subject: [PATCH 044/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 83 files changed, 489 insertions(+), 379 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 7cb6a064759ca9c7c9f8e20a5854a1482f40b16c Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:33:08 +0100 Subject: [PATCH 045/390] update indentation --- python/python-core/meet-python/what-is-python.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 9e142357ba..4410bfd850 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -44,7 +44,6 @@ Python is also a *general-purpose* programming language. That means it can be us You can use it to build websites, web apps and desktop apps. But it's also used in scientific computing, artificial intelligence, and data analysis! - > 💬 Why are you interested in Python? > > Leave a comment or view some of the other comments for inspiration before moving on. @@ -62,7 +61,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print From d73be9e31b14e24837d6416572f4302922656d76 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:33:47 +0100 Subject: [PATCH 046/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..8b0066deea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Meet Python - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3003) ## January 4th 2022 From 19519caa0d2490a68f1333f1a3e2a8c54d4c45ce Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:37:14 +0100 Subject: [PATCH 047/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 486 insertions(+), 377 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 6a00e58fcb0e2976af59d1dac77a7767ce9610ae Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:38:22 +0100 Subject: [PATCH 048/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..d7f24c2015 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - More On Dictionaries - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3004) ## January 4th 2022 From e975cec82db304c88e275f702e4961212fce3a0c Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:40:50 +0100 Subject: [PATCH 049/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 82 files changed, 479 insertions(+), 369 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 5cf284d5a21669c9e6b96fbebd4f26ea318c9419 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:41:03 +0100 Subject: [PATCH 050/390] minor grammar improvement --- python/python-core/more-on-lists/lists-vs-dictionaries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/more-on-lists/lists-vs-dictionaries.md b/python/python-core/more-on-lists/lists-vs-dictionaries.md index dfc1d2f4ba..cb97a5992e 100644 --- a/python/python-core/more-on-lists/lists-vs-dictionaries.md +++ b/python/python-core/more-on-lists/lists-vs-dictionaries.md @@ -47,7 +47,7 @@ dict = { } ``` -Because elements stored in **lists** can be accessed using **indices**, the retrieving of an element will be done in `O(n)` in the worst case scenario. When using **dictionaries**, indices are replaced by **keys** (hashable types). This means that retrieving a certain element would be done in `O(1)` as we can find each **value** associated to each **key** directly. +Because elements stored in **lists** can be accessed using **indices**, the retrieving of an element will be done in `O(n)` in the worst-case scenario. When using **dictionaries**, indices are replaced by **keys** (hashable types). This means that retrieving a certain element would be done in `O(1)` as we can find each **value** associated to each **key** directly. Let's see an example: From bc66e3da4e4e6b201ed642810be819f18c89547b Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:41:44 +0100 Subject: [PATCH 051/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..4d994ae479 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - More On Lists - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3005) ## January 4th 2022 From 7f5e1e3d94a3647ac66ad134b3763f11e6837a53 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:47:06 +0100 Subject: [PATCH 052/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 485 insertions(+), 377 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From af4c6bcd369b22c9ef4437e24f699b00d8a78a65 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:47:15 +0100 Subject: [PATCH 053/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..b8c216d90f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Playing With Time - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3007) ## January 4th 2022 From c71abb5598d0f6c0d14760f5750d8a21bcae6a07 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:08:25 +0100 Subject: [PATCH 054/390] minor grammar improvement --- python/python-core/playing-with-time/datetime-module.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/playing-with-time/datetime-module.md b/python/python-core/playing-with-time/datetime-module.md index c2c43047c3..e852780ff7 100644 --- a/python/python-core/playing-with-time/datetime-module.md +++ b/python/python-core/playing-with-time/datetime-module.md @@ -39,7 +39,7 @@ datetime.MAXYEAR # 9999 ## largest year of date/datetime objects ``` -Keep in mind that in the `datetime` **module** there is also a `datetime` **class** and they shouldn't be confused. +Keep in mind that in the `datetime` **module**, there is also a `datetime` **class**; they shouldn't be confused. ```python # printing the current date and time From 4f589a86ddff3313bd4331c2eab6d71bedf9ed8a Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:12:12 +0100 Subject: [PATCH 055/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 79 files changed, 457 insertions(+), 347 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From b99e7f9a12d9168002fd4931f7ce7e47e2f577eb Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:12:20 +0100 Subject: [PATCH 056/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..01cc7fd118 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Python Functions - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3008) ## January 4th 2022 From c328944c902e6681d437f3602d4702fae6d5c24e Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:18:18 +0100 Subject: [PATCH 057/390] revert other folder --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 82 files changed, 484 insertions(+), 377 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 10adddda9419fa963f9dbbb13a21e4ff524bd387 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:18:23 +0100 Subject: [PATCH 058/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..3f199f4862 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Python Recipes - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3009) ## January 4th 2022 From c636599c05f31c5443a77d01c4a719e5e0651695 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:20:33 +0100 Subject: [PATCH 059/390] minor grammar improvements --- python/python-core/python-recipes/parallel-sorting-of-lists.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/python-recipes/parallel-sorting-of-lists.md b/python/python-core/python-recipes/parallel-sorting-of-lists.md index 9d63f26718..d276f2ce3c 100644 --- a/python/python-core/python-recipes/parallel-sorting-of-lists.md +++ b/python/python-core/python-recipes/parallel-sorting-of-lists.md @@ -43,7 +43,7 @@ age = [18, 21, 40, 32] names, age = zip(*sorted(zip(names, age))) ``` -The `sorted()` method is the equivalent of `sort()` in python3. It sorts the tuples formed from the first `zip` comparing them by the *1st* element of each tuple. +The `sorted()` method is the equivalent of `sort()` in python3. It sorts the tuples formed from the first `zip`, comparing them by each tuple's *1st* element. --- From e4dd53fcec21dff5a70c10ae1ceebe3fc1e20729 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:26:48 +0100 Subject: [PATCH 060/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 82 files changed, 487 insertions(+), 378 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From ff451a6ace71566fd0793688bff37f5a5ff5830e Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:27:15 +0100 Subject: [PATCH 061/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..51d417ea8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Python Tips - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3010) ## January 4th 2022 From 6633817e620807f10f54fe6dc9d2f71c142ad153 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:27:21 +0100 Subject: [PATCH 062/390] minor grammar improvements --- python/python-core/python-tips/dynamic-typing.md | 4 ++-- .../python-core/python-tips/exiting-the-interpreter.md | 2 +- .../python-tips/following-pep-8-styling-guideline.md | 9 ++++----- .../python-tips/pretty-print-data-structures.md | 2 +- 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/python/python-core/python-tips/dynamic-typing.md b/python/python-core/python-tips/dynamic-typing.md index c8aa72110e..54efba0cde 100644 --- a/python/python-core/python-tips/dynamic-typing.md +++ b/python/python-core/python-tips/dynamic-typing.md @@ -20,7 +20,7 @@ revisionQuestion: ## Content -Unlike in statically-typed programming language, Python variables are dynamically typed. That means that a variable (e.g. `x`) can take the value of a number, a string or even a function, but not at the same time. +Unlike in statically-typed programming language, Python variables are dynamically-typed. That means that a variable (e.g. `x`) can take the value of a number, a string, or even a function, but not simultaneously. Some people consider Python's dynamic typing a weakness as it can lead to hard to find bugs. @@ -33,7 +33,7 @@ def x(): pass ``` -In Python, variables do not represent a portion of computer's memory where their value is written, but *tags* pointing to objects. +In Python, variables do not represent a portion of a computer's memory where their value is written, but *tags* pointing to objects. Keep in mind that it is a **bad practice** to use the same variable name for different data types. Instead, use meaningful names for variables. diff --git a/python/python-core/python-tips/exiting-the-interpreter.md b/python/python-core/python-tips/exiting-the-interpreter.md index 43ae3c9f1f..d46c17c665 100644 --- a/python/python-core/python-tips/exiting-the-interpreter.md +++ b/python/python-core/python-tips/exiting-the-interpreter.md @@ -68,7 +68,7 @@ sys.??? ## Revision -What is the key stroke for exiting python interpreter (REPL)? +What is the keyboard shortcut for exiting python interpreter (REPL)? ??? diff --git a/python/python-core/python-tips/following-pep-8-styling-guideline.md b/python/python-core/python-tips/following-pep-8-styling-guideline.md index 828f5d33dc..554012c428 100644 --- a/python/python-core/python-tips/following-pep-8-styling-guideline.md +++ b/python/python-core/python-tips/following-pep-8-styling-guideline.md @@ -23,10 +23,10 @@ revisionQuestion: ## Content -The most common and standard styling guideline for Python is known as PEP 8. -It is designed to improve readability. +Python's most common and standard styling guideline is PEP 8, designed to improve readability. + +It can, however, be quite strict (e.g. in the case of whitespaces). -It can however be quite strict (e.g. in the case of whitespaces). For instance, this is OK in PEP 8: ```python @@ -47,8 +47,7 @@ Raymond Hettinger's word of wisdom: "Do not PEP 8 unto others; only PEP 8 thy self. Don't let PEP 8 make you insanely intolerant of other people's code." -To PEP 8 yourself, use a linter and an autoformatter. These -exist for all the popular editors. +To PEP 8 yourself, use a linter and an autoformatter. These exist for all the popular editors. --- diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..034009fcd1 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -50,7 +50,7 @@ for x in range(4): print(pprint.pformat(data, width=19)) ``` -Instead of a single line our output will be: +Instead of a single line, our output will be: ```python [(0, {0: 0, 1: 1}), From c83fdb45b2e01249c055a14df1d6835661b3a81b Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:32:54 +0100 Subject: [PATCH 063/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 83 files changed, 489 insertions(+), 379 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From cadaa160bdc2aeff4075817ea223afea94ab50b5 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:34:18 +0100 Subject: [PATCH 064/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..10fb71cf9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Sequential Data Types II - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3012) ## January 4th 2022 From 388e1e8e346f9d78238b48246a90d60282f66047 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:34:28 +0100 Subject: [PATCH 065/390] minor grammar improvements --- .../sequential-data-types-ii/del-statement-for-lists.md | 2 +- python/python-core/sequential-data-types-ii/python-lists.md | 2 +- python/python-core/sequential-data-types-ii/ranges.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/python/python-core/sequential-data-types-ii/del-statement-for-lists.md b/python/python-core/sequential-data-types-ii/del-statement-for-lists.md index eb00b22f63..bbdb1b21f4 100644 --- a/python/python-core/sequential-data-types-ii/del-statement-for-lists.md +++ b/python/python-core/sequential-data-types-ii/del-statement-for-lists.md @@ -54,7 +54,7 @@ print(a) Note that `[0:2]` does not include the item at index `2`. -We can also use `del` to delete all of the items inside a `list`, or the whole object itself: +We can also use `del` to delete all of the items inside a `list` or the whole object itself: ```python # delete all the items diff --git a/python/python-core/sequential-data-types-ii/python-lists.md b/python/python-core/sequential-data-types-ii/python-lists.md index 4e6fbfc56a..b3effbf3ac 100644 --- a/python/python-core/sequential-data-types-ii/python-lists.md +++ b/python/python-core/sequential-data-types-ii/python-lists.md @@ -25,7 +25,7 @@ revisionQuestion: A list is a **sequential data type** that acts as a container for objects. -Lists are separated by commas and *must be wrapped in square brackets*, `[ ]`. +Lists are separated by commas, and *must be wrapped in square brackets*, `[ ]`. ```python my_first_list = ['apples', 'oranges'] diff --git a/python/python-core/sequential-data-types-ii/ranges.md b/python/python-core/sequential-data-types-ii/ranges.md index fde9ffa956..422cdd40fa 100644 --- a/python/python-core/sequential-data-types-ii/ranges.md +++ b/python/python-core/sequential-data-types-ii/ranges.md @@ -43,7 +43,7 @@ list(range(1, 10)) # [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` -The first argument here is where the range starts, and second argument is where it ends. This second argument is *not inclusive*. +The first argument here is where the range starts, and the second argument is where it ends. This second argument is *not inclusive*. > Notice how the range function doesn't automatically generate the `list`. When using Python 3 we must always pass our range to the `list` method first. From 6d48d05edbe8c21d3647a9305f5d4a5abb468e60 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:39:11 +0100 Subject: [PATCH 066/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 485 insertions(+), 377 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From a1e04b6e338caa2b4ef19a11e0bdf3266cb424ea Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:39:17 +0100 Subject: [PATCH 067/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..7bd5d2bfcb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - String Recipes - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3013) ## January 4th 2022 From 2f88e7a08280edf9a0d145a3984f7521ff97bcf8 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:40:34 +0100 Subject: [PATCH 068/390] minor grammar improvement --- python/python-core/string-recipes/stringprep-module.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/string-recipes/stringprep-module.md b/python/python-core/string-recipes/stringprep-module.md index 831952f246..69bf36d48f 100644 --- a/python/python-core/string-recipes/stringprep-module.md +++ b/python/python-core/string-recipes/stringprep-module.md @@ -28,7 +28,7 @@ The **RFC 3454** international memo defines the procedure of *preparing* Unicode Often, it is necessary to compare identifications for things such as **host names** for **equality**. -The main purpose of **RFC 3454** is providing a framework for ensuring string input and comparison work for users throughout the world. +The main purpose of **RFC 3454** is to provide a framework for ensuring string input and comparison work for users throughout the world. Python provides the `stringprep` module filled with static methods used for checking if your input is in the specified **RFC 3454** table. From b45878aa71dbacc35f1822460abcfec304190641 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:42:31 +0100 Subject: [PATCH 069/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 83 files changed, 489 insertions(+), 379 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 73a93458d0815270f5bdaafb021ed26ce89aeb90 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:42:36 +0100 Subject: [PATCH 070/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..84b1c5fb5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Syntax And Numerical Operators - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3014) ## January 4th 2022 From 806726e55b8de307cdf27218e8693b6af887183f Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:45:51 +0100 Subject: [PATCH 071/390] minor grammar improvements --- .../syntax-and-numerical-operators/arithmetic-operators.md | 2 +- .../syntax-and-numerical-operators/python-variables.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/python/python-core/syntax-and-numerical-operators/arithmetic-operators.md b/python/python-core/syntax-and-numerical-operators/arithmetic-operators.md index cc91b18343..d9ebc54ead 100644 --- a/python/python-core/syntax-and-numerical-operators/arithmetic-operators.md +++ b/python/python-core/syntax-and-numerical-operators/arithmetic-operators.md @@ -56,7 +56,7 @@ If you want to perform floor division to return an `int`, use the `//` operator: # 6 ``` -When using the `//` operator, you only return the whole number part of the division. Any digits after the decimal point will be removed. +When using the `//` operator, you only return the whole number part of the division. Digits after the decimal point are removed. --- diff --git a/python/python-core/syntax-and-numerical-operators/python-variables.md b/python/python-core/syntax-and-numerical-operators/python-variables.md index da1693076d..7079c658e8 100644 --- a/python/python-core/syntax-and-numerical-operators/python-variables.md +++ b/python/python-core/syntax-and-numerical-operators/python-variables.md @@ -34,7 +34,7 @@ number = 10 number = 100 ``` -Initially the value of `number` was `10`. Later it was changed to `100`. +Initially, the value of `number` was `10`. Later it was changed to `100`. ```python print(number) From f83dd62735c48b81b95c757726e231eb851f3982 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:48:50 +0100 Subject: [PATCH 072/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 +++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 +++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++++--- .../comprehension/set-comprehension.md | 8 +++- ...r-loop-using-map-or-list-comprehensions.md | 8 ++-- .../decorators/decorators-methods.md | 12 ++++-- .../decorators/decorators-syntax.md | 12 ++++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++++--- .../functional-particularities-of-python.md | 7 +++- .../what-is-functional-programming.md | 13 ++++--- .../generators/generator-of-generators.md | 7 ++-- .../generators/recursive-generator.md | 16 ++++---- .../generators/yield-and-next.md | 14 +++---- .../iterators/the-iteration-protocol.md | 28 ++++++------- .../iterators/the-itertools-module-ii.md | 39 ++++++++++++++----- .../atomicity-of-failure.md | 10 +++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++++------ .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 ++++---- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++--- .../python-core/classes-i/creating-classes.md | 5 ++- .../classes-i/method-overriding.md | 16 ++++---- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++--- .../classes-iii/dynamically-create-types.md | 11 ++++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 +++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++++------ .../control-flow-i/if-statements.md | 14 +++---- .../indentation-and-commenting.md | 14 +++---- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 ++-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 ++++----- .../the-from-import-statement.md | 14 ++++--- .../debugging-with-print.md | 34 ++++++++-------- .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 +++++----- .../looping/break-and-continue-statements.md | 12 +++--- python/python-core/looping/for-loops.md | 12 +++--- .../python-core/looping/looping-techniques.md | 12 +++--- .../looping/using-else-in-loops.md | 36 ++++++++--------- python/python-core/looping/while-loops.md | 10 ++--- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++++----- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 +++--- .../python-functions/defining-functions.md | 14 +++---- .../python-functions/nested-functions.md | 34 ++++++++-------- .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 +++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 +++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 +++-- 80 files changed, 455 insertions(+), 345 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 844415b384a263ddc7187516f52ecba6eee3dab3 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:49:07 +0100 Subject: [PATCH 073/390] minor grammar and indentation improvements --- python/python-core/testing/mocking-tests.md | 9 ++++----- python/python-core/testing/pytest.md | 8 ++++---- python/python-core/testing/unit-testing.md | 1 - 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f2b05b66e7 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -45,15 +45,14 @@ If we would run a basic **unittest** on this class, it'll take `10` seconds plus Let's define a **unittest** using a mock example: -```plain-text +```python from unittest import TestCase from unittest.mock import patch class TestCalculator(TestCase): - @patch('main.Calculator.multiply', - return_value=9) - def test_multiply(self, multiply): - self.assertEqual(multiply(2,3), 9) + @patch('main.Calculator.multiply', return_value=9) + def test_multiply(self, multiply): + self.assertEqual(multiply(2,3), 9) ``` We are importing the `patch` decorator[1] from `unittest.mock`. It replaces the actual `multiply` function with a **mock function** that behaves exactly how we want it to. In this case, our **mock function** always returns `9`. During the lifetime of our **test**, the `multiply` function is replaced with its **mocked version**. diff --git a/python/python-core/testing/pytest.md b/python/python-core/testing/pytest.md index 53b14f0c13..3479c0e571 100644 --- a/python/python-core/testing/pytest.md +++ b/python/python-core/testing/pytest.md @@ -32,11 +32,11 @@ Note that for pytest to run the assertion function, it has to start with `test_` ```python # multiply_pytest.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` The test can be run issuing the following command[1]: @@ -75,7 +75,7 @@ The **output** is split into two main parts. The first half contains information - the number of **tests** collected from that file; - the label: `F` if tests fail, or `P` if they pass. -If any **test** fails, then pytest will generate the second part. This part shows the line that causes each **test case** to fail, marked by the `>` sign. Furthermore, it gives a detailed explanation of the **assertion** and finally it states what type of **error** was encountered. +If any **test** fails, then pytest will generate the second part. This part shows the line that causes each **test case** to fail, marked by the `>` sign. Furthermore, it gives a detailed explanation of the **assertion**, and finally, it states what type of **error** was encountered. --- diff --git a/python/python-core/testing/unit-testing.md b/python/python-core/testing/unit-testing.md index 07a00f9374..986c32bb00 100644 --- a/python/python-core/testing/unit-testing.md +++ b/python/python-core/testing/unit-testing.md @@ -33,7 +33,6 @@ Consider the following example: import unittest class SimplisticTest(unittest.TestCase): - def test_True(self): self.assertTrue(True) From 3a9c04e1ee8bd7d97eba58d64936cb2d8ca9cb7c Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:50:00 +0100 Subject: [PATCH 074/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..34c58fe31b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Testing - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3015) ## January 4th 2022 From ba4d53f2b24e2ab86f9e7bc8e5f6ee7ce2b80104 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:53:15 +0100 Subject: [PATCH 075/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 486 insertions(+), 378 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 1d6b82800a2c41a5f2925fab7fbc1ec9e9cf5ba5 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:53:22 +0100 Subject: [PATCH 076/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..ccc2ae791e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Unordered Data Types - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3016) ## January 4th 2022 From dea76ebeafd556653a202508198c355fa250406c Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:53:31 +0100 Subject: [PATCH 077/390] minor improvements --- .../unordered-data-types/dictionary-methods-ii.md | 7 ++----- python/python-core/unordered-data-types/set-methods.md | 4 ++-- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..b58d06a0a7 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -31,11 +31,9 @@ revisionQuestion: ```python square_numbers.keys() - # dict_keys([1, 2, 3, 4, 5]) square_numbers.values() - # dict_values([1, 4, 9, 16, 25]) ``` @@ -43,16 +41,15 @@ square_numbers.values() ```python square_numbers.pop(1) - # 1 print(square_numbers) # {2: 4, 3: 9, 4: 16, 5: 25} ``` -- `popitem()` removes the last item that was inserted in the dictionary, and returns it. +- `popitem()` removes the last item that was inserted in the dictionary and returns it. -> For versions prior to Python 3.7, `popitem()` removed an arbitrary item from the dictionary. For more information check out the links in the "Learn More" section. +> For versions prior to Python 3.7, `popitem()` removed an arbitrary item from the dictionary. For more information, check out the links in the "Learn More" section. ```python square_numbers.popitem() diff --git a/python/python-core/unordered-data-types/set-methods.md b/python/python-core/unordered-data-types/set-methods.md index fcc30f99d5..8282db0168 100644 --- a/python/python-core/unordered-data-types/set-methods.md +++ b/python/python-core/unordered-data-types/set-methods.md @@ -48,13 +48,13 @@ print(my_set) # {'rabbit', 'parrot', 'cat', 'horse', 'dog'} ``` -As you can see, *duplicate* values aren't added to `my_set`. Also note how the *order of items doesn't matter*. +As you can see, *duplicate* values aren't added to `my_set`. Also, note how the *order of items doesn't matter*. To remove items, we can use: - `discard()` -> removes an item if it exists and does nothing if it does not -- `remove()` -> removes an item if it exists, but raises an error if it does not exist. +- `remove()` -> removes an item if it exists but raises an error if it does not exist. ```python my_set.remove('dog') From 6f454329b029e227a36ccc3fac45f28fd345c848 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:55:23 +0100 Subject: [PATCH 078/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 82 files changed, 487 insertions(+), 378 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 2eedbbe65f270447cdf81241d3d4be2567417032 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:55:29 +0100 Subject: [PATCH 079/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..dc22bd1594 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Utilities I - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3017) ## January 4th 2022 From 72d9d93f7112284683f6fe1ab915af2fbfc9cd94 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:01:06 +0100 Subject: [PATCH 080/390] minor grammar improvements --- .../check-available-python-modules.md | 8 ++++---- .../utilities-i/schedule-events-with-sched.md | 8 ++++---- .../utilities-i/your-own-python-calendar.md | 18 +++++++++--------- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/python/python-core/utilities-i/check-available-python-modules.md b/python/python-core/utilities-i/check-available-python-modules.md index 5c3a6e78d1..1b94eb491d 100644 --- a/python/python-core/utilities-i/check-available-python-modules.md +++ b/python/python-core/utilities-i/check-available-python-modules.md @@ -28,13 +28,13 @@ revisionQuestion: ## Content -Find a list of all python modules installed on a machine by running the following command in a terminal. +Find a list of all Python modules installed on a machine by running the following command in a terminal. ```bash pydoc modules ``` -Or, inside of a python interactive shell: +Or, inside of a Python interactive shell: ```python >>> help('modules') @@ -45,7 +45,7 @@ Or, inside of a python interactive shell: ## Practice -Complete the following command such that when used in the Python interactive shell it will show all modules installed on the machine: +Complete the following command such that when used in the Python interactive shell, it will show all modules installed on the machine: ```py >>> ???('???') @@ -63,7 +63,7 @@ Complete the following command such that when used in the Python interactive she ## Revision -What command/s can be ran in **a terminal*** in order to see all Python modules installed on the machine? +What command can be used in **a terminal*** to see all Python modules installed on the machine? ??? diff --git a/python/python-core/utilities-i/schedule-events-with-sched.md b/python/python-core/utilities-i/schedule-events-with-sched.md index f2d04938e1..c61d691bf0 100644 --- a/python/python-core/utilities-i/schedule-events-with-sched.md +++ b/python/python-core/utilities-i/schedule-events-with-sched.md @@ -22,7 +22,7 @@ revisionQuestion: ## Content -Another useful **Python** module is `sched` and it's used for general purpose event scheduling. +Another useful **Python** module is `sched`, and it's used for general-purpose event scheduling. Import the module: @@ -31,7 +31,7 @@ import sched import time # we will use this ``` -Every operation is done with the help of a `scheduler` class that needs two time functions. The first one to determine the current time and the second to wait for a specific period of time. (e.g. `time.time` and `time.sleep`) +Every operation is done with the help of a `scheduler` class that needs two-time functions. The first one to determine the current time and the second to wait for a specific period of time. (e.g. `time.time` and `time.sleep`) ```python s = sched.scheduler(time.time, time.sleep) @@ -55,7 +55,7 @@ Then we run our scheduler: s.run() ``` -`first` is printed after 2 seconds while `second` is printed after 3 seconds. +`first` is printed after 2 seconds, and the `second` after 3 seconds. --- @@ -92,7 +92,7 @@ Given the scheduler code: ```python sched.enter(3,2,print,argument=('second',)) ``` -What is the priority and what the delay? +What is the priority, and what is the delay? ```python # Priority ??? # Delay ??? diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..58026056a2 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -54,13 +54,13 @@ print(cal) The output will look like this: ```plain-text - January 2016 - Mo Tu We Th Fr Sa Su - 1 2 3 - 4 5 6 7 8 9 10 - 11 12 13 14 15 16 17 - 18 19 20 21 22 23 24 - 25 26 27 28 29 30 31 + January 2016 +Mo Tu We Th Fr Sa Su + 1 2 3 + 4 5 6 7 8 9 10 +11 12 13 14 15 16 17 +18 19 20 21 22 23 24 +25 26 27 28 29 30 31 ``` @@ -77,9 +77,9 @@ To print a whole year's calendar: print(calendar.calendar(2016)) ``` -Output not shown since it is too large. +The output is not shown since it is too large. -This module provide other useful methods for working with dates, times and calendars such as `calendar.isleap` (checks if a year is a leap year). +This module provides other useful methods for working with dates, times, and calendars, such as `calendar.isleap` (checks if a year is a leap year). --- From 41dd34aa7e55c6e0e6acea264ba9e6182fb206a8 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:03:26 +0100 Subject: [PATCH 081/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 482 insertions(+), 375 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From bd0e11daa828abeda74e25f4d317b6348804cb5a Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:04:31 +0100 Subject: [PATCH 082/390] minor grammar updates --- .../utilities-ii/get-the-similarity-ratio-of-two-sequences.md | 4 ++-- .../utilities-ii/use-struct-to-work-with-binary-data.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/python/python-core/utilities-ii/get-the-similarity-ratio-of-two-sequences.md b/python/python-core/utilities-ii/get-the-similarity-ratio-of-two-sequences.md index 4397eae47b..59b0de40fb 100644 --- a/python/python-core/utilities-ii/get-the-similarity-ratio-of-two-sequences.md +++ b/python/python-core/utilities-ii/get-the-similarity-ratio-of-two-sequences.md @@ -21,7 +21,7 @@ revisionQuestion: ## Content -`difflib`'s `SequenceMatcher` class and its ratio method makes it easy to compute the "similarity" of two sequences. +`difflib`'s `SequenceMatcher` class and its ratio method make it easy to compute the "similarity" of two sequences. ```python import difflib @@ -42,7 +42,7 @@ With the output: 40.0 ``` -*Junk* sequences (such as whitespace or blank lines) can be passed as the first argument of the function, for them not to be taken into account. The default value is `None`, when nothing is ignored. +*Junk* sequences (such as whitespace or blank lines) can be passed as the first argument of the function, for them not to be taken into account. The default value is `None` when nothing is ignored. It can be used to compare sequences of characters as well, i.e. strings. diff --git a/python/python-core/utilities-ii/use-struct-to-work-with-binary-data.md b/python/python-core/utilities-ii/use-struct-to-work-with-binary-data.md index 3a8260883c..2f1c0aee74 100644 --- a/python/python-core/utilities-ii/use-struct-to-work-with-binary-data.md +++ b/python/python-core/utilities-ii/use-struct-to-work-with-binary-data.md @@ -29,7 +29,7 @@ revisionQuestion: ## Content -Python's `struct` module has routines for converting between binary and text data, in both directions. +Python's `struct` module has routines for converting between binary and text data in both directions. Import the module: From 33397acb812a722eaaea1b3726b2eefd0e7e2609 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:04:37 +0100 Subject: [PATCH 083/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..ae94d870fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Utilities II - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3018) ## January 4th 2022 From 4ac0a159880f5643a78c5c65b3e367ae228c545e Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:07:18 +0100 Subject: [PATCH 084/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- 81 files changed, 481 insertions(+), 375 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` From 3d8621d91a4983252679fdc0ef18e7ff9e3e0b66 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:07:24 +0100 Subject: [PATCH 085/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..4ddbb65c07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Working With Strings - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3019) ## January 4th 2022 From 5d773ba7adadecda8b319151886d3469d93d0189 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:07:31 +0100 Subject: [PATCH 086/390] minor grammar improvements --- python/python-core/working-with-strings/string-formatting.md | 2 +- python/python-core/working-with-strings/string-operations.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/python/python-core/working-with-strings/string-formatting.md b/python/python-core/working-with-strings/string-formatting.md index 0ff0486dcd..889bb8dcfa 100644 --- a/python/python-core/working-with-strings/string-formatting.md +++ b/python/python-core/working-with-strings/string-formatting.md @@ -53,7 +53,7 @@ print(a_string) # Learning Python with Enki, workout number 3. ``` -As you can see, the `format` method takes in the replacements as arguments, and returns the formatted string. Another useful feature of this method is that you can decide which argument is replaced, by using indexes: +As you can see, the `format` method takes in the replacements as arguments and returns the formatted string. Another useful feature of this method is that you can decide which argument is replaced by using indexes: ```py app = 'Enki' diff --git a/python/python-core/working-with-strings/string-operations.md b/python/python-core/working-with-strings/string-operations.md index f8c3b722f0..f4e50558a5 100644 --- a/python/python-core/working-with-strings/string-operations.md +++ b/python/python-core/working-with-strings/string-operations.md @@ -23,7 +23,7 @@ revisionQuestion: Strings are bits of text either defined with 'single' or "double" quotations. Python has a number of built-in methods which perform a variety of operations on strings. -First we'll declare a string for method testing purposes: +First, we'll declare a string for method testing purposes: ```python testString = 'operations' From 5b5484e8a0760464dfb31ef92b2d71cf0981087f Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:10:55 +0100 Subject: [PATCH 087/390] revert other folders --- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 475 insertions(+), 375 deletions(-) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From a269899e05e980d8a3037df3c5fbcb684eea7e60 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:11:29 +0100 Subject: [PATCH 088/390] minor grammar improvements --- .../arrays-i/the-reversed-built-in-function.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/functional-programming/arrays-i/the-reversed-built-in-function.md b/python/functional-programming/arrays-i/the-reversed-built-in-function.md index 6072750eee..bf849dfe4b 100644 --- a/python/functional-programming/arrays-i/the-reversed-built-in-function.md +++ b/python/functional-programming/arrays-i/the-reversed-built-in-function.md @@ -31,7 +31,7 @@ The `reversed` built-in allows us to create an iterator for an iterable sequence reversed(seq) ``` -Where `seq` is an iterable sequence such as a tuple, list, string or range. This returns an iterator which accesses the elements in the sequence in the reverse order. For example, we may use `reversed` to reverse the order of characters in a string. +Where `seq` is an iterable sequence such as a tuple, list, string, or range. This returns an iterator, which accesses the elements in the sequence in the reverse order. For example, we may use `reversed` to reverse the order of characters in a string. ```python ourString = 'enki' @@ -39,7 +39,7 @@ print(list(reversed(ourString))) # Result: ['i', 'k', 'n', 'e'] ``` -Notice how we could create custom classes that implement the `__reversed__()` method and then use `reversed` on them to quickly and efficiently reverse their ordering. In this way we can begin to see how often the `reversed` function might be useful in day-to-day programming tasks. +Notice how we could create custom classes that implement the `__reversed__()` method and then use `reversed` on them to quickly and efficiently reverse their ordering. In this way, we can begin to see how often the `reversed` function might be useful in day-to-day programming tasks. --- From 4116e31f85d4b9f49f0f66a3a97b3a999fe96397 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:11:35 +0100 Subject: [PATCH 089/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..69ccdc00b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Arrays I - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3020) ## January 4th 2022 From ff4f11bbdb8e997fa1cffe89ba66a01ae9d50b0f Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:14:10 +0100 Subject: [PATCH 090/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 485 insertions(+), 377 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 2daad363cec2e12a90d4114b0a0fc9b56119c600 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:14:25 +0100 Subject: [PATCH 091/390] minor grammar improvements --- .../arrays-ii/the-map-built-in-function.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..a0f4c4fa55 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -29,7 +29,7 @@ revisionQuestion: ## Content -The `map` function is built in to the Python language. Together with the other built-in functions `filter` and `reduce`, `map` allows us to take a functional approach to programming in Python. +The `map` function is built into the Python language. Together with the other built-in functions `filter` and `reduce`, `map` allows us to take a functional approach to programming in Python. `map` applies a given function—`function_here` in the case below—iteratively to all items in a given `input_list`[1]. The basic syntax looks like this: From 75fed3c9cdcbd175242b995754a7ced90f4fbbe6 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:14:43 +0100 Subject: [PATCH 092/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..c3378a2ccb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Arrays II - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3021) ## January 4th 2022 From 3c107d8b36bf9ef02cc3807e59784eb9fd98e683 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:16:59 +0100 Subject: [PATCH 093/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 78 files changed, 458 insertions(+), 362 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From fbb73f7b7c71c530842a7403552881f5af7f3281 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:17:11 +0100 Subject: [PATCH 094/390] add space for consistency --- .../comprehension/dictionary-comprehension.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..9ed597844c 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -34,7 +34,7 @@ cube_dict = {x: x ** 3 for x in num_list} ``` -Now if we print cube_dict, we get: +Now, if we print `cube_dict`, we get: ```python for k, v in cube_dict.items(): @@ -60,7 +60,8 @@ print(lcase_freqs) {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ 'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... -'g': 0, 'a': 0, 'n': 0} + 'g': 0, 'a': 0, 'n': 0} + # Check it is correct: lfk = list(lcase_freqs.keys()) lfk.sort() From 2a1df8d3fe8dba92819abc7548a2cf3a6d003a4c Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:17:43 +0100 Subject: [PATCH 095/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..9f1e2edca9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Comprehension - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3022) ## January 4th 2022 From efd963eb6a43bde33e14011533a0f81c4f498e6a Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:20:20 +0100 Subject: [PATCH 096/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 79 files changed, 458 insertions(+), 363 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 3627d41878b214e3166e72de765af0a2dafda17e Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:20:42 +0100 Subject: [PATCH 097/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..d2dc3ece53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Decorators - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3023) ## January 4th 2022 From 57e5e6ff9da7654d5721f98e7724808fd708a221 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:22:49 +0100 Subject: [PATCH 098/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 82 files changed, 482 insertions(+), 373 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 66944196ab8f55a6d7aeb42cd4843182cc3f4575 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:22:58 +0100 Subject: [PATCH 099/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..2e96531945 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Functional Programming - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3024) ## January 4th 2022 From cd3a69079ed0e745eba5d1327b48f60462c78a0d Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:24:54 +0100 Subject: [PATCH 100/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 82 files changed, 484 insertions(+), 377 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From ec6801e721e7163dccdaf6c0c82f1dbbc0956afb Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:25:54 +0100 Subject: [PATCH 101/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..54eb1712af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Functional Programming II - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3025) ## January 4th 2022 From 735b24ec962ff35fade8ba223bd36acd05e1b2c6 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:26:05 +0100 Subject: [PATCH 102/390] remove extra spacing --- .../functional-particularities-of-python.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..99e8bf3e6a 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -35,7 +35,7 @@ Generators allow us to make functions which essentially keep these variables fro ```python def generate_ints(N): for i in range(N): - yield i + yield i ``` This is a simple generator, identified by the `yield` keyword. (Any function with a `yield` is a generator.) When it is called, instead of returning a value, a generator object is returned instead which supports the iterator protocol. Calling `next()` on the generator object will continually run and return the result, "pausing" the function every time after it reaches `yield`. From 111d2f7d6f905535c36db8164032b31471e8ccca Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:30:34 +0100 Subject: [PATCH 103/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 80 files changed, 470 insertions(+), 361 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 6a422887ebb36827e1b2c99a5ad6e108caa75215 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:30:40 +0100 Subject: [PATCH 104/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..f361cc1883 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Generators - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3026) ## January 4th 2022 From 8f0a8be16118dfbcd1836aa7a31a11c7edc35135 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:32:28 +0100 Subject: [PATCH 105/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 445 insertions(+), 356 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have less than zero items in the basket!""") + raise ValueError("""You can't have + less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -43,7 +44,8 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + str(self.itemcount) + " items.") + return("Shopping Basket with " + + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -90,7 +92,9 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) +conn = Connection( + http.client.HTTPConnection( + "httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 12ef6c24e8..41028ca9e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 10d592e97d..5e91664bd1 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,8 +41,10 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request(self.method, "/") - self.result = self.httpconnection.getresponse() + self.httpconnection.request( + self.method, "/") + self.result = + self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From cc392d9aacbc0ba44e4b7e7b5d05653fc63f18a2 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:32:38 +0100 Subject: [PATCH 106/390] open changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..9c3f501df8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Iterators - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3027) ## January 4th 2022 From 0760130659e4d00a2bed28faee3ad7ca54c25d16 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:34:11 +0100 Subject: [PATCH 107/390] revert other folders --- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 60 files changed, 320 insertions(+), 283 deletions(-) diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index b7eb62504a..c46e623a7e 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,7 +61,8 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..d82ec7a030 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) ``` To create an instance of the class: @@ -66,7 +67,8 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}".format(self.name, self.idnum)) + print("{0} is employee no. {1}" + .format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..2ef3a3fad2 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 185ecf2c0f..3764220c60 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..fddf5854b2 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -62,7 +62,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) + for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') +normal = unicodedata.normalize\ + ('NFKD', data).\ + encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index 47b9648e51..eeca38504e 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example, we'll **run** the test with `-v` (verbose) flag: +For this example we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???([1, 2, 3, 4, 5], ???) +new_dictionary = ???.???( + [1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 07273fb6c8..57d4e2cec9 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,6 +95,7 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python + animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.???(calendar.MONDAY) +calendar.??? \ + (calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, " abcd", "abcd abcd") +s = SequenceMatcher(None, \ + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -50,7 +51,8 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", + " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -63,7 +65,8 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, + “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,7 +57,8 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) for elt in somelist] +slist = [some_function(elt) \ + for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 191401d6d7..7554291e53 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,8 +73,10 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string.???("It's ???weather") -print(t.???(weather="sunny")) +t = string + .???("It's ???weather") +print(t + .???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From eff426abfd76827082b84852f8fbef588bb32157 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:34:18 +0100 Subject: [PATCH 108/390] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..91e56b3a00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) -- [Python - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [Python - Python Immutability - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3028) ## January 4th 2022 From b8b67f474cc23972413e356d0a5fe3f8421a73b3 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 23:21:10 +0100 Subject: [PATCH 109/390] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 +++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 +++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++++--- .../comprehension/set-comprehension.md | 8 +++- ...r-loop-using-map-or-list-comprehensions.md | 8 ++-- .../decorators/decorators-methods.md | 12 ++++-- .../decorators/decorators-syntax.md | 12 ++++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++++--- .../functional-particularities-of-python.md | 7 +++- .../what-is-functional-programming.md | 13 ++++--- .../generators/generator-of-generators.md | 7 ++-- .../generators/recursive-generator.md | 16 ++++---- .../generators/yield-and-next.md | 14 +++---- .../iterators/the-iteration-protocol.md | 28 ++++++------- .../iterators/the-itertools-module-ii.md | 39 ++++++++++++++----- 20 files changed, 155 insertions(+), 88 deletions(-) diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 1dfc4bd811..7fef3fb0db 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,7 +105,8 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', + '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 7ff2fc725f..3c66abce92 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,9 +105,18 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', 'FR', 'FR', 'RU'] -fnames = ['italo', 'jean', 'emily', 'katya'] -lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] +locations = ['IT', + 'FR', + 'FR', + 'RU'] +fnames = ['italo', + 'jean', + 'emily', + 'katya'] +lnames = ['calvino', + 'micheal', + 'rambert', + 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index 9f60eb2eb9..eb43dabe6c 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,8 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', + 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 86709fed22..8987a02dd7 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,7 +105,8 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, +'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ Now if we print cube_dict, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,7 +58,7 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ - 'b': 0, 'c': 0, 't': 0, 'h': 0, \ +'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... 'g': 0, 'a': 0, 'n': 0} # Check it is correct: @@ -66,9 +66,9 @@ lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ - 'g', 'h', 'i', 'j', 'k', 'l', \ - 'm', 'n', 'o', 'p','q', 'r', \ - 's', 't', 'u', 'v', 'w', 'x', \ - 'y', 'z'] +'g', 'h', 'i', 'j', 'k', 'l', \ +'m', 'n', 'o', 'p','q', 'r', \ +'s', 't', 'u', 'v', 'w', 'x', \ +'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 \ + ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +matrix = [[1, 2, 3], [4, 5, 6], \ +[7, 8, 9]] + ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] +matrix2 = [[x**2 for x in row] for \ +row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36],\ +# [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ - range(10) if x % 2 == 0 \ - for y in range(20) if \ - y % 3 == 0 ] +range(10) if x % 2 == 0 \ +for y in range(20) if \ +y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -66,6 +70,7 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python + l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] + ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} + ``` We can now check the result: @@ -46,6 +48,7 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} + ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -64,8 +67,10 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python + l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else/ + ??? for x ??? l} ``` - if @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} What will the `odd_set` look like after we run the following code snippet? ```python + l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index a188eea03f..105042a723 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,7 +47,8 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() for word in input_list] +lower_list = [word.lower() \ + for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -62,7 +63,8 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? for word in ???] +lower_list = [word.??? \ + for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F".format(method(self) * 1.8 + 32) + return "{0} F" + .format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -54,7 +55,8 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F".format(method(*args,**kwargs)*1.8+32) + return "{0} F" + .format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -63,8 +65,10 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, extra3 = 0): - return self.degrees + extra1 + extra2 + extra3 + def get_temp(self, extra1, extra2 = 0, + extra3 = 0): + return self.degrees + extra1 + extra2 + + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -36,7 +37,8 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper @h2_decorate @@ -53,7 +55,8 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = div_decorate(h2_decorate(say_hello)) +long_wrap = + div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -80,7 +83,8 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}".format(tag, string_function(name)) + return "<{0}>{1}" + .format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" \ + .format(string_function(name)) return func_wrapper @h2_decorate @@ -52,7 +53,8 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -52,7 +53,8 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

".format(say_goodbye(name)) + return "

{0}

" + .format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -60,7 +62,8 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

".format(string_function(name)) + return "

{0}

" + .format(string_function(name)) return func_wrapper ``` @@ -84,7 +87,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar-looking functions that can be decorated using the same decorator is +The number of similar looking functions that can be decorated using the same decorator is ??? @@ -105,11 +108,13 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

".format(say_hello(name)) + return "

{0}

" + .format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

".format(func(name)) + return "

{0}

" + .format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -47,14 +47,17 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and condition2(element): + if condition1(element) and + condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] +collection = [e if condition1(e) and + condition2(e) else + modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( \ - lambda x: x % 2 == 0,foo -))) +print(list(filter( + lambda x: x % 2 == 0,foo)) + ) # Output: [2, 4, 6] ``` @@ -108,9 +108,10 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list(filter( \ - lambda x: x / 2 == 1 ,foo -)) +result = list( + filter( + lambda x: x / 2 == 1 ,foo + )) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```python +```plain-text def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power(power_of_two(), 4))) +print(list(n_power( + power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ea9b3d8141..ecd93de7f6 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index cb18f961a9..d010cc6313 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print(list(itertools.chain(letters, numbers))) +print( + list( + itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -46,7 +48,10 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) +print( + list( + itertools.filterfalse( + lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -57,7 +62,9 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print(list(itertools.compress(numbers, boolean))) +print( + list( + itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -79,18 +86,26 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = iter(itertools.???(discounts, isInSale)) +discountIterator = +iter( + itertools.???( + discounts, isInSale)) -fullPricesInSale = itertools.compress(prices, isInSale) +fullPricesInSale = +itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print(list(itertools.???(lambda x: f(x), fullPricesInSale))) +print( + list( + itertools.???( + lambda x: f(x), fullPricesInSale))) -print(list(salePrices)) +print( + list(salePrices)) ``` - `compress` @@ -110,10 +125,16 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', + 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) +print( + list( + itertools.islice( + itertools.cycle( + itertools.compress( + names, boolean)), 0, 6))) ``` ??? From 49fee7ede016358761882df3273d3899c50b3734 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 10 Jan 2022 14:23:06 -0800 Subject: [PATCH 110/390] Update python/functional-programming/arrays-ii/the-map-built-in-function.md Co-authored-by: Nemanja Stojanovic --- .../arrays-ii/the-map-built-in-function.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index a0f4c4fa55..24be068738 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -68,7 +68,7 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` From d4d53693e8121b8c82843a7c8cf8809689cf68e2 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Thu, 13 Jan 2022 11:06:53 +0100 Subject: [PATCH 111/390] Update datetime-module.md replace the link for an older version with the current stable version one --- python/python-core/playing-with-time/datetime-module.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/playing-with-time/datetime-module.md b/python/python-core/playing-with-time/datetime-module.md index c2c43047c3..71d526775b 100644 --- a/python/python-core/playing-with-time/datetime-module.md +++ b/python/python-core/playing-with-time/datetime-module.md @@ -4,7 +4,7 @@ type: normal category: feature links: - >- - [docs.python.org](https://docs.python.org/3.5/library/datetime.html){website} + [docs.python.org](https://docs.python.org/3.10/library/datetime.html){website} practiceQuestion: formats: - fill-in-the-gap From 5b67450c5847f5e5d5bb4ea31b232430847b7dde Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 17 Jan 2022 04:47:38 -0800 Subject: [PATCH 112/390] Update web/html/html-images/image-base.md Co-authored-by: Nemanja Stojanovic --- web/html/html-images/image-base.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web/html/html-images/image-base.md b/web/html/html-images/image-base.md index 9d5c72fdaa..798f8b8ae9 100755 --- a/web/html/html-images/image-base.md +++ b/web/html/html-images/image-base.md @@ -61,9 +61,9 @@ All links in the web page or document will lead to the `https://www.enki.com` li > ❗ OpenGraph meta tag links ignore the `` tag and need to have absolute URL paths: ```html - + + content='http://enki.com/facebook-image.jpg'> ``` From 8c5d1dfaf32a012a1b660bd66537b2a964dd87e6 Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic Date: Sun, 23 Jan 2022 20:16:03 -0500 Subject: [PATCH 113/390] Update tsc-extending-interfaces.md Add more info on the syntax about extending interfaces (and change code formatting since code will wrap according to user screen) --- .../tsc-classes-and-interfaces/tsc-extending-interfaces.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-extending-interfaces.md b/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-extending-interfaces.md index 8a0abbc9f0..4bdd9e606e 100644 --- a/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-extending-interfaces.md +++ b/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-extending-interfaces.md @@ -57,7 +57,7 @@ console.log( This allows you to combine information from one interface into another and organize the types into reusable shapes that makes the most sense for your program. -In fact, more than one interface can be extended: +In fact, more than one interface can be extended by writing them one after another separated by a comma: ```ts interface Skill { @@ -71,9 +71,7 @@ interface Habit { // to master a skill // we need to build a habit // of practicing it -interface SkillMastery - extends Skill, - Habit { +interface SkillMastery extends Skill, Habit { isFun: boolean; } From 2dd721915b291158b667acc00469d9cfb071fb1f Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 24 Jan 2022 10:32:16 +0100 Subject: [PATCH 114/390] Update go-for-loops.md Remove type-in-the-gap --- go/go-introduction/for-and-switch/go-for-loops.md | 1 - 1 file changed, 1 deletion(-) diff --git a/go/go-introduction/for-and-switch/go-for-loops.md b/go/go-introduction/for-and-switch/go-for-loops.md index 3df9f25968..6e84141b7a 100644 --- a/go/go-introduction/for-and-switch/go-for-loops.md +++ b/go/go-introduction/for-and-switch/go-for-loops.md @@ -5,7 +5,6 @@ category: how-to practiceQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone revisionQuestion: formats: From 93262530e0026bdbbca5a1f38f7fb9542ea33697 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 24 Jan 2022 10:33:37 +0100 Subject: [PATCH 115/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e06dea0cda..0e945f2406 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## Jauary 24th 2022 + +### Changed +- [Go - For Loops - Make the question fill in the gap only](https://github.com/enkidevs/curriculum/pull/3030) + ## January 10th 2022 ### Fixed From 6ed91ed979155d6818121b45e19b723024f40682 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 24 Jan 2022 10:37:51 +0100 Subject: [PATCH 116/390] Update list-orders.md remove extra ??? from RQ --- web/html/lists/list-orders.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/web/html/lists/list-orders.md b/web/html/lists/list-orders.md index 007faabd84..d7e9306d69 100755 --- a/web/html/lists/list-orders.md +++ b/web/html/lists/list-orders.md @@ -154,8 +154,6 @@ What does this code create? Choose the appropriate option. ``` -??? - Option 1 ```html From 550cee61e17ebfcd66e01a44618ad1010b921b9e Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 24 Jan 2022 10:38:47 +0100 Subject: [PATCH 117/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e06dea0cda..9ac804510a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +### January 24th 2022 + +### Fixed +- [HTML - List Orders - Remove extra answer field from RQ](https://github.com/enkidevs/curriculum/pull/3031) + ## January 10th 2022 ### Fixed From dde5a4734dd3db29b5a5ccf53449f89b828b5947 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 25 Jan 2022 14:10:34 +0100 Subject: [PATCH 118/390] Update don-t-repeat-yourself-dry-principle.md replace 404 link with an alternative working one --- .../java-patterns/don-t-repeat-yourself-dry-principle.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/java-fundamentals/java-patterns/don-t-repeat-yourself-dry-principle.md b/java/java-fundamentals/java-patterns/don-t-repeat-yourself-dry-principle.md index 5f6c920f72..e902c4057e 100644 --- a/java/java-fundamentals/java-patterns/don-t-repeat-yourself-dry-principle.md +++ b/java/java-fundamentals/java-patterns/don-t-repeat-yourself-dry-principle.md @@ -10,7 +10,7 @@ tags: - repetition links: - >- - [www.thejavageek.com](http://www.thejavageek.com/2015/04/10/dont-repeat-yourself-principle/){website} + [www.thejavageek.com](https://www.geeksforgeeks.org/dry-dont-repeat-yourself-principle-in-java-with-examples/){website} notes: 'static workout ' --- From 0c517991b72eff6ea6cfbdc8118a6b68a42bade0 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 25 Jan 2022 14:10:59 +0100 Subject: [PATCH 119/390] Update don-t-repeat-yourself-dry-principle.md --- .../java-patterns/don-t-repeat-yourself-dry-principle.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/java-fundamentals/java-patterns/don-t-repeat-yourself-dry-principle.md b/java/java-fundamentals/java-patterns/don-t-repeat-yourself-dry-principle.md index e902c4057e..cd32f023c1 100644 --- a/java/java-fundamentals/java-patterns/don-t-repeat-yourself-dry-principle.md +++ b/java/java-fundamentals/java-patterns/don-t-repeat-yourself-dry-principle.md @@ -10,7 +10,7 @@ tags: - repetition links: - >- - [www.thejavageek.com](https://www.geeksforgeeks.org/dry-dont-repeat-yourself-principle-in-java-with-examples/){website} + [The DRY Principle](https://www.geeksforgeeks.org/dry-dont-repeat-yourself-principle-in-java-with-examples/){website} notes: 'static workout ' --- From b8a379f6ab68de73589ae5f822ffc30c8efc5ff5 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 25 Jan 2022 14:11:30 +0100 Subject: [PATCH 120/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9872f30e67..bb8132afde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## January 25th 2022 + +### Fixed +- [Java - DRY Principle - Replace 404 link](https://github.com/enkidevs/curriculum/pull/3032) + ## January 10th 2022 ### Fixed From 9937e41543d24aeac6346e24fcb97c08b5baf642 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 25 Jan 2022 14:43:40 +0100 Subject: [PATCH 121/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e06dea0cda..1f5d0ebc03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## January 25th 2022 + +### Added +- [TypeScript - tsc Extending Interfaces - Add more info](https://github.com/enkidevs/curriculum/pull/3029) + ## January 10th 2022 ### Fixed From 1cfcfe2168863965aef00a1c13df89af3ad15dba Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 25 Jan 2022 16:12:19 +0100 Subject: [PATCH 122/390] Update README.md remove reference from readme --- git/essentials/remote-repository/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/git/essentials/remote-repository/README.md b/git/essentials/remote-repository/README.md index 7ec4b95a90..b444e5013f 100644 --- a/git/essentials/remote-repository/README.md +++ b/git/essentials/remote-repository/README.md @@ -3,7 +3,6 @@ description: Learn the in's and out's of git's remote repository. insights: - introduction-to-remote-repositories - working-with-remotes - - tracking-and-staging-files - merging - pushing game: git-erminology From ddbbbf6263712cbb20f3e92778960532459c017d Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 25 Jan 2022 16:13:26 +0100 Subject: [PATCH 123/390] Update CHANGELOG.md --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 49a91415b3..bea906f02f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,9 @@ Types of change: ### Added - [TypeScript - tsc Extending Interfaces - Add more info](https://github.com/enkidevs/curriculum/pull/3029) +### Archived +- [Git - Remote Repository - Tracking and staging files duplicate](https://github.com/enkidevs/curriculum/pull/2970) + ## January 24th 2022 ### Changed From f425eb5a994d03705db168229c07a3be4a5544f7 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 31 Jan 2022 12:10:01 +0100 Subject: [PATCH 124/390] Update python-debugger-ii.md --- .../python-core/is-your-python-healthy/python-debugger-ii.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..37b9e8d784 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -31,14 +31,14 @@ Considering the **source code** exemplified in the previous insight[1], lets see (Pdb) list -> num_list = [1, 2] chars = ['a', 'b'] - + def nested_loop(): for nr in num_list: print(nr) for char in chars: print(char) - if __name__ == '__main__': + if __name__ == '__main__': (Pdb) ``` From c572119867cf5b89314393b53983d72bf817f3ca Mon Sep 17 00:00:00 2001 From: Gabor Gyure Date: Tue, 1 Feb 2022 08:45:41 +0100 Subject: [PATCH 125/390] Update end-goals.md Fix typo --- .../python-data-analysis-core/analyzing/end-goals.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python-data-analysis/python-data-analysis-core/analyzing/end-goals.md b/python-data-analysis/python-data-analysis-core/analyzing/end-goals.md index 96ead0fe7d..4a4c22a578 100644 --- a/python-data-analysis/python-data-analysis-core/analyzing/end-goals.md +++ b/python-data-analysis/python-data-analysis-core/analyzing/end-goals.md @@ -26,7 +26,7 @@ What do we know? We know that we have ratings, cast members, genre (`listed_in`), year of release, type of content, and the duration of it. -Here're are some of the questions we can answer about this dataset: +Here are some of the questions we can answer about this dataset: - How many movies vs TV shows are there? - How many ratings exist? - How many movies vs TV shows of a specific ratings are there? From 9f81ddd64fd55332bcf21c23d0475dce7645efd0 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 7 Feb 2022 10:45:57 +0100 Subject: [PATCH 126/390] Update aggregation-with-last.md replace incorrect aggregation operator: `$first` with the correct one: `$last` --- .../aggregation-iii/aggregation-with-last.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mongodb/mongodb-introduction/aggregation-iii/aggregation-with-last.md b/mongodb/mongodb-introduction/aggregation-iii/aggregation-with-last.md index 89f6bb975f..6cd51874a9 100644 --- a/mongodb/mongodb-introduction/aggregation-iii/aggregation-with-last.md +++ b/mongodb/mongodb-introduction/aggregation-iii/aggregation-with-last.md @@ -75,7 +75,7 @@ db.pokemon.aggregate([ - `$group` - `$type` - `nameOfLast ` -- `$first` +- `$last` - `$Type` - `$Group` @@ -95,4 +95,4 @@ Which of these is not a valid accumulator for the `$group` stage? - `$max` - `$push` - `$sum` - \ No newline at end of file + From 8e29a9d1234bbe1b161c6c705d65fe9724c4966e Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 7 Feb 2022 10:47:52 +0100 Subject: [PATCH 127/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7512fff482..420d772680 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 7th 2022 + +### Fixed +- [MongoDb - Aggregation With $last - Replace $first operator with $last](https://github.com/enkidevs/curriculum/pull/3038) + ## January 25th 2022 ### Added From 040c09ce9d68134372361011ef3975c6b8186a79 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 8 Feb 2022 11:39:10 +0100 Subject: [PATCH 128/390] fix spelling of summed replace sumed -> summed --- .../js-sum-and-product-of-two-arrays.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/javascript/javascript-playground-questions/js-sum-and-product-of-two-arrays/js-sum-and-product-of-two-arrays.md b/javascript/javascript-playground-questions/js-sum-and-product-of-two-arrays/js-sum-and-product-of-two-arrays.md index 44c7d785c2..a4b7e6e350 100644 --- a/javascript/javascript-playground-questions/js-sum-and-product-of-two-arrays/js-sum-and-product-of-two-arrays.md +++ b/javascript/javascript-playground-questions/js-sum-and-product-of-two-arrays/js-sum-and-product-of-two-arrays.md @@ -29,7 +29,7 @@ setupCode: > 👩‍💻 Your task is to define a function that: > - **takes two arrays as input** > - **sums up the values in each array** -> - **multiplies the sumed values** +> - **multiplies the summed values** > - **outputs the result** Example arrays: @@ -84,4 +84,4 @@ function sum(arr) { } ``` -Call the function with the arrays and output the result. \ No newline at end of file +Call the function with the arrays and output the result. From f9d2f8655fd6a78ddf6d01b802dfb33c0d4305df Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 8 Feb 2022 11:40:35 +0100 Subject: [PATCH 129/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 800d445bb8..00cf5dbe88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 8th 2022 + +### Fixed +- [JavaScript - Sum And Product Of Two Arrays Exercise - Fix spelling of Summed in question](https://github.com/enkidevs/curriculum/pull/3039) + ## February 7th 2022 ### Fixed From ee50523f3ef9c01690ee3a95cac6dde9fedb4ca0 Mon Sep 17 00:00:00 2001 From: rettal Date: Sun, 13 Feb 2022 20:49:15 +0000 Subject: [PATCH 130/390] Correct table name Previous questions call the table "item", and the questions expect such. --- sql/dql/aggregate-queries/sum-clause.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sql/dql/aggregate-queries/sum-clause.md b/sql/dql/aggregate-queries/sum-clause.md index c7d850caa1..d7416f47e1 100644 --- a/sql/dql/aggregate-queries/sum-clause.md +++ b/sql/dql/aggregate-queries/sum-clause.md @@ -86,7 +86,7 @@ FROM ## Revision -We have a table called `items` that contains the name and cost of every item in Pokeland. We want to know how much it would cost to buy all items... +We have a table called `item` that contains the name and cost of every item in Pokeland. We want to know how much it would cost to buy all items... | id | cost | name | | -- | ---- | ----------- | From 9c4f069279e93df5b3b67a3b31609c05ba4a8662 Mon Sep 17 00:00:00 2001 From: rettal Date: Sun, 13 Feb 2022 21:02:11 +0000 Subject: [PATCH 131/390] Clarification to question Previous question is/was missing vital information for the question to make sense. --- sql/dql/aggregate-queries/distinct-clause.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/sql/dql/aggregate-queries/distinct-clause.md b/sql/dql/aggregate-queries/distinct-clause.md index b94c5af6b3..aef945a7d5 100644 --- a/sql/dql/aggregate-queries/distinct-clause.md +++ b/sql/dql/aggregate-queries/distinct-clause.md @@ -92,21 +92,21 @@ FROM pokedex_name; ## Revision -Consider the following table and the following query. Fill the gaps such that we will have no duplicates in the resulting table: +Consider the following table named GRADES with the following query. Fill the gaps such that we will have no duplicate NAME's in the resulting table: -| NAME | GRADES | -|-----------|--------| -| John | 56% | -| Sebastian | 68% | -| Doris | 56% | -| Alice | 88% | -| Stefan | 68% | -| Raul | 50% | +| NAME | GRADE_PERC | +|-----------|------------| +| John | 56% | +| Sebastian | 68% | +| Doris | 56% | +| Alice | 88% | +| Stefan | 68% | +| Raul | 50% | ```sql SELECT ??? FROM ??? -??? BY GRADES; +??? BY GRADE_PERC; ``` - `DISTINCT name` From 0e539bec3e8312c2acfa2136fc660149e7c0a735 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 14 Feb 2022 11:44:44 +0100 Subject: [PATCH 132/390] remove type in the gap from RQ in nested lists Remove type in the gap as there is no benefit in typing out the 1 or 2 compared to selecting them --- web/html/lists/nested-lists.md | 1 - 1 file changed, 1 deletion(-) diff --git a/web/html/lists/nested-lists.md b/web/html/lists/nested-lists.md index 9ad2c996dc..a319ab396f 100755 --- a/web/html/lists/nested-lists.md +++ b/web/html/lists/nested-lists.md @@ -19,7 +19,6 @@ practiceQuestion: revisionQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone --- From 4365924312d04a3ac0879c6ec9f0e945ad9021c5 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 14 Feb 2022 11:45:53 +0100 Subject: [PATCH 133/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 800d445bb8..a9478f2794 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 14th 2022 + +### Changed +-[Web - Nested Lists - Remove type in the gap as it has no value](https://github.com/enkidevs/curriculum/pull/3040) + ## February 7th 2022 ### Fixed From 6a69dd8fad15b34aad8064b30e98ad3d769d2876 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 14 Feb 2022 14:18:07 +0100 Subject: [PATCH 134/390] Update anchor-links.md --- web/html/links/anchor-links.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/html/links/anchor-links.md b/web/html/links/anchor-links.md index aeb629beda..aebfdedc03 100644 --- a/web/html/links/anchor-links.md +++ b/web/html/links/anchor-links.md @@ -79,7 +79,7 @@ Link to the ## Revision -What denotes an anchor link? +Add the missing code to create an anchor link that navigates to the portion of the page whose id is `contact`: ```html From c86c3a1aa2f80fcafae7be6ca3a682d6797af6c8 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 14 Feb 2022 14:19:12 +0100 Subject: [PATCH 135/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 800d445bb8..7fa5fec674 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 14th 2022 + +### Changed +-[Web - Anchor Links - Make RQ clearer](https://github.com/enkidevs/curriculum/pull/3041) + ## February 7th 2022 ### Fixed From 72177ab972b8b836e521b7efddf6be5534367a60 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 14 Feb 2022 14:21:06 +0100 Subject: [PATCH 136/390] Update python-packages.md remove whitespace from import example as it makes the code create an error(by making the import a 2 liner when it is a oneliner ) --- python/python-core/intro-to-modules/python-packages.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/python/python-core/intro-to-modules/python-packages.md b/python/python-core/intro-to-modules/python-packages.md index 97d7e1ac2f..2890a8baec 100644 --- a/python/python-core/intro-to-modules/python-packages.md +++ b/python/python-core/intro-to-modules/python-packages.md @@ -52,8 +52,7 @@ Now that we have these files defined in our **Hotel package**, we can use them i ```python # rooms_update.py -from Hotel -import available_rooms, total_rooms +from Hotel import available_rooms, total_rooms available_rooms.available(10) # 10 rooms are available. From c24cdd8b2188e2b7f805cbc684c7fde9c924cd5b Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 14 Feb 2022 14:22:14 +0100 Subject: [PATCH 137/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 800d445bb8..1c8fdac8f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 14th 2022 + +### Changed +-[Python - Python Packages - Remove whitespace from a one liner code that spanned two lines](https://github.com/enkidevs/curriculum/pull/3042) + ## February 7th 2022 ### Fixed From d45b8a10b926847a37c653111540000db46d108f Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 15 Feb 2022 07:50:54 +0100 Subject: [PATCH 138/390] Update what-are-formulas.md add spacing between the table and sentence above it --- .../intro-to-functions-and-formulas/what-are-formulas.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spreadsheets/spreadsheets-introduction/intro-to-functions-and-formulas/what-are-formulas.md b/spreadsheets/spreadsheets-introduction/intro-to-functions-and-formulas/what-are-formulas.md index 986b475c21..ebaa5fd1aa 100644 --- a/spreadsheets/spreadsheets-introduction/intro-to-functions-and-formulas/what-are-formulas.md +++ b/spreadsheets/spreadsheets-introduction/intro-to-functions-and-formulas/what-are-formulas.md @@ -42,7 +42,8 @@ Now, every time you update the data in one of the cells found in the formula (`B ## Practice Consider the following spreadsheet: -| ‏‏‎ ‎ | A | B | + +|   | A | B | |---|------|----------| | 1 | Week | Spending | | 2 | 1 | 23 | From d3bc0d94ae1d5603b75e219ca35fcd00f1e42ab1 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 15 Feb 2022 07:57:44 +0100 Subject: [PATCH 139/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 800d445bb8..7a0036ba44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 15th 2022 + +### Fixed +- [Spreadsheets - What Are Formulas - fix markdown table not rendering correctly in PQ](https://github.com/enkidevs/curriculum/pull/3043) + ## February 7th 2022 ### Fixed From 2bf37d63b09f649acdde045f13f8dd909e762efd Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 15 Feb 2022 10:44:50 +0100 Subject: [PATCH 140/390] Update joins-role.md replace wrong output table with correct one --- sql/dql/intro-joins/joins-role.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/sql/dql/intro-joins/joins-role.md b/sql/dql/intro-joins/joins-role.md index 057a46d027..4344e276ee 100644 --- a/sql/dql/intro-joins/joins-role.md +++ b/sql/dql/intro-joins/joins-role.md @@ -60,13 +60,13 @@ FROM pokemon JOIN attack Notice that the query makes references to both tables and then also states the **joining condition**[1] (`pokemon.id = attack.id`). This query returns the following: -| name | route | -| ---------- | ----- | -| venusaur | NULL | -| charmeleon | 4 | -| pikachu | 4 | -| squirtle | 25 | -| magikarp | 6 | +| name | type1 | +|------------|----------| +| venusaur | grass | +| charmeleon | fire | +| pikachu | electric | +| squirtle | water | +| magikarp | water | > 💡 There are many different types of joins, with different implementations and different results. These are covered in the following few workouts. From 07bd7f0c803416e98da71391370e74cb0f6f69c1 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 15 Feb 2022 10:45:39 +0100 Subject: [PATCH 141/390] Update CHANGELOG.md --- CHANGELOG.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b96d94cd7..a61cf72eca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,8 +51,11 @@ Types of change: ## February 14th 2022 ### Changed --[Web - Nested Lists - Remove type in the gap as it has no value](https://github.com/enkidevs/curriculum/pull/3040) --[Python - Python Packages - Remove whitespace from a one liner code that spanned two lines](https://github.com/enkidevs/curriculum/pull/3042) +- [Web - Nested Lists - Remove type in the gap as it has no value](https://github.com/enkidevs/curriculum/pull/3040) +- [Python - Python Packages - Remove whitespace from a one liner code that spanned two lines](https://github.com/enkidevs/curriculum/pull/3042) + +### Fixed +- [SQL - The Roles That Joins Play - Replace wrong output table with the correct one](https://github.com/enkidevs/curriculum/pull/3044) ## February 7th 2022 From bcc18fb93e8c7fc7e84185339d3412daaa8ceb06 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 15 Feb 2022 01:46:32 -0800 Subject: [PATCH 142/390] Apply suggestions from code review Co-authored-by: Andrei Calabangiu --- CHANGELOG.md | 2 +- web/html/links/anchor-links.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fa5fec674..88ced36e70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,7 +51,7 @@ Types of change: ## February 14th 2022 ### Changed --[Web - Anchor Links - Make RQ clearer](https://github.com/enkidevs/curriculum/pull/3041) +- [Web - Anchor Links - Make RQ clearer](https://github.com/enkidevs/curriculum/pull/3041) ## February 7th 2022 diff --git a/web/html/links/anchor-links.md b/web/html/links/anchor-links.md index aebfdedc03..f413fcd348 100644 --- a/web/html/links/anchor-links.md +++ b/web/html/links/anchor-links.md @@ -79,7 +79,7 @@ Link to the ## Revision -Add the missing code to create an anchor link that navigates to the portion of the page whose id is `contact`: +Create an anchor link that navigates to the HTML element with the `contact` id: ```html From b9151494c16c7eedfba30a3207bf686374c68a1e Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 28 Feb 2022 12:44:49 +0100 Subject: [PATCH 143/390] Update sorting-and-filtering.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit add missing L to calculations in 💡 note --- .../data-analysis-using-spreadsheets/sorting-and-filtering.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data-analysis/data-analysis-core/data-analysis-using-spreadsheets/sorting-and-filtering.md b/data-analysis/data-analysis-core/data-analysis-using-spreadsheets/sorting-and-filtering.md index b4bf726676..145ffbcd33 100644 --- a/data-analysis/data-analysis-core/data-analysis-using-spreadsheets/sorting-and-filtering.md +++ b/data-analysis/data-analysis-core/data-analysis-using-spreadsheets/sorting-and-filtering.md @@ -33,7 +33,7 @@ Another great way to spot trends or to explore your data is to use **filters**. Filtering is the process of choosing a smaller part of your data and using that subset for viewing or analysis. -> 💡 Filtering is generally temporary – the original data is kept, but only part of it is used for calcuations. +> 💡 Filtering is generally temporary – the original data is kept, but only part of it is used for calculations. You can click on this icon to turn every column into a filter. From here you can then manipulate each column to display the desired information. From b36ac15626e87f6bc4276bea4fc550d10fc6bedf Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 28 Feb 2022 12:46:18 +0100 Subject: [PATCH 144/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 94d38dc2e9..17bae4f286 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 28th 2022 + +### Fixed +- [Data Analysis - Sorting And Filtering - Add missing L to calculations word in note](https://github.com/enkidevs/curriculum/pull/3047) + ## February 15th 2022 ### Fixed From fc01bddc037080e1ea80e1a691038da2fc7892f4 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 28 Feb 2022 16:43:31 +0100 Subject: [PATCH 145/390] Update battery-api.md Update correct name for `'levelchange'` in the content --- javascript/browser-apis/toolbox-i/battery-api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/browser-apis/toolbox-i/battery-api.md b/javascript/browser-apis/toolbox-i/battery-api.md index fff74e6897..3cfa01f417 100644 --- a/javascript/browser-apis/toolbox-i/battery-api.md +++ b/javascript/browser-apis/toolbox-i/battery-api.md @@ -70,7 +70,7 @@ navigator.???() - getBattery - battery - addEventListener -- 'levelChange' +- 'levelchange' - logBatteryLevel - addListener - bat From d7f3ec2174932fa4d0ac987a6631f499789bd002 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 28 Feb 2022 16:45:32 +0100 Subject: [PATCH 146/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 94d38dc2e9..16bb3fbd06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 28th 2022 + +### Fixed +- [Javascript - Battery API - Replace incorrect levelChange event name with the correct levelchange one](https://github.com/enkidevs/curriculum/pull/3048) + ## February 15th 2022 ### Fixed From b993c9b1750f27f587e68dbfb920ae9824fed083 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 28 Feb 2022 17:00:32 +0100 Subject: [PATCH 147/390] Update chain-comparison-operators.md --- .../python-core/control-flow-ii/chain-comparison-operators.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/control-flow-ii/chain-comparison-operators.md b/python/python-core/control-flow-ii/chain-comparison-operators.md index 374895820f..4b9a9dd088 100644 --- a/python/python-core/control-flow-ii/chain-comparison-operators.md +++ b/python/python-core/control-flow-ii/chain-comparison-operators.md @@ -8,7 +8,7 @@ tags: - operators links: - >- - [stackoverflow.com](http://stackoverflow.com/questions/101268/hidden-features-of-python){website} + [Chaining Comparison Operators](https://mathspp.com/blog/pydonts/chaining-comparison-operators){website} practiceQuestion: formats: - fill-in-the-gap From f8452fc3c5fa9f2fbe67c250077e27319264522a Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 28 Feb 2022 17:01:19 +0100 Subject: [PATCH 148/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 94d38dc2e9..3c9e7d71f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 28th 2022 + +### Fixed +- [Python - Chain Comparison Operators - Replace outdated link](https://github.com/enkidevs/curriculum/pull/3049) + ## February 15th 2022 ### Fixed From 844a44cbb3c0a571b90eb4aa8ee7f91c7fe01195 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Wed, 2 Mar 2022 15:07:20 +0100 Subject: [PATCH 149/390] Update avg-clause.md Remove LIMIT 5 as it has no effect coming after AVG(experience) --- sql/dql/aggregate-queries/avg-clause.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/sql/dql/aggregate-queries/avg-clause.md b/sql/dql/aggregate-queries/avg-clause.md index dc3dd23140..763261555d 100644 --- a/sql/dql/aggregate-queries/avg-clause.md +++ b/sql/dql/aggregate-queries/avg-clause.md @@ -35,12 +35,11 @@ Using the following segment of the `experience` **table**: | 2 | 2 | 10 | 1 | | 3 | 3 | 33 | 1 | -Let's see what the first five values of the `experience` **column** look like: +Let's see what the values of the `experience` **column** look like: ```sql SELECT experience FROM experience -LIMIT 5; ``` Output: @@ -53,12 +52,11 @@ Output: | 80 | | 156 | -Using the `AVG` function, you can find the average of the first five values: +Using the `AVG` function, you can find the average of the values in a select column: ```sql SELECT AVG(experience) as Result FROM experience -LIMIT 5; ``` Output: From cac1ce11c033a8d60c6fbac2d5159af603ff3c00 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Wed, 2 Mar 2022 15:08:12 +0100 Subject: [PATCH 150/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a77fde6bee..9c4fd83b25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## March 2nd 2022 + +### Changed +- [SQL - AVG Clause - Remove LIMIT as it has no effect on the provided queries](https://github.com/enkidevs/curriculum/pull/3050) + ## February 28th 2022 ### Fixed From a58f1a68544c8c19656a3179c14250f44a29d5ac Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Fri, 4 Mar 2022 10:54:18 +0100 Subject: [PATCH 151/390] Update usermod-recipes.md Move one-liner in PQ back to a single-line command (currently shown as 2 lines in the app) --- .../user-management/usermod-recipes.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/linux/user-and-file-management/user-management/usermod-recipes.md b/linux/user-and-file-management/user-management/usermod-recipes.md index 90ca113ce3..71ce2a64ba 100644 --- a/linux/user-and-file-management/user-management/usermod-recipes.md +++ b/linux/user-and-file-management/user-management/usermod-recipes.md @@ -84,8 +84,7 @@ As you've already seen, there are multiple ways to achieve the same result. It's Add the user `user` to the group `root`: ```bash -??? ??? ??? - root user +??? ??? ??? root user ``` - `usermod` From 474ba283f4f43ad4cba2f53d8116f0e12b2bce00 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Fri, 4 Mar 2022 10:56:54 +0100 Subject: [PATCH 152/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c4fd83b25..cb0c995cfe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## March 4th 2022 + +### Fixed +- [Linux - User Mod Recipies - Move Single Line Command in PQ Back To A Single Line](https://github.com/enkidevs/curriculum/pull/3051) + ## March 2nd 2022 ### Changed From 025d17151016aa56e0d4498d59c578e872f68043 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Fri, 4 Mar 2022 11:01:59 +0100 Subject: [PATCH 153/390] Update changing-group-membership-with-usermod.md --- .../changing-group-membership-with-usermod.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/linux/user-and-file-management/user-permissions/changing-group-membership-with-usermod.md b/linux/user-and-file-management/user-permissions/changing-group-membership-with-usermod.md index 302711150f..a6776674d0 100644 --- a/linux/user-and-file-management/user-permissions/changing-group-membership-with-usermod.md +++ b/linux/user-and-file-management/user-permissions/changing-group-membership-with-usermod.md @@ -45,8 +45,7 @@ sudo gpasswd -d jesse new-group Add `john` to the `enki` group: ```plain-text -sudo ??? ??? ??? - ??? ??? +sudo ??? ??? ??? ??? ??? ``` - `usermod` @@ -65,8 +64,7 @@ sudo ??? ??? ??? Make `john` a member of the `enki` group, and of this group only: ```plain-text -sudo ??? ??? - ??? ??? +sudo ??? ??? ??? ??? ``` - `usermod` From 2f24efd9895f5d14bfc5faf373063e515a97d671 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Fri, 11 Mar 2022 11:01:44 +0100 Subject: [PATCH 154/390] Update battery-api.md add one more wrong example (levelChange) for `levelchange` event --- javascript/browser-apis/toolbox-i/battery-api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/browser-apis/toolbox-i/battery-api.md b/javascript/browser-apis/toolbox-i/battery-api.md index 3cfa01f417..9fd99755a5 100644 --- a/javascript/browser-apis/toolbox-i/battery-api.md +++ b/javascript/browser-apis/toolbox-i/battery-api.md @@ -77,7 +77,7 @@ navigator.???() - 'level' - 'change' - BatteryAPI - +- 'levelChange' --- From 78a2489bb30232c1d1ec1490e8aecbf46b04abf8 Mon Sep 17 00:00:00 2001 From: rettal Date: Sun, 13 Mar 2022 20:54:48 +0000 Subject: [PATCH 155/390] Question clarity The correct term for a class variable is a "member". --- .../ecmascript-2015/classes-modules/classes-and-constructor.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/ecmascript-2015/classes-modules/classes-and-constructor.md b/javascript/ecmascript-2015/classes-modules/classes-and-constructor.md index 33e3b58adc..264b121fee 100644 --- a/javascript/ecmascript-2015/classes-modules/classes-and-constructor.md +++ b/javascript/ecmascript-2015/classes-modules/classes-and-constructor.md @@ -107,7 +107,7 @@ console.log(myRec.length) ## Revision -How would you assign a variable `volume` passed to the constructor to a class? +How would you assign a variable `volume` passed to the constructor to a class member variable? ```javascript class Sphere() { From 19a3b5ef2eaf5909d8023d4aa5d4993111abab16 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 14 Mar 2022 09:23:38 +0100 Subject: [PATCH 156/390] Update how-npm3-handles-dependencies.md --- .../npm/packages-modules/how-npm3-handles-dependencies.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/javascript/npm/packages-modules/how-npm3-handles-dependencies.md b/javascript/npm/packages-modules/how-npm3-handles-dependencies.md index 5eb2d87b05..ae0ba61970 100644 --- a/javascript/npm/packages-modules/how-npm3-handles-dependencies.md +++ b/javascript/npm/packages-modules/how-npm3-handles-dependencies.md @@ -82,13 +82,13 @@ It doesn't seem like much, but be aware of this behavior as it might cause *not ## Practice -What is the main difference between how npm2 and npm3 handles dependencies? +What is the main difference between how npm2 and npm3 handle dependencies? ??? -- `node_modules` structure depends on the declaration order +- node_modules structure depends on the declaration order - dependencies are always updated to their latest version -- dependencies can be locked to at specific version +- dependencies can be locked to a specific version --- From 916b04c56aeee67ab8eaeea2fcb126ef2f211354 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 14 Mar 2022 09:24:55 +0100 Subject: [PATCH 157/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb0c995cfe..34fad292fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## March 14th 2022 + +### Fixed +- [JavaScript - How Npm3 Handles Dependencies - Fix answer flowing out of screen and minor spelling mistake](https://github.com/enkidevs/curriculum/pull/3058) + ## March 4th 2022 ### Fixed From b8c4d0a6f996cc0cac46af913eeb3ec773f8e330 Mon Sep 17 00:00:00 2001 From: rettal Date: Mon, 14 Mar 2022 20:47:28 +0000 Subject: [PATCH 158/390] Update sql/dql/aggregate-queries/distinct-clause.md I agree with suggestions, thank you. Co-authored-by: Andrei Calabangiu --- sql/dql/aggregate-queries/distinct-clause.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sql/dql/aggregate-queries/distinct-clause.md b/sql/dql/aggregate-queries/distinct-clause.md index aef945a7d5..91e0adf0c5 100644 --- a/sql/dql/aggregate-queries/distinct-clause.md +++ b/sql/dql/aggregate-queries/distinct-clause.md @@ -92,7 +92,7 @@ FROM pokedex_name; ## Revision -Consider the following table named GRADES with the following query. Fill the gaps such that we will have no duplicate NAME's in the resulting table: +Consider the following table named `GRADES` with the following query. Fill the gaps such that we will have no duplicate `NAME`s in the resulting table: | NAME | GRADE_PERC | |-----------|------------| From f594e04591a03789ffe2226438160bbe468a42f1 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 15 Mar 2022 15:29:14 +0100 Subject: [PATCH 159/390] Fix grammar mistake you -> your --- .../environmental-variables-and-flags-for-npm.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/npm/npm-features-ii/environmental-variables-and-flags-for-npm.md b/javascript/npm/npm-features-ii/environmental-variables-and-flags-for-npm.md index b09df1562a..3b95e1112b 100644 --- a/javascript/npm/npm-features-ii/environmental-variables-and-flags-for-npm.md +++ b/javascript/npm/npm-features-ii/environmental-variables-and-flags-for-npm.md @@ -55,7 +55,7 @@ Suppose your application relies on the `env NODE_PATH ./` trick, but also on oth ## Practice -How would you add an environmental variable called `API_KEY` that's equal to `xyz` at the runtime of you node application? Suppose the main file of you application is `index.js` +How would you add an environmental variable called `API_KEY` that's equal to `xyz` at the runtime of your node application? Suppose the main file of your application is `index.js` ```bash ??? ??? ??? ??? ??? From b323ff9d0966df136f19da8588e4a896449dadde Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 15 Mar 2022 15:30:32 +0100 Subject: [PATCH 160/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d5dfdf70c..4eaff9bfc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## March 15th 2022 + +### Fixed +- [JavaScript - Flags For NPM - Fix grammar (you to your) in pq](https://github.com/enkidevs/curriculum/pull/3059) + ## March 4th 2022 ### Fixed From 2adb96d14bdc0221555909efc6af6bd9cee4f399 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Wed, 16 Mar 2022 08:45:52 +0100 Subject: [PATCH 161/390] Update intro-cite.md Remove `<` `>` from answers as the code block already has in it making the current correct answer: <> instead of --- web/html/citation-elements/intro-cite.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/web/html/citation-elements/intro-cite.md b/web/html/citation-elements/intro-cite.md index bef0ace373..19504de922 100755 --- a/web/html/citation-elements/intro-cite.md +++ b/web/html/citation-elements/intro-cite.md @@ -98,12 +98,12 @@ What HTML element is best to use in this example? tag = ??? ``` -- `` -- `` -- `
` -- `` -- `` -- `` +- `cite` +- `quote` +- `blockquote` +- `q` +- `movie` +- `title` --- From 466e4742042b43a9875dbde767f532d54ac7ef54 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 16 Mar 2022 08:47:16 +0100 Subject: [PATCH 162/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d5dfdf70c..ba13ce0b2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## March 16th 2022 + +### Fixed +- [HTML - Intro cite - Remove double bigger than and smaller than signs from RQ answer](https://github.com/enkidevs/curriculum/pull/3060) + ## March 4th 2022 ### Fixed From 008e29d57d7b3634d41285142c3036ff48751e39 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 16 Mar 2022 08:55:40 +0100 Subject: [PATCH 163/390] Update transforming-text-with-sed.md Remove extra whitespace from lin 33-59 It looked like this in the app: ![placeholder]() After removing whitespace it looks like this: ![placeholder]() --- .../transforming-text-with-sed.md | 37 ++++++++++--------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/linux/jobs-and-processes-data-manipulation/file-streams/transforming-text-with-sed.md b/linux/jobs-and-processes-data-manipulation/file-streams/transforming-text-with-sed.md index 4e071c190c..8b7fabf8d4 100644 --- a/linux/jobs-and-processes-data-manipulation/file-streams/transforming-text-with-sed.md +++ b/linux/jobs-and-processes-data-manipulation/file-streams/transforming-text-with-sed.md @@ -28,34 +28,35 @@ To use it to full effect you have to know a little bit about regular expressions We will pretend that there's a filename called `data.txt` whose contents we're interested in modifying in various ways. `sed` will read the contents of the file, modify the contents according to the rules we specify, and print out the modified content to the console. If we want to save the output to a file we can use the `>` redirection operator. -1. **Simple Text Replacement** +### Simple Text Replacement - This will replace every instance of `apples` with `bananas`. +This will replace every instance of `apples` with `bananas`. - ```shell - sed 's/apples/bananas/g' data.txt - ``` +```shell +sed 's/apples/bananas/g' data.txt +``` + +The general format for "search and replace" is `s/stuff-to-find/stuff-to-replace/flags`. The `flags` allow us to specify different modes for the search and replace command. - The general format for "search and replace" is `s/stuff-to-find/stuff-to-replace/flags`. The `flags` allow us to specify different modes for the search and replace command. +Here `/g` tells `sed` to replace every instance of `apples` on a given line with `bananas`. Without `/g` `sed` would replace only the first instance. - Here `/g` tells `sed` to replace every instance of `apples` on a given line with `bananas`. Without `/g` `sed` would replace only the first instance. -2. **More Advanced Text Replacement** +### More Advanced Text Replacement - This will remove any trailing whitespace from each line, i.e., any extra spaces or tabs at the end of a line. +This will remove any trailing whitespace from each line, i.e., any extra spaces or tabs at the end of a line. - ```shell - sed 's/[ \t]*$//' data.txt - ``` +```shell +sed 's/[ \t]*$//' data.txt +``` - We won't dive into the syntax here, but `[ \t]*$` is regular-expression-ese for "zero or more space or tab characters followed by the end of a line." +We won't dive into the syntax here, but `[ \t]*$` is regular-expression-ese for "zero or more space or tab characters followed by the end of a line." - Likewise, this will remove any *leading* whitespace from each line, aligning all text flush left: +Likewise, this will remove any *leading* whitespace from each line, aligning all text flush left: - ```shell - sed 's/^[ \t]*//' data.txt - ``` +```shell +sed 's/^[ \t]*//' data.txt +``` - Here `^[ \t]*` is regular-expression-ese for "the beginning of a line followed by zero or more space or tab characters". +Here `^[ \t]*` is regular-expression-ese for "the beginning of a line followed by zero or more space or tab characters". As you can see, `sed` offers powerful tools for manipulating text. It's one of the most common tools if you want to transform the output of one program or the contents of a file according to some rule. We've only touched the surface here. From 0a07ce65aea38a22e07ce61fe5a28c921baefed7 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 16 Mar 2022 08:58:13 +0100 Subject: [PATCH 164/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d5dfdf70c..f71402e3a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +### March 16th 2022 + +### Fixed +- [Linux - Transforming Text With Sed - Fix text not showing](https://github.com/enkidevs/curriculum/pull/3061) + ## March 4th 2022 ### Fixed From a7b85441864896dac264aa9714157ca8e9a07395 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 25 Mar 2022 15:51:42 +0100 Subject: [PATCH 165/390] Update dates-in-git.md add example with --until (--until is asked in question) --- git/essentials/git-features-ii/dates-in-git.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/git/essentials/git-features-ii/dates-in-git.md b/git/essentials/git-features-ii/dates-in-git.md index fa7600d5d0..cbb3a508b6 100644 --- a/git/essentials/git-features-ii/dates-in-git.md +++ b/git/essentials/git-features-ii/dates-in-git.md @@ -38,6 +38,11 @@ To see the commits since the 1st Jan 2016: git log --since="01/01/2016" ``` +To see the commits between two dates: +```bash +git log --since=<01/01/2016> --until=<01/01/2017> +``` + To compare the repository between two different dates: ```bash @@ -80,4 +85,4 @@ git ??? --since=??? ???="yesterday" - can - can’t - \ No newline at end of file + From 541610da972c86330e65b59c2421f537f333c98e Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 25 Mar 2022 15:53:02 +0100 Subject: [PATCH 166/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3583ab167a..3f671f92ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## March 25th 2022 + +### Added +- [Git - Git Features II - Add example with until date](https://github.com/enkidevs/curriculum/pull/3062) + ## March 17th 2022 ### Fixed From 30f33563765d74471066ccdbe486561a77e4baee Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 25 Mar 2022 15:53:54 +0100 Subject: [PATCH 167/390] Update dates-in-git.md --- git/essentials/git-features-ii/dates-in-git.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git/essentials/git-features-ii/dates-in-git.md b/git/essentials/git-features-ii/dates-in-git.md index cbb3a508b6..309571fd6e 100644 --- a/git/essentials/git-features-ii/dates-in-git.md +++ b/git/essentials/git-features-ii/dates-in-git.md @@ -40,7 +40,7 @@ git log --since="01/01/2016" To see the commits between two dates: ```bash -git log --since=<01/01/2016> --until=<01/01/2017> +git log --since="01/01/2016" --until="01/01/2017" ``` To compare the repository between two different dates: From 45c16834fff5e88c62150ff80d34c22c74b79422 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Sun, 27 Mar 2022 19:16:00 +0200 Subject: [PATCH 168/390] Update boolean-operators.md --- python/python-core/control-flow-i/boolean-operators.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..7befdbd9b9 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -62,7 +62,7 @@ When using the `or` operator, *at least one of the conditions* must evaluate to ## Practice -Complete the code snippet so that both conditions must evaluate to `True` for the word `'yes'` to be printed: +Complete the code snippet so that **both** conditions must evaluate to `True` for the word `'yes'` to be printed: ```python x = 6 @@ -85,7 +85,7 @@ else: ## Revision -Complete the code snippet so that at least one of the conditions must evaluate to `True` for the word `'yes'` to be printed: +Complete the code snippet so that **at least one** of the conditions must evaluate to `True` for the word `'yes'` to be printed: ```python x = 6 From 5fde3f8db5e3cf15221d33762eb11108cb18435c Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Sun, 27 Mar 2022 19:18:15 +0200 Subject: [PATCH 169/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3583ab167a..d381190fa9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## March 27th 2022 + +### Changed +- [Python - Boolean Operators - Bold words that describe question ](https://github.com/enkidevs/curriculum/pull/3063) + ## March 17th 2022 ### Fixed From 14dd951c19f0f113ed61db0c621a7f18c8541a12 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 30 Mar 2022 10:16:54 +0200 Subject: [PATCH 170/390] Update looping-techniques.md replace javascript comment identifier `//` with pythons `#`. Update the question to avoid getting wrong answer due to whitespace `k, v` != `k,v` --- .../python-core/looping/looping-techniques.md | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 7cca772a89..f05a55fa51 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -48,8 +48,8 @@ Python has multiple techniques for looping over data structures. my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): print(k, v) -#first a -#second b +# first a +# second b ``` The `enumerate()` function allows looping with both `index` and `value` through any **sequence**: @@ -105,20 +105,23 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???, ???) -//Expected output: -// a one -// b two -// c three +# Expected output: +# a one +# b two +# c three ``` - `zip` -- `k, v` -- `f, s` +- `k` +- `v` +- `f` +- `s` - `pair` - `parallel` -- `list_a, list_one` +- `list_a` +- `list_one` --- From 22e9809f8a178adc250593a7eb4be43fecf71cd5 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 30 Mar 2022 10:18:12 +0200 Subject: [PATCH 171/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f671f92ab..c07ae0030c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## March 30th 2022 + +### Fixed +- [Python - Looping Techniques - Fix pq and replace incorrect comment sign](https://github.com/enkidevs/curriculum/pull/3064) + ## March 25th 2022 ### Added From 55478042e4533e24883622c3afe78def2d5b2914 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 30 Mar 2022 20:27:48 +0200 Subject: [PATCH 172/390] Update class-keywords.md remove type in the gap --- python/python-core/classes-i/class-keywords.md | 1 - 1 file changed, 1 deletion(-) diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..1c304b98fa 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -5,7 +5,6 @@ category: must-know practiceQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone revisionQuestion: formats: From c2f6751bbcf9751d9f700cf1a5adc606b6032457 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 30 Mar 2022 20:29:04 +0200 Subject: [PATCH 173/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f671f92ab..ca7b1597ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## March 30th 2022 + +### Changed +- [Python - Clas Keywords - Remove type in the gap](https://github.com/enkidevs/curriculum/pull/3065) + ## March 25th 2022 ### Added From 43e639356c8689234e6b43671df9930ca3e70358 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Sun, 3 Apr 2022 16:19:24 +0200 Subject: [PATCH 174/390] Update distinction-between-stack-and-heap-memory.md --- .../distinction-between-stack-and-heap-memory.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/java/java-fundamentals/memory/distinction-between-stack-and-heap-memory.md b/java/java-fundamentals/memory/distinction-between-stack-and-heap-memory.md index f8c3ece3f7..1acf422426 100644 --- a/java/java-fundamentals/memory/distinction-between-stack-and-heap-memory.md +++ b/java/java-fundamentals/memory/distinction-between-stack-and-heap-memory.md @@ -46,16 +46,18 @@ If there is a lack of heap space, then a `java.lang.OutOfMemoryError: Java Heap ## Practice -Stack memory is used to store ???, ???, and ???. +??? memory is used to store ??? variables, ??? calls, and references to objects stored in ??? memory. -Heap memory is used to store ???. +??? memory is used to store ???. -- local variables -- method calls -- references to objects stored in heap memory +- Stack +- local +- method +- heap +- Heap - objects -- global variables - +- global +- stack --- From e724d649a1ae16b33f3a36fd0b425c202e2c3fd2 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Sun, 3 Apr 2022 16:21:21 +0200 Subject: [PATCH 175/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12c9c15ac9..a4479a3ca7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## April 3rd 2022 + +### Fixed +- [Java - Distinction Between Stack and Heap Memory - Update questions to have only one order](https://github.com/enkidevs/curriculum/pull/3066) + ## March 30th 2022 ### Changed From 01912ff371489677bbd42ec36f1b59d76a2987a5 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 4 Apr 2022 14:14:21 +0200 Subject: [PATCH 176/390] Update input-and-output-redirection-with-and.md shorten names in RQ --- .../pipelines/input-and-output-redirection-with-and.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/linux/user-and-file-management/pipelines/input-and-output-redirection-with-and.md b/linux/user-and-file-management/pipelines/input-and-output-redirection-with-and.md index 22a5195dc5..e14b275303 100644 --- a/linux/user-and-file-management/pipelines/input-and-output-redirection-with-and.md +++ b/linux/user-and-file-management/pipelines/input-and-output-redirection-with-and.md @@ -89,7 +89,7 @@ Which of the following can redirect the output of a process to a file? Piping `cat` like this: ```bash -cat some_file.txt | some_command +cat file.txt | command ``` Is the same as running: @@ -98,7 +98,7 @@ Is the same as running: ??? ??? ??? ``` -- `some_command` +- `command` - `<` -- `some_file.txt` +- `file.txt` - `>` From 20d4f726706b0dcbb774921aa975ccc213be95d9 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 4 Apr 2022 14:15:23 +0200 Subject: [PATCH 177/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12c9c15ac9..7d854590ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## April 4th 2022 + +### Changed +- [Linux - Input and Output Redirection With And - Shorten names in RQ](https://github.com/enkidevs/curriculum/pull/3067) + ## March 30th 2022 ### Changed From 3a410498b778d1cb2d78aaed15234dc58787c000 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 5 Apr 2022 11:02:55 +0200 Subject: [PATCH 178/390] Update blocks.md replace broken link with correct one --- blockchain/blockchain-fundamentals/the-blockchain/blocks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/blockchain/blockchain-fundamentals/the-blockchain/blocks.md b/blockchain/blockchain-fundamentals/the-blockchain/blocks.md index 1a97e3b286..c5e3b1c99f 100644 --- a/blockchain/blockchain-fundamentals/the-blockchain/blocks.md +++ b/blockchain/blockchain-fundamentals/the-blockchain/blocks.md @@ -5,7 +5,7 @@ category: must-know links: - >- [Interactive tutorial of how blocks are - built](https://anders.com/blockchain/){website} + built](https://andersbrownworth.com/blockchain){website} practiceQuestion: formats: - fill-in-the-gap From 410826e709dca34d2802e4d466cb334345ea378b Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 5 Apr 2022 11:05:05 +0200 Subject: [PATCH 179/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a4479a3ca7..3c6854d261 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## April 5th 2022 + +### Fixed +- [Blockhain - Blocks - Replace broken link with new one](https://github.com/enkidevs/curriculum/pull/3068) + ## April 3rd 2022 ### Fixed From 6d0c3865c133e3ae257b03a5dd5794ecf634d5f9 Mon Sep 17 00:00:00 2001 From: kapnobatai137 <andrei@enki.com> Date: Thu, 7 Apr 2022 10:38:15 +0100 Subject: [PATCH 180/390] :speech_balloons: update the contact emails --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8dcb09c43d..a0ce89ef94 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,6 @@ Welcome to our open-source content repository! At Enki, we feel that education is a community effort, and is best approached when everyone is involved and engaged. To that end, we have an entirely open-source curriculum available for you to edit, comment on, and contribute to! **To get started, have a look at our [Wiki](https://github.com/enkidevs/curriculum/wiki)**. -Learning happens best in a psychologically safe environment, so we've adopted the [contributor covenant](https://www.contributor-covenant.org/) as our code of conduct. If a list of rules isn't helping you envision what we're after, [here's another great resource](https://www.recurse.com/manual#sec-environment) (from The Recurse Center, read the Social Rules section) for how to participate in creating a community you'd like to be a part of. We _will_ enforce this, please get in touch with andrei@enki.com or stefan.stojanovic@enki.com with questions or concerns. **Everyone** is learning all the time, so disputes will be arbitrated first, and good-faith efforts are what is expected. +Learning happens best in a psychologically safe environment, so we've adopted the [contributor covenant](https://www.contributor-covenant.org/) as our code of conduct. If a list of rules isn't helping you envision what we're after, [here's another great resource](https://www.recurse.com/manual#sec-environment) (from The Recurse Center, read the Social Rules section) for how to participate in creating a community you'd like to be a part of. We _will_ enforce this, please get in touch with stefan.stojanovic@enki.com with questions or concerns. **Everyone** is learning all the time, so disputes will be arbitrated first, and good-faith efforts are what is expected. This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>. In simpler terms, it means you can't charge other people to use it, or use it to make money, but you can definitely use it to help people learn and you're free to remix or adapt what we have, so long as you attribute Enki, and the author of the work. From ae6da69791c578d3d3b11982e502b9c7f1f6e598 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Thu, 7 Apr 2022 15:54:09 +0200 Subject: [PATCH 181/390] Add back ticks to answers that do not render colors. --- .../parsing-reverse-polish-notation.md | 10 ++--- .../range-map-make/make-a-slice.md | 10 ++--- .../browser-apis/reading-writing/blobs.md | 16 ++++---- .../array-updates/array-extensions.md | 32 +++++++-------- .../destructuring/destructuring-part-3.md | 40 +++++++++---------- .../promises/promise-api-methods.md | 18 ++++----- .../spread-map-set-math/spread-part-2.md | 8 ++-- .../symbol/symbol-special-properties.md | 8 ++-- .../comprehension/list-comprehension.md | 20 +++++----- .../advanced-queues/prioritize-your-queue.md | 6 +-- .../parallel-sorting-of-lists.md | 6 +-- .../del-statement-for-lists.md | 10 ++--- .../more-practical-examples/credit-cards-i.md | 16 ++++---- .../tsc-interfaces-intro.md | 12 +++--- 14 files changed, 106 insertions(+), 106 deletions(-) diff --git a/comp-sci/data-structures-and-algorithms/algorithms-ii/parsing-reverse-polish-notation.md b/comp-sci/data-structures-and-algorithms/algorithms-ii/parsing-reverse-polish-notation.md index 3e2a4e48c6..8ef66e6498 100644 --- a/comp-sci/data-structures-and-algorithms/algorithms-ii/parsing-reverse-polish-notation.md +++ b/comp-sci/data-structures-and-algorithms/algorithms-ii/parsing-reverse-polish-notation.md @@ -58,11 +58,11 @@ What values would be left in the stack after the evaluation of `10 5 * 2 + 3 3`? ??? -- [52,3,3] -- [55,3] -- [55] -- [58] -- [23,3] +- `[52,3,3]` +- `[55,3]` +- `[55]` +- `[58]` +- `[23,3]` --- diff --git a/go/go-introduction/range-map-make/make-a-slice.md b/go/go-introduction/range-map-make/make-a-slice.md index 544a10acd2..bdec912cf3 100644 --- a/go/go-introduction/range-map-make/make-a-slice.md +++ b/go/go-introduction/range-map-make/make-a-slice.md @@ -75,8 +75,8 @@ Create an integer slice called `slice` with a length of `0` and a capacity of `7 ??? := make(???, ???, ???) ``` -- slice -- []int -- 0 -- 7 -- ()int +- `slice` +- `[]int` +- `0` +- `7` +- `()int` diff --git a/javascript/browser-apis/reading-writing/blobs.md b/javascript/browser-apis/reading-writing/blobs.md index f75997508c..5b6467ad96 100644 --- a/javascript/browser-apis/reading-writing/blobs.md +++ b/javascript/browser-apis/reading-writing/blobs.md @@ -101,14 +101,14 @@ new ???( ); ``` -- Blob -- ["parts"] -- type -- endings -- blob -- "parts" -- mimeType -- newLines +- `Blob` +- `["parts"]` +- `type` +- `endings` +- `blob` +- `"parts"` +- `mimeType` +- `newLines` --- diff --git a/javascript/ecmascript-2015/array-updates/array-extensions.md b/javascript/ecmascript-2015/array-updates/array-extensions.md index e3dba2c5a1..10932a4ad5 100644 --- a/javascript/ecmascript-2015/array-updates/array-extensions.md +++ b/javascript/ecmascript-2015/array-updates/array-extensions.md @@ -93,20 +93,20 @@ console.log(???.value) // ??? ``` -- entries -- next -- value -- 1 -- second -- [1, 1] -- [1, 4] -- [0, 1] -- first -- keys -- iterator -- toIterator -- key -- 2 -- 3 -- 0 +- `entries` +- `next` +- `value` +- `1` +- `second` +- `[1, 1]` +- `[1, 4]` +- `[0, 1]` +- `first` +- `keys` +- `iterator` +- `toIterator` +- `key` +- `2` +- `3` +- `0` diff --git a/javascript/ecmascript-2015/destructuring/destructuring-part-3.md b/javascript/ecmascript-2015/destructuring/destructuring-part-3.md index e5dd9f7576..ed05552587 100644 --- a/javascript/ecmascript-2015/destructuring/destructuring-part-3.md +++ b/javascript/ecmascript-2015/destructuring/destructuring-part-3.md @@ -68,14 +68,14 @@ console.log(z) // z == 15 ``` -- x, -- , -- z -- x -- y -- ,y -- y, -- ,x +- `x,` +- `,` +- `z` +- `x` +- `y` +- `,y` +- `y,` +- `,x` --- @@ -92,16 +92,16 @@ let x, y, z; // z = ??? ``` -- 10 -- undefined -- 30 -- 20 -- [20] -- [10, 30] -- [10, 20] -- [20, 30] -- [10, 20, 30] -- null -- [10] -- [30] +- `10` +- `undefined` +- `30` +- `20` +- `[20]` +- `[10, 30]` +- `[10, 20]` +- `[20, 30]` +- `[10, 20, 30]` +- `null` +- `[10]` +- `[30]` diff --git a/javascript/ecmascript-2015/promises/promise-api-methods.md b/javascript/ecmascript-2015/promises/promise-api-methods.md index 008166036d..cfa9afbcb4 100644 --- a/javascript/ecmascript-2015/promises/promise-api-methods.md +++ b/javascript/ecmascript-2015/promises/promise-api-methods.md @@ -86,15 +86,15 @@ Promise.race([p1, p2, p3]).then(res => // ??? ``` -- ['a', 'b', 'c'] -- 'b' -- 'a' -- 'c' -- ['b', 'c', 'a'] -- ['a', 'c', 'b'] -- ['b', 'a', 'c'] -- ['c', 'b', 'a'] -- ['c', 'a', 'b'] +- `['a', 'b', 'c']` +- `'b'` +- `'a'` +- `'c'` +- `['b', 'c', 'a']` +- `['a', 'c', 'b']` +- `['b', 'a', 'c']` +- `['c', 'b', 'a']` +- `['c', 'a', 'b']` --- diff --git a/javascript/ecmascript-2015/spread-map-set-math/spread-part-2.md b/javascript/ecmascript-2015/spread-map-set-math/spread-part-2.md index e414c0c35c..80220354f9 100644 --- a/javascript/ecmascript-2015/spread-map-set-math/spread-part-2.md +++ b/javascript/ecmascript-2015/spread-map-set-math/spread-part-2.md @@ -96,10 +96,10 @@ console.log(final); // ??? ``` -- [3, 6, 2, 4, 3, 6, 2, 3, 6, 2] -- [4, 3, 6, 2, 3, 6, 2, 3, 6, 2] -- [3, 6, 2, 3, 6, 2, 4, 3, 6, 2] -- [3, 6, 2, 2, 3, 6, 2, 4, 6, 2] +- `[3, 6, 2, 4, 3, 6, 2, 3, 6, 2]` +- `[4, 3, 6, 2, 3, 6, 2, 3, 6, 2]` +- `[3, 6, 2, 3, 6, 2, 4, 3, 6, 2]` +- `[3, 6, 2, 2, 3, 6, 2, 4, 6, 2]` --- diff --git a/javascript/ecmascript-2015/symbol/symbol-special-properties.md b/javascript/ecmascript-2015/symbol/symbol-special-properties.md index 48af130d46..7854c94f06 100644 --- a/javascript/ecmascript-2015/symbol/symbol-special-properties.md +++ b/javascript/ecmascript-2015/symbol/symbol-special-properties.md @@ -126,8 +126,8 @@ console.log( // ??? ``` -- [] -- ['Symbol()'] -- ['Symbol(enki)'] -- ['Symbol()', 'Symbol(enki)'] +- `[]` +- `['Symbol()']` +- `['Symbol(enki)']` +- `['Symbol()', 'Symbol(enki)']` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index cfd08dff50..2caed0fa69 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -100,12 +100,12 @@ l = [1,2,3,4,5] x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] ``` -- if -- else -- for -- l -- x -- while +- `if` +- `else` +- `for` +- `l` +- `x` +- `while` --- @@ -121,8 +121,8 @@ x = [x if x % 2 for x in l] ??? -- [1,3,5] -- [1,3] -- [2, 4] -- [1,2,3,4,5] +- `[1,3,5]` +- `[1,3]` +- `[2, 4]` +- `[1,2,3,4,5]` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index b1e82b6f0b..3485cf52c9 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -94,12 +94,12 @@ temp.put(Order(1000)) # 1000 / 10 / 1 ``` -- priority +- `priority` - `__lt__` - `>` -- PriorityQueue() +- `PriorityQueue()` - `<` -- queue +- `queue` - `__order__` diff --git a/python/python-core/python-recipes/parallel-sorting-of-lists.md b/python/python-core/python-recipes/parallel-sorting-of-lists.md index d276f2ce3c..ae5f1d2889 100644 --- a/python/python-core/python-recipes/parallel-sorting-of-lists.md +++ b/python/python-core/python-recipes/parallel-sorting-of-lists.md @@ -89,6 +89,6 @@ cities, temps = zip(*sorted(zipped)) ??? -- [12, 17, 16, 21] -- [12, 16, 17, 21] -- [12, 16, 21, 16] +- `[12, 17, 16, 21]` +- `[12, 16, 17, 21]` +- `[12, 16, 21, 16]` diff --git a/python/python-core/sequential-data-types-ii/del-statement-for-lists.md b/python/python-core/sequential-data-types-ii/del-statement-for-lists.md index bbdb1b21f4..ae3ebc0ed3 100644 --- a/python/python-core/sequential-data-types-ii/del-statement-for-lists.md +++ b/python/python-core/sequential-data-types-ii/del-statement-for-lists.md @@ -88,11 +88,11 @@ print(e) ??? ``` -- [7, 8, 15, 19] -- [7, 8, 19] -- [] -- [7, 11, 15, 19] -- [7, 15, 19] +- `[7, 8, 15, 19]` +- `[7, 8, 19]` +- `[]` +- `[7, 11, 15, 19]` +- `[7, 15, 19]` --- diff --git a/regular-expressions/regular-expressions-introduction/more-practical-examples/credit-cards-i.md b/regular-expressions/regular-expressions-introduction/more-practical-examples/credit-cards-i.md index 55fa61cdb5..227b1209b7 100644 --- a/regular-expressions/regular-expressions-introduction/more-practical-examples/credit-cards-i.md +++ b/regular-expressions/regular-expressions-introduction/more-practical-examples/credit-cards-i.md @@ -62,10 +62,10 @@ Imagine that we don't want to include hyphens or spaces in our pattern for Visa ??? -- [-\s]? -- [-\s] -- ? -- \d +- `[-\s]?` +- `[-\s]` +- `?` +- `\d` --- @@ -78,10 +78,10 @@ Imagine that we don't want to include hyphens or spaces in our pattern for Ameri ??? -- [-\s]? -- [-\s] -- ? -- \d +- `[-\s]?` +- `[-\s]` +- `?` +- `\d` --- diff --git a/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-interfaces-intro.md b/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-interfaces-intro.md index f5fa189150..783f914d28 100644 --- a/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-interfaces-intro.md +++ b/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-interfaces-intro.md @@ -102,12 +102,12 @@ let reader??? = { }; ``` -- Array<Book> -- : BookReader -- satisfy BookReader -- []Book -- = BookReader -- Array<string> +- `Array<Book>` +- `: BookReader` +- `satisfy BookReader` +- `[]Book` +- `= BookReader` +- `Array<string>` --- From 2ab1c80518fe0cf9f5cf439aacccff1e847990fb Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Thu, 7 Apr 2022 15:57:02 +0200 Subject: [PATCH 182/390] Add changelog --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c6854d261..ecf21f0157 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## April 6th 2022 + +### Fixed +- [Multple Topics - Multiple Insights - Add back ticks to all array like answers as they do not render the color](https://github.com/enkidevs/curriculum/pull/3070) + ## April 5th 2022 ### Fixed From 12631b15294feaa70af2a6a4b4e258b61018e657 Mon Sep 17 00:00:00 2001 From: Andrei Calabangiu <andrei@enki.com> Date: Thu, 7 Apr 2022 16:27:43 +0100 Subject: [PATCH 183/390] Update README.md Co-authored-by: Nemanja Stojanovic <n.stojanovic035@gmail.com> --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a0ce89ef94..874739155f 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,6 @@ Welcome to our open-source content repository! At Enki, we feel that education is a community effort, and is best approached when everyone is involved and engaged. To that end, we have an entirely open-source curriculum available for you to edit, comment on, and contribute to! **To get started, have a look at our [Wiki](https://github.com/enkidevs/curriculum/wiki)**. -Learning happens best in a psychologically safe environment, so we've adopted the [contributor covenant](https://www.contributor-covenant.org/) as our code of conduct. If a list of rules isn't helping you envision what we're after, [here's another great resource](https://www.recurse.com/manual#sec-environment) (from The Recurse Center, read the Social Rules section) for how to participate in creating a community you'd like to be a part of. We _will_ enforce this, please get in touch with stefan.stojanovic@enki.com with questions or concerns. **Everyone** is learning all the time, so disputes will be arbitrated first, and good-faith efforts are what is expected. +Learning happens best in a psychologically safe environment, so we've adopted the [contributor covenant](https://www.contributor-covenant.org/) as our code of conduct. If a list of rules isn't helping you envision what we're after, [here's another great resource](https://www.recurse.com/manual#sec-environment) (from The Recurse Center, read the Social Rules section) for how to participate in creating a community you'd like to be a part of. We _will_ enforce this, please get in touch with content-team@enki.com with questions or concerns. **Everyone** is learning all the time, so disputes will be arbitrated first, and good-faith efforts are what is expected. This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>. In simpler terms, it means you can't charge other people to use it, or use it to make money, but you can definitely use it to help people learn and you're free to remix or adapt what we have, so long as you attribute Enki, and the author of the work. From 69422009105679db91a8152aca7aef1edc4171a4 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 14 Apr 2022 09:25:41 +0200 Subject: [PATCH 184/390] Update the-sum-built-in-function.md Update code block and answers to better match the question that is being asked --- .../arrays-i/the-sum-built-in-function.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/python/functional-programming/arrays-i/the-sum-built-in-function.md b/python/functional-programming/arrays-i/the-sum-built-in-function.md index 2c354e89aa..d64b3837c4 100644 --- a/python/functional-programming/arrays-i/the-sum-built-in-function.md +++ b/python/functional-programming/arrays-i/the-sum-built-in-function.md @@ -70,13 +70,16 @@ Let's imagine we are comparing the bill totals for two customers. Fill in the bl bill1 = [2.5, 3, 16, 18] bill2 = [4.5, 4.5, 18, 18, 3.99] -print(bill1 if ??? > ??? else bill2) +sum1 = ??? +sum2 = ??? + +print(sum1 if ??? > ??? else sum2) ``` - sum(bill1, 8) - sum(bill2, 8) -- sum(bill1) -- sum(bill2) +- sum1 +- sum2 - sum(bill1, bill2) - sum(bill2, bill1) From 1e83c719f7ad397195c160942b4061acbdc5307c Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 14 Apr 2022 09:26:52 +0200 Subject: [PATCH 185/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ecf21f0157..f269ef0c74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## April 14th 2022 + +### Fixed +- [Python - The Sum Built In Function - Fix code block and answers in RQ](https://github.com/enkidevs/curriculum/pull/3071) + ## April 6th 2022 ### Fixed From f9768461867a77e755f1158fe69ec58353d971e8 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 15 Apr 2022 09:51:41 +0200 Subject: [PATCH 186/390] Update tsc-number-string-boolean.md --- .../tsc-using-types/tsc-number-string-boolean.md | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/typescript/typescript-introduction/tsc-using-types/tsc-number-string-boolean.md b/typescript/typescript-introduction/tsc-using-types/tsc-number-string-boolean.md index f67f84c72f..10de7a7898 100644 --- a/typescript/typescript-introduction/tsc-using-types/tsc-number-string-boolean.md +++ b/typescript/typescript-introduction/tsc-using-types/tsc-number-string-boolean.md @@ -4,14 +4,7 @@ type: normal category: must-know links: - >- - [Number - Type](https://www.typescriptlang.org/docs/handbook/basic-types.html#number){documentation} - - >- - [String - Type](https://www.typescriptlang.org/docs/handbook/basic-types.html#string){documentation} - - >- - [Boolean - Type](https://www.typescriptlang.org/docs/handbook/basic-types.html#boolean){documentation} + [Number, Boolean, String Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html){documentation} practiceQuestion: formats: - fill-in-the-gap From ecc09cc95c714feee69dae8d07830cc6714c0a80 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 15 Apr 2022 09:54:11 +0200 Subject: [PATCH 187/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f269ef0c74..d802a8bc1a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## April 15th 2022 + +### Fixed +- [TypeScript - Number, String, Boolean - Replace Deprecated Links With Updated Ones](https://github.com/enkidevs/curriculum/pull/3072) + ## April 14th 2022 ### Fixed From a00c47dd52b240d1f1eab976cd9f0e5d93fc31ff Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 18 Apr 2022 11:00:42 +0200 Subject: [PATCH 188/390] Update product-analytics-tools.md Minor grammar improvements --- .../product-analytics/product-analytics-tools.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/data-analysis/data-analysis-core/product-analytics/product-analytics-tools.md b/data-analysis/data-analysis-core/product-analytics/product-analytics-tools.md index aa85da5cd0..7bee064e21 100644 --- a/data-analysis/data-analysis-core/product-analytics/product-analytics-tools.md +++ b/data-analysis/data-analysis-core/product-analytics/product-analytics-tools.md @@ -17,13 +17,13 @@ category: must-know There are so many great tools out there. Here are a few of our favorites! ### Mixpanel -Mixpanel can collect a lot of data for your CRO[1] experiments. Mixpanel helps you find the ‘hidden gems buried in your data automatically’ like the user segments who are underperforming, anomalies in your data trends and more. +Mixpanel can collect a lot of data for your CRO[1] experiments. Mixpanel helps you find the 'hidden gems buried in your data automatically' like the underperforming user segments, anomalies in your data trends, and more. ### Amplitude Amplitude is very similar to Mixpanel as an essential Product Analytics tool. One key difference is that it automatically clusters similar users into behavioral cohorts — via their Personas. ### KissMetrics -KissMetrics helps you understand the customer behavior of your clients across **different devices** and identify what’s working and what's not. +KissMetrics helps you understand the customer behavior of your clients across **different devices** and identify what's working and what's not. ### Optimizely This is one of the oldest and most powerful CRO tools on the market. It allows marketing departments and software development teams to apply a “culture of optimization” to their offerings. @@ -32,9 +32,9 @@ This is one of the oldest and most powerful CRO tools on the market. It allows m HotJar helps you visualize the visitor behavior on your website with click, move, and scroll heatmaps. ### Google Analytics -Google Analytics is the #1 source for collecting website analytics data. You can either use its free version or if you want more advanced features there's a premium version — Google Analytics 360 — that unlocks deeper insights. +Google Analytics is the #1 source for collecting website analytics data. You can use the free version, or if you want the more advanced features, a premium version — Google Analytics 360 — unlocks deeper insights. -We're dedicating a whole workout to Google Analytics where we'll explore key features next! +We're dedicating a whole workout to Google Analytics, where we'll explore key features next! 👇 Comment below to let us know **your favorite tools** and why. @@ -42,5 +42,5 @@ We're dedicating a whole workout to Google Analytics where we'll explore key fea ## Footnotes [1:CRO] -CRO stands for Conversion Rate Optimization and is an area of marketing that aims to ncrease the percentage of visitors to a website that convert into customers, or more generally, take any desired action on a webpage. +CRO stands for Conversion Rate Optimization and is an area of marketing that aims to increase the percentage of visitors to a website that converts into customers or, more generally, takes any desired action on a webpage. From ee20b913d55b02f984059e5cd9fd023d2b2b4776 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 18 Apr 2022 11:01:55 +0200 Subject: [PATCH 189/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f269ef0c74..0432fdc650 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## April 18th 2022 + +### Fixed +- [Data Analysis - Product Analytics Tools - Minor Grammar Improvements](https://github.com/enkidevs/curriculum/pull/3073) + ## April 14th 2022 ### Fixed From 87272553380abd82508376cd11c8becf527ddcaa Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 18 Apr 2022 11:05:42 +0200 Subject: [PATCH 190/390] Update pandas-functions-i.md --- .../data-analysis-using-python/pandas-functions-i.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/data-analysis/data-tools/data-analysis-using-python/pandas-functions-i.md b/data-analysis/data-tools/data-analysis-using-python/pandas-functions-i.md index 5160e39cfa..c6a459a89f 100644 --- a/data-analysis/data-tools/data-analysis-using-python/pandas-functions-i.md +++ b/data-analysis/data-tools/data-analysis-using-python/pandas-functions-i.md @@ -27,13 +27,13 @@ revisionQuestion: ## Content -Once you've set up your Jupyter workspace and imported some libraries you're nearly ready to explore some data. +Once you've set up your Jupyter workspace and imported some libraries, you're nearly ready to explore some data. First, we need to have access to our data! -There are several ways to do this, depending on where your data is stored. We're going to show you how to access **csv data** using `pandas`. +There are several ways to do this, depending on where your data is stored. First, we will show you how to access **CSV data** using `pandas`. -Imagine we have a csv file on our laptop filled with data on all of our products. +Imagine we have a **CSV** file on our laptop filled with data on all of our products. You can create a DataFrame[1] variable, *"products_data"*, using the `read_csv` function. @@ -43,7 +43,7 @@ products_data = pd.read_csv(<INSERT_PATH_TO_CSV>) > 💡 Remember that **pd** is our pandas alias. So we're calling the `read_csv` function on the pandas library. The CSV path could be a local file directory or a URL. -Now we have some data we're ready to go. +Now we have some data, we're ready to go. The `head()` function gives us *the top n rows of our data*. Running this code returns a table of the first 10 rows: @@ -57,7 +57,7 @@ The `unique()` function returns the unique values of any column we choose to use products_data['category'].unique() ``` -The `shape` fucntion returns the number of rows and columns as a tuple (number of rows, number of columns). +The `shape` function returns the number of rows and columns as a tuple (number of rows, number of columns). ```py products_data.shape @@ -65,7 +65,7 @@ products_data.shape # (891, 12) ``` -Check out the **Learn More** link to discover some other useful functions like `tail()`, `columns`, `dtypes` and others! +Check out the **Learn More** link to discover other useful functions like `tail()`, `columns`, `dtypes` and others! --- From 1627908e6204a1a708db7708794bc2a18d4f1c05 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 18 Apr 2022 11:07:07 +0200 Subject: [PATCH 191/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f269ef0c74..d8e20ac115 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## April 18th 2022 + +### Fixed +- [Data Analysis - Pandas Functions I - Minor Grammar Improvements](https://github.com/enkidevs/curriculum/pull/3074) + ## April 14th 2022 ### Fixed From a1b8790d63279d59f83407f332767f43c93fa368 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 21 Apr 2022 12:41:50 +0200 Subject: [PATCH 192/390] Update header.md add <> to the question and remove it from all answers as it has no benefit having to explicitly write <> when asked about the elements name --- web/html/sectioning-elements/header.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/web/html/sectioning-elements/header.md b/web/html/sectioning-elements/header.md index 805f10b0db..a746358c7b 100755 --- a/web/html/sectioning-elements/header.md +++ b/web/html/sectioning-elements/header.md @@ -88,15 +88,15 @@ The `<header>` element is encouraged to do which of the following? Which container is best to organize the top of a web page or content section? ```html -??? +<???> ``` -- `<header>` -- `<head>` -- `<top>` -- `<section>` -- `<main>` -- `<nav>` +- `header` +- `head` +- `top` +- `section` +- `main` +- `nav` --- From 96323b8f42b8fec95872e241e1b43a41db27e3f6 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 21 Apr 2022 12:42:37 +0200 Subject: [PATCH 193/390] Update footer.md --- web/html/sectioning-elements/footer.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/web/html/sectioning-elements/footer.md b/web/html/sectioning-elements/footer.md index e8d7536a4e..8621ee1ca4 100755 --- a/web/html/sectioning-elements/footer.md +++ b/web/html/sectioning-elements/footer.md @@ -73,15 +73,15 @@ The `<footer>` element is encouraged to contain which of the following? Which container is best to organize the bottom of a web page or content section? ```html -??? +<???> ``` -- `<footer>` -- `<foot>` -- `<bottom>` -- `<section>` -- `<main>` -- `<nav>` +- `footer` +- `foot` +- `bottom` +- `section` +- `main` +- `nav` --- From 00177148aaa246dfe422243b174a9e4485f63d69 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 21 Apr 2022 12:43:04 +0200 Subject: [PATCH 194/390] Update main.md --- web/html/sectioning-elements/main.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/web/html/sectioning-elements/main.md b/web/html/sectioning-elements/main.md index 53dc3d9297..21d5b6c40d 100755 --- a/web/html/sectioning-elements/main.md +++ b/web/html/sectioning-elements/main.md @@ -115,15 +115,15 @@ As you can see in the example above, we have added `<article>` within our `<main Which HTML container element should only be used once within a page layout? ```html -??? +<???> ``` -- `<main>` -- `<nav>` -- `<head>` -- `<footer>` -- `<one>` -- `<solo>` +- `main` +- `nav` +- `head` +- `footer` +- `one` +- `solo` --- From 0228f0e6692a6f02c44c8819a3e3a22839cc91c9 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 21 Apr 2022 12:44:42 +0200 Subject: [PATCH 195/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d802a8bc1a..144fa0534e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## April 21st 2022 + +### Changed +- [HTML - Sectioning Elements - Move less than and greater than symbols to code block and remove from answers](https://github.com/enkidevs/curriculum/pull/3075) + ## April 15th 2022 ### Fixed From d78ad384b58e94cc0d838ad2880f7c53729c3656 Mon Sep 17 00:00:00 2001 From: Ovid <66392475+jixiangox@users.noreply.github.com> Date: Mon, 25 Apr 2022 09:40:07 +0800 Subject: [PATCH 196/390] Update react-what-is-jsx.md Parameters to sync or async --- react/react-introduction/intro-react/react-what-is-jsx.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react/react-introduction/intro-react/react-what-is-jsx.md b/react/react-introduction/intro-react/react-what-is-jsx.md index 5b43a2c712..d0a0815acc 100644 --- a/react/react-introduction/intro-react/react-what-is-jsx.md +++ b/react/react-introduction/intro-react/react-what-is-jsx.md @@ -68,7 +68,7 @@ You can use **JSX** expressions anywhere. For example, you can: - `return` them - use them in `for` loops - use them in `if` statements -- accept them as `function` arguments +- accept them as `function` parameters - etc. Although writing `React.createElement` statements is perfectly valid, the main reason developers prefer to use JSX is the familiarity of HTML-like syntax. From 7f838b44a423089ac50fde4c884f246eb190fd04 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 25 Apr 2022 13:58:20 +0200 Subject: [PATCH 197/390] Update securing-the-presentation-layer.md Move link to Learn More section --- .../securing-the-presentation-layer.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/security/appsec/securing-each-layer-ii/securing-the-presentation-layer.md b/security/appsec/securing-each-layer-ii/securing-the-presentation-layer.md index a64bcde505..073a27dfeb 100644 --- a/security/appsec/securing-each-layer-ii/securing-the-presentation-layer.md +++ b/security/appsec/securing-each-layer-ii/securing-the-presentation-layer.md @@ -6,6 +6,9 @@ links: - >- [SANS Institute](https://www.sans.org/reading-room/whitepapers/protocols/applying-osi-layer-network-model-information-security-1309){website} + - >- + [OWASP + Buffer Overflow](www.owasp.org/index.php/Buffer_Overflow){website} practiceQuestion: formats: - fill-in-the-gap @@ -29,11 +32,7 @@ One such vulnerability is the **buffer overflow**. In short, this condition occurs when a program attempts to write to a memory address outside of its restricted bounds, tampering with the memory of other programs. This can result in crashing, corruption of memory, and execution of malicious code. -For more in-depth information on this vulnerability, check out the *OWASP Page*: - -```plain-text -www.owasp.org/index.php/Buffer_Overflow -``` +For more in-depth information on this vulnerability, check out the *OWASP Buffer Overflow* link in the **Learn More** section. The possibility of this happening can be mitigated with untrusting code practices. When making network calls, be sure to extensively validate the contents of the response before parsing it. From 0420f17baf26931e0711075a8343c48c4c9b12f1 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 25 Apr 2022 13:59:49 +0200 Subject: [PATCH 198/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 872a017f4a..d635beb988 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## April 25th 2022 + +### Changed +- [Security - Securing The Presentation Layer - Move link to Learn More section](https://github.com/enkidevs/curriculum/pull/3077) + ## April 21st 2022 ### Changed From 51040501eb67f285e7bc42558443179f1ae78ba6 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 25 Apr 2022 15:34:42 +0200 Subject: [PATCH 199/390] remove extra space --- react/react-introduction/intro-react/react-what-is-jsx.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react/react-introduction/intro-react/react-what-is-jsx.md b/react/react-introduction/intro-react/react-what-is-jsx.md index d0a0815acc..99a8a65b7d 100644 --- a/react/react-introduction/intro-react/react-what-is-jsx.md +++ b/react/react-introduction/intro-react/react-what-is-jsx.md @@ -68,7 +68,7 @@ You can use **JSX** expressions anywhere. For example, you can: - `return` them - use them in `for` loops - use them in `if` statements -- accept them as `function` parameters +- accept them as `function` parameters - etc. Although writing `React.createElement` statements is perfectly valid, the main reason developers prefer to use JSX is the familiarity of HTML-like syntax. From 56d690ff2deb313c76ebb70579a696eee672779d Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 26 Apr 2022 19:31:10 +0200 Subject: [PATCH 200/390] Update page-breaks-for-printing.md --- web/styling/practical-css/page-breaks-for-printing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/styling/practical-css/page-breaks-for-printing.md b/web/styling/practical-css/page-breaks-for-printing.md index d5c8762ba9..2ce86b3d49 100644 --- a/web/styling/practical-css/page-breaks-for-printing.md +++ b/web/styling/practical-css/page-breaks-for-printing.md @@ -20,7 +20,7 @@ revisionQuestion: ## Content -**CSS** provide with a set of properties in order to define how a document is printed: +**CSS** provides us with a set of properties in order to define how a document is printed: - `page-break-before` : will break the page before the element on which is applied - `page-break-after` : will break the page after the element on which is applied From aa221d61279ea0709d5df27f80742251f14e09e0 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 26 Apr 2022 19:33:04 +0200 Subject: [PATCH 201/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 872a017f4a..3ff39ba4d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## April 26th 2022 + +### Fixed +- [Styling - Page Break for Printing - Minor grammar improvement](https://github.com/enkidevs/curriculum/pull/3078) + ## April 21st 2022 ### Changed From 46426878d7766ee950103335d030d9592a2c0bc2 Mon Sep 17 00:00:00 2001 From: Ovid <66392475+jixiangox@users.noreply.github.com> Date: Wed, 27 Apr 2022 15:58:14 +0800 Subject: [PATCH 202/390] Update react-why-use-react.md Meta instead of --- react/react-introduction/intro-react/react-why-use-react.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react/react-introduction/intro-react/react-why-use-react.md b/react/react-introduction/intro-react/react-why-use-react.md index 587bc8f963..3ccd40d248 100644 --- a/react/react-introduction/intro-react/react-why-use-react.md +++ b/react/react-introduction/intro-react/react-why-use-react.md @@ -28,7 +28,7 @@ In addition to the previously stated reasons why developers are eager to adopt t - easier debugging with **out-of-the-box tools** such as the `React Developer Tools` extension for Chrome or Firefox - knowing **React** allows you to easily switch to **React Native** to build native mobile applications -**React Native** is a different JS open-source library released by *Facebook* that follows the same design patterns as **React**. It's used to create applications for specific operating systems such as `Android`, `iOS` or `UWP`[4], but it lets you share a large percentage of code between them. +**React Native** is a different JS open-source library released by *Meta* that follows the same design patterns as **React**. It's used to create applications for specific operating systems such as `Android`, `iOS` or `UWP`[4], but it lets you share a large percentage of code between them. --- From e3464b36b6dff2b286a22db56f11faa3153aef7e Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 2 May 2022 09:04:23 +0200 Subject: [PATCH 203/390] Update dictionary-methods-i.md add the missing `print()` in the fourth code block --- python/python-core/unordered-data-types/dictionary-methods-i.md | 1 + 1 file changed, 1 insertion(+) diff --git a/python/python-core/unordered-data-types/dictionary-methods-i.md b/python/python-core/unordered-data-types/dictionary-methods-i.md index b84dae25db..ff0b3711bd 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-i.md +++ b/python/python-core/unordered-data-types/dictionary-methods-i.md @@ -61,6 +61,7 @@ print(new) ```python square_numbers.items() +print(square_numbers.items()) # dict_items([(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]) ``` From 6ed4297711e9becc4a57934789725d505675f50c Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 2 May 2022 09:05:33 +0200 Subject: [PATCH 204/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa1e697406..0b5e4eb09e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## May 2nd 2022 + +### Fixed +- [Python - Dictionary Methods I - Add missing print to 4th code block](https://github.com/enkidevs/curriculum/pull/3081) + ## April 26th 2022 ### Fixed From c6b30bf0eb7451d4d0ad8d9116e76977336d4bc3 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Sun, 15 May 2022 20:56:27 +0200 Subject: [PATCH 205/390] Update the-abstract-keyword.md make the answer match the method name --- .../abstract-keyword/the-abstract-keyword.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/java/java-fundamentals/abstract-keyword/the-abstract-keyword.md b/java/java-fundamentals/abstract-keyword/the-abstract-keyword.md index 2c4373e290..667f827d50 100644 --- a/java/java-fundamentals/abstract-keyword/the-abstract-keyword.md +++ b/java/java-fundamentals/abstract-keyword/the-abstract-keyword.md @@ -66,9 +66,9 @@ abstract String optionZ(String s); ??? -- Option Z -- Option X -- Option Y +- `optionZ` +- `optionX` +- `optionY` --- @@ -87,6 +87,6 @@ abstract float optionC(float e) { ??? -- Option A -- Option B -- Option C +- optionA +- optionB +- optionC From 6feeec84205a911fae24d3c58bf330cec0061203 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Sun, 15 May 2022 21:16:42 +0200 Subject: [PATCH 206/390] Update CHANGELOG.md --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa1e697406..5169895dfe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,12 @@ Types of change: ### Fixed + +## May 15th 2022 + +### Changed +- [Java - Abstract Keyword - Make answers match method names](https://github.com/enkidevs/curriculum/pull/3082) + ## April 26th 2022 ### Fixed From 40395a1f7019ec58056d9c0404f993b1062e275f Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 16 May 2022 09:55:17 +0200 Subject: [PATCH 207/390] Update marketing-metrics.md --- .../marketing-analytics/marketing-metrics.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/data-analysis/data-analysis-core/marketing-analytics/marketing-metrics.md b/data-analysis/data-analysis-core/marketing-analytics/marketing-metrics.md index d77ddf43f3..1d9a7f143d 100644 --- a/data-analysis/data-analysis-core/marketing-analytics/marketing-metrics.md +++ b/data-analysis/data-analysis-core/marketing-analytics/marketing-metrics.md @@ -58,7 +58,7 @@ Other key marketing metrics to track are: Customer Aquisition Cost can be measured using the following formula: ```plain-text -??? + Time Spent / ??? +(??? + Time Spent) / ??? ``` - Money @@ -74,7 +74,7 @@ Customer Aquisition Cost can be measured using the following formula: Customer Aquisition Cost can be measured using the following formula: ```plain-text -??? + ??? / ??? +(??? + ???) / ??? ``` - Money From 4665e4f9cb22ed94bf5b70305c2dd4aef3a0bbc4 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 16 May 2022 10:04:09 +0200 Subject: [PATCH 208/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa1e697406..9c1fb6f1b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## May 16th + +### Fixed +- [Data Analysis - Marketing Metricts - Add missing parenthesis to the equations in PQ and RQ](https://github.com/enkidevs/curriculum/pull/3083) + ## April 26th 2022 ### Fixed From a11a150aa0b1a8cf6f8503210bcad9c136a2382c Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 16 May 2022 10:09:25 +0200 Subject: [PATCH 209/390] Update blocks-iii.md Update new domain for demo blockchain --- blockchain/blockchain-fundamentals/the-blockchain/blocks-iii.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/blockchain/blockchain-fundamentals/the-blockchain/blocks-iii.md b/blockchain/blockchain-fundamentals/the-blockchain/blocks-iii.md index 598c5d3cbf..b0ca1beffa 100644 --- a/blockchain/blockchain-fundamentals/the-blockchain/blocks-iii.md +++ b/blockchain/blockchain-fundamentals/the-blockchain/blocks-iii.md @@ -5,7 +5,7 @@ category: must-know links: - >- [Interactive tutorial of how blocks are - built](https://anders.com/blockchain/){website} + built](https://andersbrownworth.com/blockchain){website} practiceQuestion: formats: - fill-in-the-gap From 5cd051ebaf6c545459e1680e81756fb82187f586 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 16 May 2022 10:10:21 +0200 Subject: [PATCH 210/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa1e697406..14f3f44ee6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## May 16th 2022 + +### Fixed +- [Blockchain - Blocks III - Update new domain on demo link](https://github.com/enkidevs/curriculum/pull/3084) + ## April 26th 2022 ### Fixed From 4d1e0439576a09d70d52fe9ae1843e0f0b967a5f Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 16 May 2022 16:55:01 +0200 Subject: [PATCH 211/390] Update the-abstract-keyword.md --- .../abstract-keyword/the-abstract-keyword.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java/java-fundamentals/abstract-keyword/the-abstract-keyword.md b/java/java-fundamentals/abstract-keyword/the-abstract-keyword.md index 667f827d50..c95e6c7cac 100644 --- a/java/java-fundamentals/abstract-keyword/the-abstract-keyword.md +++ b/java/java-fundamentals/abstract-keyword/the-abstract-keyword.md @@ -87,6 +87,6 @@ abstract float optionC(float e) { ??? -- optionA -- optionB -- optionC +- `optionA` +- `optionB` +- `optionC` From 93464d95e107d6eb13710b9b89a369671adfe61e Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 18 May 2022 10:46:49 +0200 Subject: [PATCH 212/390] Update react-what-is-state.md minor grammar fix 'possibility' misspelled --- .../react-fundamentals-ii/react-what-is-state.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react/react-introduction/react-fundamentals-ii/react-what-is-state.md b/react/react-introduction/react-fundamentals-ii/react-what-is-state.md index 06dee1ae66..2391892a38 100644 --- a/react/react-introduction/react-fundamentals-ii/react-what-is-state.md +++ b/react/react-introduction/react-fundamentals-ii/react-what-is-state.md @@ -78,7 +78,7 @@ The snippet above will update the `state` one second after construction. Specifi `render`ing our component now, we'll first see `"Hello"` which will change to `"World"` after one second. -Note that we are setting the `state` here inside a `setTimeout` call. This might not be recommended (depending on your application) due to the posibility of creating memory leaks[3]. +Note that we are setting the `state` here inside a `setTimeout` call. This might not be recommended (depending on your application) due to the possibility of creating memory leaks[3]. --- From 974ef3eb39b99352ebb3c30c7a8e9f1a9fe023ae Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 18 May 2022 10:48:29 +0200 Subject: [PATCH 213/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 14f3f44ee6..59931d6718 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## May 18th 2022 + +### Fixed +- [React - React What Is State - Minor grammar improvement](https://github.com/enkidevs/curriculum/pull/3085) + ## May 16th 2022 ### Fixed From 7d81330c668e6a9a4a458a703d9e9527da88d452 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 18 May 2022 10:55:05 +0200 Subject: [PATCH 214/390] Update the-heap-data-structure.md --- .../heap-and-trie/the-heap-data-structure.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/comp-sci/data-structures-and-algorithms/heap-and-trie/the-heap-data-structure.md b/comp-sci/data-structures-and-algorithms/heap-and-trie/the-heap-data-structure.md index faf49c7bf5..8fae7e1bf9 100644 --- a/comp-sci/data-structures-and-algorithms/heap-and-trie/the-heap-data-structure.md +++ b/comp-sci/data-structures-and-algorithms/heap-and-trie/the-heap-data-structure.md @@ -26,7 +26,7 @@ revisionQuestion: ## Content -A *heap* is tree-based data structure designed to support a constant-time `find-max` (or `find-min`) operation in addition to efficient insertion of new elements and efficient removal of the maximum (or minimum) element. They are frequently used to implement priority queues, where the elements are ordered by priority (or some other factor) rather then their insertion order. +A *heap* is a tree-based data structure designed to support a constant-time `find-max` (or `find-min`) operation and the efficient insertion of new elements and efficient removal of the maximum (or minimum) element. In addition, they are frequently used to implement priority queues, where the elements are ordered by priority (or some other factor) rather than their insertion order. A heap that supports the `find-max` operation is called a *max heap* while a heap that supports a `find-min` operation is called a *min heap*. The values in a heap are often called *keys* and must satisfy what is known as the *heap property*: for a max heap, the keys of parent nodes are always greater than or equal to those of the children and the highest key is in the root node. For a min heap, replace "greater than" with "less than" and "highest key" with "lowest key". From 01968baf82a3eb4256b1668b9d4e5287d3fd322e Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 18 May 2022 10:56:04 +0200 Subject: [PATCH 215/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 14f3f44ee6..dc5b6811db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## May 18th 2022 + +### Fixed +- [Computer Science - Heap Data Structure - Minor grammar improvement](https://github.com/enkidevs/curriculum/pull/3086) + ## May 16th 2022 ### Fixed From e1770ecd24ac72a1dac1e92d30c119f1679b9830 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 25 May 2022 10:54:32 +0200 Subject: [PATCH 216/390] Update what-is-stored-in-a-commit.md --- git/essentials/commits/what-is-stored-in-a-commit.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/git/essentials/commits/what-is-stored-in-a-commit.md b/git/essentials/commits/what-is-stored-in-a-commit.md index 591118c196..fde28e31d3 100644 --- a/git/essentials/commits/what-is-stored-in-a-commit.md +++ b/git/essentials/commits/what-is-stored-in-a-commit.md @@ -41,12 +41,10 @@ The commit object contains a checksum[1], the author's name and email, the commi ## Revision -The usual commit object contains a hash-code, author’s name and email, date and ??? . - -- description -- SHA-1 -- checksum +The usual commit object contains a checksum, author’s name and email, date and a ??? . +- commit message +- hash code --- From 4f6b7e232a669bdb7f66015945a45350edb92a8b Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 25 May 2022 22:10:19 +0200 Subject: [PATCH 217/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e5e6c01ef7..43fb94e907 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,11 @@ Types of change: ## May 18th 2022 +### Changed +- [Git - What Is Stored In A Checksum - Update question](https://github.com/enkidevs/curriculum/pull/3088) + +## May 18th 2022 + ### Fixed - [React - React What Is State - Minor grammar improvement](https://github.com/enkidevs/curriculum/pull/3085) From b93903ab82038b21f0400c29c137139e8f80af7a Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 7 Jun 2022 13:04:58 +0200 Subject: [PATCH 218/390] Update yield.md add `;` to answers in RQ as adding `;` before now would make the answer incorrect, even though semi-colons would make the question correct --- javascript/ecmascript-2015/generators-proxy/yield.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/javascript/ecmascript-2015/generators-proxy/yield.md b/javascript/ecmascript-2015/generators-proxy/yield.md index 682ec59600..78a1927c22 100644 --- a/javascript/ecmascript-2015/generators-proxy/yield.md +++ b/javascript/ecmascript-2015/generators-proxy/yield.md @@ -107,8 +107,8 @@ Fill in the missing gaps such that the `next()` calls' output stand true: } function* gen2() { - ??? - ??? + ???; + ???; } let x = gen1(); From 92b638f1112c54a7f5bbd993a77bd88881581e65 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 7 Jun 2022 13:07:43 +0200 Subject: [PATCH 219/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a183a117de..0c521df16b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## June 7th 2022 + +### Fixed +- [JavaScript - Yield - Add missing semicolons in RQ](https://github.com/enkidevs/curriculum/pull/3089) + ## May 18th 2022 ### Fixed From d5f9926483234a5fec7647ed92f257f1248c3150 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 7 Jun 2022 22:06:30 +0200 Subject: [PATCH 220/390] Update CHANGELOG.md --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a183a117de..50bba47d44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,10 @@ Types of change: ### Fixed +### Changed + +- [Curriculum - README - Update emails](https://github.com/enkidevs/curriculum/pull/3069) + ## May 18th 2022 ### Fixed From 37aefe1edf74dd131057ca104e88d98b1cdbfb69 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 16 Jun 2022 12:11:57 +0200 Subject: [PATCH 221/390] Update cherry-pick-a-commit.md Replace broken link with a working one --- git/essentials/commits/cherry-pick-a-commit.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/git/essentials/commits/cherry-pick-a-commit.md b/git/essentials/commits/cherry-pick-a-commit.md index d3fe924d61..c2ed6f861e 100644 --- a/git/essentials/commits/cherry-pick-a-commit.md +++ b/git/essentials/commits/cherry-pick-a-commit.md @@ -4,8 +4,8 @@ type: normal category: feature links: - >- - [Cherry Picking Small Git - Lesson](https://swsblog.stanford.edu/blog/cherry-picking-small-git-lesson){website} + [Cherry Picking Git + Documentation](https://git-scm.com/docs/git-cherry-pick){website} practiceQuestion: formats: - fill-in-the-gap From d246c1b928eb2174bbd66d12a2fecddb69c58aa2 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 16 Jun 2022 12:13:16 +0200 Subject: [PATCH 222/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50bba47d44..9e4c2a9ae6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## June 16th 2022 + +### Fixed +- [Git - Cherry Pick A Commit - Replace broken link with a working one](https://github.com/enkidevs/curriculum/pull/3092) + ### Changed - [Curriculum - README - Update emails](https://github.com/enkidevs/curriculum/pull/3069) From d4cb92cad75affa63c25fa3075e2d7d0558a0492 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 30 Jun 2022 15:07:05 +0200 Subject: [PATCH 223/390] Update why-functional-programming-ii.md Withtout -> Without --- .../functional-programming/why-functional-programming-ii.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/functional-programming/functional-programming/why-functional-programming-ii.md b/python/functional-programming/functional-programming/why-functional-programming-ii.md index c5075f71a8..43fdaa8198 100644 --- a/python/functional-programming/functional-programming/why-functional-programming-ii.md +++ b/python/functional-programming/functional-programming/why-functional-programming-ii.md @@ -44,5 +44,5 @@ A shared state is ??? ## Footnotes [1:Designing away Bugs] -For example, a shopping website might have a "basket" object which is passed as a parameter to various scopes. The objects within that basket and the data about which user the basket belongs to would be mutated by various sections of code in these different scopes. If there was some temporal dependency between functions being called on the basket, altering or removing one function may accidentally (and not obviously) ripple out and break other functionality. Withtout shared state, you can ensure an entire class of bugs cannot manifest in our program. +For example, a shopping website might have a "basket" object which is passed as a parameter to various scopes. The objects within that basket and the data about which user the basket belongs to would be mutated by various sections of code in these different scopes. If there was some temporal dependency between functions being called on the basket, altering or removing one function may accidentally (and not obviously) ripple out and break other functionality. Without shared state, you can ensure an entire class of bugs cannot manifest in our program. From 872cdf810b59cfac5338a12a3ce4087f4cd074ce Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 30 Jun 2022 15:08:09 +0200 Subject: [PATCH 224/390] Update CHANGELOG.md --- CHANGELOG.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50bba47d44..1e9a70dfa9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,8 +48,13 @@ Types of change: ### Fixed -### Changed +## June 30th 2022 + +### Fixed +- [Python - Why Functional Programming - Fix typo in footnote](https://github.com/enkidevs/curriculum/pull/3093) + +### Changed - [Curriculum - README - Update emails](https://github.com/enkidevs/curriculum/pull/3069) ## May 18th 2022 From f6bd7e5fd205b6da4a671012c5b5be0c9ea15fe2 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 30 Jun 2022 15:10:00 +0200 Subject: [PATCH 225/390] Update why-functional-programming-iii.md --- .../functional-programming/why-functional-programming-iii.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/functional-programming/functional-programming/why-functional-programming-iii.md b/python/functional-programming/functional-programming/why-functional-programming-iii.md index b9fe87d1e0..3efa18a9f4 100644 --- a/python/functional-programming/functional-programming/why-functional-programming-iii.md +++ b/python/functional-programming/functional-programming/why-functional-programming-iii.md @@ -24,7 +24,7 @@ practiceQuestion: As you might remember from the insights on *immutability*, there are a number of advantages to using immutable data instead of mutable state objects. -To recap: an **immutable** object is an object which cannot be modified after its creation. In order to make changes to state using immutable obejcts, a new copy of the state object needs to be created, with the desired modifications added at the time of the creation of the copy. +To recap: an **immutable** object is an object which cannot be modified after its creation. In order to make changes to state using immutable objects, a new copy of the state object needs to be created, with the desired modifications added at the time of the creation of the copy. Why is immutability so useful? Using immutable objects to keep track of your program's state means that there is a fully-traceable, completely accurate state history, which is not easily possible using traditional imperative programming. From f207ed4e9bb88cc22e78531766f05380a547e65a Mon Sep 17 00:00:00 2001 From: Abraham Sanchez <abrahamsanchez89@gmail.com> Date: Mon, 4 Jul 2022 15:22:18 -0600 Subject: [PATCH 226/390] Fix: Typo, -m was missing --- git/essentials/commits/how-to-write-a-git-commit-message.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git/essentials/commits/how-to-write-a-git-commit-message.md b/git/essentials/commits/how-to-write-a-git-commit-message.md index 2b8e85a66b..6d348d0825 100644 --- a/git/essentials/commits/how-to-write-a-git-commit-message.md +++ b/git/essentials/commits/how-to-write-a-git-commit-message.md @@ -39,7 +39,7 @@ git commit -m "Fix typo in README" For a longer commit, you should leave a line after the subject and include more description in the body of the commit: ```bash -git commit +git commit -m # commit message editor Redirect user to the login form From 2a8543f40889ec34edc88c0593006210c6b9c053 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 13 Jul 2022 11:00:21 +0200 Subject: [PATCH 227/390] Update key-metrics.md --- .../data-analysis-core/data-analysis-buzzwords/key-metrics.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data-analysis/data-analysis-core/data-analysis-buzzwords/key-metrics.md b/data-analysis/data-analysis-core/data-analysis-buzzwords/key-metrics.md index e22ec3571b..5fd7ffa87e 100644 --- a/data-analysis/data-analysis-core/data-analysis-buzzwords/key-metrics.md +++ b/data-analysis/data-analysis-core/data-analysis-buzzwords/key-metrics.md @@ -43,7 +43,7 @@ If a company's goal is to *make more money*, it might want to focus on **sales g If a company's goal is to *drive engagement*, it might want to focus on things like **daily active users/monthly active users (DAU/MAU)**, **pageviews** and **average session duration**. -If a company's goal is *customer satisafaction*, it might want to focus on **NPS (Net Promoter Score)**[1] or **customer retention rate**. +If a company's goal is *customer satisfaction*, it might want to focus on **NPS (Net Promoter Score)**[1] or **customer retention rate**. If a company wants to attract new customers by *creating a great brand*, it might focus on **brand equity** and **brand awareness**. From 32d3d0369db2581630814fc349e30a89e562d42b Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 13 Jul 2022 21:35:48 +0200 Subject: [PATCH 228/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2316da16f7..23272e8b6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## July 13th 2022 + +### Fixed +- [Data Analysis - Key Metrics - Minor grammar improvement](https://github.com/enkidevs/curriculum/pull/3095) + ## June 16th 2022 ### Fixed From 46aeb40ffef91984bee1acc61fee0682f726b51b Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 29 Jul 2022 14:36:14 +0200 Subject: [PATCH 229/390] Replace deprecated links with new ones --- .../tsc-using-types/tsc-any-void-null-undefined.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/typescript/typescript-introduction/tsc-using-types/tsc-any-void-null-undefined.md b/typescript/typescript-introduction/tsc-using-types/tsc-any-void-null-undefined.md index 12e68c7836..711ae0e7a5 100644 --- a/typescript/typescript-introduction/tsc-using-types/tsc-any-void-null-undefined.md +++ b/typescript/typescript-introduction/tsc-using-types/tsc-any-void-null-undefined.md @@ -5,13 +5,13 @@ category: must-know links: - >- [Any - Type](https://www.typescriptlang.org/docs/handbook/basic-types.html#any){documentation} + Type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any){documentation} - >- [Void - Type](https://www.typescriptlang.org/docs/handbook/basic-types.html#void){documentation} + Type](https://www.typescriptlang.org/docs/handbook/2/functions.html#void){documentation} - >- [Null & - Undefined](https://www.typescriptlang.org/docs/handbook/basic-types.html#null-and-undefined){documentation} + Undefined](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined){documentation} practiceQuestion: formats: - fill-in-the-gap From a87aed290158650f8c84bc5b5b916bd3f3c91ffa Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 29 Jul 2022 14:37:08 +0200 Subject: [PATCH 230/390] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e6a53075e8..32d642bdb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,8 @@ Types of change: ### Fixed +[TypeScript - TSC Any Void Null Undefined - Replace deprecated links](https://github.com/enkidevs/curriculum/pull/3096) + ## July 13th 2022 ### Fixed From 7f96559c2e250f91cf7c77f7b2b87cd5b164f787 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 1 Aug 2022 15:03:28 +0200 Subject: [PATCH 231/390] Update insight headline --- .../delete-query-documents/delete-documents-3.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mongodb/mongodb-introduction/delete-query-documents/delete-documents-3.md b/mongodb/mongodb-introduction/delete-query-documents/delete-documents-3.md index c3f048998c..a71299d083 100644 --- a/mongodb/mongodb-introduction/delete-query-documents/delete-documents-3.md +++ b/mongodb/mongodb-introduction/delete-query-documents/delete-documents-3.md @@ -9,7 +9,7 @@ practiceQuestion: context: standalone --- -# findOneAndUpdate() +# findOneAndDelete() --- @@ -61,4 +61,4 @@ db.pokemon.???({ - `findOneAndUpdate` - `$is` - `$set` - \ No newline at end of file + From 3eb67011f01780740e03b69ecd79f24a52bbdb3f Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 1 Aug 2022 15:04:12 +0200 Subject: [PATCH 232/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 28269442f7..11857fe35d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## August 1st 2022 + +### Fixed +- [MongoDB - Find One And Delete - Fix wrong headline](https://github.com/enkidevs/curriculum/pull/3098) + ## July 20th 2022 ### Changed From 604a5db70236f6e93a2c6efe0a370d4065c2d581 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 8 Aug 2022 15:20:07 +0200 Subject: [PATCH 233/390] Update threads-and-gil.md --- python/python-core/python-threading/threads-and-gil.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/python-threading/threads-and-gil.md b/python/python-core/python-threading/threads-and-gil.md index 50eeed6925..b18d40fdde 100644 --- a/python/python-core/python-threading/threads-and-gil.md +++ b/python/python-core/python-threading/threads-and-gil.md @@ -6,7 +6,7 @@ tags: type: normal -category: coding +category: must-know links: - >- From 0476fa50b6f55a487071ec53b01e7c133ce34210 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 8 Aug 2022 15:20:20 +0200 Subject: [PATCH 234/390] Update creating-threads.md --- python/python-core/python-threading/creating-threads.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/python-threading/creating-threads.md b/python/python-core/python-threading/creating-threads.md index 420ebbdf51..b048feaf27 100644 --- a/python/python-core/python-threading/creating-threads.md +++ b/python/python-core/python-threading/creating-threads.md @@ -6,7 +6,7 @@ tags: type: normal -category: coding +category: must-know revisionQuestion: formats: From b4c7c8f5485cbea7d356fd759bf01711219c4211 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 8 Aug 2022 15:20:46 +0200 Subject: [PATCH 235/390] Update README.md --- python/python-core/python-threading/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/python/python-core/python-threading/README.md b/python/python-core/python-threading/README.md index da53e40a40..eeaeafa8c7 100644 --- a/python/python-core/python-threading/README.md +++ b/python/python-core/python-threading/README.md @@ -10,6 +10,5 @@ insights: - threading-with-join-2 aspects: - - new - obscura - workout From 649581d3150ac1858c344b27e93eda481137d1f3 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 9 Aug 2022 14:14:14 +0200 Subject: [PATCH 236/390] Update tvshow-ratings.md remove empty answer as it breaks the app --- .../python-data-analysis-core/analyzing-ii/tvshow-ratings.md | 1 - 1 file changed, 1 deletion(-) diff --git a/python-data-analysis/python-data-analysis-core/analyzing-ii/tvshow-ratings.md b/python-data-analysis/python-data-analysis-core/analyzing-ii/tvshow-ratings.md index d8af9743d2..8998aac633 100644 --- a/python-data-analysis/python-data-analysis-core/analyzing-ii/tvshow-ratings.md +++ b/python-data-analysis/python-data-analysis-core/analyzing-ii/tvshow-ratings.md @@ -100,7 +100,6 @@ Group the `people` `DataFrame` by its `Age` column. Count the number of rows for - `Count By Age` - `count by age` - `age` -- --- From 33aecb679ee47ccc890bc63ae6dde7ebdc408f68 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 9 Aug 2022 14:14:59 +0200 Subject: [PATCH 237/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fc23bd2e6c..1fe42ec652 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## August 9th 2022 + +### Fixed +- [Python Data Analysis - TVShow Ratings - Remove empty answer](https://github.com/enkidevs/curriculum/pull/3099) + ## August 1st 2022 ### Fixed From 85a99026361c7d3360bfba7de61ebdc22d23a264 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 30 Aug 2022 11:51:43 +0200 Subject: [PATCH 238/390] replace 404 link with a working one --- python/python-core/classes-i/method-overriding.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index bdd02dd8b1..793e4374c3 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -4,7 +4,7 @@ type: normal category: tip links: - >- - [lgiordani.com](http://lgiordani.com/blog/2014/05/19/method-overriding-in-python/#.Vsx21JyLRhF){website} + [Method Overriding in Python](https://www.geeksforgeeks.org/method-overriding-in-python/){website} notes: > Again, preferably use other names for classes instead of words containing Enki all the time. More realistic names would help. E.g. Animal for the parent From 2270ff32c9dd122c5e80a8e17fab8d2b09187788 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 30 Aug 2022 11:52:34 +0200 Subject: [PATCH 239/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1fe42ec652..4089678c3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## August 30th 2022 + +### Fixed +- [Python - Method Overriding - Replace 404 link](https://github.com/enkidevs/curriculum/pull/3104) + ## August 9th 2022 ### Fixed From a61b45f8d6b25e23eb2a50527e26c7e18973c044 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Sep 2022 16:06:02 +0200 Subject: [PATCH 240/390] Update README.md --- python/python-core/python-threading/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/python-threading/README.md b/python/python-core/python-threading/README.md index eeaeafa8c7..dd33457e84 100644 --- a/python/python-core/python-threading/README.md +++ b/python/python-core/python-threading/README.md @@ -1,4 +1,4 @@ -name: Introduction +name: Threading description: Intro to Threading. From 64ad8a3f55333321750e1b08463d621735272dc3 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Sep 2022 16:07:13 +0200 Subject: [PATCH 241/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3faab13e60..0aabf65668 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## September 16th 2022 + +### Fixed +- [Python - Threading - Fix Workout Name](https://github.com/enkidevs/curriculum/pull/3106) + ## September 15th 2022 ### Added From 9ab291a914514e53dd003ae7b29d6c1fb2859937 Mon Sep 17 00:00:00 2001 From: digiacom <74780997+digiacom@users.noreply.github.com> Date: Sun, 18 Sep 2022 11:16:55 +0200 Subject: [PATCH 242/390] Update custom-commit-template.md Fix filename '.template.txt' --- git/essentials/commits/custom-commit-template.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git/essentials/commits/custom-commit-template.md b/git/essentials/commits/custom-commit-template.md index 82e8ce629e..8605514e86 100644 --- a/git/essentials/commits/custom-commit-template.md +++ b/git/essentials/commits/custom-commit-template.md @@ -27,7 +27,7 @@ revisionQuestion: You can add a commit message template to git, to help you write clear messages. -First, you create a template file `template.txt`: +First, you create a template file `.template.txt`: ```plain-text subject line (50 chars) From 3cc1c8fe5cb26cd3ffe06cfe60b8471a202892a2 Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic <n.stojanovic035@gmail.com> Date: Wed, 28 Sep 2022 10:58:28 +0100 Subject: [PATCH 243/390] Update inner-join.md Explain that `JOIN` and `INNER JOIN` are the same thing --- sql/dql/joins/inner-join.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sql/dql/joins/inner-join.md b/sql/dql/joins/inner-join.md index e67b4f10b9..876879d5dc 100644 --- a/sql/dql/joins/inner-join.md +++ b/sql/dql/joins/inner-join.md @@ -81,6 +81,8 @@ Here's the operation depiction: An *INNER JOIN* is a type of join that only returns rows for which the joined field (`id` for `ability` and `ability_id` for `ability_effect_text`) are common. +> 💡 `JOIN` and `INNER JOIN` are the same in SQL. When you write just `JOIN`, the `INNER` is implied. + If there were some abilities without an effect text or some effects not describing an ability, they wouldn't be included in query result. So, if the `ability` table has `251` records and the `ability_effect_text` has `191` records, the total number of returned rows after the inner join operation will be `191`. This is because there would be no matches for the extra `60` records in the `ability table`. From a4fd6296e183743a65eaec8e6fb5b49d25794164 Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic <n.stojanovic035@gmail.com> Date: Wed, 28 Sep 2022 11:07:28 +0100 Subject: [PATCH 244/390] Update inner-join.md --- sql/dql/joins/inner-join.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sql/dql/joins/inner-join.md b/sql/dql/joins/inner-join.md index 876879d5dc..741cef8bc9 100644 --- a/sql/dql/joins/inner-join.md +++ b/sql/dql/joins/inner-join.md @@ -52,6 +52,8 @@ The short and long ability descriptions can be found inside the `ability_effect_ What if we wanted to write a query that shows the `name` of an ability and its description? This is where `JOIN`s come in. +> 💡 `JOIN` and `INNER JOIN` are the same in SQL. When you write just `JOIN`, the `INNER` is implied. + To match records from both tables you need to find a column that has the same values **for both tables**. In our case, we have the `id` column in the `ability` table and the `ability_id` column in the `ability_effect_text` table. @@ -62,7 +64,7 @@ Knowing that, here is how you do an inner join: SELECT ability.name, ability_effect_text.effect FROM ability -INNER JOIN ability_effect_text ON +JOIN ability_effect_text ON -- you don't need the word INNER before JOIN because it's implied ability.id = ability_effect_text.ability_id; ``` @@ -79,9 +81,7 @@ Here's the operation depiction: ![inner](https://img.enkipro.com/95135d7d0e142beccf7aa4ca6924530d.png) -An *INNER JOIN* is a type of join that only returns rows for which the joined field (`id` for `ability` and `ability_id` for `ability_effect_text`) are common. - -> 💡 `JOIN` and `INNER JOIN` are the same in SQL. When you write just `JOIN`, the `INNER` is implied. +An *INNER JOIN* is a type of join that only returns rows for which the joined fields (`id` for `ability` and `ability_id` for `ability_effect_text`) are shared. If there were some abilities without an effect text or some effects not describing an ability, they wouldn't be included in query result. From e6b5d1a604906c100017c7315d4e01a5eb71cf19 Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic <n.stojanovic035@gmail.com> Date: Wed, 28 Sep 2022 11:12:11 +0100 Subject: [PATCH 245/390] Update inner-join.md --- sql/dql/joins/inner-join.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sql/dql/joins/inner-join.md b/sql/dql/joins/inner-join.md index 741cef8bc9..07cb000109 100644 --- a/sql/dql/joins/inner-join.md +++ b/sql/dql/joins/inner-join.md @@ -81,12 +81,13 @@ Here's the operation depiction: ![inner](https://img.enkipro.com/95135d7d0e142beccf7aa4ca6924530d.png) -An *INNER JOIN* is a type of join that only returns rows for which the joined fields (`id` for `ability` and `ability_id` for `ability_effect_text`) are shared. +An *INNER JOIN* is a type of join that only returns rows for which the joined fields (`id` for `ability` and `ability_id` for `ability_effect_text`) are common. If there were some abilities without an effect text or some effects not describing an ability, they wouldn't be included in query result. So, if the `ability` table has `251` records and the `ability_effect_text` has `191` records, the total number of returned rows after the inner join operation will be `191`. This is because there would be no matches for the extra `60` records in the `ability table`. +> 💡 Inner join lets us combine data from two tables whenever there are matching values in a field common to both tables. --- From de1a49090d2c0d35917acfc340115ab89acb1fbe Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 28 Sep 2022 12:26:26 +0200 Subject: [PATCH 246/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0aabf65668..5d2d0a32c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## September 28th 2022 + +### Fixed +- [SQL - Inner Join - Explain Inner join and Join are the same thing](https://github.com/enkidevs/curriculum/pull/3109) + ## September 16th 2022 ### Fixed From 5cf505cf8fb29bf61e1dc9174587041016f23be3 Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic <n.stojanovic035@gmail.com> Date: Wed, 12 Oct 2022 11:32:48 +0200 Subject: [PATCH 247/390] Update README.md --- .../javascript-playground-questions/js-word-length/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/javascript-playground-questions/js-word-length/README.md b/javascript/javascript-playground-questions/js-word-length/README.md index 66fa468a5a..3a74194507 100644 --- a/javascript/javascript-playground-questions/js-word-length/README.md +++ b/javascript/javascript-playground-questions/js-word-length/README.md @@ -1,4 +1,4 @@ -name: Output Words Longer than N Characters +name: Words Length description: Create a program to only output words longer than N characters from a string. From e13b7964f4e471dfcb54a92fa60b57b76c64872e Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic <n.stojanovic035@gmail.com> Date: Wed, 12 Oct 2022 11:33:55 +0200 Subject: [PATCH 248/390] Update README.md --- .../js-miles-to-kilometres/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/javascript/javascript-playground-questions/js-miles-to-kilometres/README.md b/javascript/javascript-playground-questions/js-miles-to-kilometres/README.md index 2e72e66a1e..75d5b3a0d0 100644 --- a/javascript/javascript-playground-questions/js-miles-to-kilometres/README.md +++ b/javascript/javascript-playground-questions/js-miles-to-kilometres/README.md @@ -1,9 +1,9 @@ -name: Miles To Kilometres +name: Miles to Kilometres -description: Create a program to transform Miles to Kilometres or vice versa. +description: Create a program to transform miles to kilometres or vice versa. aspects: - workout insights: - - js-miles-to-kilometres \ No newline at end of file + - js-miles-to-kilometres From dbbd2bb68d7813bffbe2b24d6352ef37c094a670 Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic <n.stojanovic035@gmail.com> Date: Wed, 12 Oct 2022 11:34:52 +0200 Subject: [PATCH 249/390] Update README.md --- .../python-playground-questions/miles-to-kilometres/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-playground-questions/miles-to-kilometres/README.md b/python/python-playground-questions/miles-to-kilometres/README.md index d6c52f8f1c..6d790d958e 100644 --- a/python/python-playground-questions/miles-to-kilometres/README.md +++ b/python/python-playground-questions/miles-to-kilometres/README.md @@ -1,4 +1,4 @@ -name: Miles To Kilometers +name: Miles to Kilometers description: Create a program to transform miles to kilometers or vice versa. From 77cbcce709755107ed0faee0b34ee6ec97328aaf Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic <n.stojanovic035@gmail.com> Date: Wed, 12 Oct 2022 11:35:12 +0200 Subject: [PATCH 250/390] Update README.md --- python/python-playground-questions/word-length/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/python-playground-questions/word-length/README.md b/python/python-playground-questions/word-length/README.md index fd3bf1fef4..1e42616397 100644 --- a/python/python-playground-questions/word-length/README.md +++ b/python/python-playground-questions/word-length/README.md @@ -1,4 +1,4 @@ -name: Output Words Longer than N Characters +name: Words Length description: Create a program to only output words longer than N characters from a string. @@ -6,4 +6,4 @@ aspects: - workout insights: - - word-length \ No newline at end of file + - word-length From 778f2e7ade0f04fa9b97d0d9954a8731d8e73e09 Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic <n.stojanovic035@gmail.com> Date: Wed, 12 Oct 2022 11:36:24 +0200 Subject: [PATCH 251/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d2d0a32c4..d08010573d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,11 @@ Types of change: ## September 28th 2022 +### Changed +- [Playgroud workouts names are more succinct](https://github.com/enkidevs/curriculum/pull/3110) + +## September 28th 2022 + ### Fixed - [SQL - Inner Join - Explain Inner join and Join are the same thing](https://github.com/enkidevs/curriculum/pull/3109) From 07cefcf3297ecda8b681c669441637220cfb1fc8 Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic <n.stojanovic035@gmail.com> Date: Wed, 12 Oct 2022 11:38:32 +0200 Subject: [PATCH 252/390] Update custom-commit-template.md --- git/essentials/commits/custom-commit-template.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/git/essentials/commits/custom-commit-template.md b/git/essentials/commits/custom-commit-template.md index 8605514e86..00c2b5d0f5 100644 --- a/git/essentials/commits/custom-commit-template.md +++ b/git/essentials/commits/custom-commit-template.md @@ -27,7 +27,7 @@ revisionQuestion: You can add a commit message template to git, to help you write clear messages. -First, you create a template file `.template.txt`: +First, you create a template file `template.txt`: ```plain-text subject line (50 chars) @@ -40,7 +40,7 @@ commit body (72 chars) Then you set this template to be the default commit editor message using `commit.template`: ```bash -git config --global commit.template ~/.template.txt +git config --global commit.template path/to/template.txt ``` When you run `git commit` the template will appear in the editor. @@ -53,7 +53,7 @@ When you run `git commit` the template will appear in the editor. You can add a commit message template using: ```bash -git ??? --global ???.??? ~/.template.txt +git ??? --global ???.??? path/to/template.txt ``` - `config` @@ -70,7 +70,7 @@ git ??? --global ???.??? ~/.template.txt You can add a commit message template using: ```bash -git ??? --global ???.??? ~/.template.txt +git ??? --global ???.??? path/to/template.txt ``` - `config` From dc20f9300717ddc64d2cd97fd043ab36c4308187 Mon Sep 17 00:00:00 2001 From: rettal <dan.latter@gmail.com> Date: Fri, 14 Oct 2022 21:34:36 +0100 Subject: [PATCH 253/390] Missing opening brace. --- .../annotations-iii/including-annotations-in-javadoc.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/java-fundamentals/annotations-iii/including-annotations-in-javadoc.md b/java/java-fundamentals/annotations-iii/including-annotations-in-javadoc.md index 0a15354537..8fdeaf1ac8 100644 --- a/java/java-fundamentals/annotations-iii/including-annotations-in-javadoc.md +++ b/java/java-fundamentals/annotations-iii/including-annotations-in-javadoc.md @@ -49,7 +49,7 @@ Suppose the following annotation. Complete the snippet so it will be included in ```java @??? -@Enki +@Enki { String enki = "enki"; } ``` From 443c0ae6a97e92e1bf16d53aee5bab4da0414cce Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 19 Oct 2022 11:36:25 +0200 Subject: [PATCH 254/390] Update commands-to-shutdown-or-restart-the-system.md --- ...mands-to-shutdown-or-restart-the-system.md | 55 ++++++++++++++++--- 1 file changed, 47 insertions(+), 8 deletions(-) diff --git a/linux/system-and-package-management/system-monitoring-i/commands-to-shutdown-or-restart-the-system.md b/linux/system-and-package-management/system-monitoring-i/commands-to-shutdown-or-restart-the-system.md index 564a5bb74e..58dcd9bc8d 100644 --- a/linux/system-and-package-management/system-monitoring-i/commands-to-shutdown-or-restart-the-system.md +++ b/linux/system-and-package-management/system-monitoring-i/commands-to-shutdown-or-restart-the-system.md @@ -26,23 +26,54 @@ revisionQuestion: ## Content -To shutdown: +There are several ways to shut down or restart your Linux system. +First, we have these commands: ```bash -sudo shutdown -h now -sudo halt sudo poweroff + +sudo reboot +``` + +Next, we have `init` commands that tell the system to change the current *run level*[1]: +```bash +# To shutdown: sudo init 0 + +# To restart: +sudo init 6 ``` -To restart: +Next, a `halt` command can stop all CPU functions. ```bash -sudo reboot +sudo halt +``` + +Finally, we can also use these commands: + +```bash +# To shutdown +sudo shutdown -h now + +# or you can set a shutdown in 30 seconds: +sudo shutdown -h -t30 + + +# the -h means "halt the system after shutdown" +# while the -r means "restart the system after shutdown" + +# To restart: sudo shutdown -r now -sudo init 6 + +# you can also add a time: +# erestart at 14:20 +sudo shutdown -r 14:20 + ``` +Note: you can also use `--help` to view additional options for the shutdown command. + --- @@ -64,13 +95,21 @@ What is the command to make the system start the restart process `now`? ## Revision What is the command to shutdown the system `now`? + ```bash ??? ``` - - - `sudo shutdown -h now` - `sudo reboot` - `sudo init 6` - `sudo shutdown -r now` + + +--- + +## Footnotes + +[1: Run Levels] + +A run level is a software configuration which allows only a selected group of processes to exist. They determine which program can execute after the OS boots up. From 89b59d0ee5f1b701c13712e90711b36eeb104567 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 19 Oct 2022 11:37:49 +0200 Subject: [PATCH 255/390] Update CHANGELOG.md --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d08010573d..3135f31da9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,13 @@ Types of change: ### Fixed + + +## October 19th 2022 + +### Added +- [Linux - Command to shutdown or restart the system - Add additional information](https://github.com/enkidevs/curriculum/pull/3114) + ## September 28th 2022 ### Changed From 6e92fb5d675efad3320916c7d99f295c4f150f17 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 19 Oct 2022 11:56:12 +0200 Subject: [PATCH 256/390] Update go-logical-operators.md --- .../go-operators/go-logical-operators.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/go/go-introduction/go-operators/go-logical-operators.md b/go/go-introduction/go-operators/go-logical-operators.md index 9c49f278d8..676c4d88e2 100644 --- a/go/go-introduction/go-operators/go-logical-operators.md +++ b/go/go-introduction/go-operators/go-logical-operators.md @@ -82,13 +82,13 @@ Which group of operators do `&&`, `||` and `!` fall into? Match the name with the operator. ```plain-text -&& - ??? -|| - ??? -! - ??? +AND - ??? +OR - ??? +NOT - ??? ``` -- AND -- OR -- NOT -- WITH -- IF +- `&&` +- `||` +- `!` +- `&` +- `^^` From b807d2e4ce02915b1d6a776d9d9d3d3aebc5fb80 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 19 Oct 2022 11:58:26 +0200 Subject: [PATCH 257/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d08010573d..4271a0dbef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## October 19th 2022 + +### Changed +- [Golang - Logical Operators - Switch answers around so different capitalizations dont make the answer wrong](https://github.com/enkidevs/curriculum/pull/3115) + ## September 28th 2022 ### Changed From 4956b28613c6278126dc5f48b25d3102530889e3 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 20 Oct 2022 11:27:28 +0200 Subject: [PATCH 258/390] Update sql-not-example.md update question so users do not get it wrong by switching order. --- sql/dql/building-queries/sql-not-example.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/sql/dql/building-queries/sql-not-example.md b/sql/dql/building-queries/sql-not-example.md index 4ec6bf3ec2..877e42b52c 100644 --- a/sql/dql/building-queries/sql-not-example.md +++ b/sql/dql/building-queries/sql-not-example.md @@ -104,12 +104,11 @@ FROM pokemon ???; ``` -- `WHERE` -- `name = 'bulbasaur' OR` +- `WHERE name = 'bulbasaur'` +- `OR` - `name = 'ivysaur' OR` - `name = 'venusaur'` - `name IS` -- `OR` - `name IN` - `'ivysaur'` - `'bulbasaur'` From 9a1d172b68f8cf35b40b1f55b236aa3a61797287 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 20 Oct 2022 11:28:46 +0200 Subject: [PATCH 259/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 894c9d7f68..31d743d540 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## October 20th 2022 + +### Changed +- [Sql - SQL NOT Example - Fix revision answers so people dont get it wrong due to different ordering](https://github.com/enkidevs/curriculum/pull/3116) + ## October 19th 2022 ### Changed From cdb034dea0f6370979f7910b6f9c6398342be95a Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 21 Oct 2022 13:04:27 +0200 Subject: [PATCH 260/390] Update group-by-clause.md --- sql/dql/aggregate-queries/group-by-clause.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sql/dql/aggregate-queries/group-by-clause.md b/sql/dql/aggregate-queries/group-by-clause.md index a33daadeee..d09754fa41 100644 --- a/sql/dql/aggregate-queries/group-by-clause.md +++ b/sql/dql/aggregate-queries/group-by-clause.md @@ -92,10 +92,10 @@ Output: ## Revision -`item` is a table with the following columns: -`id` - unique id of the item -`cost` - item's cost -`item_category_id` - ID category +`item` is a table with the following columns: +`id` - unique id of the item +`cost` - item's cost +`item_category_id` - ID category `name` - item's name Find the _average cost of items in each category_. From 33c3b187f6ff8e767a774e58e06349ce161c2d37 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 21 Oct 2022 13:06:18 +0200 Subject: [PATCH 261/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 31d743d540..a817198695 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## October 21st 2022 + +### Fixed +- [SQL - Group By Clause - fix markdown issue](https://github.com/enkidevs/curriculum/pull/3117) + ## October 20th 2022 ### Changed From f385afcc7f2b5f80499e225d43b05f0b3b7b8ea7 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 31 Oct 2022 12:15:17 +0100 Subject: [PATCH 262/390] Update pushing.md replace `master` branch with `main` branch --- git/essentials/remote-repository/pushing.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/git/essentials/remote-repository/pushing.md b/git/essentials/remote-repository/pushing.md index 94cdeadab3..6e0b7b9590 100644 --- a/git/essentials/remote-repository/pushing.md +++ b/git/essentials/remote-repository/pushing.md @@ -32,10 +32,10 @@ The basic syntax of the `git push` command is: git push [remote-name] [branch-name] ``` -If you want to push all your local commits to the `origin` server on the `master` branch (both automatically named) you can use: +If you want to push all your local commits to the `origin` server on the `main` branch (both automatically named) you can use: ```bash -git push origin master +git push origin main ``` You can also run `git push` without arguments to push to the upstream of your current local branch. From 529deb09254ca8916da962040c7736227310dc9e Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 31 Oct 2022 12:16:14 +0100 Subject: [PATCH 263/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a817198695..44fcf54c3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## October 31st 2022 + +### Changed +- [Git - Pushing - Replace master branch name with main](https://github.com/enkidevs/curriculum/pull/3121) + ## October 21st 2022 ### Fixed From 53ebc5814508c686e049900ba72cdf78f6eda516 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 31 Oct 2022 13:04:37 +0100 Subject: [PATCH 264/390] Update use-em-instead-of-px-for-sizes.md Remove type in the gap as it can cause a correct answer that was written differently to be evaluated as incorrect --- .../use-em-instead-of-px-for-sizes.md | 1 - 1 file changed, 1 deletion(-) diff --git a/web/styling/dimensioning-and-box-sizing/use-em-instead-of-px-for-sizes.md b/web/styling/dimensioning-and-box-sizing/use-em-instead-of-px-for-sizes.md index 83af8777b6..89925a2e2c 100644 --- a/web/styling/dimensioning-and-box-sizing/use-em-instead-of-px-for-sizes.md +++ b/web/styling/dimensioning-and-box-sizing/use-em-instead-of-px-for-sizes.md @@ -12,7 +12,6 @@ links: practiceQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone revisionQuestion: formats: From b71c934c15a83e5f020f9c2e4e2fc0b5f722d5d4 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 31 Oct 2022 13:05:51 +0100 Subject: [PATCH 265/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a817198695..9ecf22aa1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## October 31st 2022 + +### Fixed +- [Web - Use em instead of px for sizes - Remove type in the gap as it can cause correct answers to be incorrect](https://github.com/enkidevs/curriculum/pull/3122) + ## October 21st 2022 ### Fixed From d7afb0fb693f6f3230185294884f5039f3b37b80 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 3 Nov 2022 03:06:07 -0700 Subject: [PATCH 266/390] Add files via upload --- tech-interviews/README.md | 12 ++ .../tech-interviews-core/README.md | 15 +++ .../array-and-map-tips/README.md | 14 +++ .../array-and-map-tips/array-edge-cases.md | 19 +++ .../array-interview-tips.md | 99 ++++++++++++++++ .../map-takes-space-and-gives-time.md | 70 +++++++++++ .../static-vs-dynamic-arrays.md | 71 ++++++++++++ .../arrays-and-maps/README.md | 14 +++ .../arrays-and-maps/array-operations.md | 52 +++++++++ .../arrays-and-maps/what-is-a-map.md | 76 ++++++++++++ .../arrays-and-maps/what-is-array.md | 38 ++++++ .../why-data-structures-matter.md | 26 +++++ .../behavioral-interview-prep/README.md | 15 +++ .../come-prepared-with-questions.md | 91 +++++++++++++++ .../common-soft-skill-questions-2.md | 79 +++++++++++++ .../common-soft-skill-questions.md | 73 ++++++++++++ .../example-introduction.md | 37 ++++++ .../practice-your-intro.md | 75 ++++++++++++ .../tech-interviews-core/big-o-tips/README.md | 16 +++ .../big-o-tips/linear-complexity.md | 54 +++++++++ .../big-o-tips/logarithmic-complexity.md | 55 +++++++++ .../big-o-tips/quadratic-complexity.md | 52 +++++++++ .../big-o-tips/space-complexity.md | 69 +++++++++++ .../coding-interview-prep/README.md | 14 +++ .../dont-jump-into-coding.md | 94 +++++++++++++++ .../general-vs-specialized-knowledge.md | 81 +++++++++++++ .../coding-interview-prep/mock-interviews.md | 48 ++++++++ .../picking-programming-language.md | 109 ++++++++++++++++++ .../tech-interviews-overview/README.md | 16 +++ .../behavioral-interview.md | 101 ++++++++++++++++ .../big-companies-vs-startups.md | 46 ++++++++ .../take-home-interviews.md | 83 +++++++++++++ .../tech-interview-structure.md | 45 ++++++++ .../welcome-to-tech-interviews.md | 48 ++++++++ .../whiteboard-interviews.md | 89 ++++++++++++++ .../what-is-big-o/README.md | 15 +++ .../what-is-big-o/big-o-notation.md | 81 +++++++++++++ .../what-is-big-o/big-o-visualized.md | 51 ++++++++ .../what-is-big-o/common-big-os-1-n-nn.md | 70 +++++++++++ .../what-is-big-o/common-big-os-logn.md | 68 +++++++++++ .../how-to-know-code-efficiency.md | 27 +++++ 41 files changed, 2208 insertions(+) create mode 100644 tech-interviews/README.md create mode 100644 tech-interviews/tech-interviews-core/README.md create mode 100644 tech-interviews/tech-interviews-core/array-and-map-tips/README.md create mode 100644 tech-interviews/tech-interviews-core/array-and-map-tips/array-edge-cases.md create mode 100644 tech-interviews/tech-interviews-core/array-and-map-tips/array-interview-tips.md create mode 100644 tech-interviews/tech-interviews-core/array-and-map-tips/map-takes-space-and-gives-time.md create mode 100644 tech-interviews/tech-interviews-core/array-and-map-tips/static-vs-dynamic-arrays.md create mode 100644 tech-interviews/tech-interviews-core/arrays-and-maps/README.md create mode 100644 tech-interviews/tech-interviews-core/arrays-and-maps/array-operations.md create mode 100644 tech-interviews/tech-interviews-core/arrays-and-maps/what-is-a-map.md create mode 100644 tech-interviews/tech-interviews-core/arrays-and-maps/what-is-array.md create mode 100644 tech-interviews/tech-interviews-core/arrays-and-maps/why-data-structures-matter.md create mode 100644 tech-interviews/tech-interviews-core/behavioral-interview-prep/README.md create mode 100644 tech-interviews/tech-interviews-core/behavioral-interview-prep/come-prepared-with-questions.md create mode 100644 tech-interviews/tech-interviews-core/behavioral-interview-prep/common-soft-skill-questions-2.md create mode 100644 tech-interviews/tech-interviews-core/behavioral-interview-prep/common-soft-skill-questions.md create mode 100644 tech-interviews/tech-interviews-core/behavioral-interview-prep/example-introduction.md create mode 100644 tech-interviews/tech-interviews-core/behavioral-interview-prep/practice-your-intro.md create mode 100644 tech-interviews/tech-interviews-core/big-o-tips/README.md create mode 100644 tech-interviews/tech-interviews-core/big-o-tips/linear-complexity.md create mode 100644 tech-interviews/tech-interviews-core/big-o-tips/logarithmic-complexity.md create mode 100644 tech-interviews/tech-interviews-core/big-o-tips/quadratic-complexity.md create mode 100644 tech-interviews/tech-interviews-core/big-o-tips/space-complexity.md create mode 100644 tech-interviews/tech-interviews-core/coding-interview-prep/README.md create mode 100644 tech-interviews/tech-interviews-core/coding-interview-prep/dont-jump-into-coding.md create mode 100644 tech-interviews/tech-interviews-core/coding-interview-prep/general-vs-specialized-knowledge.md create mode 100644 tech-interviews/tech-interviews-core/coding-interview-prep/mock-interviews.md create mode 100644 tech-interviews/tech-interviews-core/coding-interview-prep/picking-programming-language.md create mode 100644 tech-interviews/tech-interviews-core/tech-interviews-overview/README.md create mode 100644 tech-interviews/tech-interviews-core/tech-interviews-overview/behavioral-interview.md create mode 100644 tech-interviews/tech-interviews-core/tech-interviews-overview/big-companies-vs-startups.md create mode 100644 tech-interviews/tech-interviews-core/tech-interviews-overview/take-home-interviews.md create mode 100644 tech-interviews/tech-interviews-core/tech-interviews-overview/tech-interview-structure.md create mode 100644 tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md create mode 100644 tech-interviews/tech-interviews-core/tech-interviews-overview/whiteboard-interviews.md create mode 100644 tech-interviews/tech-interviews-core/what-is-big-o/README.md create mode 100644 tech-interviews/tech-interviews-core/what-is-big-o/big-o-notation.md create mode 100644 tech-interviews/tech-interviews-core/what-is-big-o/big-o-visualized.md create mode 100644 tech-interviews/tech-interviews-core/what-is-big-o/common-big-os-1-n-nn.md create mode 100644 tech-interviews/tech-interviews-core/what-is-big-o/common-big-os-logn.md create mode 100644 tech-interviews/tech-interviews-core/what-is-big-o/how-to-know-code-efficiency.md diff --git a/tech-interviews/README.md b/tech-interviews/README.md new file mode 100644 index 0000000000..541f66d92c --- /dev/null +++ b/tech-interviews/README.md @@ -0,0 +1,12 @@ +name: Tech Interviews + +icon: 'https://img.enkipro.com/db79b7f9f0366f0c0e4183480a71fb91.png' + +color: 'ffe0a6' + +description: The ultimate guide to preparing for tech interviews + +language: python + +availableAspects: + - introduction diff --git a/tech-interviews/tech-interviews-core/README.md b/tech-interviews/tech-interviews-core/README.md new file mode 100644 index 0000000000..a50cd7e4a6 --- /dev/null +++ b/tech-interviews/tech-interviews-core/README.md @@ -0,0 +1,15 @@ +name: Preparation + +description: Prepare in the best way for tech interviews + +core: true + +sections: + '0': + - tech-interviews-overview + - behavioral-interview-prep + - coding-interview-prep + - what-is-big-o + - big-o-tips + - arrays-and-maps + - array-and-map-tips \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/array-and-map-tips/README.md b/tech-interviews/tech-interviews-core/array-and-map-tips/README.md new file mode 100644 index 0000000000..c8bccd14e1 --- /dev/null +++ b/tech-interviews/tech-interviews-core/array-and-map-tips/README.md @@ -0,0 +1,14 @@ +name: Array & Map Tips + +description: Best practices for efficient solutions + +aspects: + - introduction + +learnType: GROKKING + +insights: + - array-edge-cases + - static-vs-dynamic-arrays + - array-interview-tips + - map-takes-space-and-gives-time \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/array-and-map-tips/array-edge-cases.md b/tech-interviews/tech-interviews-core/array-and-map-tips/array-edge-cases.md new file mode 100644 index 0000000000..a90fe368fd --- /dev/null +++ b/tech-interviews/tech-interviews-core/array-and-map-tips/array-edge-cases.md @@ -0,0 +1,19 @@ +--- +author: nemanjaenki +category: tip +type: normal + +--- + +# Arrays Edge Cases + +--- +## Content + +Pay close attention to: + +- Empty arrays +- Duplicated values +- Going out of bounds +- Sort order (or lack thereof) +- Min and max value to store (do you have enough memory?) \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/array-and-map-tips/array-interview-tips.md b/tech-interviews/tech-interviews-core/array-and-map-tips/array-interview-tips.md new file mode 100644 index 0000000000..5204f3eded --- /dev/null +++ b/tech-interviews/tech-interviews-core/array-and-map-tips/array-interview-tips.md @@ -0,0 +1,99 @@ +--- +author: nemanjaenki +category: tip +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +--- + +# Array Interview Tips + +--- +## Content + +Here're some useful techniques when using arrays to solve coding interview problems. + +--- + +#### Traversing from the right + +Sometimes it's more suitable to go through the array from the end instead of the start. + +![traversing-from-the-right](https://img.enkipro.com/8a4ff0dfd4d47d8a792a72df3afc44fd.gif) + +--- + +#### Sorting the array + +Sorting the array first may simplify the problem. + +Note that this makes your program at least an O(NlogN)[1]. If you're creating a new sorted array, you're also adding O(N) space complexity to hold that array. + +> 💡 Always consider preprocessing your data to create an ideal starting point for an efficient solution. + +--- + +#### Traversing the array more than once + +Traversing the array multiple times doesn't affect complexity unless the number of traversals depends on input size N. [2] + +![traverse-more-than-once](https://img.enkipro.com/22e925bbf1ad225d20c1e05302e44bdb.gif) + +--- +## Practice + +What's the Big-O for traversing an input array 1337 times, irrespective of the size of the input data? + +??? + +- O(N) +- O(N²) +- O(logN) +- O(N + N) + +--- +## Revision + +What's the space complexity for a program that takes in an array of length N, combines all of its elements into another array of length N, and returns the new array? + +??? + +- O(N) +- O(N²) +- O(logN) +- O(N + N) + +--- +## Footnotes + +[1: Sorting is logarithmic] +The best sorting algorithms, like QuickSort or MergeSort, have O(NlogN) complexity. + +[2: Traverse more than once is O(N)] + +```js +// this program is still O(N) +// because no matter how big the input is +// we're always doing 2 loops +// => # of loops doesn't depend on input.length +function program(input) { + + // loop 1 + for (item in input) { + + } + + // loop 2 + for (item in input) { + + } + + // ... +} +``` \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/array-and-map-tips/map-takes-space-and-gives-time.md b/tech-interviews/tech-interviews-core/array-and-map-tips/map-takes-space-and-gives-time.md new file mode 100644 index 0000000000..3195fb316b --- /dev/null +++ b/tech-interviews/tech-interviews-core/array-and-map-tips/map-takes-space-and-gives-time.md @@ -0,0 +1,70 @@ +--- +author: nemanjaenki +category: tip +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +--- + +# Map Takes Space and Gives Time + +--- +## Content + +In interviews, using a map is the most common example of sacrificing space to gain time, i.e. sacrificing memory to create a map such that your code can have fast lookups. + +> 💡 Sacrificing space for time is an essential technique to make your solution faster. + +--- + +Imagine that your goal is to build a program that tells you how many times each word is mentioned in a book. + +### Slow solution: O(N²) + +For each word in the book, go through the whole book and count how many times it's mentioned. + +### Fast solution: O(N) time and O(N) space + +Go through the book twice. + +First, build a map of each word and a counter number, equal to 0. + +Then, go through all the words again and increment the counter for each word as you see it. + +> 💡 Remember: O(2N) is the same as O(N) in Big-O![1] + +Note that you're also adding O(N) of space complexity to store all the words in the map. + +--- +## Practice + +A map is a data structure that lets us write more efficient code by trading ??? for ???. + +- space +- time +- size +- access + +--- +## Revision + +If you want to speed up your solution, the first data structure that should come to mind is ??? + +- a map +- a list +- an array +- a tree + +--- +## Footnotes + +[1: Constant Factors] +O(N), O(2N) and O(1337N) are all O(N). Constant factors don't affect Big-O. + +But they're still important, especially if they're large. If you had O(100¹⁰⁰N) it would be quite a lot slower than O(N). \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/array-and-map-tips/static-vs-dynamic-arrays.md b/tech-interviews/tech-interviews-core/array-and-map-tips/static-vs-dynamic-arrays.md new file mode 100644 index 0000000000..709652583f --- /dev/null +++ b/tech-interviews/tech-interviews-core/array-and-map-tips/static-vs-dynamic-arrays.md @@ -0,0 +1,71 @@ +--- +author: abd147 +category: tip +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Static vs Dynamic Arrays + +--- +## Content + +Different programming languages implement arrays differently, which can affect the complexity of array operations. + +--- + +#### Static arrays + +In C++ or Java, arrays are **static** and have a fixed size you set when creating an array. + +Adding or removing an item takes as many steps as the size of the array, i.e. O(N), because you need to create a new array with the changed size and copy all the items over. + +An exception to this is if the position to be inserted/removed is at the end of the array. + +> 💡 C++ and Java have library data structures that behave like dynamic arrays. + +--- + +#### Dynamic arrays + +In Python, JavaScript, Ruby, or PHP, arrays are **dynamic** and can grow as needed. + +Dynamic arrays are appropriate when you don't know how many items you'll need to store. + +A dynamic array is typically a wrapper around a fixed-size static array with extra room. + +Once the extra room starts filling up, a new static array is created, and elements are copied over. + +--- +## Practice + +What's the Big-O for adding an element in the middle of a fixed-size array? + +Hint: elements need to be shifted to accommodate the newly added one. + +??? + +- O(N) +- O(N²) +- O(logN) +- O(1) + +--- +## Revision + +What's the Big-O for adding an element in the middle of a fixed-size array? + +??? + +- O(N) +- O(N²) +- O(logN) +- O(1) diff --git a/tech-interviews/tech-interviews-core/arrays-and-maps/README.md b/tech-interviews/tech-interviews-core/arrays-and-maps/README.md new file mode 100644 index 0000000000..6c709df2b9 --- /dev/null +++ b/tech-interviews/tech-interviews-core/arrays-and-maps/README.md @@ -0,0 +1,14 @@ +name: Arrays & Maps + +description: A fundamental data structure in interview problems + +aspects: + - introduction + +learnType: GROKKING + +insights: + - why-data-structures-matter + - what-is-array + - array-operations + - what-is-a-map \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/arrays-and-maps/array-operations.md b/tech-interviews/tech-interviews-core/arrays-and-maps/array-operations.md new file mode 100644 index 0000000000..128687702b --- /dev/null +++ b/tech-interviews/tech-interviews-core/arrays-and-maps/array-operations.md @@ -0,0 +1,52 @@ +--- +author: nemanjaenki +category: must-know +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +--- + +# Arrays Operations + +--- +## Content + +If you know its position, finding an element in an array is O(1). + +![find-by-position](https://img.enkipro.com/da9c0bd0b13222e99d54fcc27c3d5092.gif) + +If you don't, it's O(N) because, in the worst case, we have to look through the whole array if the element we're looking for happens to be at the end. + +![find-by-value](https://img.enkipro.com/36b76b4148fecaffbe9bddeb50f1c2ff.gif) + +Adding a new element is O(N) because we have to shift other elements to make room for it. + +![add](https://img.enkipro.com/60396f0be43edc16ece0bf52f58f1fd3.gif) + +Unless you're adding to the start or end of the array, which is O(1) because no shifting is needed. + +![add-at-edge](https://img.enkipro.com/06323c60953fd8d435ae329a0e93665d.gif) + +Removing an element is also O(N) because we have to shift other elements to fill up the empty space. + +![remove](https://img.enkipro.com/4e0ae2186d80a5b3cea946d16496147a.gif) + +The exception is removing from either edge being O(1) as no shifting is needed. + +![remove-at-edge](https://img.enkipro.com/81d116cd33690a1f7b4cea74672497de.gif) + +> 💡 Be careful when altering or combining arrays in your interview solutions as that's usually O(N). If you can, alter at the start or end, which is O(1). + +--- +## Practice + +What's the Big-O for finding an element in an array if you don't know its position? + +??? + +- O(N) +- O(N²) +- O(log N) +- O(1) diff --git a/tech-interviews/tech-interviews-core/arrays-and-maps/what-is-a-map.md b/tech-interviews/tech-interviews-core/arrays-and-maps/what-is-a-map.md new file mode 100644 index 0000000000..fcb5a8b7b7 --- /dev/null +++ b/tech-interviews/tech-interviews-core/arrays-and-maps/what-is-a-map.md @@ -0,0 +1,76 @@ +--- +author: nemanjaenki +category: must-know +type: normal +links: + - '[What is a Map data structure?](https://www.quora.com/What-is-a-map-data-structure-How-does-it-store-data){discussion}' + +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# What's a Map? + +--- +## Content + +A Map is a data structure that links keys to values. + +> 💡 Note that a dictionary or an associative array are different names for the same data structure, i.e. a key-value store. + +Finding a value by its key is O(1) because, no matter how big a map is, it takes the same time to do it[1]. + +![map-get-banana](https://img.enkipro.com/207792353e00a4117cbbc62594a8788f.gif) + +Adding value to and removing values from a map are also unaffected by map size and are thus O(1). + +![map-add-or-remove](https://img.enkipro.com/eebddfae318999c0c250463a9596cd74.gif) + +> 💡 A Map is different from an array because it can typically contain anything as the key whereas arrays can only use numbers (usually called indexes). + +--- +## Practice + +Adding an element into a map is ??? + +Removing an element from a map is the same. + +??? + +- O(1) +- true +- O(N) +- false +- O(logN) +- O(K*V) + +--- +## Revision + +A map key can be ???, but an array key can only be ???. + +- any type +- an integer +- a string +- an object +- a boolean + +--- +## Footnotes + +[1: Map Implementation] + +Maps aren't always O(1)! + +A Map is sometimes implemented as a HashMap, which is a Map with a special way of building keys. + +This special way is something called a *hash function*, which is a function that takes in a value and returns a unique number for it, called a *hash code*, which is used as the key. + +Except this value isn't always unique which leads to collisions (i.e. same key for different values). Maps have to account for that by adding the element into a different key or storing multiple elements at the same key, which makes some operations go from O(1) to O(N). \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/arrays-and-maps/what-is-array.md b/tech-interviews/tech-interviews-core/arrays-and-maps/what-is-array.md new file mode 100644 index 0000000000..8eb753b867 --- /dev/null +++ b/tech-interviews/tech-interviews-core/arrays-and-maps/what-is-array.md @@ -0,0 +1,38 @@ +--- +author: nemanjaenki +category: discussion +type: normal +--- + +# What's an Array? + +--- +## Content + +Arra is an ordered collection of items, accessible by their position in constant time[1]. + +> 💡 In most languages, all items of an array have to be the same type + +They're useful when the order of elements matters or finding elements by their position happens often. + +For instance, you could use an array to store the top 5 highest scores in a video game. + +```js +high_scores = [123, 99, 95, 87, 79] + +// get 3rd best result +third_best = high_scores[2] // 95 +``` + +On the other hand, if you want to keep track of all streets in your city, an array might not be as appropriate. + +> 💡 Because both arrays and strings are sequences (a string is an array of characters), most of these lessons will apply to string interview problems too. + +--- +## Footnotes + +[1: O(1) → Constant Time] + +O(1) means your program will take the same amount of steps for 1 item and 1 million items. + +For instance, using bookmarks, we can find a page in a single step regardless of how many pages a book has. \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/arrays-and-maps/why-data-structures-matter.md b/tech-interviews/tech-interviews-core/arrays-and-maps/why-data-structures-matter.md new file mode 100644 index 0000000000..3e3f417a13 --- /dev/null +++ b/tech-interviews/tech-interviews-core/arrays-and-maps/why-data-structures-matter.md @@ -0,0 +1,26 @@ +--- +author: nemanjaenki +category: must-know +type: normal +--- + +# Arrays + +--- +## Content + +A data structure is a way we store and organize our data. + +Think about organizing books in a room - we can keep those books on a shelf, or make a stack of them on a table or even just put them randomly anywhere in the room. + +![books-messy-room](https://img.enkipro.com/ffe1d2c97323327984f918d208110228.jpeg) + +It makes sense to pick a way of organizing our books so that finding specific ones is quick and easy. For example: sorting them alphabetically. + +Great programs (and great interview solutions) do the same thing! They organize data to make doing important tasks more efficient. + +It's crucial to become confident in fundamental data structures if you want to excel in interviews (and in your job!) + +> 💡 Along with Big-O, Lists and Trees, Arrays will give you a great foundation for language-agnostic problem-solving. + +Let's get started! \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/behavioral-interview-prep/README.md b/tech-interviews/tech-interviews-core/behavioral-interview-prep/README.md new file mode 100644 index 0000000000..c925396262 --- /dev/null +++ b/tech-interviews/tech-interviews-core/behavioral-interview-prep/README.md @@ -0,0 +1,15 @@ +name: Behavioral Interview Prep + +description: Be ready for the soft skills test + +aspects: + - introduction + +learnType: GROKKING + +insights: + - practice-your-intro + - example-introduction + - come-prepared-with-questions + - common-soft-skill-questions + - common-soft-skill-questions-2 \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/behavioral-interview-prep/come-prepared-with-questions.md b/tech-interviews/tech-interviews-core/behavioral-interview-prep/come-prepared-with-questions.md new file mode 100644 index 0000000000..a9eea79003 --- /dev/null +++ b/tech-interviews/tech-interviews-core/behavioral-interview-prep/come-prepared-with-questions.md @@ -0,0 +1,91 @@ +--- +author: abd147 +category: discussion +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +links: + - '[Questions to ask the company during the interview](https://github.com/viraptor/reverse-interview){documentation}' + +--- + +# Come Prepared with Questions + +--- +## Content + +Most interviews end by offering the candidate a few minutes to ask questions. + +This is a great chance to learn more about the company and see if you'd like to work there. + +Not having questions makes it seem you're not that interested in the role, or you're not too proactive in general. + +Let's look at an example question for each category: + +--- + +#### Ask about work projects + +*"What is the most exciting or challenging project you've worked on here so far?"* + +--- + +#### Ask about the role + +*"What would be the most critical problem I might be solving if I joined the team?"* + +--- + +#### Ask about the culture + +*"What is something you wish was different about your job?"* + +--- + +#### Ask about the org setup + +*"How does the company decide on what to work on next?"* + +--- + +#### Ask about team leadership or management** + +*"Can you tell me about a time you resolved a conflict in the team?"* + +This last one might be more suitable if the interviewer has a managerial role in the company. + +--- + +> 💬 Do you have a favorite question to ask during interviews? +> +> Leave a comment or view some of the other comments for inspiration before moving on. + +--- +## Practice + +What is **NOT** a great question to ask about the team culture? + +??? + +- Will the free yoga benefit be reinstated at all? +- How often does the dev team meet up outside of work? +- How do devs debate ideas at the company? +- How do employees get visibility on the company strategy? + +--- +## Revision + +What is **NOT** a great question to ask about the team culture? + +??? + +- How do I tell my manager about PTO I'll take? +- How often do employees meet up outside of work? +- How do execs at the company make decisions? +- Does the team celebrate success in any way? \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/behavioral-interview-prep/common-soft-skill-questions-2.md b/tech-interviews/tech-interviews-core/behavioral-interview-prep/common-soft-skill-questions-2.md new file mode 100644 index 0000000000..c174b162a3 --- /dev/null +++ b/tech-interviews/tech-interviews-core/behavioral-interview-prep/common-soft-skill-questions-2.md @@ -0,0 +1,79 @@ +--- +author: abd147 +tags: + - introduction +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Bonus: Answering Common Qs 2/2 + +--- +## Content + +*Q: "Tell me about a time you failed."* + +This is the perfect time to share a story about your resilience, how you learn from tough times and most importantly, how you grow from your experiences. + +Have at least one specific story to share, and be as clear as possible. + + +*Q: "Why are you leaving your job?"* + +Answer this one positively! + +Highlight why the new role is a better fit for your goals. + +Avoid saying anything negative about your former employer. You don't want to come off touchy about the subject. + + +*Q: "How do you handle stress?"* + +Everyone gets stressed - no point in hiding it. + +Focus on 1-2 specific tactics for stress management, like going for a walk or meditation. + +You can also highlight an instance when stress led you to rise to the occasion. + + +*Q: "Where do you see yourself in 10 years?"* + +This is an assessment of your ambition. And whether your ambition aligns with your growth opportunity at the company. + +This one's more open-ended than the others, so you can be a little creative here. Just try to relate it to your desired role. + +> 💬 We'll cover introductions and post-interview questions in more detail in upcoming workouts. + + +--- +## Practice + +What is **NOT** a great answer to "What motivates you long term?" + +??? + +- To make as much money as possible +- To build technology used by many people +- To be part of an influential company +- To set an example for others + +--- +## Revision + +What is **NOT** a great answer to "What motivates you long term?" + +??? + +- To live the nomadic lifestyle +- To work on cutting-edge technology +- Become known as a top developer +- To create influential products \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/behavioral-interview-prep/common-soft-skill-questions.md b/tech-interviews/tech-interviews-core/behavioral-interview-prep/common-soft-skill-questions.md new file mode 100644 index 0000000000..5d65406a24 --- /dev/null +++ b/tech-interviews/tech-interviews-core/behavioral-interview-prep/common-soft-skill-questions.md @@ -0,0 +1,73 @@ +--- +author: abd147 +tags: + - introduction +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Bonus: Answering Common Qs 1/2 + +--- +## Content + +Many software engineering candidates tend to struggle with behavioral questions that come up in the middle of technical interviews. + +Here are some common questions and tips for how to answer them: + + +1. *Q: "Why this company?"* + +This is a standard question. But, unfortunately, answering poorly can hurt your chances of getting the job. + +Try to avoid a generic answer - you should have 2-3 unique points about the company prepared beforehand. + +Ideally, the reasons are genuinely appealing to you and they show through your body language. + + +2. *Q: "What are your strengths?"* + +Stick to 1-2 strengths that you can relate directly to the role and company. + +Where possible, leverage storytelling - bring them to life with anecdotes! + + +3. *Q: "What are your weaknesses?"* + +Don't try to subtly pitch a strength as a weakness. + +Go for a real weakness and address how you're working on it. + + +--- +## Practice + +What is something you might **NOT** want to say about why you left your last company? + +??? + +- My last manager was too demanding +- I wasn't challenged enough +- They shifted strategy which I didn't believe in +- I saw your role and it's a better fit for me + +--- +## Revision + +What is something you might **NOT** want to say about why you left your last company? + +??? + +- My former colleagues were idiots +- My manager moved companies to another industry +- The company is not heading in the right direction +- I'm much more excited about the role here diff --git a/tech-interviews/tech-interviews-core/behavioral-interview-prep/example-introduction.md b/tech-interviews/tech-interviews-core/behavioral-interview-prep/example-introduction.md new file mode 100644 index 0000000000..b1b63aa35c --- /dev/null +++ b/tech-interviews/tech-interviews-core/behavioral-interview-prep/example-introduction.md @@ -0,0 +1,37 @@ +--- +author: abd147 +category: discussion +type: normal + +--- + +# Example: Interview Introduction + +--- +## Content + +Let's look at an example introduction for a hypothetical Android Developer position at JengaHub. + +We've commented on why each part is good! + +*"Hi, I'm Al, a recent grad from XYZ University with a degree in Computer Science."* + +> 💡 Simple, to the point background. + +*"Back in school, I built an app for planning class timetables. It still gets around 10k page views each month and is used by over 200 students at my school."* + +> 💡 This is an example of an **impactful achievement** that is functional and stands out. + +*"Typically, I code apps in Kotlin, but I built this one using Flutter because I wanted to learn a different modern dev tool."* + +> 💡 This highlights skills in modern Android technologies, as well as passion for learning new ones. + +*"I'm interested in a role at JengaHub because I've been an avid player of your games since I was a kid and would love to have a chance to design and build them."* + +> 💡 This shows passion for the company, along with sincere interest. + +--- + +> 💬 Now it's your turn to show us what is a good intro for your dream position. Open the comment section and show everyone how it's done! Keep it professional and helpful to others, please. :) +> +> Leave a comment or view some of the other comments for inspiration before moving on. \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/behavioral-interview-prep/practice-your-intro.md b/tech-interviews/tech-interviews-core/behavioral-interview-prep/practice-your-intro.md new file mode 100644 index 0000000000..1b3621347c --- /dev/null +++ b/tech-interviews/tech-interviews-core/behavioral-interview-prep/practice-your-intro.md @@ -0,0 +1,75 @@ +--- +author: abd147 +category: discussion +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +links: + - '[How To Answer "Why Are You Interested In This Job?"](https://www.workitdaily.com/answer-why-you-want-this-job/what-is-the-best-way-to-answer-why-are-you-interested-in-this-position){article}' + +--- + +# Practice Your Intro + +--- +## Content + +Almost always, the first questions you'll get in a tech interview will be something like: + +*"Tell me about your journey so far. How did you get interested in coding, and why is this role a good fit for you?"* + +This is a chance for you to tell your story. But since you won't have much time, you must be clear and *to the point*! + +> 💡 You want the intro to feel natural and genuine. Practice by writing it out or saying it to a friend. + +The interviewer wants to know what you are doing these days, how you got here, and why you're in this career in the first place. + +Think about what got you into tech and answer honestly. + +Put yourself in their shoes. **What aspects of your career so far would impress you if you heard them from someone else?** + +Make sure to emphasize any skills you have that are relevant to the company - for instance, experience with their tech stack. + +--- + +> 💬 How would you describe your career journey so far? Why are you interested in a tech job? +> +> Leave a comment or view some of the other comments for inspiration before moving on. + +--- +## Practice + +Imagine an interviewer asked you the following question: + +*"Why do you think you'd succeed in this role?"* + +What is **NOT** a great example of something you might mention immediately in your answer? + +??? + +- Your goal to be a manager one day +- Your leadership qualities at school +- Building a side project +- Having a great coding mentor + +--- +## Revision + +Imagine an interviewer asked you the following question: + +*"Why are you interested in this role?"* + +What is **NOT** a great example of something you might mention immediately in your answer? + +??? + +- the reasonable salary level +- passion for the company's product +- knowledge about the company's market +- recommendations from a friend that works there \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/big-o-tips/README.md b/tech-interviews/tech-interviews-core/big-o-tips/README.md new file mode 100644 index 0000000000..0c072dffb8 --- /dev/null +++ b/tech-interviews/tech-interviews-core/big-o-tips/README.md @@ -0,0 +1,16 @@ +name: Big-O Tips + +description: Proven advice for grokking Big-O + +slug: big-o-tips + +aspects: + - introduction + +learnType: GROKKING + +insights: + - linear-complexity + - quadratic-complexity + - logarithmic-complexity + - space-complexity \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/big-o-tips/linear-complexity.md b/tech-interviews/tech-interviews-core/big-o-tips/linear-complexity.md new file mode 100644 index 0000000000..d7770adb8c --- /dev/null +++ b/tech-interviews/tech-interviews-core/big-o-tips/linear-complexity.md @@ -0,0 +1,54 @@ +--- +author: nemanjaenki +category: must-know +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Recognizing Linear Complexity + +--- +## Content + +Imagine you're part of the soccer and chess clubs and going through the school, high-fiving your teammates. + +The complexity of this is linear, but it's not O(N). + +It's O(S + C), where S is the number of soccer teammates and C is the number of chess teammates. + +Linear solutions are decently fast for interview problems. + +> 💡 If a piece of code is doing one thing after another, it most likely has linear complexity. + + +--- +## Practice + +When dealing with a lot of data, O(N) is more efficient than O(N²). + +??? + +- True +- False + +--- +## Revision + +What's the complexity of this program: + +Increment all items in list A. Then increment all items in list B. + +??? + +- O(A + B) +- O(A * B) +- O(A) +- O(B) \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/big-o-tips/logarithmic-complexity.md b/tech-interviews/tech-interviews-core/big-o-tips/logarithmic-complexity.md new file mode 100644 index 0000000000..ced0ccee5d --- /dev/null +++ b/tech-interviews/tech-interviews-core/big-o-tips/logarithmic-complexity.md @@ -0,0 +1,55 @@ +--- +author: nemanjaenki +category: tip +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Recognizing Logarithmic Complexity + +--- +## Content + +Imagine that you're sorting all employees of a company by height. + +They are all standing in a crowd and you start moving them across the park into a sorted line. + +For each employee, you compare their height with the height of the employee in the middle of the sorted line, then go left if their height is smaller or right if their height is equal or larger. + +You repeat the process again by comparing to the middle of the left or right subgroup. + +With each step, you go left or right, dividing the N employees: N, N / 2, N /4 ... + +And you do this N times (i.e. for each employee). + +The complexity thus is O(NlogN),because, for every employee (of which there're N), we're dividing the line over and over. + +> 💡 If a piece of code divides your input over and over, it most likely has logarithmic complexity. + +--- +## Practice + +An indicator of logarithmic complexity is if a program ??? the input on every step. + +- splits +- traverses +- multiplies +- truncates + +--- +## Revision + +The fastest sorting algorithms are ??? + +- O(NlogN) +- O(N) +- O(logN) +- O(1) diff --git a/tech-interviews/tech-interviews-core/big-o-tips/quadratic-complexity.md b/tech-interviews/tech-interviews-core/big-o-tips/quadratic-complexity.md new file mode 100644 index 0000000000..b69332c7f5 --- /dev/null +++ b/tech-interviews/tech-interviews-core/big-o-tips/quadratic-complexity.md @@ -0,0 +1,52 @@ +--- +author: nemanjaenki +category: tip +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Recognizing Quadratic Complexity + +--- +## Content + +Imagine that you have a list of cities and want to find all mentions of each city in a pile of magazines. + +This complexity is quadratic, but it's not O(N²). Instead, it's O(C * M), where C is the number of cities and M is the number of magazines. + +Although sometimes you can't do better than it, quadratic performance is considered slow. + +> 💡 If a piece of code is processing one thing for every item of another thing, it most likely has quadratic complexity. + +--- +## Practice + +O(N²) is usually the most efficient solution for most interview problems. + +??? + +- False +- True + + +--- +## Revision + +What's the complexity of this program: + +For every item in list A, find all items in list B that are equal to it. + +??? + +- O(A * B) +- O(A + B) +- O(AlogA) +- O(ABlogAB) \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/big-o-tips/space-complexity.md b/tech-interviews/tech-interviews-core/big-o-tips/space-complexity.md new file mode 100644 index 0000000000..2ab7be759e --- /dev/null +++ b/tech-interviews/tech-interviews-core/big-o-tips/space-complexity.md @@ -0,0 +1,69 @@ +--- +author: nemanjaenki +category: must-know +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Space Complexity + +--- +## Content + +Space complexity is affected if your code creates new structures from the input data, such as copying it into another place, temporarily storing it somewhere, etc. + +A real-life example would be washing the dishes. If you're putting the clean dishes somewhere else, you're using O(N) space, where N is the number of dishes. + +> 💡 If you're using extra space and the amount of used space depends on the size of the input data, you're affecting space complexity. + +--- + +One of the best ways to make your interview solutions faster is to sacrifice space to store the input data in a way such that it can be retrieved more efficiently. + +Imagine that somebody gives you a box of unsorted books, and your goal is to make it easy to find a book by its name. A way to make that task fast is to move and sort them onto a labelled shelf. + +> 💡 If you're not sure how to make your solution faster, trade space to gain time! + +--- +## Practice + +Imagine that you're sorting a box of toys by their height. + +You decide to take another empty box and insert toys into it one by one, but maintain the order as you do it. + +If T is the number of toys you have, the time complexity of this task is O(TlogT). + +What is the space complexity? + +??? + +- O(T) +- O(1) +- O(logT) +- O(T²) + +--- +## Revision + +Imagine that you're sorting a box of toys by their height. + +You decide to take another empty box and insert toys into it one by one, but maintain the order as you do it. + +If T is the number of toys you have, the time complexity of this task is O(T). + +What is the space complexity? + +??? + +- O(T) +- O(1) +- O(logT) +- O(T²) diff --git a/tech-interviews/tech-interviews-core/coding-interview-prep/README.md b/tech-interviews/tech-interviews-core/coding-interview-prep/README.md new file mode 100644 index 0000000000..30b64de902 --- /dev/null +++ b/tech-interviews/tech-interviews-core/coding-interview-prep/README.md @@ -0,0 +1,14 @@ +name: Coding Interview Prep + +description: Prep for the coding skills test + +aspects: + - introduction + - workout +learnType: GROKKING + +insights: + - picking-programming-language + - general-vs-specialized-knowledge + - dont-jump-into-coding + - mock-interviews \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/coding-interview-prep/dont-jump-into-coding.md b/tech-interviews/tech-interviews-core/coding-interview-prep/dont-jump-into-coding.md new file mode 100644 index 0000000000..65d184fee6 --- /dev/null +++ b/tech-interviews/tech-interviews-core/coding-interview-prep/dont-jump-into-coding.md @@ -0,0 +1,94 @@ +--- +author: abd147 +category: discussion +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +--- + +# Don't Just Jump into Coding + +--- +## Content + +Coding questions tend to be vague and *underspecified on purpose* to allow the interviewer to gauge the candidate's attention to detail and *attentiveness*. + +> 💡 Don't rush. Be methodical. Clarify your assumptions until the interviewer gives you the green light to start coding. + +--- + +#### Understand what's being asked + +Paraphrase and repeat the question back to the interviewer to make sure you are clear on what to solve. + +--- + +#### Clarify assumptions + +Build a clearer picture of the problem to understand what's being asked of you and what's already presumed. + +Think of questions like: + +- *How is the data provided to me?* +- *What's the longest string I can expect?* +- *Should I account for negative values?* + +--- + +#### Confirm with a few examples + +Before diving in, work through a simplified example of the problem to make sure you know what's being asked. + +Imagine you're asked to write a palindrome checker. Before coding, come up with simple test cases like `"ROTATOR" => true`, `"TIGER" => false`. Then check with the interviewer if those example cases align with their expectations. Don't forget about edge cases like `""` and faulty values like `null`. + +--- + +> 💡 These tips are valid for take-home interviews too! You should always understand the problem first before trying to solve it. + +--- +## Practice + + +Imagine you're on a call with an interviewer and they open a Google Doc and write out the following problem: + +```js +// given an array of nums and another target num +// return indices of the two numbers such that they add up to the target. +``` + +What's an example of a good question to ask? + +??? + +- all the other answers +- how big is the array? +- are the numbers integers? +- can the numbers be negative? +- is there more than one solution? +- can I use the same element twice? + +--- +## Revision + + +Imagine you're on a call with an interviewer and they open a Google Doc and write out the following problem: + +```js +// given an array of nums and another target num +// return indices of the two numbers such that they add up to the target. +``` + +What is something you should probably **NOT** do straightaway? + +??? + +- jump into coding +- clarify assumptions +- write out a few examples +- understand the input data better \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/coding-interview-prep/general-vs-specialized-knowledge.md b/tech-interviews/tech-interviews-core/coding-interview-prep/general-vs-specialized-knowledge.md new file mode 100644 index 0000000000..96acf3da5e --- /dev/null +++ b/tech-interviews/tech-interviews-core/coding-interview-prep/general-vs-specialized-knowledge.md @@ -0,0 +1,81 @@ +--- +author: abd147 +category: tip +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +links: + - '[Generalists vs specialists - which one should you strive for as a developer?](https://dev.to/kethmars/generalists-vs-specialists-which-one-should-you-strive-for-as-a-developer-pg3){article}' + - '[Who is a T-shaped developer?](https://infinum.com/blog/t-shaped-developers/){article}' + +--- + +# General vs Specialized Interviews + +--- +## Content + +Typically, companies require good knowledge of fundamental CS topics like data structures and algorithms[1] as well as proficiency in at least one programming language. + +If you're applying for a more specialized job like a front-end developer, the focus might be more on your web dev knowledge[2]. + +How much focus is put on general versus specialized knowledge depends on the role and on the company size. + +Startups tend to focus more on specific knowledge as they need you to be productive from the start while big companies require strong fundamentals and can afford to train you for the specialized role once you join. + +> 💡 Strive to become a mix of both, where you're great in your own field but also have general knowledge of other fields. This is usually called a T-shaped developer. + +**Generalist** + +![generalist](https://img.enkipro.com/562a86cfac15924fc664a8618e312c85.png) + +**Specialist** + +![specialist](https://img.enkipro.com/b09b425dc2c29f69ab8aa17336a53fba.png) + +**T-shaped dev** + +![t-shaped](https://img.enkipro.com/215fc81adc6a8b6e46cba345462738b6.png) + +--- +## Practice + +For tech interviews, you'll increase your chances by focusing on general ??? knowledge and proficiency in ???. + +- computer science +- one coding language +- web design +- databases +- api +- java +- python +- sql + +--- +## Revision + +Advice you'd give a friend interviewing for a tech job: "Nail the CS fundamentals and become as fluent as you can in one programming language." + +??? + +- true +- false + +--- +## Footnotes + +[1: Generalist Interview Question] +Example of a question you might encounter for a general software engineering interview: + +*Given arrays A, B, find the smallest number in A that exists in B.* + +[2: Specialist Interview Question] +Example of a question you might encounter for a front-end interview: + +*Given some text on a web page, how many ways can you make the text disappear?* \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/coding-interview-prep/mock-interviews.md b/tech-interviews/tech-interviews-core/coding-interview-prep/mock-interviews.md new file mode 100644 index 0000000000..6ae79ac170 --- /dev/null +++ b/tech-interviews/tech-interviews-core/coding-interview-prep/mock-interviews.md @@ -0,0 +1,48 @@ +--- +author: abd147 +category: must-know +type: normal +links: + - '[interviewing.io](https://interviewing.io){website}' + - '[Pramp](https://www.pramp.com/#/){website}' + +--- + +# Mock Interviews + +--- +## Content + +Interviewing is a skill, and like any other skill, you can get better at it with practice. + +Ideally, you should rehearse the steps outlined across this course until they become second nature to you. + +A great way to practice is with a friend, taking turns to interview each other. + +If that's not an option for you, there are a few sites that can pair you with others to practice real interviews: + +--- + +#### interviewing.io + +This website provides anonymous practice technical interviews with Google and Facebook engineers, which can lead to real jobs and internships. + +If you do well in the mock interviews, you'll unlock the jobs page which allows you to book interviews (anonymously) with top companies like Uber, Lyft, Quora, Asana and more. + +Since the interview process is anonymous, it's more objective and less stressful. + +--- + +#### 2. Pramp + +Pramp's approach is slightly different. It pairs you up with another peer who is also a job seeker, and both of you take turns to assume the role of interviewer and interviewee. + +Pramp also prepares questions for you, along with suggested solutions and prompts to guide the interviewee. + +One drawback of this platform is that your experience is heavily reliant on the person you are matched with. + +--- + +> 💬 Can you recommend any other resources for interview practice? +> +> Leave a comment or view some of the other comments for inspiration before moving on. \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/coding-interview-prep/picking-programming-language.md b/tech-interviews/tech-interviews-core/coding-interview-prep/picking-programming-language.md new file mode 100644 index 0000000000..8cf962568a --- /dev/null +++ b/tech-interviews/tech-interviews-core/coding-interview-prep/picking-programming-language.md @@ -0,0 +1,109 @@ +--- +author: abd147 +category: discussion +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +links: + - '[The Best Programming Language For Coding Interviews](https://www.youtube.com/watch?v=kYpxolRkaSo){video}' + - '[How to get strategic about programming languages in interviews](https://triplebyte.com/blog/you-must-choose-wisely-how-to-get-strategic-about-programming-languages-in-interviews){article}' + +--- + +# Picking a Programming Language + +--- +## Content + +It's essential to pick a suitable programming language early in your interview preparation and use it regularly when practicing. + +> 💡 Most companies let you choose any[1] language you want for coding interviews. + +--- + +#### 🧠 Stick to the language you know the best + +Languages take time to master. Rather than spending tens of hours learning a new language, it's wiser to spend your time solving practice problems and learning algorithms and data structures. + +> 📣 We'll deep-dive into the fundamentals of those soon! + +--- + +#### ⚖️ Pick a language that does more with less code + +If you're not comfortable in any particular language, learn one that lets you move fast and be effective. + +> 💡 You want to spend your time solving the problem without needing to write long words and statements. + +--- + +#### ⌨️ Java, Python or JavaScript are popular choices + +C++ and Java are old-school favorites. They provide standard libraries you can lean on to move faster but they can also be verbose[2] or make you work more to do simple things. + +Modern languages like Python and JavaScript are popular choices these days due to their succinct syntax and rich ecosystem of libraries. But keep in mind that they can be quirky![3]. + +> 🌟 Check out our courses in [Python](https://app.enki.com/skill/python), [JavaScript](https://app.enki.com/skill/javascript) or [Java](https://app.enki.com/skill/java) to level up in time for your interview. + +--- + +> 💬 What language would you use in an interview? Tell the community why you prefer it! +> +> Leave a comment or view some of the other comments for inspiration before moving on. + +--- +## Practice + +When picking a programming language, which one of these is **NOT** a great reason to learn a new language: + +??? + +- you want to use a trendy language +- you're bored with existing tech +- you want to impress the interviewer +- all the other answers + +--- +## Revision + +When picking a programming language, which one of these is a good reason to learn a new language: + +??? + +- your interviews require using that language +- you want to use a trendy language +- you want to impress the interviewer +- you're bored with existing tech + +--- +## Footnotes + +[1: Some jobs require specific languages] + +If you're applying for a domain-specific position, such as a front-end, iOS or Android engineer, you'll have to choose from specific languages on those platforms: JavaScript, Swift, Java, Kotlin, etc. + +[2: Java is verbose for interviews] +Java is verbose compared to other languages, meaning that you have to write more (or a lot more) code to perform the same task as in another language. + +For example, here's "Hello World" in Java and in Python: + +```java +class HelloWorld { + public static void main(String[] args) { + System.out.println("Hello, World!"); + } +} +``` + +```python +print("Hello World") +``` + +[3: Languages have different behaviors] +If a language doesn't support a particular data structure, ask the interviewer if you can assume it exists so you can focus on the meat of the problem. But make sure you can understand the space/time complexities of that data structure if it comes up. More on this in the next workout! \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/tech-interviews-overview/README.md b/tech-interviews/tech-interviews-core/tech-interviews-overview/README.md new file mode 100644 index 0000000000..9475bca59f --- /dev/null +++ b/tech-interviews/tech-interviews-core/tech-interviews-overview/README.md @@ -0,0 +1,16 @@ +name: Tech Interview Overview + +description: How its structured and tips for acing it + +aspects: + - introduction + +learnType: GROKKING + +insights: + - welcome-to-tech-interviews + - tech-interview-structure + - whiteboard-interviews + - take-home-interviews + - behavioral-interview + - big-companies-vs-startups \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/tech-interviews-overview/behavioral-interview.md b/tech-interviews/tech-interviews-core/tech-interviews-overview/behavioral-interview.md new file mode 100644 index 0000000000..5c841e62b4 --- /dev/null +++ b/tech-interviews/tech-interviews-core/tech-interviews-overview/behavioral-interview.md @@ -0,0 +1,101 @@ +--- +author: abd147 +category: discussion +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +links: + - '[STAR Interview Technique - Top 10 Behavioral Questions](https://www.youtube.com/watch?v=WSbN-0swDgM){video}' + - '[10 Common Behavioral Interview Questions](https://www.thebalancecareers.com/top-behavioral-interview-questions-2059618){article}' + +--- + +# Behavioral interview + +--- +## Content + +The goal here is to get a sense of how you react to stress, what your personality is like, and how you conduct yourself at work. + +Be honest but strategic in your approach. You should demonstrate what happened and what you did as a result. + +A common answering technique to use for these is the STAR method. Let's run through an example. + +--- + +### ⭐ STAR Method + +> 💡 STAR stands for: Situation, Task, Action, Result. + +Here's a sample question: + +*"Tell me about a time you were new to a job or school. How did you adapt?"* + +--- + +#### 📋 Situation: Set the scene + +*"When I started my last job, I had never worked as a full-time software engineer and knew I had a lot to learn."* + +--- + +#### 🗳️ Task: Describe your responsibility in that situation + +*"Everyone seemed to know what they were doing, and I felt somewhat lost, so I decided to put in extra time and effort to adjust to my new role."* + +--- + +#### 💪 Action: Explain the steps you took to address it + +*"I made sure to read the team docs, ask questions from senior coworkers, and take notes about what I learned. On the weekends, I spent a few hours learning Python online."* + +--- + +#### ✅ Result: What outcomes did your actions achieve + +*"Six months into the job, I became comfortable with the codebase and shipped my first feature. It was a button you press to receive an invoice for your order!* + +--- + +> 💬 Your turn! How would you answer the same question using the STAR method? Feel free to suggest other questions and engage the community! +> +> Leave a comment or view some of the other comments for inspiration before moving on. + +--- +## Practice + +What does the STAR method stand for? + +S: ??? +T: ??? +A: ??? +R: ??? + +- Situation +- Task +- Action +- Result +- Setup +- Scene +- ToDo +- Trigger +- Advice +- Adapt +- Respect +- Rampage + +--- +## Revision + +The ??? technique is most commonly used to answer behavioral questions during tech interviews. + +- STAR +- ICE +- MOON +- HAWK \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/tech-interviews-overview/big-companies-vs-startups.md b/tech-interviews/tech-interviews-core/tech-interviews-overview/big-companies-vs-startups.md new file mode 100644 index 0000000000..d5e738f136 --- /dev/null +++ b/tech-interviews/tech-interviews-core/tech-interviews-overview/big-companies-vs-startups.md @@ -0,0 +1,46 @@ +--- +author: abd147 +category: discussion +type: normal +links: + - "[Startup vs. corporate: What's best for your career?](https://angel.co/blog/startup-vs-corporate){article}" + - '[How Interviews at Startups and Big Companies Differ](https://theundercoverrecruiter.com/startups-interviews-differ/){article}' + +--- + +# Big Companies vs Startups + +--- +## Content + +The size of the company you're applying to impacts not only your career prospects but also how you should approach job search and interviews. + +--- + +#### Big company interviews are organized but rigid + +Big companies pay high salaries and have established brand names, so they get hundreds or even thousands of applicants for any job. + +This requires them to have standardized and rigorous interview processes led by a dedicated department for that purpose, i.e. the HR department. + +They'll usually explain the structure of the interview beforehand as well as give you resources to learn from and prepare. + +Applicants go through multiple interviews, and the whole process typically takes more than a month. + +--- + +#### Startup interviews are chaotic but flexible + +Startups have small teams and typically don't have a strict structure to their interviewing process. + +Everybody is wearing many hats, many times without a full-time hiring manager, and so often the process is more disorganized. + +The flip side is that it's also more casual, and there's room for you to impact the direction of the interview and show off your strengths. + +You'll probably be interviewed by people across the team and in different roles, including the CEO. The process should take a couple of weeks. + +--- + +> 💬 Where do you want to work next - a startup or a big company? Why? +> +> Leave a comment or view some of the other comments for inspiration before moving on. \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/tech-interviews-overview/take-home-interviews.md b/tech-interviews/tech-interviews-core/tech-interviews-overview/take-home-interviews.md new file mode 100644 index 0000000000..a6553ea9b2 --- /dev/null +++ b/tech-interviews/tech-interviews-core/tech-interviews-overview/take-home-interviews.md @@ -0,0 +1,83 @@ +--- +author: abd147 +category: discussion +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +links: + - '[Take-Home Projects Are the New Resume](https://coderpad.io/blog/interviewing/take-homes-are-the-new-resume/){blog}' + +--- + +# Take-home Interviews + +--- +## Content + +Take-home interviews are mini work projects that can take several hours to a few days to complete 🕟. + +The great thing about them is that you can work on them from the comfort of your home or your favorite coffee shop - with no one looking over your shoulder. + +![coding at home](https://img.enkipro.com/005c36011d13b678cd7f64c852f4c6f3.jpeg) + +The flip side is that take-home tests are usually difficult and will take a while to complete! + +> 💡 Start as soon as you can to give yourself time for any surprises or delays. + +--- + +#### 💡 Tips + +The most important aspect of a take-home project is that your solution is correct and clear to whoever reviews it. + +- Focus on **building a working prototype quickly**, then work on improving it and handling any edge cases. + +- **Take notes and add documentation**. It's important to know how to run your project but also understand your thinking and design choices. + +- If you don't complete the project, **document the attempts you took**. An honest effort will still count for something. + +- **Remember to make your code easy to follow**. Use formatting, clear names, common patterns and best practices. + +- If you have time, **add an extra feature or a visual demo** to stand out and show your passion for the job. + +--- + +> 💬 How do you think take-home interviews compare to whiteboard ones? Which do you prefer? +> +> Leave a comment or view some of the other comments for inspiration before moving on. + +--- +## Practice + +After reading the requirements for a take-home task, you get an idea for a cool animation you can add that wasn't asked for, but you think it would make you stand out. + +You remember seeing an animation library in a blog post and are eager to start researching the animation API to learn how to use it. + +When is the best moment to start working on that? + +??? + +- only after satisfying the main requirements +- before doing anything else +- whenever you feel like it + +--- +## Revision + +Sort the actions below in the order that you'd do them while completing a take-home task effectively: + +??? + +??? + +??? + +- solve the main requirements +- handle edge cases +- add extra features \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/tech-interviews-overview/tech-interview-structure.md b/tech-interviews/tech-interviews-core/tech-interviews-overview/tech-interview-structure.md new file mode 100644 index 0000000000..0f6373c9b6 --- /dev/null +++ b/tech-interviews/tech-interviews-core/tech-interviews-overview/tech-interview-structure.md @@ -0,0 +1,45 @@ +--- +author: abd147 +category: discussion +type: normal + +--- + +# Tech Interview Structure + +--- +## Content + +Although the details vary across companies and countries, the core of any technical interview is split into two parts: + +#### 1. 💻 Coding test + +The coding test covers your coding and problem-solving skills. Most of the time it's done in two steps: + +1. a phone call or online assessment using a word editor or a coding interview site. +2. The second (and typically final) step is a whiteboard interview[1] or a take-home assignment[2]. + +#### 2. 🧠 Behavioral test + +This part is more company-specific but generally focuses on your soft skills. For example - how would you behave in situations that require the ability to handle conflict or challenges. + +The rest of this workout will cover some key tips for every type of interview or test you might expect. + +> 💬 Do you have an interview coming up, or are you just interested in learning? Share your goals with the community. +> +> Leave a comment or view some of the other comments for inspiration before moving on. + +--- +## Footnotes + +[1: Whiteboard Interviews] +A whiteboard interview takes place in the interviewing company's office. It typically involves writing code and sometimes diagrams on a whiteboard while the interviewing team observes and asks you further questions. They usually take 2-4 hours. + +![whiteboard interview](https://img.enkipro.com/689d80a9bc20c4e3e27e40f5aa994c89.jpeg) +*Silicon Valley Season 1, Episode 2 Review - Culturefly +Visit* + +[2: Take home test] +A take-home interview is a mini-project a company asks you to complete. The goal is to make the interview more realistic and similar to the actual job. The time you spend ranges from 3 hours to multiple days. + +![coding at home](https://img.enkipro.com/1f324d1e3a9c27cfb1abae2404d0a1e2.jpeg) \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md b/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md new file mode 100644 index 0000000000..e380c4abfc --- /dev/null +++ b/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md @@ -0,0 +1,48 @@ +--- +author: nemanjaenki +category: must-know +type: normal +links: + - '[People in tech are happier than other industries](https://skillcrush.com/blog/happy-tech-jobs/){blog}' + - '[Developer is one of the best jobs](https://money.usnews.com/careers/best-jobs/rankings/the-100-best-jobs){article}' + - '[Developers make $110,140 on average](Software Developers made a median salary of $110,140 in 2020){article}' + +--- + +# Welcome to tech interviews! + +--- +## Content + +We're glad you're here - the right job in tech can change your life! + +> 💡 A software developer is one of the happiest and highest-paying jobs in the world. + +#### What you'll learn + +This Enki course will help you prep for a tech interview and land your dream job. + +> 💡 We cover best practices and advice to know about well before you start the actual interview process! + +The content has been reviewed by top software engineers and is optimized to teach you what matters quickly. + +You'll learn: + +1. How to navigate the **interview process** with confidence +2. Proven tips to **maximize your chances** and make you stand out +3. Techniques for mastering **technical and non-technical interview questions** +4. Effective **practice methods** (with bookmarkable lessons to re-use as you study) + +In the beginning, we'll tackle the non-technical side. + +From workout 4, we deep-dive into what will be your best prep for interview problem-solving: using data structures, algorithms and Big-O. + +> 💡 Feel free to jump to the workouts that are most relevant for you - especially if you're not in the interview process right now! And maximize the impact of every workout by leaving comments and engaging with others. + +#### Leverage other resources + +One important note - if you intend to get a coding job, you must get pretty good at coding in a specific language. + +Alongside Tech Interviews, you might want to go through our [Coding Intro](https://app.enki.com/skill/coding-intro) or our language-specific courses like [Python](https://app.enki.com/skill/python), [JavaScript](https://app.enki.com/skill/javascript) or [Java](https://app.enki.com/skill/coding-intro). + +With that - let's get started! \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/tech-interviews-overview/whiteboard-interviews.md b/tech-interviews/tech-interviews-core/tech-interviews-overview/whiteboard-interviews.md new file mode 100644 index 0000000000..ef4c3c5199 --- /dev/null +++ b/tech-interviews/tech-interviews-core/tech-interviews-overview/whiteboard-interviews.md @@ -0,0 +1,89 @@ +--- +author: abd147 +category: discussion +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +links: + - '[Example Coding Whiteboard Interview](https://www.youtube.com/watch?v=XKu_SEDAykw){video}' + - '[Whiteboard Interview Guide: The Good, The Bad, and The Ugly](https://coderpad.io/blog/interviewing/whiteboard-interview-guide/){blog}' + - '[FAQ: Simple Whiteboard Interview Questions](https://www.indeed.com/career-advice/interviewing/simple-whiteboard-interview-questions){article}' + +--- + +# Whiteboard Interviews + +--- +## Content + +In a typical whiteboard interview setting, you solve a problem on the spot by writing code or drawing diagrams on a whiteboard. Then the interviewing team observes and asks you follow-up questions. + +![whiteboard interview](https://img.enkipro.com/531ca1fb09862f631c203de8afb0a697.jpeg) + +> 💡 Some companies might ask you to bring your own laptop to code on, so make sure to prepare your dev environment if that's the case. + +The interviewers want to see how you approach a problem you haven't seen before, as well as how you collaborate with colleagues, and troubleshoot if you hit a roadblock. + +If you feel stuck or make a mistake, don't worry! + +**Take a deep breath, ask questions, and, most importantly, explain your thought process out loud.** + +> 💡 The interviewers are often more interested in learning how you approach a problem than whether you solve it successfully. + +#### 💡 Tips + +Buy a whiteboard and **simulate the whole experience at home**. + +Practice using the whiteboard space efficiently and thinking aloud when solving the questions. + +The point is to have a productive back-and-forth with your interviewer. + +There are also websites out there that let you practice mock interviews online.[1] + +> 💡 Failing to prepare is preparing to fail. + +--- + +> 💬 Have you had a whiteboard interview before? Share your experience and help the community learn! +> +> Leave a comment or view some of the other comments for inspiration before moving on. + + +--- +## Practice + +If you are stuck during a whiteboard interview, what is something you should ****NOT**** do? + +??? + +- stay quiet until you figure it out +- ask clarifying questions +- share your thinking out loud +- retrace your solution for mistakes + +--- +## Revision + +What is a good thing to do when you are stuck during a whiteboard interview? + +??? + +- all of the other answers +- debug your solution out loud +- share your thinking out loud +- ask clarifying questions + +--- +## Footnotes + +[1: Mock Interviews Online] + +[interviewing.io](https://interviewing.io) provides anonymous practice technical interviews with Google and Facebook engineers, which can lead to real jobs and internships. + +[pramp.com](https://pramp.com) pairs you up with another peer who is also a job seeker, and both of you take turns assuming the role of interviewer and interviewee. \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/what-is-big-o/README.md b/tech-interviews/tech-interviews-core/what-is-big-o/README.md new file mode 100644 index 0000000000..82917afe0a --- /dev/null +++ b/tech-interviews/tech-interviews-core/what-is-big-o/README.md @@ -0,0 +1,15 @@ +name: What's Big-O? + +description: Learn how to evaluate code efficiency + +aspects: + - introduction + +learnType: GROKKING + +insights: + - how-to-know-code-efficiency + - big-o-notation + - common-big-os-1-n-nn + - common-big-os-logn + - big-o-visualized \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/what-is-big-o/big-o-notation.md b/tech-interviews/tech-interviews-core/what-is-big-o/big-o-notation.md new file mode 100644 index 0000000000..a7d3ba5478 --- /dev/null +++ b/tech-interviews/tech-interviews-core/what-is-big-o/big-o-notation.md @@ -0,0 +1,81 @@ +--- +author: nemanjaenki +category: must-know +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +links: + - '[Big O Notation Explained: Space and Time Complexity](https://www.freecodecamp.org/news/big-o-notation-why-it-matters-and-why-it-doesnt-1674cfa8a23c/){article}' + - '[Why is the constant always dropped from big O?](https://stackoverflow.com/a/22188943){discussion}' + +--- + +# Big-O Notation + +--- +## Content + +To gauge how efficient a program is, we want to estimate how it would worsen as more data is given to it.[1] + +#### Time Complexity + +We get this by answering: **what are the most units of execution, i.e. steps our code could take when given N items?** + +Is it N steps? Or maybe N² steps? + +#### Space Complexity + +We get this by answering: **what are the most units[2] of memory our code could take when given N items?** + +Is it log(N) units? Or does it not depend on N at all? + +#### Notation + +Big-O notation is in the form of O(fn(N)), where fn(N) could be N, N², log(N), etc.[3] + +--- + +> 💡 Big-O lets you estimate code efficiency in terms of the size of the input data. + +--- +## Practice + +Time complexity counts ??? and space complexity counts ??? + +- units of execution +- units of memory +- units of electricity +- units of storage + +--- +## Revision + +Big-O measures time and space efficiency of a program in terms of the: ??? + +- size of the input data +- type of the input data +- memory of the computer +- hardware of the computer +- electricity + +--- +## Footnotes + +[1:Time Estimation] +Estimating how many seconds a program will run or how many kilobytes it would take isn't practical because factors such as the processor, the language, or the run-time environment are unpredictable and hard to measure precisely. + +Instead, Big-O denotes efficiency in terms of the input data count. + +[2: Units of Memory] +By *units*, we don't mean bytes but individual pieces. When it comes to Big-O, memory is measured in terms of the input data N. + +[3: Constant Factors] +O(N), O(2N) and O(1337N) are all O(N). Constant factors don't affect Big-O. + +But they're still important, especially if large. If you had O(100¹⁰⁰N) it would be quite a lot slower than O(N). \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/what-is-big-o/big-o-visualized.md b/tech-interviews/tech-interviews-core/what-is-big-o/big-o-visualized.md new file mode 100644 index 0000000000..e479bfc274 --- /dev/null +++ b/tech-interviews/tech-interviews-core/what-is-big-o/big-o-visualized.md @@ -0,0 +1,51 @@ +--- +author: nemanjaenki +category: must-know +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +links: + - '[Big-O Cheat Sheet](https://www.bigocheatsheet.com/){website}' + - '[Do you use Big-O complexity evaluation in the "real world"?](https://stackoverflow.com/questions/1248509/do-you-use-big-o-complexity-evaluation-in-the-real-world){discussion}' + - '[Big O: How Code Slows as Data Grows](https://www.youtube.com/watch?v=Ee0HzlnIYWQ){video}' + +--- + +# Big-O Visualized + +--- +## Content + +Here's a visualization to help you see how Big-O estimates efficiency as the size of the input data increases. + +> 💡 When estimating Big-O, think about what happens when N grows by a lot. + +The X axis is the number of elements N, and the Y axis is the number of operations it would take to process N elements: + +![big-O-notation](https://img.enkipro.com/310d38367d826937dc21c6f20b503ac9.jpeg) + +--- +## Practice + +Is O(logN) more or less efficient than O(N²)? + +??? + +- more +- less + +--- +## Revision + +Is O(logN) more or less efficient than O(N)? + +??? + +- more +- less \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/what-is-big-o/common-big-os-1-n-nn.md b/tech-interviews/tech-interviews-core/what-is-big-o/common-big-os-1-n-nn.md new file mode 100644 index 0000000000..731bb4cc3f --- /dev/null +++ b/tech-interviews/tech-interviews-core/what-is-big-o/common-big-os-1-n-nn.md @@ -0,0 +1,70 @@ +--- +author: nemanjaenki +category: must-know +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Common Big-Os: O(1), O(N), O(N²) + +--- +## Content + + +#### O(1) → Constant Time + +O(1) means your program will take the same amount of steps for 1 item and 1 million items. + +![constant-time](https://img.enkipro.com/054fe12f263d2a9a96ca609f0f91ab9e.gif) + +#### O(N) → Linear Time + +O(N) means your program will take (at most) 100 steps for 100 items. + +![linear-time](https://img.enkipro.com/c5c20d9ddbc7c5a399516dca7fc86f0b.gif) + +#### O(N²) → Quadratic Time + +O(N²) means your program will take (at most) 10,000 steps for 100 items. + +![quadratic-time](https://img.enkipro.com/a23a37b44c99fdeec956f78c6bddcebf.gif) + +> 💡 Note that the above example is actually O(F*P) where F is the number of fruit and P is the number of people. That's still quadratic time. + +--- +## Practice + +Picture a bookstore with N books, and each book has P pages. + +Finding if the word "enki" is mentioned in a given book is: ??? + +For every book, checking if another book references it is: ??? + +Opening a book on page 35 is: ??? + +- O(P) +- O(N*P) +- O(1) + +--- +## Revision + +Picture a bookstore with N books, and each book has P pages. + +Finding if the word "enki" is mentioned in a given book is: ??? + +For every book, checking if another book references it is: ??? + +Opening a book on page 35 is: ??? + +- O(P) +- O(N*P) +- O(1) diff --git a/tech-interviews/tech-interviews-core/what-is-big-o/common-big-os-logn.md b/tech-interviews/tech-interviews-core/what-is-big-o/common-big-os-logn.md new file mode 100644 index 0000000000..30a5201d55 --- /dev/null +++ b/tech-interviews/tech-interviews-core/what-is-big-o/common-big-os-logn.md @@ -0,0 +1,68 @@ +--- +author: nemanjaenki +category: must-know +type: normal +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +links: + - '[What does O(log n) mean exactly?](https://stackoverflow.com/questions/2307283/what-does-olog-n-mean-exactly){discussion}' + +--- + +# Common Big-Os: O(logN) + +--- +## Content + +Logarithmic complexity means that your programs slows down linearly as N grows exponentially.[1] + +> 💡 O(logN) is O(log₂N). The logarithmic base is 2. + +An O(log N) program will take ~7 steps for 100 items and ~20 steps for 1 million items. + +Imagine that you want to find a book named "Enki" on a shelf with many alphabetically sorted books. + +You start from the middle (i.e. from "M") and go left or right into smaller and smaller sections based on the book's alphabetical position until you eventually find it. + +With each step, you have half as many options left. + +![find-book-sorted-shelf](https://img.enkipro.com/f986408ff4d12724c6a9a678f00e46e2.gif) + +Even if the bookstore had a billion books, you could still find your book in ~30 division steps. + +--- +## Practice + +When dealing with a lot of data, O(logN) is more efficient than O(N). + +??? + +- True +- False + +--- +## Revision + +Imagine that the photos on your phone are stored in **sorted** order, with the latest one shown first. + +If N is the number of photos, what is the Big-O (worst case!) for finding any given photo you took? + +??? + +- O(logN) +- O(N²) +- O(N) +- O(1) + +--- +## Footnotes + +[1: Linear vs Exponential vs Logarithmic] + +![linear-exponential-logarithmic](https://img.enkipro.com/7ec3bf36bf85acffb99eee4ab074f2f4.png) \ No newline at end of file diff --git a/tech-interviews/tech-interviews-core/what-is-big-o/how-to-know-code-efficiency.md b/tech-interviews/tech-interviews-core/what-is-big-o/how-to-know-code-efficiency.md new file mode 100644 index 0000000000..11045ca955 --- /dev/null +++ b/tech-interviews/tech-interviews-core/what-is-big-o/how-to-know-code-efficiency.md @@ -0,0 +1,27 @@ +--- +author: nemanjaenki +category: must-know +type: normal + +--- + +# Hacking code efficiency + +--- +## Content + +Welcome to the start of the course which will help you with problems you might get asked during interviews! + +> 💡 Along with Arrays, Maps, Lists, and Trees, Big-O will give you a great foundation for language-agnostic problem-solving. + +When solving coding interview problems, the ideal solution is correct, fast and uses as little memory as possible. + +At a job, you might download perf-measuring software and estimate your program's performance in different scenarios. + +In an interview, there's not enough time to do that, plus you might be solving the problem in real time. + +A standard technique you can use instead is called the Big-O Notation. + +The next two workouts are all about how to quickly gauge the efficiency of your code and be confident that you found the optimal solution for a given problem. + +> 💡 Some companies might not directly ask you about Big-O. Nonetheless, they still want you to write the most efficient solution. Applying the thinking behind Big-O lets you quickly gauge code efficiency without much work. \ No newline at end of file From 418a96efec02a35b194bc45ea0fdadef0ef30df5 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 3 Nov 2022 11:08:59 +0100 Subject: [PATCH 267/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 44fcf54c3a..181b766276 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## November 3rd 2022 + +### Added +- [Tech Interviews - Topic - Add new topic](https://github.com/enkidevs/curriculum/pull/3124) + ## October 31st 2022 ### Changed From 175818de6540da723d874197a601cf9b8e8f55c1 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 3 Nov 2022 11:10:51 +0100 Subject: [PATCH 268/390] Update space-complexity.md --- .../tech-interviews-core/big-o-tips/space-complexity.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tech-interviews/tech-interviews-core/big-o-tips/space-complexity.md b/tech-interviews/tech-interviews-core/big-o-tips/space-complexity.md index 2ab7be759e..34222f6a54 100644 --- a/tech-interviews/tech-interviews-core/big-o-tips/space-complexity.md +++ b/tech-interviews/tech-interviews-core/big-o-tips/space-complexity.md @@ -10,7 +10,8 @@ revisionQuestion: formats: - fill-in-the-gap context: standalone - +links: + - '[Logarithms & Exponents in Complexity Analysis](https://towardsdatascience.com/logarithms-exponents-in-complexity-analysis-b8071979e847){article}' --- # Space Complexity From 57b89fbb302011da7cade9621955466bf54426fd Mon Sep 17 00:00:00 2001 From: Bernhard Stahl <84087622+stahlb@users.noreply.github.com> Date: Thu, 3 Nov 2022 12:34:56 +0200 Subject: [PATCH 269/390] Update why-are-charts-useful.md Fix typo --- .../spreadsheets-introduction/charts/why-are-charts-useful.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spreadsheets/spreadsheets-introduction/charts/why-are-charts-useful.md b/spreadsheets/spreadsheets-introduction/charts/why-are-charts-useful.md index 089855416f..e3cd1385f3 100644 --- a/spreadsheets/spreadsheets-introduction/charts/why-are-charts-useful.md +++ b/spreadsheets/spreadsheets-introduction/charts/why-are-charts-useful.md @@ -15,7 +15,7 @@ practiceQuestion: ## Content -Charts are very useful to help **understand large quantities of data** that would otherwise be difficult do individually analyze. You can represent thousands of data points in a chart. +Charts are very useful to help **understand large quantities of data** that would otherwise be difficult to individually analyze. You can represent thousands of data points in a chart. Another good example is detecting patterns and understanding results in a more clear way. @@ -34,4 +34,4 @@ Which of these are not true? - A single chart can represent thousands of data points. - Charts can be used to detect patterns and understand results in a more clear way. - Charts are good for fast analysis of large amounts of data. - \ No newline at end of file + From aba6e90b7ea66ef277b5f6027efd2b17d10a6534 Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic <n.stojanovic035@gmail.com> Date: Thu, 3 Nov 2022 11:39:11 +0100 Subject: [PATCH 270/390] Update welcome-to-tech-interviews.md --- .../tech-interviews-overview/welcome-to-tech-interviews.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md b/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md index e380c4abfc..2e94569dd3 100644 --- a/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md +++ b/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md @@ -4,8 +4,8 @@ category: must-know type: normal links: - '[People in tech are happier than other industries](https://skillcrush.com/blog/happy-tech-jobs/){blog}' - - '[Developer is one of the best jobs](https://money.usnews.com/careers/best-jobs/rankings/the-100-best-jobs){article}' - - '[Developers make $110,140 on average](Software Developers made a median salary of $110,140 in 2020){article}' + - '[Software Developer is one of the best jobs in America](https://money.usnews.com/careers/best-jobs/rankings/the-100-best-jobs){article}' + - '[Developers make $110,140 on average]([Software Developers made a median salary of $110,140 in 2020](https://money.usnews.com/careers/best-jobs/software-developer)){article}' --- @@ -45,4 +45,4 @@ One important note - if you intend to get a coding job, you must get pretty good Alongside Tech Interviews, you might want to go through our [Coding Intro](https://app.enki.com/skill/coding-intro) or our language-specific courses like [Python](https://app.enki.com/skill/python), [JavaScript](https://app.enki.com/skill/javascript) or [Java](https://app.enki.com/skill/coding-intro). -With that - let's get started! \ No newline at end of file +With that - let's get started! From 941ef556c8c492c34ab9fd1df2994431d1287045 Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic <n.stojanovic035@gmail.com> Date: Thu, 3 Nov 2022 11:40:13 +0100 Subject: [PATCH 271/390] Update welcome-to-tech-interviews.md --- .../tech-interviews-overview/welcome-to-tech-interviews.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md b/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md index 2e94569dd3..c5c38052ae 100644 --- a/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md +++ b/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md @@ -5,7 +5,7 @@ type: normal links: - '[People in tech are happier than other industries](https://skillcrush.com/blog/happy-tech-jobs/){blog}' - '[Software Developer is one of the best jobs in America](https://money.usnews.com/careers/best-jobs/rankings/the-100-best-jobs){article}' - - '[Developers make $110,140 on average]([Software Developers made a median salary of $110,140 in 2020](https://money.usnews.com/careers/best-jobs/software-developer)){article}' + - '[Developers make $110,140 on average](https://money.usnews.com/careers/best-jobs/software-developer){article}' --- From 2bda725ce1730dda2f966afc9e7828eb14c664b8 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 3 Nov 2022 12:05:56 +0100 Subject: [PATCH 272/390] Update take-home-interviews.md Minor improvements --- .../tech-interviews-overview/take-home-interviews.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tech-interviews/tech-interviews-core/tech-interviews-overview/take-home-interviews.md b/tech-interviews/tech-interviews-core/tech-interviews-overview/take-home-interviews.md index a6553ea9b2..68f00cfae1 100644 --- a/tech-interviews/tech-interviews-core/tech-interviews-overview/take-home-interviews.md +++ b/tech-interviews/tech-interviews-core/tech-interviews-overview/take-home-interviews.md @@ -11,7 +11,7 @@ revisionQuestion: - fill-in-the-gap context: standalone links: - - '[Take-Home Projects Are the New Resume](https://coderpad.io/blog/interviewing/take-homes-are-the-new-resume/){blog}' + - '[Take-Home Projects Are the New Resume](https://coderpad.io/blog/interviewing/take-homes-are-the-new-resume/){blog}' --- @@ -80,4 +80,4 @@ Sort the actions below in the order that you'd do them while completing a take-h - solve the main requirements - handle edge cases -- add extra features \ No newline at end of file +- add extra features From 3ffb4f9b30e1837e42c9285cc743a86606e72653 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 3 Nov 2022 12:07:12 +0100 Subject: [PATCH 273/390] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 181b766276..90264a7f67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,7 @@ Types of change: ### Added - [Tech Interviews - Topic - Add new topic](https://github.com/enkidevs/curriculum/pull/3124) +- [Tech Interviews - Topic - Minor improvement](https://github.com/enkidevs/curriculum/pull/3127) ## October 31st 2022 From e40ada15e2fba95c186d6f65243d009b2d6e06ed Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 3 Nov 2022 12:08:25 +0100 Subject: [PATCH 274/390] Update whiteboard-interviews.md --- .../tech-interviews-overview/whiteboard-interviews.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tech-interviews/tech-interviews-core/tech-interviews-overview/whiteboard-interviews.md b/tech-interviews/tech-interviews-core/tech-interviews-overview/whiteboard-interviews.md index ef4c3c5199..cdf5cd356a 100644 --- a/tech-interviews/tech-interviews-core/tech-interviews-overview/whiteboard-interviews.md +++ b/tech-interviews/tech-interviews-core/tech-interviews-overview/whiteboard-interviews.md @@ -58,7 +58,7 @@ There are also websites out there that let you practice mock interviews online.[ --- ## Practice -If you are stuck during a whiteboard interview, what is something you should ****NOT**** do? +If you are stuck during a whiteboard interview, what is something you should **NOT** do? ??? @@ -86,4 +86,4 @@ What is a good thing to do when you are stuck during a whiteboard interview? [interviewing.io](https://interviewing.io) provides anonymous practice technical interviews with Google and Facebook engineers, which can lead to real jobs and internships. -[pramp.com](https://pramp.com) pairs you up with another peer who is also a job seeker, and both of you take turns assuming the role of interviewer and interviewee. \ No newline at end of file +[pramp.com](https://pramp.com) pairs you up with another peer who is also a job seeker, and both of you take turns assuming the role of interviewer and interviewee. From cc5862a70d1c072fff139891cf3704c46f6dbf06 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 7 Nov 2022 09:27:04 +0100 Subject: [PATCH 275/390] Update hexadecimal-color-system.md remove type in the gap as F is considered correct whilst f is not, even tho both are correct --- web/styling/colors-tips/hexadecimal-color-system.md | 1 - 1 file changed, 1 deletion(-) diff --git a/web/styling/colors-tips/hexadecimal-color-system.md b/web/styling/colors-tips/hexadecimal-color-system.md index 072b007eb0..df6c817721 100644 --- a/web/styling/colors-tips/hexadecimal-color-system.md +++ b/web/styling/colors-tips/hexadecimal-color-system.md @@ -10,7 +10,6 @@ links: practiceQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone revisionQuestion: formats: From ae5e5bb980b1c186dfbbfe8adf8b8701d830eb1d Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 7 Nov 2022 09:31:03 +0100 Subject: [PATCH 276/390] Update CHANGELOG.md --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 90264a7f67..0ce10c03d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,12 @@ Types of change: ### Fixed + +## November 7th 2022 + +### Fixed +- [Styling - Hexadecimal color system - Remove type in the gap as some correct answers are considered wrong](https://github.com/enkidevs/curriculum/pull/3129) + ## November 3rd 2022 ### Added From 795f11941dacb76ab3066f18fb68666f8f1c3b95 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 7 Nov 2022 10:42:40 +0100 Subject: [PATCH 277/390] replace duplicate coding-intro skill link with java --- .../tech-interviews-overview/welcome-to-tech-interviews.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md b/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md index c5c38052ae..8f6d8e476d 100644 --- a/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md +++ b/tech-interviews/tech-interviews-core/tech-interviews-overview/welcome-to-tech-interviews.md @@ -43,6 +43,6 @@ From workout 4, we deep-dive into what will be your best prep for interview prob One important note - if you intend to get a coding job, you must get pretty good at coding in a specific language. -Alongside Tech Interviews, you might want to go through our [Coding Intro](https://app.enki.com/skill/coding-intro) or our language-specific courses like [Python](https://app.enki.com/skill/python), [JavaScript](https://app.enki.com/skill/javascript) or [Java](https://app.enki.com/skill/coding-intro). +Alongside Tech Interviews, you might want to go through our [Coding Intro](https://app.enki.com/skill/coding-intro) or our language-specific courses like [Python](https://app.enki.com/skill/python), [JavaScript](https://app.enki.com/skill/javascript) or [Java](https://app.enki.com/skill/java). With that - let's get started! From 906f00ff469ef101a1f63bbd0915bfcc3e25a365 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 7 Nov 2022 10:43:35 +0100 Subject: [PATCH 278/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 90264a7f67..9ce10e5770 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## November 7th 2022 + +### Fixed +- [Tech interviews - Welcome to tech interviews - Replace duplicate coding intro skill link with the java one](https://github.com/enkidevs/curriculum/pull/3130) + ## November 3rd 2022 ### Added From 56159f91a21dec136d04a77877c7b0423aec3d6f Mon Sep 17 00:00:00 2001 From: Kirill M <kirill.makharinsky@gmail.com> Date: Sat, 12 Nov 2022 13:20:08 +0000 Subject: [PATCH 279/390] Update README.md --- .../tech-interviews-core/tech-interviews-overview/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tech-interviews/tech-interviews-core/tech-interviews-overview/README.md b/tech-interviews/tech-interviews-core/tech-interviews-overview/README.md index 9475bca59f..f9c8202046 100644 --- a/tech-interviews/tech-interviews-core/tech-interviews-overview/README.md +++ b/tech-interviews/tech-interviews-core/tech-interviews-overview/README.md @@ -1,6 +1,6 @@ name: Tech Interview Overview -description: How its structured and tips for acing it +description: Intro to each interview step, and tips for acing them aspects: - introduction @@ -13,4 +13,4 @@ insights: - whiteboard-interviews - take-home-interviews - behavioral-interview - - big-companies-vs-startups \ No newline at end of file + - big-companies-vs-startups From c774bff91fb2712f944093a9278b98d218b89332 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 17 Nov 2022 12:42:57 +0100 Subject: [PATCH 280/390] Update python-data-types.md --- .../python-data-types.md | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/python/python-core/syntax-and-numerical-operators/python-data-types.md b/python/python-core/syntax-and-numerical-operators/python-data-types.md index 2ebeadea76..427acd7373 100644 --- a/python/python-core/syntax-and-numerical-operators/python-data-types.md +++ b/python/python-core/syntax-and-numerical-operators/python-data-types.md @@ -10,7 +10,6 @@ links: practiceQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone revisionQuestion: formats: @@ -74,17 +73,23 @@ Other Python data types that you'll soon learn about are: ## Practice -What class does the following return? +Match the value to its type. ```python ->>> type('Learning Python') -# <class '???'> +type(???) +# <class 'float'> + +type(???) +# <class 'str'> + +type(???) +# <class 'int'> ``` -- str -- string -- text -- data +- 15.0 +- 'Hello World' +- 17 +- True --- From ba9df7b58463688b892bdae75989dbd565bab0e7 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 17 Nov 2022 12:46:48 +0100 Subject: [PATCH 281/390] Update CHANGELOG.md --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d45017f70..48e7964c6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,10 @@ Types of change: ### Fixed +## November 17th 2022 + +### Changed +- [Python - Python Data Types - Remove type in the gap and reorder question so different correct answers cannot be evaluated as a wrong answer](https://github.com/enkidevs/curriculum/pull/3132) ## November 7th 2022 From 40480d24eac62fe2b1b21f09b439fdd56d657acd Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 7 Dec 2022 10:37:21 +0100 Subject: [PATCH 282/390] Update creating-threads.md remove unnecessary spacing between first and second output --- python/python-core/python-threading/creating-threads.md | 1 - 1 file changed, 1 deletion(-) diff --git a/python/python-core/python-threading/creating-threads.md b/python/python-core/python-threading/creating-threads.md index b048feaf27..c3d19d4ae0 100644 --- a/python/python-core/python-threading/creating-threads.md +++ b/python/python-core/python-threading/creating-threads.md @@ -50,7 +50,6 @@ firstThread.start() Which gives us this output: ```plain-text I am a thread!!! - I am a thread!!! I am a thread!!! I am a thread!!! From ad67533c0c854cfdc0ee26eb7a5a22346eb9c4b7 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 7 Dec 2022 10:38:39 +0100 Subject: [PATCH 283/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a94085f982..b0a8327a24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,11 @@ Types of change: ### Fixed +## December 7th 2022 + +### Fixed +- [Python - Creating Threads - Remove unnecessary whitespace in output code block](https://github.com/enkidevs/curriculum/pull/3134) + ## November 7th 2022 ### Fixed From f443ba74255fe0909cf73537e620a06324d927d1 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 12 Dec 2022 11:59:03 +0100 Subject: [PATCH 284/390] Update tsc-interfaces-intro.md Remove type-in-the-gap as there are multiple correct ways of answering --- .../tsc-classes-and-interfaces/tsc-interfaces-intro.md | 1 - 1 file changed, 1 deletion(-) diff --git a/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-interfaces-intro.md b/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-interfaces-intro.md index 783f914d28..28c8395fe5 100644 --- a/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-interfaces-intro.md +++ b/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-interfaces-intro.md @@ -12,7 +12,6 @@ links: practiceQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone revisionQuestion: formats: From 4bc9d41f56d5bd6d92acaa67302dc1e835ac8805 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 12 Dec 2022 13:34:30 +0100 Subject: [PATCH 285/390] Update go-data-types.md Remove type-in-the-gap as both Basic and basic are correct answers --- go/go-introduction/data-types-and-constants/go-data-types.md | 1 - 1 file changed, 1 deletion(-) diff --git a/go/go-introduction/data-types-and-constants/go-data-types.md b/go/go-introduction/data-types-and-constants/go-data-types.md index c8fd4aa3cc..325158caea 100644 --- a/go/go-introduction/data-types-and-constants/go-data-types.md +++ b/go/go-introduction/data-types-and-constants/go-data-types.md @@ -9,7 +9,6 @@ practiceQuestion: revisionQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone --- From ccc0a51f68393336534d7ef14a101c1159b034cf Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 12 Dec 2022 13:35:56 +0100 Subject: [PATCH 286/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d8b3af7ac..22758332f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## December 12th 2022 + +### Fixed +- [Go - Go Data Types - Remove type in the gap as there is more than one way to answer correctly](https://github.com/enkidevs/curriculum/pull/3136) + ## November 17th 2022 ### Changed From 0bb2e9ab77744556a7f27e4c0bf97de7c30b2412 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 12 Dec 2022 13:36:41 +0100 Subject: [PATCH 287/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d8b3af7ac..598ebdbfd4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## December 12th 2022 + +### Fixed +- [Typescript - Tsc interface intro - Remove type in the gap as there is more than one way to answer correctly](https://github.com/enkidevs/curriculum/pull/3137) + ## November 17th 2022 ### Changed From 888c6d0f3479061f7dec8fa7ac5a84ba2534d4f6 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 13 Dec 2022 11:36:24 +0100 Subject: [PATCH 288/390] Add files via upload --- .../tech-interview-questions/README.md | 31 +++++ .../binary-search-exercise/README.md | 9 ++ .../binary-search-exercise.md | 74 ++++++++++++ .../coding-with-enki/README.md | 9 ++ .../coding-with-enki/coding-with-enki.md | 55 +++++++++ .../concatenation-of-a-list/README.md | 10 ++ .../concatenation-of-a-list.md | 60 ++++++++++ .../find-the-unique-value-exercise/README.md | 9 ++ .../find-the-unique-value-exercise.md | 59 ++++++++++ .../list-permutation/README.md | 9 ++ .../list-permutation/list-permutation.md | 62 ++++++++++ .../README.md | 9 ++ ...est-non-repeating-substring-from-string.md | 76 +++++++++++++ .../longest-palindrome/README.md | 9 ++ .../longest-palindrome/longest-palindrome.md | 71 ++++++++++++ .../most-frequent-element/README.md | 9 ++ .../most-frequent-element.md | 51 +++++++++ .../move-zeroes-to-end-of-list/README.md | 9 ++ .../move-zeroes-to-end-of-list.md | 58 ++++++++++ .../nth-largest-element-from-a-list/README.md | 9 ++ .../nth-largest-element-from-a-list.md | 59 ++++++++++ .../number-to-roman-numeral/README.md | 9 ++ .../number-to-roman-numeral.md | 107 ++++++++++++++++++ .../pascals-triangle-index-return/README.md | 9 ++ .../pascals-triangle-index-return.md | 63 +++++++++++ .../pattern-matching/README.md | 9 ++ .../pattern-matching/pattern-matching.md | 65 +++++++++++ .../README.md | 9 ++ .../product-of-a-list-excluding-self.md | 60 ++++++++++ .../return-the-middle-of-a-list/README.md | 9 ++ .../return-the-middle-of-a-list.md | 62 ++++++++++ .../reversing-a-string/README.md | 9 ++ .../reversing-a-string/reversing-a-string.md | 51 +++++++++ .../reversing-words-in-a-string/README.md | 9 ++ .../reversing-words-in-a-string.md | 53 +++++++++ .../rotating-a-list/README.md | 9 ++ .../rotating-a-list/rotating-a-list.md | 59 ++++++++++ .../squares-of-sorted-lists/README.md | 9 ++ .../squares-of-sorted-lists.md | 54 +++++++++ .../steps-to-reduce-a-num-to-zero/README.md | 9 ++ .../steps-to-reduce-a-num-to-zero.md | 71 ++++++++++++ .../string-comparison/README.md | 9 ++ .../string-comparison/string-comparison.md | 74 ++++++++++++ .../string-permutation/README.md | 9 ++ .../string-permutation/string-permutation.md | 76 +++++++++++++ .../sum-of-two-strings/README.md | 9 ++ .../sum-of-two-strings/sum-of-two-strings.md | 58 ++++++++++ .../sum-target-value-from-a-list/README.md | 9 ++ .../sum-target-value-from-a-list.md | 67 +++++++++++ .../wealthiest-citizen/README.md | 9 ++ .../wealthiest-citizen/wealthiest-citizen.md | 61 ++++++++++ 51 files changed, 1863 insertions(+) create mode 100644 tech-interviews/tech-interview-questions/README.md create mode 100644 tech-interviews/tech-interview-questions/binary-search-exercise/README.md create mode 100644 tech-interviews/tech-interview-questions/binary-search-exercise/binary-search-exercise.md create mode 100644 tech-interviews/tech-interview-questions/coding-with-enki/README.md create mode 100644 tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md create mode 100644 tech-interviews/tech-interview-questions/concatenation-of-a-list/README.md create mode 100644 tech-interviews/tech-interview-questions/concatenation-of-a-list/concatenation-of-a-list.md create mode 100644 tech-interviews/tech-interview-questions/find-the-unique-value-exercise/README.md create mode 100644 tech-interviews/tech-interview-questions/find-the-unique-value-exercise/find-the-unique-value-exercise.md create mode 100644 tech-interviews/tech-interview-questions/list-permutation/README.md create mode 100644 tech-interviews/tech-interview-questions/list-permutation/list-permutation.md create mode 100644 tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/README.md create mode 100644 tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string.md create mode 100644 tech-interviews/tech-interview-questions/longest-palindrome/README.md create mode 100644 tech-interviews/tech-interview-questions/longest-palindrome/longest-palindrome.md create mode 100644 tech-interviews/tech-interview-questions/most-frequent-element/README.md create mode 100644 tech-interviews/tech-interview-questions/most-frequent-element/most-frequent-element.md create mode 100644 tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list/README.md create mode 100644 tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list/move-zeroes-to-end-of-list.md create mode 100644 tech-interviews/tech-interview-questions/nth-largest-element-from-a-list/README.md create mode 100644 tech-interviews/tech-interview-questions/nth-largest-element-from-a-list/nth-largest-element-from-a-list.md create mode 100644 tech-interviews/tech-interview-questions/number-to-roman-numeral/README.md create mode 100644 tech-interviews/tech-interview-questions/number-to-roman-numeral/number-to-roman-numeral.md create mode 100644 tech-interviews/tech-interview-questions/pascals-triangle-index-return/README.md create mode 100644 tech-interviews/tech-interview-questions/pascals-triangle-index-return/pascals-triangle-index-return.md create mode 100644 tech-interviews/tech-interview-questions/pattern-matching/README.md create mode 100644 tech-interviews/tech-interview-questions/pattern-matching/pattern-matching.md create mode 100644 tech-interviews/tech-interview-questions/product-of-a-list-excluding-self/README.md create mode 100644 tech-interviews/tech-interview-questions/product-of-a-list-excluding-self/product-of-a-list-excluding-self.md create mode 100644 tech-interviews/tech-interview-questions/return-the-middle-of-a-list/README.md create mode 100644 tech-interviews/tech-interview-questions/return-the-middle-of-a-list/return-the-middle-of-a-list.md create mode 100644 tech-interviews/tech-interview-questions/reversing-a-string/README.md create mode 100644 tech-interviews/tech-interview-questions/reversing-a-string/reversing-a-string.md create mode 100644 tech-interviews/tech-interview-questions/reversing-words-in-a-string/README.md create mode 100644 tech-interviews/tech-interview-questions/reversing-words-in-a-string/reversing-words-in-a-string.md create mode 100644 tech-interviews/tech-interview-questions/rotating-a-list/README.md create mode 100644 tech-interviews/tech-interview-questions/rotating-a-list/rotating-a-list.md create mode 100644 tech-interviews/tech-interview-questions/squares-of-sorted-lists/README.md create mode 100644 tech-interviews/tech-interview-questions/squares-of-sorted-lists/squares-of-sorted-lists.md create mode 100644 tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero/README.md create mode 100644 tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero/steps-to-reduce-a-num-to-zero.md create mode 100644 tech-interviews/tech-interview-questions/string-comparison/README.md create mode 100644 tech-interviews/tech-interview-questions/string-comparison/string-comparison.md create mode 100644 tech-interviews/tech-interview-questions/string-permutation/README.md create mode 100644 tech-interviews/tech-interview-questions/string-permutation/string-permutation.md create mode 100644 tech-interviews/tech-interview-questions/sum-of-two-strings/README.md create mode 100644 tech-interviews/tech-interview-questions/sum-of-two-strings/sum-of-two-strings.md create mode 100644 tech-interviews/tech-interview-questions/sum-target-value-from-a-list/README.md create mode 100644 tech-interviews/tech-interview-questions/sum-target-value-from-a-list/sum-target-value-from-a-list.md create mode 100644 tech-interviews/tech-interview-questions/wealthiest-citizen/README.md create mode 100644 tech-interviews/tech-interview-questions/wealthiest-citizen/wealthiest-citizen.md diff --git a/tech-interviews/tech-interview-questions/README.md b/tech-interviews/tech-interview-questions/README.md new file mode 100644 index 0000000000..6fd41cfba0 --- /dev/null +++ b/tech-interviews/tech-interview-questions/README.md @@ -0,0 +1,31 @@ +name: Tech Interview Exercises + +description: Questions to improve your coding skills. + +sections: + '0': + - binary-search-exercise + - list-permutation + - coding-with-enki + - concatenation-of-a-list + - find-the-unique-value-exercise + - longest-non-repeating-substring-from-string + - longest-palindrome + - move-zeroes-to-end-of-list + - nth-largest-element-from-a-list + - most-frequent-element + - number-to-roman-numeral + - wealthiest-citizen + - sum-target-value-from-a-list + - string-permutation + - sum-of-two-strings + - string-comparison + - steps-to-reduce-a-num-to-zero + - squares-of-sorted-lists + - rotating-a-list + - reversing-words-in-a-string + - reversing-a-string + - return-the-middle-of-a-list + - product-of-a-list-excluding-self + - pattern-matching + - pascals-triangle-index-return \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/binary-search-exercise/README.md b/tech-interviews/tech-interview-questions/binary-search-exercise/README.md new file mode 100644 index 0000000000..196c401a1a --- /dev/null +++ b/tech-interviews/tech-interview-questions/binary-search-exercise/README.md @@ -0,0 +1,9 @@ +name: Binary Search + +description: Create an algorithm that outputs the index of a number from a list using a target value. + +aspects: + - workout + +insights: + - binary-search-exercise \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/binary-search-exercise/binary-search-exercise.md b/tech-interviews/tech-interview-questions/binary-search-exercise/binary-search-exercise.md new file mode 100644 index 0000000000..de8f4e4471 --- /dev/null +++ b/tech-interviews/tech-interview-questions/binary-search-exercise/binary-search-exercise.md @@ -0,0 +1,74 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Create a function that returns the index of the given target value from a sorted numbers list. Your algorithm should use O(log n) runtime complexity. + + # Sample input list and target to use: + numbers = [-5, -3, 1, 6, 8, 11] + target = 6 + + # Sample output: + # The target value is on index 3 + + # Type your code here: + +--- + +# Binary Search + +--- + +## Content + +> 👩‍💻 Your task is to: **Create a function that returns the index of the given `target` value from a sorted `numbers` list. Your algorithm should use `O(log n)` runtime complexity.** + +For example, if the input list is: +```python +numbers = [-5, -3, 1, 6, 8, 11] +``` + +and the target value is: +```python +target = 6 +``` + +the function should return the index of the target value inside the input list: +```plain-text +3 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read this footnote[1] or review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + +--- + +## Footnotes + +[1: Hints] + +Since the input list is sorted, you can use a binary search algorithm to find the target value in the list. This algorithm has a runtime complexity of `O(log n)`, which means it can find the target value in a list of `n` elements in a time that grows logarithmically with the size of the input. + +In a binary search, you start by comparing the target value to the middle element of the list. If the target value is smaller than the middle element, you can discard the second half of the list, because the target value cannot be in that half (since the list is sorted). Otherwise, you can discard the first half of the list. + +You then repeat this process on the remaining half of the list, until you either find the target value or determine that it does not exist in the list. \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/coding-with-enki/README.md b/tech-interviews/tech-interview-questions/coding-with-enki/README.md new file mode 100644 index 0000000000..7e220e8399 --- /dev/null +++ b/tech-interviews/tech-interview-questions/coding-with-enki/README.md @@ -0,0 +1,9 @@ +name: Coding With Enki + +description: Write a program that generates a new string list from a numbers list using a set of rules. + +aspects: + - workout + +insights: + - coding-with-enki \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md b/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md new file mode 100644 index 0000000000..5799707636 --- /dev/null +++ b/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md @@ -0,0 +1,55 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Write a program that generates a new string list from the given numbers list. + + # Conditions + If a number is divisible by both 2 and 4, replace it with "I'm". + If a number is not divisible by any number but 1 or itself (i.e. a prime number), replace it with "Enki". + If a number is divisible by 7, replace with "with". + If a number is divisible by both 3 and 5, replace with "coding". + + # Sample lists to use: + numbers = [12, 21, 15, 17] + + # Type your code here: + +--- + +# Coding With Enki + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a program that generates a new string list from the given `numbers` list.** + +Conditions: + - If a number is divisible by both 2 and 4, replace it with "I'm". + - If a number is not divisible by any number but 1 or itself (i.e. a prime number), replace it with "Enki". + - If a number is divisible by 7, replace with "with". + - If a number is divisible by both 3 and 5, replace with "coding". + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/tech-interviews/tech-interview-questions/concatenation-of-a-list/README.md b/tech-interviews/tech-interview-questions/concatenation-of-a-list/README.md new file mode 100644 index 0000000000..ab09b51b79 --- /dev/null +++ b/tech-interviews/tech-interview-questions/concatenation-of-a-list/README.md @@ -0,0 +1,10 @@ +name: Concatenation of a List + +description: Write a function that takes in a list of numbers, concatenates it to itself, and returns it as a new list. + + +aspects: + - workout + +insights: + - concatenation-of-a-list \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/concatenation-of-a-list/concatenation-of-a-list.md b/tech-interviews/tech-interview-questions/concatenation-of-a-list/concatenation-of-a-list.md new file mode 100644 index 0000000000..9e9077d2c7 --- /dev/null +++ b/tech-interviews/tech-interview-questions/concatenation-of-a-list/concatenation-of-a-list.md @@ -0,0 +1,60 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Write a function that takes in a list of numbers, concatenates it to itself, and returns it as a new list. + + # Sample program: + numbers = [7, 3, 7] + nums = build_nums_list(numbers) + # nums should become [7, 3, 7, 7, 3, 7] + + # Type your code here: + +--- + +# List Concatenation + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a function that takes in a list of numbers, concatenates it to itself, and returns it as a new list.** + +For instance, if the input list is: +```python +numbers = [7, 3, 7] +``` + +the function should return: + +```python +build_nums_list(numbers) +# [7, 3, 7, 7, 3, 7] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + + + diff --git a/tech-interviews/tech-interview-questions/find-the-unique-value-exercise/README.md b/tech-interviews/tech-interview-questions/find-the-unique-value-exercise/README.md new file mode 100644 index 0000000000..0097225ef8 --- /dev/null +++ b/tech-interviews/tech-interview-questions/find-the-unique-value-exercise/README.md @@ -0,0 +1,9 @@ +name: Find the unique value + +description: Find the unique value in a list. + +aspects: + - workout + +insights: + - find-the-unique-value-exercise \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/find-the-unique-value-exercise/find-the-unique-value-exercise.md b/tech-interviews/tech-interview-questions/find-the-unique-value-exercise/find-the-unique-value-exercise.md new file mode 100644 index 0000000000..4af21855e2 --- /dev/null +++ b/tech-interviews/tech-interview-questions/find-the-unique-value-exercise/find-the-unique-value-exercise.md @@ -0,0 +1,59 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Write a function that finds the unique value from a list of numbers. The function should have linear complexity. + + # Sample program: + numbers = [13, 13, 44, 44, 1, 1, 7, 7, 9] + find_unique(numbers) + # 9 + + # Type your code here: + +--- + +# Find the Unique Value + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a function that finds the unique value from a list of numbers. The function should have linear complexity.** + +For instance, if the input list is: + +```python +numbers = [13, 13, 44, 44, 1, 1, 7, 7, 9] +``` + +the function should return `9` since it is the only element in the list that does not have a duplicate: + +```python +find_unique(numbers) +# 9 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + diff --git a/tech-interviews/tech-interview-questions/list-permutation/README.md b/tech-interviews/tech-interview-questions/list-permutation/README.md new file mode 100644 index 0000000000..bc13f9095c --- /dev/null +++ b/tech-interviews/tech-interview-questions/list-permutation/README.md @@ -0,0 +1,9 @@ +name: List Permutations + +description: Write a function that finds all permutations of a list. + +aspects: + - workout + +insights: + - list-permutation \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/list-permutation/list-permutation.md b/tech-interviews/tech-interview-questions/list-permutation/list-permutation.md new file mode 100644 index 0000000000..c1a25f66b1 --- /dev/null +++ b/tech-interviews/tech-interview-questions/list-permutation/list-permutation.md @@ -0,0 +1,62 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Write a function that takes in list of intengers and returns a new list for each possible permutation. + + # Sample program: + # ints = [4, 7] + # [4, 7] + # [7, 4] + + # Sample list to use: + ints = [4, 0, 1, 2, 3, 5] + + # Type your code here: + +--- + +# List Permutations + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a function that takes in list of intengers and returns a new list for each possible permutation.** + +For instance, if the input list is +```python +ints = [4, 0, 7] +``` +the function should return: +```python +# [4, 0, 7] +# [4, 7, 0] +# [0, 7, 4] +# [0, 4, 7] +# [7, 4, 0] +# [7, 0, 4] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/README.md b/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/README.md new file mode 100644 index 0000000000..da3fe9ff73 --- /dev/null +++ b/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/README.md @@ -0,0 +1,9 @@ +name: Longest substring with no repeating characters. + +description: Find the longest substring with no repeating characters from a given string. + +aspects: + - workout + +insights: + - longest-non-repeating-substring-from-string \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string.md b/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string.md new file mode 100644 index 0000000000..9449d201a9 --- /dev/null +++ b/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string.md @@ -0,0 +1,76 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Write a function that finds and returns the longest substring with no repeating characters from a given string. + + # Sample program: + string1 = "asgegsagefasg" + find_longest_substring(string1) + # "gef" + + # Sample strings: + string1 = "aaaaaa" + string2 = "asdeavfeva" + + # Type your code here: + +--- + +# Find the Longest Substring With No Repeating Letters + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a function that returns the longest substring with no repeating characters from a given `string`.** + +Here is an example of how the function can be used: + +```python +string1 = "asgegsagefasg" +find_longest_substring(string1) + +# "gef" + +string2 = "abcabcbb" +find_longest_substring(string2) + +# "abc" +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read this footnote[1] or review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + + +--- + +## Footnotes + +[1: Hints] + +A substring is a contiguous sequence of characters within a string. + +For example, the substrings of the string "abcde" are: + +"a", "ab", "abc", "abcd", "abcde", "b", "bc", "bcd", "bcde", "c", "cd", "cde", "d", "de", and "e". \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/longest-palindrome/README.md b/tech-interviews/tech-interview-questions/longest-palindrome/README.md new file mode 100644 index 0000000000..002fd913b9 --- /dev/null +++ b/tech-interviews/tech-interview-questions/longest-palindrome/README.md @@ -0,0 +1,9 @@ +name: Longest Palindrome + +description: Find and return the longest possible palindrome from a given string. + +aspects: + - workout + +insights: + - longest-palindrome \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/longest-palindrome/longest-palindrome.md b/tech-interviews/tech-interview-questions/longest-palindrome/longest-palindrome.md new file mode 100644 index 0000000000..802123f6ff --- /dev/null +++ b/tech-interviews/tech-interview-questions/longest-palindrome/longest-palindrome.md @@ -0,0 +1,71 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Find the longest palindrome from the given letters string. + + # Sample program: + letters = "abbbbcceeezdda" + find_longest_palindrome(letters) + # "bbbb" + + # Type your code here: + +--- + +# Longest Palindrome + +--- + +## Content + +> 👩‍💻 Your task is to: **Find the longest palindrome from the given `letters` string.** + +Sample program: +```python +letters = "abbbbcceeezdda" +find_longest_palindrome(letters) + +#"bbbb" +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read this footnote[1] or review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + +--- + +## Footnotes + +[1: Hints] + +The time complexity of this task is *O(N)* where *N* is the length of our `letters` string. + +The Space complexity is *O(1)* as *s* is a fixed size of the alphabet. + +A palindrome is a word or phrase that reads the same forwards and backwards. I.e. **civic**, **level**, **madam**, and so on... + +In an even palindrome, each letter has an equal partner on the opposite side. + +In an odd palindrome, there is a single non-partnered letter in the middle of the pallindrome. + +If each letter occurs X times, we know that x // 2 * 2 is the number of letters that can be partnered. diff --git a/tech-interviews/tech-interview-questions/most-frequent-element/README.md b/tech-interviews/tech-interview-questions/most-frequent-element/README.md new file mode 100644 index 0000000000..a88676f731 --- /dev/null +++ b/tech-interviews/tech-interview-questions/most-frequent-element/README.md @@ -0,0 +1,9 @@ +name: Most frequent element. + +description: Return the most frequent element from a list. + +aspects: + - workout + +insights: + - most-frequent-element \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/most-frequent-element/most-frequent-element.md b/tech-interviews/tech-interview-questions/most-frequent-element/most-frequent-element.md new file mode 100644 index 0000000000..c0cf1712c9 --- /dev/null +++ b/tech-interviews/tech-interview-questions/most-frequent-element/most-frequent-element.md @@ -0,0 +1,51 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return the most frequent element from a given numbers list. The time complexity should be better than O(n logn). + + # Sample lists to use: + numbers = [1, 1, 8, 6, 4, 13, 1, 7, 8, 6] + + # Type your code here: + +--- + +# Most Frequent Element + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the most frequent element from the `numbers` list. The time complexity should be better than `O(n logn)`.** + +Sample program: +```python +numbers = [1, 1, 8, 6, 4, 13, 1, 7, 8, 6] +most_frequent_element(numbers) +# 1 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can alway review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + diff --git a/tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list/README.md b/tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list/README.md new file mode 100644 index 0000000000..0d448465e5 --- /dev/null +++ b/tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list/README.md @@ -0,0 +1,9 @@ +name: Moving 0's to the end of a list + +description: Move all 0's to the end of the given list, whilst maintaining the relative order of other numbers. + +aspects: + - workout + +insights: + - move-zeroes-to-end-of-list \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list/move-zeroes-to-end-of-list.md b/tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list/move-zeroes-to-end-of-list.md new file mode 100644 index 0000000000..bbdd81a98b --- /dev/null +++ b/tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list/move-zeroes-to-end-of-list.md @@ -0,0 +1,58 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Move all 0's to the end of the given list, whilst maintaining the relative order of other numbers. Try to solve this in-place; by not creating a new list. + + # Input + numbers = [1, 2, 0, 3, 0, 4, 0, 5] + # Function + move_zeros(numbers) + # [1, 2, 3, 4, 5, 0, 0, 0] + + # Type your code here: + +--- + +# Move Zeroes to the End of a List + +--- + +## Content + +> 👩‍💻 Your task is to: **Move all 0's to the end of the given list, whilst maintaining the relative order of other numbers. Try to solve this in-place; by not creating a new list.** + +Sample program: +```python +# Input +numbers = [1, 2, 0, 3, 0, 4, 0, 5] + +# Function +move_zeros(numbers) + +# [1, 2, 3, 4, 5, 0, 0, 0] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + diff --git a/tech-interviews/tech-interview-questions/nth-largest-element-from-a-list/README.md b/tech-interviews/tech-interview-questions/nth-largest-element-from-a-list/README.md new file mode 100644 index 0000000000..0140b4a17e --- /dev/null +++ b/tech-interviews/tech-interview-questions/nth-largest-element-from-a-list/README.md @@ -0,0 +1,9 @@ +name: Largest Element + +description: Return the Nth Largest Element From a List + +aspects: + - workout + +insights: + - nth-largest-element-from-a-list \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/nth-largest-element-from-a-list/nth-largest-element-from-a-list.md b/tech-interviews/tech-interview-questions/nth-largest-element-from-a-list/nth-largest-element-from-a-list.md new file mode 100644 index 0000000000..b2283188ad --- /dev/null +++ b/tech-interviews/tech-interview-questions/nth-largest-element-from-a-list/nth-largest-element-from-a-list.md @@ -0,0 +1,59 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return the nth largest element from the numbers list. + + # Sample variables to use: + numbers = [1, 4, 2, 8, 7, 5] + n = 3 + + # nth Largest (3rd largest) + # 5 + + # Type your code here: + +--- + +# Return the Nth Largest Element From a List + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the nth largest element from a list.** + +Sample program: +```python +# Given list +numbers = [1, 4, 2, 8, 7, 5] + +# Given n +n = 3 + +# nth Largest (3rd largest) +# 5 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/tech-interviews/tech-interview-questions/number-to-roman-numeral/README.md b/tech-interviews/tech-interview-questions/number-to-roman-numeral/README.md new file mode 100644 index 0000000000..38743fead1 --- /dev/null +++ b/tech-interviews/tech-interview-questions/number-to-roman-numeral/README.md @@ -0,0 +1,9 @@ +name: Number To Roman Numeral Converter + +description: Given a list of numbers, convert them to Roman numerals. + +aspects: + - workout + +insights: + - number-to-roman-numeral \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/number-to-roman-numeral/number-to-roman-numeral.md b/tech-interviews/tech-interview-questions/number-to-roman-numeral/number-to-roman-numeral.md new file mode 100644 index 0000000000..c112021e5f --- /dev/null +++ b/tech-interviews/tech-interview-questions/number-to-roman-numeral/number-to-roman-numeral.md @@ -0,0 +1,107 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Generate Roman numerals from a given list of numbers. + + # Sample list to use: + numbers = [1, 23, 44, 59, 1111, 127, 999] + + # Type your code here: + +--- + +# Number to Roman Numeral + +--- + +## Content + +> 👩‍💻 Your task is to: **Generate Roman numerals from a given list of numbers.** + +Roman numeral symbols are: + +| Roman Numeral | Integer | +|:-------------:|:-------:| +| I | 1 | +| V | 5 | +| X | 10 | +| L | 50 | +| C | 100 | +| D | 500 | +| M | 1000 | + +**Note: There are several rules Roman numerals follow. Take a look at this note[1].** + +Sample list to use: +```python +numbers = [1, 23, 44, 59, 1111, 127, 999] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comment section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + +--- + +## Footnotes + +[1: Notes] + +- When a value increases, up to 3 times, the symbol is added to itself. + +If the value increases more, you subtract from the next highest numeral: + +| Roman Numeral | Integer | +|:-------------:|:-------:| +| I | 1 | +| II | 2 | +| III | 3 | +| IV | 4 | +| V | 5 | +| VI | 6 | +| VII | 7 | +| VIII | 8 | +| IX | 9 | +| X | 10 | + +- When a symbol of smaller value is after a symbol of a greater value, they are added together. If the smaller symbol is before it, they are subtracted. + +| Number | Calculation | Result | +|:------:|:-----------:|:------:| +| IV | V - I | 4 | +| VI | V + I | 6 | + +Symbols like V, L, D never repeat. That is beacuse VV is X, LL is C, DD is M. + +From symbols V and X you can only subtract I, from symbols L, C and M, you can only subtract X. + +Here's a sample of wrong vs correct way of writting numbers + +| Sample | ❌ | ✅ | +|:------:|:------:|:---:| +| 41 | XXXXI | XLI | +| 100 | LL | C | +| 59 | LVIIII | LIX | +| 7 | IIIX | VII | +| 111 | CVVI | CXI | +| 400 | CCCC | CD | \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/pascals-triangle-index-return/README.md b/tech-interviews/tech-interview-questions/pascals-triangle-index-return/README.md new file mode 100644 index 0000000000..498d7cce7c --- /dev/null +++ b/tech-interviews/tech-interview-questions/pascals-triangle-index-return/README.md @@ -0,0 +1,9 @@ +name: Pascals Triangles Index + +description: Return the nth row of Pascal's triangle through its index. + +aspects: + - workout + +insights: + - pascals-triangle-index-return \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/pascals-triangle-index-return/pascals-triangle-index-return.md b/tech-interviews/tech-interview-questions/pascals-triangle-index-return/pascals-triangle-index-return.md new file mode 100644 index 0000000000..79a8ab92e2 --- /dev/null +++ b/tech-interviews/tech-interview-questions/pascals-triangle-index-return/pascals-triangle-index-return.md @@ -0,0 +1,63 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return the nth row of the Pascal's triangle. + + # If rowIndex = 4 (5th row), you return: + # [1, 4, 6, 4, 1] + # If rowIndex = 1, you return: + # [1, 1] + + # Type your code here: + +--- + +# Pascals Triangles Index + +--- + +## Content + +> 👩‍💻 Your task is to: **Create a function that returns the nth row of the Pascal's triangle.** + +For instance, if: +```python +rowIndex = 4 # (5th row) +``` + +you return: +```python +# [1, 4, 6, 4, 1] +``` + +> The Pascal triangle is a triangular array of binomial coefficients. + +![pascal-triangle](https://img.enkipro.com/9ca1eb25c5fc393b831db1556dcad889.png) + +Here is a gif from Wikipedia that demonstrates how each value is calculated: + +![wiki-explanation](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/tech-interviews/tech-interview-questions/pattern-matching/README.md b/tech-interviews/tech-interview-questions/pattern-matching/README.md new file mode 100644 index 0000000000..4fcc0d1e6c --- /dev/null +++ b/tech-interviews/tech-interview-questions/pattern-matching/README.md @@ -0,0 +1,9 @@ +name: Pattern Match + +description: Confirm if the pattern of the given strings follows the same pattern of the `pattern` variable. + +aspects: + - workout + +insights: + - pattern-matching \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/pattern-matching/pattern-matching.md b/tech-interviews/tech-interview-questions/pattern-matching/pattern-matching.md new file mode 100644 index 0000000000..54bfe82791 --- /dev/null +++ b/tech-interviews/tech-interview-questions/pattern-matching/pattern-matching.md @@ -0,0 +1,65 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Confirm if the pattern of the given strings follow the same pattern of the pattern variable. + + # Sample program: + pattern = 'aabbc' + str1 = 'meow meow woof woof oink' + str2 = 'meow woof oink' + + check_pattern(pattern, str1) + # True + + check_pattern(pattern, str2) + # False + + + # Type your code here: + +--- + +# Pattern Matching + +--- + +## Content + +> 👩‍💻 Your task is to: **Confirm if the pattern of the given strings follow the same pattern of the `pattern` variable.** + +Example input/output: +```python +pattern = 'aabbc' +str1 = 'meow meow woof woof oink' +str2 = 'meow woof oink' + +check_pattern(pattern, str1) +# True + +check_pattern(pattern, str2) +# False +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read through the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/tech-interviews/tech-interview-questions/product-of-a-list-excluding-self/README.md b/tech-interviews/tech-interview-questions/product-of-a-list-excluding-self/README.md new file mode 100644 index 0000000000..3842d6610b --- /dev/null +++ b/tech-interviews/tech-interview-questions/product-of-a-list-excluding-self/README.md @@ -0,0 +1,9 @@ +name: Product of a List Excluding Self + +description: Implement a function that returns a new list where the current element is the product of all elements in the given list excluding itself. + +aspects: + - workout + +insights: + - product-of-a-list-excluding-self \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/product-of-a-list-excluding-self/product-of-a-list-excluding-self.md b/tech-interviews/tech-interview-questions/product-of-a-list-excluding-self/product-of-a-list-excluding-self.md new file mode 100644 index 0000000000..1df1f07fc7 --- /dev/null +++ b/tech-interviews/tech-interview-questions/product-of-a-list-excluding-self/product-of-a-list-excluding-self.md @@ -0,0 +1,60 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Implement a function that returns a new list such that the current element is the product of all elements in the given list excluding itself. The function should have a runtime complexity of O(n). + + # Sample list: + numbers = [1, 3, 4, 6, 7] + + # Sample return: + product_list(numbers) + # [504, 168, 126, 84, 72] + + # Type your code here: + +--- + +# Product of List Excluding Self + +--- + +## Content + +> 👩‍💻 Your task is to: **Implement a function that returns a new list such that the current element is the product of all elements in the `numbers` list excluding itself. The function should have a runtime complexity of `O(n)`.** + +For instance, if the input list: +```python +numbers = [1, 3, 4, 6] +``` + +you would return: +```python +product_list(numbers) + +# [72, 24, 18, 12] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + diff --git a/tech-interviews/tech-interview-questions/return-the-middle-of-a-list/README.md b/tech-interviews/tech-interview-questions/return-the-middle-of-a-list/README.md new file mode 100644 index 0000000000..3ce0f29c2d --- /dev/null +++ b/tech-interviews/tech-interview-questions/return-the-middle-of-a-list/README.md @@ -0,0 +1,9 @@ +name: Return the Middle Element from a List + +description: Returns the middle element of a list. + +aspects: + - workout + +insights: + - return-the-middle-of-a-list \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/return-the-middle-of-a-list/return-the-middle-of-a-list.md b/tech-interviews/tech-interview-questions/return-the-middle-of-a-list/return-the-middle-of-a-list.md new file mode 100644 index 0000000000..bd896534b8 --- /dev/null +++ b/tech-interviews/tech-interview-questions/return-the-middle-of-a-list/return-the-middle-of-a-list.md @@ -0,0 +1,62 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Create a function that finds and returns the middle element of a list. If the list has 2 middle elements, return the first one. + + # Sample program: + numbers = [1, 2, 3, 4, 5, 6] + result = find_middle(numbers) + + # result should be 3 + + numbers = [1, 2, 3, 4, 5, 6, 7] + result = find_middle(numbers) + + # result should be 4 + + # Type your code here: + +--- + +# Return the Middle of a List + +--- + +## Content + +> 👩‍💻 Your task is to: **Implement a function that returns the middle element of a `numbers` list. If the list has 2 middle elements, return the first one.** + +Sample program: +```python +numbers = [1, 2, 3, 4, 5, 6] +find_middle(numbers) +# 3 + +numbers = [1, 2, 3, 4, 5, 6, 7] +find_middle(numbers) +# 4 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/tech-interviews/tech-interview-questions/reversing-a-string/README.md b/tech-interviews/tech-interview-questions/reversing-a-string/README.md new file mode 100644 index 0000000000..efb43efdc8 --- /dev/null +++ b/tech-interviews/tech-interview-questions/reversing-a-string/README.md @@ -0,0 +1,9 @@ +name: Reversing a String + +description: Reverse the order of characters in a given string. + +aspects: + - workout + +insights: + - reversing-a-string \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/reversing-a-string/reversing-a-string.md b/tech-interviews/tech-interview-questions/reversing-a-string/reversing-a-string.md new file mode 100644 index 0000000000..ad5f3819ec --- /dev/null +++ b/tech-interviews/tech-interview-questions/reversing-a-string/reversing-a-string.md @@ -0,0 +1,51 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Create a function that reverses the given words string. Modify the given input string list in-place with O(1) memory. + + # Sample lists to use: + words = ['H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'] + + # Type your code here: + +--- + +# Reverse a String + +--- + +## Content + +> 👩‍💻 Your task is to: **Create a function that reverses the given `words` string. Modify the given input string list in-place with `O(1)` memory.** + +Sample program: +```python +words = ['H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'] +reverse_string(words) + +# ['d', 'l', 'r', 'o', 'w', 'o', 'l', 'l', 'e', 'H'] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/tech-interviews/tech-interview-questions/reversing-words-in-a-string/README.md b/tech-interviews/tech-interview-questions/reversing-words-in-a-string/README.md new file mode 100644 index 0000000000..e4af354840 --- /dev/null +++ b/tech-interviews/tech-interview-questions/reversing-words-in-a-string/README.md @@ -0,0 +1,9 @@ +name: Reversing words in a string + +description: Reverse the order of characters in a string while preserving the space and initial order between words. + +aspects: + - workout + +insights: + - reversing-words-in-a-string \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/reversing-words-in-a-string/reversing-words-in-a-string.md b/tech-interviews/tech-interview-questions/reversing-words-in-a-string/reversing-words-in-a-string.md new file mode 100644 index 0000000000..5adea1b368 --- /dev/null +++ b/tech-interviews/tech-interview-questions/reversing-words-in-a-string/reversing-words-in-a-string.md @@ -0,0 +1,53 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Reverse the order of characters in the given sentence while preserving the whitespace and initial order between words. + + # Sample sentence to reverse: + sentence = "Enki is the god of knowledge, water, crafts and creation" + reverse_sentence(sentence) + + # noitaerc dna stfarc ,retaw ,egdelwonk fo dog eht si iknE + # Type your code here: + +--- + +# Reversing Words in a String + +--- + +## Content + +> 👩‍💻 Your task is to: **Reverse the order of characters in the given string while preserving the whitespace and initial order between words.** + +Sample program: +```python +sentence = "You passed the test" +reverse_sentence(sentence) + +# "uoY dessap eht tset" +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/tech-interviews/tech-interview-questions/rotating-a-list/README.md b/tech-interviews/tech-interview-questions/rotating-a-list/README.md new file mode 100644 index 0000000000..ebb692c5db --- /dev/null +++ b/tech-interviews/tech-interview-questions/rotating-a-list/README.md @@ -0,0 +1,9 @@ +name: Rotating a list + +description: Rotate the given list to the right by n steps. + +aspects: + - workout + +insights: + - rotating-a-list \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/rotating-a-list/rotating-a-list.md b/tech-interviews/tech-interview-questions/rotating-a-list/rotating-a-list.md new file mode 100644 index 0000000000..7d6a64f333 --- /dev/null +++ b/tech-interviews/tech-interview-questions/rotating-a-list/rotating-a-list.md @@ -0,0 +1,59 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Rotate the given numbers list to the right by n steps. Could you solve this in-place using O(1) extra space? + + # Sample variables to use: + numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] + n = 4 + + # Result: + rotate_list(numbers, n) + + # [6, 7, 8, 9, 1, 2, 3, 4, 5] + + # Type your code here: + +--- + +# Find the Non-Duplicate Value + +--- + +## Content + +> 👩‍💻 Your task is to: **Rotate the given `numbers` list to the right by `n` steps. Could you solve this in-place using `O(1)` extra space?** + +Sample variables to use: +```python +numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] +n = 4 + +rotate_list(numbers, n) + +# [6, 7, 8, 9, 1, 2, 3, 4, 5] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/squares-of-sorted-lists/README.md b/tech-interviews/tech-interview-questions/squares-of-sorted-lists/README.md new file mode 100644 index 0000000000..34011de3c9 --- /dev/null +++ b/tech-interviews/tech-interview-questions/squares-of-sorted-lists/README.md @@ -0,0 +1,9 @@ +name: Squares of a Sorted List + +description: Create an algorithm that returns squared values for each element of the given list. + +aspects: + - workout + +insights: + - squares-of-sorted-lists \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/squares-of-sorted-lists/squares-of-sorted-lists.md b/tech-interviews/tech-interview-questions/squares-of-sorted-lists/squares-of-sorted-lists.md new file mode 100644 index 0000000000..6ec6a9e2ee --- /dev/null +++ b/tech-interviews/tech-interview-questions/squares-of-sorted-lists/squares-of-sorted-lists.md @@ -0,0 +1,54 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return a list of squares from a given non-squared list of integers. The new list should be sorted in an ascending order. Try to find an O(n) solution. + + # Sample lists to use: + numbers = [-9, -3, 0, 1, 3, 4, 9, 12] + sort_squares(numbers) + + # [0, 1, 9, 9, 16, 81, 81, 144] + + # Type your code here: +--- + +# Squares of a Sorted List + +--- + +## Content + +> 👩‍💻 Your task is to: **Return a list of squares from a given non-squared list of integers. The new list should be sorted in an ascending order. Try to find an `O(n)` solution.** + +Sample program: + +```python +numbers = [-9, -3, 0, 1, 3, 4, 9, 12] +sort_squares(numbers) + +# [0, 1, 9, 9, 16, 81, 81, 144] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero/README.md b/tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero/README.md new file mode 100644 index 0000000000..a1196a0e8a --- /dev/null +++ b/tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero/README.md @@ -0,0 +1,9 @@ +name: Number of steps to reduce a number to zero + +description: Return the number of steps necessary to reduce a number to zero. + +aspects: + - workout + +insights: + - steps-to-reduce-a-num-to-zero \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero/steps-to-reduce-a-num-to-zero.md b/tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero/steps-to-reduce-a-num-to-zero.md new file mode 100644 index 0000000000..cb043c48f3 --- /dev/null +++ b/tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero/steps-to-reduce-a-num-to-zero.md @@ -0,0 +1,71 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return the number of steps needed to reduce a given number to 0. + + # Rules: If the current number is even, you divide it by 2, if it is odd, you reduce it by 1. + + # Sample numbers to use: + num1 = 314 + num2 = 7 + num3 = 15 + num4 = 555 + + # Type your code here: + +--- + +# Steps to Reduce a Number to Zero + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the number of steps needed to reduce a given number to 0.** + +Rules: +- If the current number is even, you divide it by 2, +- if it is odd, you reduce it by 1. + +Sample program: +```python +num1 = 314 +reduce_to_zero(num1) +# 13 + +num2 = 7 +reduce_to_zero(num2) +# 5 + +num3 = 15 +reduce_to_zero(num3) +# 7 + +num4 = 555 +reduce_to_zero(num4) +# 14 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/tech-interviews/tech-interview-questions/string-comparison/README.md b/tech-interviews/tech-interview-questions/string-comparison/README.md new file mode 100644 index 0000000000..d45d7bb3b0 --- /dev/null +++ b/tech-interviews/tech-interview-questions/string-comparison/README.md @@ -0,0 +1,9 @@ +name: String Comparison + +description: Given a string of characters, check if any of the given words can be constructed using those characters. + +aspects: + - workout + +insights: + - string-comparison \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/string-comparison/string-comparison.md b/tech-interviews/tech-interview-questions/string-comparison/string-comparison.md new file mode 100644 index 0000000000..9f5130f12a --- /dev/null +++ b/tech-interviews/tech-interview-questions/string-comparison/string-comparison.md @@ -0,0 +1,74 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return true if the characters from the given letters string can be used to construct any of the word strings; otherwise return false. You can use each letter only once. + + # Sample lists to use: + letters = 'aaabnn' + word1 = 'banana' + word2 = 'apple' + word3 = 'ban' + word4 = 'bananas' + + print(can_construct_words(letters, word1)) + # True + print(can_construct_words(letters, word2)) + # False + print(can_construct_words(letters, word3)) + # True + print(can_construct_words(letters, word4)) + # False + + # Type your code here: + +--- + +# String Comparison + +--- + +## Content + +> 👩‍💻 Your task is to: **Check if the characters in the `letters` string can be used to construct any of the `word` strings without repeating any letters. Return `true` if any of the `word` strings can be constructed, and `false` otherwise.** + +Sample strings to use: +```python +letters = 'aaabnn' +word1 = 'banana' +word2 = 'apple' +word3 = 'ban' +word4 = 'bananas' + +print(can_construct_words(letters, word1)) +# True +print(can_construct_words(letters, word2)) +# False +print(can_construct_words(letters, word3)) +# True +print(can_construct_words(letters, word4)) +# False +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/tech-interviews/tech-interview-questions/string-permutation/README.md b/tech-interviews/tech-interview-questions/string-permutation/README.md new file mode 100644 index 0000000000..0a471ada01 --- /dev/null +++ b/tech-interviews/tech-interview-questions/string-permutation/README.md @@ -0,0 +1,9 @@ +name: String Permutation + +description: Given a substring and some strings, determine if any permutation of the given substring is located inside the strings. + +aspects: + - workout + +insights: + - string-permutation \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/string-permutation/string-permutation.md b/tech-interviews/tech-interview-questions/string-permutation/string-permutation.md new file mode 100644 index 0000000000..aa9827608d --- /dev/null +++ b/tech-interviews/tech-interview-questions/string-permutation/string-permutation.md @@ -0,0 +1,76 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return true if a permutation of the given substring is located inside the given strings. + + # Sample lists to use: + subStr = 'ao' + str1 = 'boat' + str2 = 'broader' + str3 = 'milk' + + print(has_permutation_in_string(subStr, str1)) + # True + print(has_permutation_in_string(subStr, str2)) + # True + print(has_permutation_in_string(subStr, str3)) + # False + + # Type your code here: + +--- + +# String Permutation + +--- + +## Content + +> 👩‍💻 Your task is to: **Return `true` if a permutation of the given substring can be found within any of the given strings.** + +Sample variables to use: +```python +subStr = 'ao' +str1 = 'boat' +str2 = 'broader' +str3 = 'milk' + +print(has_permutation_in_string(subStr, str1)) +# True +print(has_permutation_in_string(subStr, str2)) +# True +print(has_permutation_in_string(subStr, str3)) +# False +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read this footnote[1] or review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + +--- + +## Footnotes + +[1: Hints] + +You can sort the strings and substrings, then check if the substring is located inside the strings. \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/sum-of-two-strings/README.md b/tech-interviews/tech-interview-questions/sum-of-two-strings/README.md new file mode 100644 index 0000000000..20c8d5c21f --- /dev/null +++ b/tech-interviews/tech-interview-questions/sum-of-two-strings/README.md @@ -0,0 +1,9 @@ +name: Sum of Two Strings + +description: Return the sum of two integer values represented as strings, as a single string value. + +aspects: + - workout + +insights: + - sum-of-two-strings \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/sum-of-two-strings/sum-of-two-strings.md b/tech-interviews/tech-interview-questions/sum-of-two-strings/sum-of-two-strings.md new file mode 100644 index 0000000000..bf2227074d --- /dev/null +++ b/tech-interviews/tech-interview-questions/sum-of-two-strings/sum-of-two-strings.md @@ -0,0 +1,58 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return the sum of two integer values represented as strings, as a single string value. Try to solve this by not directly transforming the values with `int()`. + + # Strings to use: + num1 = "19" + num2 = "7" + + # Test the function + print(add_integer_strings(num1, num2)) + # "26" + + # Type your code here: + +--- + +# Sum of Two Strings + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the sum of two integer values represented as strings, as a single string value. Try to solve this by not directly transforming the values with `int()`.** + +Sample list to use: +```python +num1 = "19" +num2 = "7" + +# Test the function +print(add_integer_strings(num1, num2)) +# "26" +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/tech-interviews/tech-interview-questions/sum-target-value-from-a-list/README.md b/tech-interviews/tech-interview-questions/sum-target-value-from-a-list/README.md new file mode 100644 index 0000000000..787cd8e0b3 --- /dev/null +++ b/tech-interviews/tech-interview-questions/sum-target-value-from-a-list/README.md @@ -0,0 +1,9 @@ +name: Sum Target Value From a Given List + +description: Find which two numbers of the given `numbers` list, when summed up, equal the `target` value. Return their indices. + +aspects: + - workout + +insights: + - sum-target-value-from-a-list \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/sum-target-value-from-a-list/sum-target-value-from-a-list.md b/tech-interviews/tech-interview-questions/sum-target-value-from-a-list/sum-target-value-from-a-list.md new file mode 100644 index 0000000000..8818df8fb1 --- /dev/null +++ b/tech-interviews/tech-interview-questions/sum-target-value-from-a-list/sum-target-value-from-a-list.md @@ -0,0 +1,67 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Find which two numbers of the given numbers list, when summed up, equal the target value. Return their indices. + + # Sample lists to use: + numbers = [1, 2, 4, 7, 12] + target1 = 6 + target2 = 11 + + print(find_indices_of_target_sum(numbers, target1)) + # (1, 2) + + print(find_indices_of_target_sum(numbers, target2)) + # (2, 3) + + # Type your code here: + +--- + +# Sum Target Value From a List + +--- + +## Content + +> 👩‍💻 Your task is to: **Find which two numbers of the given `numbers` list, when summed up, equal the `target` value. Return their indices.** + +Sample program: +```python +numbers = [1, 2, 4, 7, 12] +target1 = 6 +target2 = 11 + +print(find_indices_of_target_sum(numbers, target1)) +# (1, 2) + +print(find_indices_of_target_sum(numbers, target2)) +# (2, 3) +``` + +To solve this, try using the following concepts: +- function definition (`def x(): ...`) +- built-in methods (`len()`) +- flow control (`if (age > 30) ...`, `for x in y...`) + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/tech-interviews/tech-interview-questions/wealthiest-citizen/README.md b/tech-interviews/tech-interview-questions/wealthiest-citizen/README.md new file mode 100644 index 0000000000..489e3e3357 --- /dev/null +++ b/tech-interviews/tech-interview-questions/wealthiest-citizen/README.md @@ -0,0 +1,9 @@ +name: Wealthiest Citizen + +description: Find the citizen with the most wealth from a list of bank accounts. + +aspects: + - workout + +insights: + - wealthiest-citizen \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/wealthiest-citizen/wealthiest-citizen.md b/tech-interviews/tech-interview-questions/wealthiest-citizen/wealthiest-citizen.md new file mode 100644 index 0000000000..2a3cf73851 --- /dev/null +++ b/tech-interviews/tech-interview-questions/wealthiest-citizen/wealthiest-citizen.md @@ -0,0 +1,61 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return the wealthiest citizen from a list of bank accounts. Each person will have multiple accounts. Add their accounts together to determine their total wealth. + + # Sample accounts to use: + accounts = [[2, 1, 7], [7, 5, -3], [12, -5, 1], [1, 0, 11]] + + print(return_wealthiest_citizen(accounts)) + + # Sample outputs: + # 12 + # [1, 0, 11] is the wealthiest citizen with total wealth = 12 + + + # Type your code here: + +--- + +# Wealthiest Citizen + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the wealthiest citizen from a list of bank accounts. Each person will have multiple accounts. Add their accounts together to determine their total wealth.** + +Sample program: +```python +accounts = [[2, 1, 7], [7, 5, -3], [12, -5, 1], [1, 0, 11]] + +print(return_wealthiest_citizen(accounts)) + +# Sample outputs: +# 12 +# [1, 0, 11] is the wealthiest citizen with total wealth = 12 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! From 079e5680e3e1a289fc1d67428efab102ac6a79ec Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 13 Dec 2022 11:39:33 +0100 Subject: [PATCH 289/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22758332f3..79e4872c1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## December 13th 2022 + +### Added +- [Tech Interviews - Tech Interview Exercises - Add 25 exercises](https://github.com/enkidevs/curriculum/pull/3139) + ## December 12th 2022 ### Fixed From 5ab5af9e4ad0d622c39cfaf9b1960b3d9bd85694 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 15 Dec 2022 16:04:25 +0100 Subject: [PATCH 290/390] Update coding-with-enki.md --- .../coding-with-enki/coding-with-enki.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md b/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md index 5799707636..bdc41fc8cf 100644 --- a/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md +++ b/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md @@ -14,10 +14,10 @@ setupCode: # Write a program that generates a new string list from the given numbers list. # Conditions - If a number is divisible by both 2 and 4, replace it with "I'm". - If a number is not divisible by any number but 1 or itself (i.e. a prime number), replace it with "Enki". - If a number is divisible by 7, replace with "with". - If a number is divisible by both 3 and 5, replace with "coding". + # If a number is divisible by both 2 and 4, replace it with "I'm". + # If a number is not divisible by any number but 1 or itself (i.e. a prime number), replace it with "Enki". + # If a number is divisible by 7, replace with "with". + # If a number is divisible by both 3 and 5, replace with "coding". # Sample lists to use: numbers = [12, 21, 15, 17] From 732fed3805ab0f6906d77ecf25677005a0cc0bce Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 15 Dec 2022 16:04:54 +0100 Subject: [PATCH 291/390] Update concatenation-of-a-list.md --- .../concatenation-of-a-list/concatenation-of-a-list.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tech-interviews/tech-interview-questions/concatenation-of-a-list/concatenation-of-a-list.md b/tech-interviews/tech-interview-questions/concatenation-of-a-list/concatenation-of-a-list.md index 9e9077d2c7..07a8730d25 100644 --- a/tech-interviews/tech-interview-questions/concatenation-of-a-list/concatenation-of-a-list.md +++ b/tech-interviews/tech-interview-questions/concatenation-of-a-list/concatenation-of-a-list.md @@ -15,8 +15,8 @@ setupCode: # Sample program: numbers = [7, 3, 7] - nums = build_nums_list(numbers) - # nums should become [7, 3, 7, 7, 3, 7] + build_nums_list(numbers) + # [7, 3, 7, 7, 3, 7] # Type your code here: From 99668475758c543c8d2adc14931bcb7c29c36a48 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 15 Dec 2022 16:05:47 +0100 Subject: [PATCH 292/390] Update longest-non-repeating-substring-from-string.md --- .../longest-non-repeating-substring-from-string.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string.md b/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string.md index 9449d201a9..c97399e609 100644 --- a/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string.md +++ b/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string.md @@ -14,8 +14,8 @@ setupCode: # Write a function that finds and returns the longest substring with no repeating characters from a given string. # Sample program: - string1 = "asgegsagefasg" - find_longest_substring(string1) + str = "asgegsagefasg" + find_longest_substring(str) # "gef" # Sample strings: @@ -73,4 +73,4 @@ A substring is a contiguous sequence of characters within a string. For example, the substrings of the string "abcde" are: -"a", "ab", "abc", "abcd", "abcde", "b", "bc", "bcd", "bcde", "c", "cd", "cde", "d", "de", and "e". \ No newline at end of file +"a", "ab", "abc", "abcd", "abcde", "b", "bc", "bcd", "bcde", "c", "cd", "cde", "d", "de", and "e". From d32eb0bf31acbb2256167668cc20c7a95877349c Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Dec 2022 12:48:43 +0100 Subject: [PATCH 293/390] Update list-permutation.md --- .../list-permutation/list-permutation.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/tech-interviews/tech-interview-questions/list-permutation/list-permutation.md b/tech-interviews/tech-interview-questions/list-permutation/list-permutation.md index c1a25f66b1..76a56bc431 100644 --- a/tech-interviews/tech-interview-questions/list-permutation/list-permutation.md +++ b/tech-interviews/tech-interview-questions/list-permutation/list-permutation.md @@ -11,12 +11,11 @@ category: coding setupCode: startingPoint: | # Welcome to the Python coding playground. - # Write a function that takes in list of intengers and returns a new list for each possible permutation. + # Write a function that takes in list of intengers and returns a new list of each possible permutation. # Sample program: # ints = [4, 7] - # [4, 7] - # [7, 4] + newList = [[4, 7], [7, 4]] # Sample list to use: ints = [4, 0, 1, 2, 3, 5] @@ -39,12 +38,7 @@ ints = [4, 0, 7] ``` the function should return: ```python -# [4, 0, 7] -# [4, 7, 0] -# [0, 7, 4] -# [0, 4, 7] -# [7, 4, 0] -# [7, 0, 4] +newList = [[4, 0, 7], [4, 7, 0], [0, 7, 4], [0, 4, 7], [7, 4, 0], [7, 0, 4]] ``` --- From 3d4d5bac424cc9675b4d951aa626cf2e9a202028 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Dec 2022 12:53:16 +0100 Subject: [PATCH 294/390] Update coding-with-enki.md --- .../coding-with-enki/coding-with-enki.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md b/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md index bdc41fc8cf..244f113973 100644 --- a/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md +++ b/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md @@ -40,6 +40,18 @@ Conditions: - If a number is divisible by 7, replace with "with". - If a number is divisible by both 3 and 5, replace with "coding". +For instance, if the input list was: +```pytho +numbers = [17, 19, 23, 29] +``` + +The result would be: +```python +newList = ["Enki", "Enki", "Enki", "Enki"] +``` + +Since all of these numbers satisfy the second condition. + --- Give it an honest try, and feel free to share your solution! From f24b773c1020bdbbfab3d421ec93a637af40f371 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Dec 2022 12:53:45 +0100 Subject: [PATCH 295/390] Update README.md --- .../concatenation-of-a-list/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tech-interviews/tech-interview-questions/concatenation-of-a-list/README.md b/tech-interviews/tech-interview-questions/concatenation-of-a-list/README.md index ab09b51b79..e95e232591 100644 --- a/tech-interviews/tech-interview-questions/concatenation-of-a-list/README.md +++ b/tech-interviews/tech-interview-questions/concatenation-of-a-list/README.md @@ -1,4 +1,4 @@ -name: Concatenation of a List +name: List Concatenation description: Write a function that takes in a list of numbers, concatenates it to itself, and returns it as a new list. @@ -7,4 +7,4 @@ aspects: - workout insights: - - concatenation-of-a-list \ No newline at end of file + - concatenation-of-a-list From 07401b4cd1dd9234ea8ff42bff5bcbe07ec4a3b7 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Dec 2022 12:56:33 +0100 Subject: [PATCH 296/390] Update README.md --- .../longest-non-repeating-substring-from-string/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/README.md b/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/README.md index da3fe9ff73..4535c8f22b 100644 --- a/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/README.md +++ b/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/README.md @@ -1,4 +1,4 @@ -name: Longest substring with no repeating characters. +name: Longest substring with no repeating characters description: Find the longest substring with no repeating characters from a given string. @@ -6,4 +6,4 @@ aspects: - workout insights: - - longest-non-repeating-substring-from-string \ No newline at end of file + - longest-non-repeating-substring-from-string From ff69dcd09053ca3560e488bfe43867188ebcbe1b Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Dec 2022 12:57:06 +0100 Subject: [PATCH 297/390] Update sum-target-value-from-a-list.md --- .../sum-target-value-from-a-list.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tech-interviews/tech-interview-questions/sum-target-value-from-a-list/sum-target-value-from-a-list.md b/tech-interviews/tech-interview-questions/sum-target-value-from-a-list/sum-target-value-from-a-list.md index 8818df8fb1..a2aac1e950 100644 --- a/tech-interviews/tech-interview-questions/sum-target-value-from-a-list/sum-target-value-from-a-list.md +++ b/tech-interviews/tech-interview-questions/sum-target-value-from-a-list/sum-target-value-from-a-list.md @@ -49,10 +49,7 @@ print(find_indices_of_target_sum(numbers, target2)) # (2, 3) ``` -To solve this, try using the following concepts: -- function definition (`def x(): ...`) -- built-in methods (`len()`) -- flow control (`if (age > 30) ...`, `for x in y...`) +--- Give it an honest try, and feel free to share your solution! From f585de087e51273d3720981afb58e5e8d1d7b12a Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Dec 2022 12:58:35 +0100 Subject: [PATCH 298/390] Update README.md --- .../tech-interview-questions/most-frequent-element/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tech-interviews/tech-interview-questions/most-frequent-element/README.md b/tech-interviews/tech-interview-questions/most-frequent-element/README.md index a88676f731..6eef7524a4 100644 --- a/tech-interviews/tech-interview-questions/most-frequent-element/README.md +++ b/tech-interviews/tech-interview-questions/most-frequent-element/README.md @@ -1,4 +1,4 @@ -name: Most frequent element. +name: Most frequent element description: Return the most frequent element from a list. @@ -6,4 +6,4 @@ aspects: - workout insights: - - most-frequent-element \ No newline at end of file + - most-frequent-element From 49d596d406fbceb37774e1479fa0bd1b8b40b2b7 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Dec 2022 15:15:12 +0100 Subject: [PATCH 299/390] Update coding-with-enki.md --- .../coding-with-enki/coding-with-enki.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md b/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md index 244f113973..d4cf56c6c3 100644 --- a/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md +++ b/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md @@ -41,7 +41,7 @@ Conditions: - If a number is divisible by both 3 and 5, replace with "coding". For instance, if the input list was: -```pytho +```python numbers = [17, 19, 23, 29] ``` From 6a79ebd3aeafa9a4c48d1fa4bb34e1812032c400 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Fri, 16 Dec 2022 15:26:40 +0100 Subject: [PATCH 300/390] add interview questions to python --- python/python-playground-questions/README.md | 3 + python/tech-interview-questions-py/README.md | 31 +++++ .../binary-search-exercise/README.md | 9 ++ .../binary-search-exercise-py.md | 74 ++++++++++++ .../coding-with-enki/README.md | 9 ++ .../coding-with-enki/coding-with-enki-py.md | 67 +++++++++++ .../concatenation-of-a-list/README.md | 10 ++ .../concatenation-of-a-list-py.md | 60 ++++++++++ .../find-the-unique-value-exercise/README.md | 9 ++ .../find-the-unique-value-exercise-py.md | 59 ++++++++++ .../list-permutation/README.md | 9 ++ .../list-permutation/list-permutation-py.md | 56 +++++++++ .../README.md | 9 ++ ...-non-repeating-substring-from-string-py.md | 76 +++++++++++++ .../longest-palindrome/README.md | 9 ++ .../longest-palindrome-py.md | 71 ++++++++++++ .../most-frequent-element/README.md | 9 ++ .../most-frequent-element-py.md | 51 +++++++++ .../move-zeroes-to-end-of-list/README.md | 9 ++ .../move-zeroes-to-end-of-list-py.md | 58 ++++++++++ .../nth-largest-element-from-a-list/README.md | 9 ++ .../nth-largest-element-from-a-list-py.md | 59 ++++++++++ .../number-to-roman-numeral/README.md | 9 ++ .../number-to-roman-numeral-py.md | 107 ++++++++++++++++++ .../pascals-triangle-index-return/README.md | 9 ++ .../pascals-triangle-index-return-py.md | 63 +++++++++++ .../pattern-matching/README.md | 9 ++ .../pattern-matching/pattern-matching-py.md | 65 +++++++++++ .../README.md | 9 ++ .../product-of-a-list-excluding-self-py.md | 60 ++++++++++ .../return-the-middle-of-a-list/README.md | 9 ++ .../return-the-middle-of-a-list-py.md | 62 ++++++++++ .../reversing-a-string/README.md | 9 ++ .../reversing-a-string-py.md | 51 +++++++++ .../reversing-words-in-a-string/README.md | 9 ++ .../reversing-words-in-a-string-py.md | 53 +++++++++ .../rotating-a-list/README.md | 9 ++ .../rotating-a-list/rotating-a-list-py.md | 59 ++++++++++ .../squares-of-sorted-lists/README.md | 9 ++ .../squares-of-sorted-lists-py.md | 54 +++++++++ .../steps-to-reduce-a-num-to-zero/README.md | 9 ++ .../steps-to-reduce-a-num-to-zero-py.md | 71 ++++++++++++ .../string-comparison/README.md | 9 ++ .../string-comparison/string-comparison-py.md | 74 ++++++++++++ .../string-permutation/README.md | 9 ++ .../string-permutation-py.md | 76 +++++++++++++ .../sum-of-two-strings/README.md | 9 ++ .../sum-of-two-strings-py.md | 58 ++++++++++ .../sum-target-value-from-a-list/README.md | 9 ++ .../sum-target-value-from-a-list-py.md | 64 +++++++++++ .../wealthiest-citizen/README.md | 9 ++ .../wealthiest-citizen-py.md | 61 ++++++++++ 52 files changed, 1869 insertions(+) create mode 100644 python/tech-interview-questions-py/README.md create mode 100644 python/tech-interview-questions-py/binary-search-exercise/README.md create mode 100644 python/tech-interview-questions-py/binary-search-exercise/binary-search-exercise-py.md create mode 100644 python/tech-interview-questions-py/coding-with-enki/README.md create mode 100644 python/tech-interview-questions-py/coding-with-enki/coding-with-enki-py.md create mode 100644 python/tech-interview-questions-py/concatenation-of-a-list/README.md create mode 100644 python/tech-interview-questions-py/concatenation-of-a-list/concatenation-of-a-list-py.md create mode 100644 python/tech-interview-questions-py/find-the-unique-value-exercise/README.md create mode 100644 python/tech-interview-questions-py/find-the-unique-value-exercise/find-the-unique-value-exercise-py.md create mode 100644 python/tech-interview-questions-py/list-permutation/README.md create mode 100644 python/tech-interview-questions-py/list-permutation/list-permutation-py.md create mode 100644 python/tech-interview-questions-py/longest-non-repeating-substring-from-string/README.md create mode 100644 python/tech-interview-questions-py/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string-py.md create mode 100644 python/tech-interview-questions-py/longest-palindrome/README.md create mode 100644 python/tech-interview-questions-py/longest-palindrome/longest-palindrome-py.md create mode 100644 python/tech-interview-questions-py/most-frequent-element/README.md create mode 100644 python/tech-interview-questions-py/most-frequent-element/most-frequent-element-py.md create mode 100644 python/tech-interview-questions-py/move-zeroes-to-end-of-list/README.md create mode 100644 python/tech-interview-questions-py/move-zeroes-to-end-of-list/move-zeroes-to-end-of-list-py.md create mode 100644 python/tech-interview-questions-py/nth-largest-element-from-a-list/README.md create mode 100644 python/tech-interview-questions-py/nth-largest-element-from-a-list/nth-largest-element-from-a-list-py.md create mode 100644 python/tech-interview-questions-py/number-to-roman-numeral/README.md create mode 100644 python/tech-interview-questions-py/number-to-roman-numeral/number-to-roman-numeral-py.md create mode 100644 python/tech-interview-questions-py/pascals-triangle-index-return/README.md create mode 100644 python/tech-interview-questions-py/pascals-triangle-index-return/pascals-triangle-index-return-py.md create mode 100644 python/tech-interview-questions-py/pattern-matching/README.md create mode 100644 python/tech-interview-questions-py/pattern-matching/pattern-matching-py.md create mode 100644 python/tech-interview-questions-py/product-of-a-list-excluding-self/README.md create mode 100644 python/tech-interview-questions-py/product-of-a-list-excluding-self/product-of-a-list-excluding-self-py.md create mode 100644 python/tech-interview-questions-py/return-the-middle-of-a-list/README.md create mode 100644 python/tech-interview-questions-py/return-the-middle-of-a-list/return-the-middle-of-a-list-py.md create mode 100644 python/tech-interview-questions-py/reversing-a-string/README.md create mode 100644 python/tech-interview-questions-py/reversing-a-string/reversing-a-string-py.md create mode 100644 python/tech-interview-questions-py/reversing-words-in-a-string/README.md create mode 100644 python/tech-interview-questions-py/reversing-words-in-a-string/reversing-words-in-a-string-py.md create mode 100644 python/tech-interview-questions-py/rotating-a-list/README.md create mode 100644 python/tech-interview-questions-py/rotating-a-list/rotating-a-list-py.md create mode 100644 python/tech-interview-questions-py/squares-of-sorted-lists/README.md create mode 100644 python/tech-interview-questions-py/squares-of-sorted-lists/squares-of-sorted-lists-py.md create mode 100644 python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero/README.md create mode 100644 python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero/steps-to-reduce-a-num-to-zero-py.md create mode 100644 python/tech-interview-questions-py/string-comparison/README.md create mode 100644 python/tech-interview-questions-py/string-comparison/string-comparison-py.md create mode 100644 python/tech-interview-questions-py/string-permutation/README.md create mode 100644 python/tech-interview-questions-py/string-permutation/string-permutation-py.md create mode 100644 python/tech-interview-questions-py/sum-of-two-strings/README.md create mode 100644 python/tech-interview-questions-py/sum-of-two-strings/sum-of-two-strings-py.md create mode 100644 python/tech-interview-questions-py/sum-target-value-from-a-list/README.md create mode 100644 python/tech-interview-questions-py/sum-target-value-from-a-list/sum-target-value-from-a-list-py.md create mode 100644 python/tech-interview-questions-py/wealthiest-citizen/README.md create mode 100644 python/tech-interview-questions-py/wealthiest-citizen/wealthiest-citizen-py.md diff --git a/python/python-playground-questions/README.md b/python/python-playground-questions/README.md index 7bf4ffd92b..1b40b9a326 100644 --- a/python/python-playground-questions/README.md +++ b/python/python-playground-questions/README.md @@ -34,3 +34,6 @@ sections: - pascals-triangle - beginning-and-end-pairs - harmonic-series + +next: + - python:tech-interview-questions-py diff --git a/python/tech-interview-questions-py/README.md b/python/tech-interview-questions-py/README.md new file mode 100644 index 0000000000..b04e9c27b0 --- /dev/null +++ b/python/tech-interview-questions-py/README.md @@ -0,0 +1,31 @@ +name: Interview Exercises + +description: Questions to improve your coding skills. + +sections: + '0': + - binary-search-exercise-py + - list-permutation-py + - coding-with-enki-py + - concatenation-of-a-list-py + - find-the-unique-value-exercise-py + - longest-non-repeating-substring-from-string-py + - longest-palindrome-py + - move-zeroes-to-end-of-list-py + - nth-largest-element-from-a-list-py + - most-frequent-element-py + - number-to-roman-numeral-py + - wealthiest-citizen-py + - sum-target-value-from-a-list-py + - string-permutation-py + - sum-of-two-strings-py + - string-comparison-py + - steps-to-reduce-a-num-to-zero-py + - squares-of-sorted-lists-py + - rotating-a-list-py + - reversing-words-in-a-string-py + - reversing-a-string-py + - return-the-middle-of-a-list-py + - product-of-a-list-excluding-self-py + - pattern-matching-py + - pascals-triangle-index-return-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/binary-search-exercise/README.md b/python/tech-interview-questions-py/binary-search-exercise/README.md new file mode 100644 index 0000000000..196c401a1a --- /dev/null +++ b/python/tech-interview-questions-py/binary-search-exercise/README.md @@ -0,0 +1,9 @@ +name: Binary Search + +description: Create an algorithm that outputs the index of a number from a list using a target value. + +aspects: + - workout + +insights: + - binary-search-exercise \ No newline at end of file diff --git a/python/tech-interview-questions-py/binary-search-exercise/binary-search-exercise-py.md b/python/tech-interview-questions-py/binary-search-exercise/binary-search-exercise-py.md new file mode 100644 index 0000000000..de8f4e4471 --- /dev/null +++ b/python/tech-interview-questions-py/binary-search-exercise/binary-search-exercise-py.md @@ -0,0 +1,74 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Create a function that returns the index of the given target value from a sorted numbers list. Your algorithm should use O(log n) runtime complexity. + + # Sample input list and target to use: + numbers = [-5, -3, 1, 6, 8, 11] + target = 6 + + # Sample output: + # The target value is on index 3 + + # Type your code here: + +--- + +# Binary Search + +--- + +## Content + +> 👩‍💻 Your task is to: **Create a function that returns the index of the given `target` value from a sorted `numbers` list. Your algorithm should use `O(log n)` runtime complexity.** + +For example, if the input list is: +```python +numbers = [-5, -3, 1, 6, 8, 11] +``` + +and the target value is: +```python +target = 6 +``` + +the function should return the index of the target value inside the input list: +```plain-text +3 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read this footnote[1] or review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + +--- + +## Footnotes + +[1: Hints] + +Since the input list is sorted, you can use a binary search algorithm to find the target value in the list. This algorithm has a runtime complexity of `O(log n)`, which means it can find the target value in a list of `n` elements in a time that grows logarithmically with the size of the input. + +In a binary search, you start by comparing the target value to the middle element of the list. If the target value is smaller than the middle element, you can discard the second half of the list, because the target value cannot be in that half (since the list is sorted). Otherwise, you can discard the first half of the list. + +You then repeat this process on the remaining half of the list, until you either find the target value or determine that it does not exist in the list. \ No newline at end of file diff --git a/python/tech-interview-questions-py/coding-with-enki/README.md b/python/tech-interview-questions-py/coding-with-enki/README.md new file mode 100644 index 0000000000..7e220e8399 --- /dev/null +++ b/python/tech-interview-questions-py/coding-with-enki/README.md @@ -0,0 +1,9 @@ +name: Coding With Enki + +description: Write a program that generates a new string list from a numbers list using a set of rules. + +aspects: + - workout + +insights: + - coding-with-enki \ No newline at end of file diff --git a/python/tech-interview-questions-py/coding-with-enki/coding-with-enki-py.md b/python/tech-interview-questions-py/coding-with-enki/coding-with-enki-py.md new file mode 100644 index 0000000000..d4cf56c6c3 --- /dev/null +++ b/python/tech-interview-questions-py/coding-with-enki/coding-with-enki-py.md @@ -0,0 +1,67 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Write a program that generates a new string list from the given numbers list. + + # Conditions + # If a number is divisible by both 2 and 4, replace it with "I'm". + # If a number is not divisible by any number but 1 or itself (i.e. a prime number), replace it with "Enki". + # If a number is divisible by 7, replace with "with". + # If a number is divisible by both 3 and 5, replace with "coding". + + # Sample lists to use: + numbers = [12, 21, 15, 17] + + # Type your code here: + +--- + +# Coding With Enki + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a program that generates a new string list from the given `numbers` list.** + +Conditions: + - If a number is divisible by both 2 and 4, replace it with "I'm". + - If a number is not divisible by any number but 1 or itself (i.e. a prime number), replace it with "Enki". + - If a number is divisible by 7, replace with "with". + - If a number is divisible by both 3 and 5, replace with "coding". + +For instance, if the input list was: +```python +numbers = [17, 19, 23, 29] +``` + +The result would be: +```python +newList = ["Enki", "Enki", "Enki", "Enki"] +``` + +Since all of these numbers satisfy the second condition. + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/python/tech-interview-questions-py/concatenation-of-a-list/README.md b/python/tech-interview-questions-py/concatenation-of-a-list/README.md new file mode 100644 index 0000000000..e95e232591 --- /dev/null +++ b/python/tech-interview-questions-py/concatenation-of-a-list/README.md @@ -0,0 +1,10 @@ +name: List Concatenation + +description: Write a function that takes in a list of numbers, concatenates it to itself, and returns it as a new list. + + +aspects: + - workout + +insights: + - concatenation-of-a-list diff --git a/python/tech-interview-questions-py/concatenation-of-a-list/concatenation-of-a-list-py.md b/python/tech-interview-questions-py/concatenation-of-a-list/concatenation-of-a-list-py.md new file mode 100644 index 0000000000..07a8730d25 --- /dev/null +++ b/python/tech-interview-questions-py/concatenation-of-a-list/concatenation-of-a-list-py.md @@ -0,0 +1,60 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Write a function that takes in a list of numbers, concatenates it to itself, and returns it as a new list. + + # Sample program: + numbers = [7, 3, 7] + build_nums_list(numbers) + # [7, 3, 7, 7, 3, 7] + + # Type your code here: + +--- + +# List Concatenation + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a function that takes in a list of numbers, concatenates it to itself, and returns it as a new list.** + +For instance, if the input list is: +```python +numbers = [7, 3, 7] +``` + +the function should return: + +```python +build_nums_list(numbers) +# [7, 3, 7, 7, 3, 7] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + + + diff --git a/python/tech-interview-questions-py/find-the-unique-value-exercise/README.md b/python/tech-interview-questions-py/find-the-unique-value-exercise/README.md new file mode 100644 index 0000000000..0097225ef8 --- /dev/null +++ b/python/tech-interview-questions-py/find-the-unique-value-exercise/README.md @@ -0,0 +1,9 @@ +name: Find the unique value + +description: Find the unique value in a list. + +aspects: + - workout + +insights: + - find-the-unique-value-exercise \ No newline at end of file diff --git a/python/tech-interview-questions-py/find-the-unique-value-exercise/find-the-unique-value-exercise-py.md b/python/tech-interview-questions-py/find-the-unique-value-exercise/find-the-unique-value-exercise-py.md new file mode 100644 index 0000000000..4af21855e2 --- /dev/null +++ b/python/tech-interview-questions-py/find-the-unique-value-exercise/find-the-unique-value-exercise-py.md @@ -0,0 +1,59 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Write a function that finds the unique value from a list of numbers. The function should have linear complexity. + + # Sample program: + numbers = [13, 13, 44, 44, 1, 1, 7, 7, 9] + find_unique(numbers) + # 9 + + # Type your code here: + +--- + +# Find the Unique Value + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a function that finds the unique value from a list of numbers. The function should have linear complexity.** + +For instance, if the input list is: + +```python +numbers = [13, 13, 44, 44, 1, 1, 7, 7, 9] +``` + +the function should return `9` since it is the only element in the list that does not have a duplicate: + +```python +find_unique(numbers) +# 9 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + diff --git a/python/tech-interview-questions-py/list-permutation/README.md b/python/tech-interview-questions-py/list-permutation/README.md new file mode 100644 index 0000000000..bc13f9095c --- /dev/null +++ b/python/tech-interview-questions-py/list-permutation/README.md @@ -0,0 +1,9 @@ +name: List Permutations + +description: Write a function that finds all permutations of a list. + +aspects: + - workout + +insights: + - list-permutation \ No newline at end of file diff --git a/python/tech-interview-questions-py/list-permutation/list-permutation-py.md b/python/tech-interview-questions-py/list-permutation/list-permutation-py.md new file mode 100644 index 0000000000..76a56bc431 --- /dev/null +++ b/python/tech-interview-questions-py/list-permutation/list-permutation-py.md @@ -0,0 +1,56 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Write a function that takes in list of intengers and returns a new list of each possible permutation. + + # Sample program: + # ints = [4, 7] + newList = [[4, 7], [7, 4]] + + # Sample list to use: + ints = [4, 0, 1, 2, 3, 5] + + # Type your code here: + +--- + +# List Permutations + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a function that takes in list of intengers and returns a new list for each possible permutation.** + +For instance, if the input list is +```python +ints = [4, 0, 7] +``` +the function should return: +```python +newList = [[4, 0, 7], [4, 7, 0], [0, 7, 4], [0, 4, 7], [7, 4, 0], [7, 0, 4]] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/python/tech-interview-questions-py/longest-non-repeating-substring-from-string/README.md b/python/tech-interview-questions-py/longest-non-repeating-substring-from-string/README.md new file mode 100644 index 0000000000..4535c8f22b --- /dev/null +++ b/python/tech-interview-questions-py/longest-non-repeating-substring-from-string/README.md @@ -0,0 +1,9 @@ +name: Longest substring with no repeating characters + +description: Find the longest substring with no repeating characters from a given string. + +aspects: + - workout + +insights: + - longest-non-repeating-substring-from-string diff --git a/python/tech-interview-questions-py/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string-py.md b/python/tech-interview-questions-py/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string-py.md new file mode 100644 index 0000000000..c97399e609 --- /dev/null +++ b/python/tech-interview-questions-py/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string-py.md @@ -0,0 +1,76 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Write a function that finds and returns the longest substring with no repeating characters from a given string. + + # Sample program: + str = "asgegsagefasg" + find_longest_substring(str) + # "gef" + + # Sample strings: + string1 = "aaaaaa" + string2 = "asdeavfeva" + + # Type your code here: + +--- + +# Find the Longest Substring With No Repeating Letters + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a function that returns the longest substring with no repeating characters from a given `string`.** + +Here is an example of how the function can be used: + +```python +string1 = "asgegsagefasg" +find_longest_substring(string1) + +# "gef" + +string2 = "abcabcbb" +find_longest_substring(string2) + +# "abc" +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read this footnote[1] or review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + + +--- + +## Footnotes + +[1: Hints] + +A substring is a contiguous sequence of characters within a string. + +For example, the substrings of the string "abcde" are: + +"a", "ab", "abc", "abcd", "abcde", "b", "bc", "bcd", "bcde", "c", "cd", "cde", "d", "de", and "e". diff --git a/python/tech-interview-questions-py/longest-palindrome/README.md b/python/tech-interview-questions-py/longest-palindrome/README.md new file mode 100644 index 0000000000..002fd913b9 --- /dev/null +++ b/python/tech-interview-questions-py/longest-palindrome/README.md @@ -0,0 +1,9 @@ +name: Longest Palindrome + +description: Find and return the longest possible palindrome from a given string. + +aspects: + - workout + +insights: + - longest-palindrome \ No newline at end of file diff --git a/python/tech-interview-questions-py/longest-palindrome/longest-palindrome-py.md b/python/tech-interview-questions-py/longest-palindrome/longest-palindrome-py.md new file mode 100644 index 0000000000..802123f6ff --- /dev/null +++ b/python/tech-interview-questions-py/longest-palindrome/longest-palindrome-py.md @@ -0,0 +1,71 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Find the longest palindrome from the given letters string. + + # Sample program: + letters = "abbbbcceeezdda" + find_longest_palindrome(letters) + # "bbbb" + + # Type your code here: + +--- + +# Longest Palindrome + +--- + +## Content + +> 👩‍💻 Your task is to: **Find the longest palindrome from the given `letters` string.** + +Sample program: +```python +letters = "abbbbcceeezdda" +find_longest_palindrome(letters) + +#"bbbb" +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read this footnote[1] or review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + +--- + +## Footnotes + +[1: Hints] + +The time complexity of this task is *O(N)* where *N* is the length of our `letters` string. + +The Space complexity is *O(1)* as *s* is a fixed size of the alphabet. + +A palindrome is a word or phrase that reads the same forwards and backwards. I.e. **civic**, **level**, **madam**, and so on... + +In an even palindrome, each letter has an equal partner on the opposite side. + +In an odd palindrome, there is a single non-partnered letter in the middle of the pallindrome. + +If each letter occurs X times, we know that x // 2 * 2 is the number of letters that can be partnered. diff --git a/python/tech-interview-questions-py/most-frequent-element/README.md b/python/tech-interview-questions-py/most-frequent-element/README.md new file mode 100644 index 0000000000..6eef7524a4 --- /dev/null +++ b/python/tech-interview-questions-py/most-frequent-element/README.md @@ -0,0 +1,9 @@ +name: Most frequent element + +description: Return the most frequent element from a list. + +aspects: + - workout + +insights: + - most-frequent-element diff --git a/python/tech-interview-questions-py/most-frequent-element/most-frequent-element-py.md b/python/tech-interview-questions-py/most-frequent-element/most-frequent-element-py.md new file mode 100644 index 0000000000..c0cf1712c9 --- /dev/null +++ b/python/tech-interview-questions-py/most-frequent-element/most-frequent-element-py.md @@ -0,0 +1,51 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return the most frequent element from a given numbers list. The time complexity should be better than O(n logn). + + # Sample lists to use: + numbers = [1, 1, 8, 6, 4, 13, 1, 7, 8, 6] + + # Type your code here: + +--- + +# Most Frequent Element + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the most frequent element from the `numbers` list. The time complexity should be better than `O(n logn)`.** + +Sample program: +```python +numbers = [1, 1, 8, 6, 4, 13, 1, 7, 8, 6] +most_frequent_element(numbers) +# 1 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can alway review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + diff --git a/python/tech-interview-questions-py/move-zeroes-to-end-of-list/README.md b/python/tech-interview-questions-py/move-zeroes-to-end-of-list/README.md new file mode 100644 index 0000000000..0d448465e5 --- /dev/null +++ b/python/tech-interview-questions-py/move-zeroes-to-end-of-list/README.md @@ -0,0 +1,9 @@ +name: Moving 0's to the end of a list + +description: Move all 0's to the end of the given list, whilst maintaining the relative order of other numbers. + +aspects: + - workout + +insights: + - move-zeroes-to-end-of-list \ No newline at end of file diff --git a/python/tech-interview-questions-py/move-zeroes-to-end-of-list/move-zeroes-to-end-of-list-py.md b/python/tech-interview-questions-py/move-zeroes-to-end-of-list/move-zeroes-to-end-of-list-py.md new file mode 100644 index 0000000000..bbdd81a98b --- /dev/null +++ b/python/tech-interview-questions-py/move-zeroes-to-end-of-list/move-zeroes-to-end-of-list-py.md @@ -0,0 +1,58 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Move all 0's to the end of the given list, whilst maintaining the relative order of other numbers. Try to solve this in-place; by not creating a new list. + + # Input + numbers = [1, 2, 0, 3, 0, 4, 0, 5] + # Function + move_zeros(numbers) + # [1, 2, 3, 4, 5, 0, 0, 0] + + # Type your code here: + +--- + +# Move Zeroes to the End of a List + +--- + +## Content + +> 👩‍💻 Your task is to: **Move all 0's to the end of the given list, whilst maintaining the relative order of other numbers. Try to solve this in-place; by not creating a new list.** + +Sample program: +```python +# Input +numbers = [1, 2, 0, 3, 0, 4, 0, 5] + +# Function +move_zeros(numbers) + +# [1, 2, 3, 4, 5, 0, 0, 0] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + diff --git a/python/tech-interview-questions-py/nth-largest-element-from-a-list/README.md b/python/tech-interview-questions-py/nth-largest-element-from-a-list/README.md new file mode 100644 index 0000000000..0140b4a17e --- /dev/null +++ b/python/tech-interview-questions-py/nth-largest-element-from-a-list/README.md @@ -0,0 +1,9 @@ +name: Largest Element + +description: Return the Nth Largest Element From a List + +aspects: + - workout + +insights: + - nth-largest-element-from-a-list \ No newline at end of file diff --git a/python/tech-interview-questions-py/nth-largest-element-from-a-list/nth-largest-element-from-a-list-py.md b/python/tech-interview-questions-py/nth-largest-element-from-a-list/nth-largest-element-from-a-list-py.md new file mode 100644 index 0000000000..b2283188ad --- /dev/null +++ b/python/tech-interview-questions-py/nth-largest-element-from-a-list/nth-largest-element-from-a-list-py.md @@ -0,0 +1,59 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return the nth largest element from the numbers list. + + # Sample variables to use: + numbers = [1, 4, 2, 8, 7, 5] + n = 3 + + # nth Largest (3rd largest) + # 5 + + # Type your code here: + +--- + +# Return the Nth Largest Element From a List + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the nth largest element from a list.** + +Sample program: +```python +# Given list +numbers = [1, 4, 2, 8, 7, 5] + +# Given n +n = 3 + +# nth Largest (3rd largest) +# 5 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/python/tech-interview-questions-py/number-to-roman-numeral/README.md b/python/tech-interview-questions-py/number-to-roman-numeral/README.md new file mode 100644 index 0000000000..38743fead1 --- /dev/null +++ b/python/tech-interview-questions-py/number-to-roman-numeral/README.md @@ -0,0 +1,9 @@ +name: Number To Roman Numeral Converter + +description: Given a list of numbers, convert them to Roman numerals. + +aspects: + - workout + +insights: + - number-to-roman-numeral \ No newline at end of file diff --git a/python/tech-interview-questions-py/number-to-roman-numeral/number-to-roman-numeral-py.md b/python/tech-interview-questions-py/number-to-roman-numeral/number-to-roman-numeral-py.md new file mode 100644 index 0000000000..c112021e5f --- /dev/null +++ b/python/tech-interview-questions-py/number-to-roman-numeral/number-to-roman-numeral-py.md @@ -0,0 +1,107 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Generate Roman numerals from a given list of numbers. + + # Sample list to use: + numbers = [1, 23, 44, 59, 1111, 127, 999] + + # Type your code here: + +--- + +# Number to Roman Numeral + +--- + +## Content + +> 👩‍💻 Your task is to: **Generate Roman numerals from a given list of numbers.** + +Roman numeral symbols are: + +| Roman Numeral | Integer | +|:-------------:|:-------:| +| I | 1 | +| V | 5 | +| X | 10 | +| L | 50 | +| C | 100 | +| D | 500 | +| M | 1000 | + +**Note: There are several rules Roman numerals follow. Take a look at this note[1].** + +Sample list to use: +```python +numbers = [1, 23, 44, 59, 1111, 127, 999] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comment section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + +--- + +## Footnotes + +[1: Notes] + +- When a value increases, up to 3 times, the symbol is added to itself. + +If the value increases more, you subtract from the next highest numeral: + +| Roman Numeral | Integer | +|:-------------:|:-------:| +| I | 1 | +| II | 2 | +| III | 3 | +| IV | 4 | +| V | 5 | +| VI | 6 | +| VII | 7 | +| VIII | 8 | +| IX | 9 | +| X | 10 | + +- When a symbol of smaller value is after a symbol of a greater value, they are added together. If the smaller symbol is before it, they are subtracted. + +| Number | Calculation | Result | +|:------:|:-----------:|:------:| +| IV | V - I | 4 | +| VI | V + I | 6 | + +Symbols like V, L, D never repeat. That is beacuse VV is X, LL is C, DD is M. + +From symbols V and X you can only subtract I, from symbols L, C and M, you can only subtract X. + +Here's a sample of wrong vs correct way of writting numbers + +| Sample | ❌ | ✅ | +|:------:|:------:|:---:| +| 41 | XXXXI | XLI | +| 100 | LL | C | +| 59 | LVIIII | LIX | +| 7 | IIIX | VII | +| 111 | CVVI | CXI | +| 400 | CCCC | CD | \ No newline at end of file diff --git a/python/tech-interview-questions-py/pascals-triangle-index-return/README.md b/python/tech-interview-questions-py/pascals-triangle-index-return/README.md new file mode 100644 index 0000000000..498d7cce7c --- /dev/null +++ b/python/tech-interview-questions-py/pascals-triangle-index-return/README.md @@ -0,0 +1,9 @@ +name: Pascals Triangles Index + +description: Return the nth row of Pascal's triangle through its index. + +aspects: + - workout + +insights: + - pascals-triangle-index-return \ No newline at end of file diff --git a/python/tech-interview-questions-py/pascals-triangle-index-return/pascals-triangle-index-return-py.md b/python/tech-interview-questions-py/pascals-triangle-index-return/pascals-triangle-index-return-py.md new file mode 100644 index 0000000000..79a8ab92e2 --- /dev/null +++ b/python/tech-interview-questions-py/pascals-triangle-index-return/pascals-triangle-index-return-py.md @@ -0,0 +1,63 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return the nth row of the Pascal's triangle. + + # If rowIndex = 4 (5th row), you return: + # [1, 4, 6, 4, 1] + # If rowIndex = 1, you return: + # [1, 1] + + # Type your code here: + +--- + +# Pascals Triangles Index + +--- + +## Content + +> 👩‍💻 Your task is to: **Create a function that returns the nth row of the Pascal's triangle.** + +For instance, if: +```python +rowIndex = 4 # (5th row) +``` + +you return: +```python +# [1, 4, 6, 4, 1] +``` + +> The Pascal triangle is a triangular array of binomial coefficients. + +![pascal-triangle](https://img.enkipro.com/9ca1eb25c5fc393b831db1556dcad889.png) + +Here is a gif from Wikipedia that demonstrates how each value is calculated: + +![wiki-explanation](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/python/tech-interview-questions-py/pattern-matching/README.md b/python/tech-interview-questions-py/pattern-matching/README.md new file mode 100644 index 0000000000..4fcc0d1e6c --- /dev/null +++ b/python/tech-interview-questions-py/pattern-matching/README.md @@ -0,0 +1,9 @@ +name: Pattern Match + +description: Confirm if the pattern of the given strings follows the same pattern of the `pattern` variable. + +aspects: + - workout + +insights: + - pattern-matching \ No newline at end of file diff --git a/python/tech-interview-questions-py/pattern-matching/pattern-matching-py.md b/python/tech-interview-questions-py/pattern-matching/pattern-matching-py.md new file mode 100644 index 0000000000..54bfe82791 --- /dev/null +++ b/python/tech-interview-questions-py/pattern-matching/pattern-matching-py.md @@ -0,0 +1,65 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Confirm if the pattern of the given strings follow the same pattern of the pattern variable. + + # Sample program: + pattern = 'aabbc' + str1 = 'meow meow woof woof oink' + str2 = 'meow woof oink' + + check_pattern(pattern, str1) + # True + + check_pattern(pattern, str2) + # False + + + # Type your code here: + +--- + +# Pattern Matching + +--- + +## Content + +> 👩‍💻 Your task is to: **Confirm if the pattern of the given strings follow the same pattern of the `pattern` variable.** + +Example input/output: +```python +pattern = 'aabbc' +str1 = 'meow meow woof woof oink' +str2 = 'meow woof oink' + +check_pattern(pattern, str1) +# True + +check_pattern(pattern, str2) +# False +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read through the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/python/tech-interview-questions-py/product-of-a-list-excluding-self/README.md b/python/tech-interview-questions-py/product-of-a-list-excluding-self/README.md new file mode 100644 index 0000000000..3842d6610b --- /dev/null +++ b/python/tech-interview-questions-py/product-of-a-list-excluding-self/README.md @@ -0,0 +1,9 @@ +name: Product of a List Excluding Self + +description: Implement a function that returns a new list where the current element is the product of all elements in the given list excluding itself. + +aspects: + - workout + +insights: + - product-of-a-list-excluding-self \ No newline at end of file diff --git a/python/tech-interview-questions-py/product-of-a-list-excluding-self/product-of-a-list-excluding-self-py.md b/python/tech-interview-questions-py/product-of-a-list-excluding-self/product-of-a-list-excluding-self-py.md new file mode 100644 index 0000000000..1df1f07fc7 --- /dev/null +++ b/python/tech-interview-questions-py/product-of-a-list-excluding-self/product-of-a-list-excluding-self-py.md @@ -0,0 +1,60 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Implement a function that returns a new list such that the current element is the product of all elements in the given list excluding itself. The function should have a runtime complexity of O(n). + + # Sample list: + numbers = [1, 3, 4, 6, 7] + + # Sample return: + product_list(numbers) + # [504, 168, 126, 84, 72] + + # Type your code here: + +--- + +# Product of List Excluding Self + +--- + +## Content + +> 👩‍💻 Your task is to: **Implement a function that returns a new list such that the current element is the product of all elements in the `numbers` list excluding itself. The function should have a runtime complexity of `O(n)`.** + +For instance, if the input list: +```python +numbers = [1, 3, 4, 6] +``` + +you would return: +```python +product_list(numbers) + +# [72, 24, 18, 12] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + diff --git a/python/tech-interview-questions-py/return-the-middle-of-a-list/README.md b/python/tech-interview-questions-py/return-the-middle-of-a-list/README.md new file mode 100644 index 0000000000..3ce0f29c2d --- /dev/null +++ b/python/tech-interview-questions-py/return-the-middle-of-a-list/README.md @@ -0,0 +1,9 @@ +name: Return the Middle Element from a List + +description: Returns the middle element of a list. + +aspects: + - workout + +insights: + - return-the-middle-of-a-list \ No newline at end of file diff --git a/python/tech-interview-questions-py/return-the-middle-of-a-list/return-the-middle-of-a-list-py.md b/python/tech-interview-questions-py/return-the-middle-of-a-list/return-the-middle-of-a-list-py.md new file mode 100644 index 0000000000..bd896534b8 --- /dev/null +++ b/python/tech-interview-questions-py/return-the-middle-of-a-list/return-the-middle-of-a-list-py.md @@ -0,0 +1,62 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Create a function that finds and returns the middle element of a list. If the list has 2 middle elements, return the first one. + + # Sample program: + numbers = [1, 2, 3, 4, 5, 6] + result = find_middle(numbers) + + # result should be 3 + + numbers = [1, 2, 3, 4, 5, 6, 7] + result = find_middle(numbers) + + # result should be 4 + + # Type your code here: + +--- + +# Return the Middle of a List + +--- + +## Content + +> 👩‍💻 Your task is to: **Implement a function that returns the middle element of a `numbers` list. If the list has 2 middle elements, return the first one.** + +Sample program: +```python +numbers = [1, 2, 3, 4, 5, 6] +find_middle(numbers) +# 3 + +numbers = [1, 2, 3, 4, 5, 6, 7] +find_middle(numbers) +# 4 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/python/tech-interview-questions-py/reversing-a-string/README.md b/python/tech-interview-questions-py/reversing-a-string/README.md new file mode 100644 index 0000000000..efb43efdc8 --- /dev/null +++ b/python/tech-interview-questions-py/reversing-a-string/README.md @@ -0,0 +1,9 @@ +name: Reversing a String + +description: Reverse the order of characters in a given string. + +aspects: + - workout + +insights: + - reversing-a-string \ No newline at end of file diff --git a/python/tech-interview-questions-py/reversing-a-string/reversing-a-string-py.md b/python/tech-interview-questions-py/reversing-a-string/reversing-a-string-py.md new file mode 100644 index 0000000000..ad5f3819ec --- /dev/null +++ b/python/tech-interview-questions-py/reversing-a-string/reversing-a-string-py.md @@ -0,0 +1,51 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Create a function that reverses the given words string. Modify the given input string list in-place with O(1) memory. + + # Sample lists to use: + words = ['H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'] + + # Type your code here: + +--- + +# Reverse a String + +--- + +## Content + +> 👩‍💻 Your task is to: **Create a function that reverses the given `words` string. Modify the given input string list in-place with `O(1)` memory.** + +Sample program: +```python +words = ['H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'] +reverse_string(words) + +# ['d', 'l', 'r', 'o', 'w', 'o', 'l', 'l', 'e', 'H'] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/python/tech-interview-questions-py/reversing-words-in-a-string/README.md b/python/tech-interview-questions-py/reversing-words-in-a-string/README.md new file mode 100644 index 0000000000..e4af354840 --- /dev/null +++ b/python/tech-interview-questions-py/reversing-words-in-a-string/README.md @@ -0,0 +1,9 @@ +name: Reversing words in a string + +description: Reverse the order of characters in a string while preserving the space and initial order between words. + +aspects: + - workout + +insights: + - reversing-words-in-a-string \ No newline at end of file diff --git a/python/tech-interview-questions-py/reversing-words-in-a-string/reversing-words-in-a-string-py.md b/python/tech-interview-questions-py/reversing-words-in-a-string/reversing-words-in-a-string-py.md new file mode 100644 index 0000000000..5adea1b368 --- /dev/null +++ b/python/tech-interview-questions-py/reversing-words-in-a-string/reversing-words-in-a-string-py.md @@ -0,0 +1,53 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Reverse the order of characters in the given sentence while preserving the whitespace and initial order between words. + + # Sample sentence to reverse: + sentence = "Enki is the god of knowledge, water, crafts and creation" + reverse_sentence(sentence) + + # noitaerc dna stfarc ,retaw ,egdelwonk fo dog eht si iknE + # Type your code here: + +--- + +# Reversing Words in a String + +--- + +## Content + +> 👩‍💻 Your task is to: **Reverse the order of characters in the given string while preserving the whitespace and initial order between words.** + +Sample program: +```python +sentence = "You passed the test" +reverse_sentence(sentence) + +# "uoY dessap eht tset" +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/python/tech-interview-questions-py/rotating-a-list/README.md b/python/tech-interview-questions-py/rotating-a-list/README.md new file mode 100644 index 0000000000..ebb692c5db --- /dev/null +++ b/python/tech-interview-questions-py/rotating-a-list/README.md @@ -0,0 +1,9 @@ +name: Rotating a list + +description: Rotate the given list to the right by n steps. + +aspects: + - workout + +insights: + - rotating-a-list \ No newline at end of file diff --git a/python/tech-interview-questions-py/rotating-a-list/rotating-a-list-py.md b/python/tech-interview-questions-py/rotating-a-list/rotating-a-list-py.md new file mode 100644 index 0000000000..7d6a64f333 --- /dev/null +++ b/python/tech-interview-questions-py/rotating-a-list/rotating-a-list-py.md @@ -0,0 +1,59 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Rotate the given numbers list to the right by n steps. Could you solve this in-place using O(1) extra space? + + # Sample variables to use: + numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] + n = 4 + + # Result: + rotate_list(numbers, n) + + # [6, 7, 8, 9, 1, 2, 3, 4, 5] + + # Type your code here: + +--- + +# Find the Non-Duplicate Value + +--- + +## Content + +> 👩‍💻 Your task is to: **Rotate the given `numbers` list to the right by `n` steps. Could you solve this in-place using `O(1)` extra space?** + +Sample variables to use: +```python +numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] +n = 4 + +rotate_list(numbers, n) + +# [6, 7, 8, 9, 1, 2, 3, 4, 5] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! \ No newline at end of file diff --git a/python/tech-interview-questions-py/squares-of-sorted-lists/README.md b/python/tech-interview-questions-py/squares-of-sorted-lists/README.md new file mode 100644 index 0000000000..34011de3c9 --- /dev/null +++ b/python/tech-interview-questions-py/squares-of-sorted-lists/README.md @@ -0,0 +1,9 @@ +name: Squares of a Sorted List + +description: Create an algorithm that returns squared values for each element of the given list. + +aspects: + - workout + +insights: + - squares-of-sorted-lists \ No newline at end of file diff --git a/python/tech-interview-questions-py/squares-of-sorted-lists/squares-of-sorted-lists-py.md b/python/tech-interview-questions-py/squares-of-sorted-lists/squares-of-sorted-lists-py.md new file mode 100644 index 0000000000..6ec6a9e2ee --- /dev/null +++ b/python/tech-interview-questions-py/squares-of-sorted-lists/squares-of-sorted-lists-py.md @@ -0,0 +1,54 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return a list of squares from a given non-squared list of integers. The new list should be sorted in an ascending order. Try to find an O(n) solution. + + # Sample lists to use: + numbers = [-9, -3, 0, 1, 3, 4, 9, 12] + sort_squares(numbers) + + # [0, 1, 9, 9, 16, 81, 81, 144] + + # Type your code here: +--- + +# Squares of a Sorted List + +--- + +## Content + +> 👩‍💻 Your task is to: **Return a list of squares from a given non-squared list of integers. The new list should be sorted in an ascending order. Try to find an `O(n)` solution.** + +Sample program: + +```python +numbers = [-9, -3, 0, 1, 3, 4, 9, 12] +sort_squares(numbers) + +# [0, 1, 9, 9, 16, 81, 81, 144] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero/README.md b/python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero/README.md new file mode 100644 index 0000000000..a1196a0e8a --- /dev/null +++ b/python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero/README.md @@ -0,0 +1,9 @@ +name: Number of steps to reduce a number to zero + +description: Return the number of steps necessary to reduce a number to zero. + +aspects: + - workout + +insights: + - steps-to-reduce-a-num-to-zero \ No newline at end of file diff --git a/python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero/steps-to-reduce-a-num-to-zero-py.md b/python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero/steps-to-reduce-a-num-to-zero-py.md new file mode 100644 index 0000000000..cb043c48f3 --- /dev/null +++ b/python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero/steps-to-reduce-a-num-to-zero-py.md @@ -0,0 +1,71 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return the number of steps needed to reduce a given number to 0. + + # Rules: If the current number is even, you divide it by 2, if it is odd, you reduce it by 1. + + # Sample numbers to use: + num1 = 314 + num2 = 7 + num3 = 15 + num4 = 555 + + # Type your code here: + +--- + +# Steps to Reduce a Number to Zero + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the number of steps needed to reduce a given number to 0.** + +Rules: +- If the current number is even, you divide it by 2, +- if it is odd, you reduce it by 1. + +Sample program: +```python +num1 = 314 +reduce_to_zero(num1) +# 13 + +num2 = 7 +reduce_to_zero(num2) +# 5 + +num3 = 15 +reduce_to_zero(num3) +# 7 + +num4 = 555 +reduce_to_zero(num4) +# 14 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/python/tech-interview-questions-py/string-comparison/README.md b/python/tech-interview-questions-py/string-comparison/README.md new file mode 100644 index 0000000000..d45d7bb3b0 --- /dev/null +++ b/python/tech-interview-questions-py/string-comparison/README.md @@ -0,0 +1,9 @@ +name: String Comparison + +description: Given a string of characters, check if any of the given words can be constructed using those characters. + +aspects: + - workout + +insights: + - string-comparison \ No newline at end of file diff --git a/python/tech-interview-questions-py/string-comparison/string-comparison-py.md b/python/tech-interview-questions-py/string-comparison/string-comparison-py.md new file mode 100644 index 0000000000..9f5130f12a --- /dev/null +++ b/python/tech-interview-questions-py/string-comparison/string-comparison-py.md @@ -0,0 +1,74 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return true if the characters from the given letters string can be used to construct any of the word strings; otherwise return false. You can use each letter only once. + + # Sample lists to use: + letters = 'aaabnn' + word1 = 'banana' + word2 = 'apple' + word3 = 'ban' + word4 = 'bananas' + + print(can_construct_words(letters, word1)) + # True + print(can_construct_words(letters, word2)) + # False + print(can_construct_words(letters, word3)) + # True + print(can_construct_words(letters, word4)) + # False + + # Type your code here: + +--- + +# String Comparison + +--- + +## Content + +> 👩‍💻 Your task is to: **Check if the characters in the `letters` string can be used to construct any of the `word` strings without repeating any letters. Return `true` if any of the `word` strings can be constructed, and `false` otherwise.** + +Sample strings to use: +```python +letters = 'aaabnn' +word1 = 'banana' +word2 = 'apple' +word3 = 'ban' +word4 = 'bananas' + +print(can_construct_words(letters, word1)) +# True +print(can_construct_words(letters, word2)) +# False +print(can_construct_words(letters, word3)) +# True +print(can_construct_words(letters, word4)) +# False +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/python/tech-interview-questions-py/string-permutation/README.md b/python/tech-interview-questions-py/string-permutation/README.md new file mode 100644 index 0000000000..0a471ada01 --- /dev/null +++ b/python/tech-interview-questions-py/string-permutation/README.md @@ -0,0 +1,9 @@ +name: String Permutation + +description: Given a substring and some strings, determine if any permutation of the given substring is located inside the strings. + +aspects: + - workout + +insights: + - string-permutation \ No newline at end of file diff --git a/python/tech-interview-questions-py/string-permutation/string-permutation-py.md b/python/tech-interview-questions-py/string-permutation/string-permutation-py.md new file mode 100644 index 0000000000..aa9827608d --- /dev/null +++ b/python/tech-interview-questions-py/string-permutation/string-permutation-py.md @@ -0,0 +1,76 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return true if a permutation of the given substring is located inside the given strings. + + # Sample lists to use: + subStr = 'ao' + str1 = 'boat' + str2 = 'broader' + str3 = 'milk' + + print(has_permutation_in_string(subStr, str1)) + # True + print(has_permutation_in_string(subStr, str2)) + # True + print(has_permutation_in_string(subStr, str3)) + # False + + # Type your code here: + +--- + +# String Permutation + +--- + +## Content + +> 👩‍💻 Your task is to: **Return `true` if a permutation of the given substring can be found within any of the given strings.** + +Sample variables to use: +```python +subStr = 'ao' +str1 = 'boat' +str2 = 'broader' +str3 = 'milk' + +print(has_permutation_in_string(subStr, str1)) +# True +print(has_permutation_in_string(subStr, str2)) +# True +print(has_permutation_in_string(subStr, str3)) +# False +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read this footnote[1] or review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + +--- + +## Footnotes + +[1: Hints] + +You can sort the strings and substrings, then check if the substring is located inside the strings. \ No newline at end of file diff --git a/python/tech-interview-questions-py/sum-of-two-strings/README.md b/python/tech-interview-questions-py/sum-of-two-strings/README.md new file mode 100644 index 0000000000..20c8d5c21f --- /dev/null +++ b/python/tech-interview-questions-py/sum-of-two-strings/README.md @@ -0,0 +1,9 @@ +name: Sum of Two Strings + +description: Return the sum of two integer values represented as strings, as a single string value. + +aspects: + - workout + +insights: + - sum-of-two-strings \ No newline at end of file diff --git a/python/tech-interview-questions-py/sum-of-two-strings/sum-of-two-strings-py.md b/python/tech-interview-questions-py/sum-of-two-strings/sum-of-two-strings-py.md new file mode 100644 index 0000000000..bf2227074d --- /dev/null +++ b/python/tech-interview-questions-py/sum-of-two-strings/sum-of-two-strings-py.md @@ -0,0 +1,58 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return the sum of two integer values represented as strings, as a single string value. Try to solve this by not directly transforming the values with `int()`. + + # Strings to use: + num1 = "19" + num2 = "7" + + # Test the function + print(add_integer_strings(num1, num2)) + # "26" + + # Type your code here: + +--- + +# Sum of Two Strings + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the sum of two integer values represented as strings, as a single string value. Try to solve this by not directly transforming the values with `int()`.** + +Sample list to use: +```python +num1 = "19" +num2 = "7" + +# Test the function +print(add_integer_strings(num1, num2)) +# "26" +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/python/tech-interview-questions-py/sum-target-value-from-a-list/README.md b/python/tech-interview-questions-py/sum-target-value-from-a-list/README.md new file mode 100644 index 0000000000..787cd8e0b3 --- /dev/null +++ b/python/tech-interview-questions-py/sum-target-value-from-a-list/README.md @@ -0,0 +1,9 @@ +name: Sum Target Value From a Given List + +description: Find which two numbers of the given `numbers` list, when summed up, equal the `target` value. Return their indices. + +aspects: + - workout + +insights: + - sum-target-value-from-a-list \ No newline at end of file diff --git a/python/tech-interview-questions-py/sum-target-value-from-a-list/sum-target-value-from-a-list-py.md b/python/tech-interview-questions-py/sum-target-value-from-a-list/sum-target-value-from-a-list-py.md new file mode 100644 index 0000000000..a2aac1e950 --- /dev/null +++ b/python/tech-interview-questions-py/sum-target-value-from-a-list/sum-target-value-from-a-list-py.md @@ -0,0 +1,64 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Find which two numbers of the given numbers list, when summed up, equal the target value. Return their indices. + + # Sample lists to use: + numbers = [1, 2, 4, 7, 12] + target1 = 6 + target2 = 11 + + print(find_indices_of_target_sum(numbers, target1)) + # (1, 2) + + print(find_indices_of_target_sum(numbers, target2)) + # (2, 3) + + # Type your code here: + +--- + +# Sum Target Value From a List + +--- + +## Content + +> 👩‍💻 Your task is to: **Find which two numbers of the given `numbers` list, when summed up, equal the `target` value. Return their indices.** + +Sample program: +```python +numbers = [1, 2, 4, 7, 12] +target1 = 6 +target2 = 11 + +print(find_indices_of_target_sum(numbers, target1)) +# (1, 2) + +print(find_indices_of_target_sum(numbers, target2)) +# (2, 3) +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/python/tech-interview-questions-py/wealthiest-citizen/README.md b/python/tech-interview-questions-py/wealthiest-citizen/README.md new file mode 100644 index 0000000000..489e3e3357 --- /dev/null +++ b/python/tech-interview-questions-py/wealthiest-citizen/README.md @@ -0,0 +1,9 @@ +name: Wealthiest Citizen + +description: Find the citizen with the most wealth from a list of bank accounts. + +aspects: + - workout + +insights: + - wealthiest-citizen \ No newline at end of file diff --git a/python/tech-interview-questions-py/wealthiest-citizen/wealthiest-citizen-py.md b/python/tech-interview-questions-py/wealthiest-citizen/wealthiest-citizen-py.md new file mode 100644 index 0000000000..2a3cf73851 --- /dev/null +++ b/python/tech-interview-questions-py/wealthiest-citizen/wealthiest-citizen-py.md @@ -0,0 +1,61 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + # Welcome to the Python coding playground. + # Return the wealthiest citizen from a list of bank accounts. Each person will have multiple accounts. Add their accounts together to determine their total wealth. + + # Sample accounts to use: + accounts = [[2, 1, 7], [7, 5, -3], [12, -5, 1], [1, 0, 11]] + + print(return_wealthiest_citizen(accounts)) + + # Sample outputs: + # 12 + # [1, 0, 11] is the wealthiest citizen with total wealth = 12 + + + # Type your code here: + +--- + +# Wealthiest Citizen + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the wealthiest citizen from a list of bank accounts. Each person will have multiple accounts. Add their accounts together to determine their total wealth.** + +Sample program: +```python +accounts = [[2, 1, 7], [7, 5, -3], [12, -5, 1], [1, 0, 11]] + +print(return_wealthiest_citizen(accounts)) + +# Sample outputs: +# 12 +# [1, 0, 11] is the wealthiest citizen with total wealth = 12 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! From 6563e6b6aff14ea992703332245c804e6fa978d6 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Fri, 16 Dec 2022 15:32:15 +0100 Subject: [PATCH 301/390] rename files with suffix py and update readme and changelog --- CHANGELOG.md | 5 +++++ .../README.md | 2 +- .../binary-search-exercise-py.md | 0 .../{coding-with-enki => coding-with-enki-py}/README.md | 2 +- .../coding-with-enki-py.md | 0 .../README.md | 2 +- .../concatenation-of-a-list-py.md | 0 .../README.md | 2 +- .../find-the-unique-value-exercise-py.md | 0 .../{list-permutation => list-permutation-py}/README.md | 2 +- .../list-permutation-py.md | 0 .../README.md | 2 +- .../longest-non-repeating-substring-from-string-py.md | 0 .../{longest-palindrome => longest-palindrome-py}/README.md | 2 +- .../longest-palindrome-py.md | 0 .../README.md | 2 +- .../most-frequent-element-py.md | 0 .../README.md | 2 +- .../move-zeroes-to-end-of-list-py.md | 0 .../README.md | 2 +- .../nth-largest-element-from-a-list-py.md | 0 .../README.md | 2 +- .../number-to-roman-numeral-py.md | 0 .../README.md | 2 +- .../pascals-triangle-index-return-py.md | 0 .../{pattern-matching => pattern-matching-py}/README.md | 2 +- .../pattern-matching-py.md | 0 .../README.md | 2 +- .../product-of-a-list-excluding-self-py.md | 0 .../README.md | 2 +- .../return-the-middle-of-a-list-py.md | 0 .../{reversing-a-string => reversing-a-string-py}/README.md | 2 +- .../reversing-a-string-py.md | 0 .../README.md | 2 +- .../reversing-words-in-a-string-py.md | 0 .../{rotating-a-list => rotating-a-list-py}/README.md | 2 +- .../rotating-a-list-py.md | 0 .../README.md | 2 +- .../squares-of-sorted-lists-py.md | 0 .../README.md | 2 +- .../steps-to-reduce-a-num-to-zero-py.md | 0 .../{string-comparison => string-comparison-py}/README.md | 2 +- .../string-comparison-py.md | 0 .../{string-permutation => string-permutation-py}/README.md | 2 +- .../string-permutation-py.md | 0 .../{sum-of-two-strings => sum-of-two-strings-py}/README.md | 2 +- .../sum-of-two-strings-py.md | 0 .../README.md | 2 +- .../sum-target-value-from-a-list-py.md | 0 .../{wealthiest-citizen => wealthiest-citizen-py}/README.md | 2 +- .../wealthiest-citizen-py.md | 0 51 files changed, 30 insertions(+), 25 deletions(-) rename python/tech-interview-questions-py/{binary-search-exercise => binary-search-exercise-py}/README.md (84%) rename python/tech-interview-questions-py/{binary-search-exercise => binary-search-exercise-py}/binary-search-exercise-py.md (100%) rename python/tech-interview-questions-py/{coding-with-enki => coding-with-enki-py}/README.md (87%) rename python/tech-interview-questions-py/{coding-with-enki => coding-with-enki-py}/coding-with-enki-py.md (100%) rename python/tech-interview-questions-py/{concatenation-of-a-list => concatenation-of-a-list-py}/README.md (85%) rename python/tech-interview-questions-py/{concatenation-of-a-list => concatenation-of-a-list-py}/concatenation-of-a-list-py.md (100%) rename python/tech-interview-questions-py/{find-the-unique-value-exercise => find-the-unique-value-exercise-py}/README.md (74%) rename python/tech-interview-questions-py/{find-the-unique-value-exercise => find-the-unique-value-exercise-py}/find-the-unique-value-exercise-py.md (100%) rename python/tech-interview-questions-py/{list-permutation => list-permutation-py}/README.md (84%) rename python/tech-interview-questions-py/{list-permutation => list-permutation-py}/list-permutation-py.md (100%) rename python/tech-interview-questions-py/{longest-non-repeating-substring-from-string => longest-non-repeating-substring-from-string-py}/README.md (77%) rename python/tech-interview-questions-py/{longest-non-repeating-substring-from-string => longest-non-repeating-substring-from-string-py}/longest-non-repeating-substring-from-string-py.md (100%) rename python/tech-interview-questions-py/{longest-palindrome => longest-palindrome-py}/README.md (84%) rename python/tech-interview-questions-py/{longest-palindrome => longest-palindrome-py}/longest-palindrome-py.md (100%) rename python/tech-interview-questions-py/{most-frequent-element => most-frequent-element-py}/README.md (80%) rename python/tech-interview-questions-py/{most-frequent-element => most-frequent-element-py}/most-frequent-element-py.md (100%) rename python/tech-interview-questions-py/{move-zeroes-to-end-of-list => move-zeroes-to-end-of-list-py}/README.md (84%) rename python/tech-interview-questions-py/{move-zeroes-to-end-of-list => move-zeroes-to-end-of-list-py}/move-zeroes-to-end-of-list-py.md (100%) rename python/tech-interview-questions-py/{nth-largest-element-from-a-list => nth-largest-element-from-a-list-py}/README.md (74%) rename python/tech-interview-questions-py/{nth-largest-element-from-a-list => nth-largest-element-from-a-list-py}/nth-largest-element-from-a-list-py.md (100%) rename python/tech-interview-questions-py/{number-to-roman-numeral => number-to-roman-numeral-py}/README.md (82%) rename python/tech-interview-questions-py/{number-to-roman-numeral => number-to-roman-numeral-py}/number-to-roman-numeral-py.md (100%) rename python/tech-interview-questions-py/{pascals-triangle-index-return => pascals-triangle-index-return-py}/README.md (79%) rename python/tech-interview-questions-py/{pascals-triangle-index-return => pascals-triangle-index-return-py}/pascals-triangle-index-return-py.md (100%) rename python/tech-interview-questions-py/{pattern-matching => pattern-matching-py}/README.md (87%) rename python/tech-interview-questions-py/{pattern-matching => pattern-matching-py}/pattern-matching-py.md (100%) rename python/tech-interview-questions-py/{product-of-a-list-excluding-self => product-of-a-list-excluding-self-py}/README.md (85%) rename python/tech-interview-questions-py/{product-of-a-list-excluding-self => product-of-a-list-excluding-self-py}/product-of-a-list-excluding-self-py.md (100%) rename python/tech-interview-questions-py/{return-the-middle-of-a-list => return-the-middle-of-a-list-py}/README.md (79%) rename python/tech-interview-questions-py/{return-the-middle-of-a-list => return-the-middle-of-a-list-py}/return-the-middle-of-a-list-py.md (100%) rename python/tech-interview-questions-py/{reversing-a-string => reversing-a-string-py}/README.md (83%) rename python/tech-interview-questions-py/{reversing-a-string => reversing-a-string-py}/reversing-a-string-py.md (100%) rename python/tech-interview-questions-py/{reversing-words-in-a-string => reversing-words-in-a-string-py}/README.md (84%) rename python/tech-interview-questions-py/{reversing-words-in-a-string => reversing-words-in-a-string-py}/reversing-words-in-a-string-py.md (100%) rename python/tech-interview-questions-py/{rotating-a-list => rotating-a-list-py}/README.md (84%) rename python/tech-interview-questions-py/{rotating-a-list => rotating-a-list-py}/rotating-a-list-py.md (100%) rename python/tech-interview-questions-py/{squares-of-sorted-lists => squares-of-sorted-lists-py}/README.md (84%) rename python/tech-interview-questions-py/{squares-of-sorted-lists => squares-of-sorted-lists-py}/squares-of-sorted-lists-py.md (100%) rename python/tech-interview-questions-py/{steps-to-reduce-a-num-to-zero => steps-to-reduce-a-num-to-zero-py}/README.md (81%) rename python/tech-interview-questions-py/{steps-to-reduce-a-num-to-zero => steps-to-reduce-a-num-to-zero-py}/steps-to-reduce-a-num-to-zero-py.md (100%) rename python/tech-interview-questions-py/{string-comparison => string-comparison-py}/README.md (88%) rename python/tech-interview-questions-py/{string-comparison => string-comparison-py}/string-comparison-py.md (100%) rename python/tech-interview-questions-py/{string-permutation => string-permutation-py}/README.md (88%) rename python/tech-interview-questions-py/{string-permutation => string-permutation-py}/string-permutation-py.md (100%) rename python/tech-interview-questions-py/{sum-of-two-strings => sum-of-two-strings-py}/README.md (86%) rename python/tech-interview-questions-py/{sum-of-two-strings => sum-of-two-strings-py}/sum-of-two-strings-py.md (100%) rename python/tech-interview-questions-py/{sum-target-value-from-a-list => sum-target-value-from-a-list-py}/README.md (85%) rename python/tech-interview-questions-py/{sum-target-value-from-a-list => sum-target-value-from-a-list-py}/sum-target-value-from-a-list-py.md (100%) rename python/tech-interview-questions-py/{wealthiest-citizen => wealthiest-citizen-py}/README.md (84%) rename python/tech-interview-questions-py/{wealthiest-citizen => wealthiest-citizen-py}/wealthiest-citizen-py.md (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c763a7407..635759527f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## December 16th 2022 + +### Added +- [Python - Tech Interview Exercises - add 25 exercises](https://github.com/enkidevs/curriculum/pull/3140) + ## December 12th 2022 ### Fixed diff --git a/python/tech-interview-questions-py/binary-search-exercise/README.md b/python/tech-interview-questions-py/binary-search-exercise-py/README.md similarity index 84% rename from python/tech-interview-questions-py/binary-search-exercise/README.md rename to python/tech-interview-questions-py/binary-search-exercise-py/README.md index 196c401a1a..dc6aaa8239 100644 --- a/python/tech-interview-questions-py/binary-search-exercise/README.md +++ b/python/tech-interview-questions-py/binary-search-exercise-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - binary-search-exercise \ No newline at end of file + - binary-search-exercise-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/binary-search-exercise/binary-search-exercise-py.md b/python/tech-interview-questions-py/binary-search-exercise-py/binary-search-exercise-py.md similarity index 100% rename from python/tech-interview-questions-py/binary-search-exercise/binary-search-exercise-py.md rename to python/tech-interview-questions-py/binary-search-exercise-py/binary-search-exercise-py.md diff --git a/python/tech-interview-questions-py/coding-with-enki/README.md b/python/tech-interview-questions-py/coding-with-enki-py/README.md similarity index 87% rename from python/tech-interview-questions-py/coding-with-enki/README.md rename to python/tech-interview-questions-py/coding-with-enki-py/README.md index 7e220e8399..5280f0e5c2 100644 --- a/python/tech-interview-questions-py/coding-with-enki/README.md +++ b/python/tech-interview-questions-py/coding-with-enki-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - coding-with-enki \ No newline at end of file + - coding-with-enki-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/coding-with-enki/coding-with-enki-py.md b/python/tech-interview-questions-py/coding-with-enki-py/coding-with-enki-py.md similarity index 100% rename from python/tech-interview-questions-py/coding-with-enki/coding-with-enki-py.md rename to python/tech-interview-questions-py/coding-with-enki-py/coding-with-enki-py.md diff --git a/python/tech-interview-questions-py/concatenation-of-a-list/README.md b/python/tech-interview-questions-py/concatenation-of-a-list-py/README.md similarity index 85% rename from python/tech-interview-questions-py/concatenation-of-a-list/README.md rename to python/tech-interview-questions-py/concatenation-of-a-list-py/README.md index e95e232591..bae0171228 100644 --- a/python/tech-interview-questions-py/concatenation-of-a-list/README.md +++ b/python/tech-interview-questions-py/concatenation-of-a-list-py/README.md @@ -7,4 +7,4 @@ aspects: - workout insights: - - concatenation-of-a-list + - concatenation-of-a-list-py diff --git a/python/tech-interview-questions-py/concatenation-of-a-list/concatenation-of-a-list-py.md b/python/tech-interview-questions-py/concatenation-of-a-list-py/concatenation-of-a-list-py.md similarity index 100% rename from python/tech-interview-questions-py/concatenation-of-a-list/concatenation-of-a-list-py.md rename to python/tech-interview-questions-py/concatenation-of-a-list-py/concatenation-of-a-list-py.md diff --git a/python/tech-interview-questions-py/find-the-unique-value-exercise/README.md b/python/tech-interview-questions-py/find-the-unique-value-exercise-py/README.md similarity index 74% rename from python/tech-interview-questions-py/find-the-unique-value-exercise/README.md rename to python/tech-interview-questions-py/find-the-unique-value-exercise-py/README.md index 0097225ef8..8cc86d0214 100644 --- a/python/tech-interview-questions-py/find-the-unique-value-exercise/README.md +++ b/python/tech-interview-questions-py/find-the-unique-value-exercise-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - find-the-unique-value-exercise \ No newline at end of file + - find-the-unique-value-exercise-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/find-the-unique-value-exercise/find-the-unique-value-exercise-py.md b/python/tech-interview-questions-py/find-the-unique-value-exercise-py/find-the-unique-value-exercise-py.md similarity index 100% rename from python/tech-interview-questions-py/find-the-unique-value-exercise/find-the-unique-value-exercise-py.md rename to python/tech-interview-questions-py/find-the-unique-value-exercise-py/find-the-unique-value-exercise-py.md diff --git a/python/tech-interview-questions-py/list-permutation/README.md b/python/tech-interview-questions-py/list-permutation-py/README.md similarity index 84% rename from python/tech-interview-questions-py/list-permutation/README.md rename to python/tech-interview-questions-py/list-permutation-py/README.md index bc13f9095c..1e39181a0e 100644 --- a/python/tech-interview-questions-py/list-permutation/README.md +++ b/python/tech-interview-questions-py/list-permutation-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - list-permutation \ No newline at end of file + - list-permutation-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/list-permutation/list-permutation-py.md b/python/tech-interview-questions-py/list-permutation-py/list-permutation-py.md similarity index 100% rename from python/tech-interview-questions-py/list-permutation/list-permutation-py.md rename to python/tech-interview-questions-py/list-permutation-py/list-permutation-py.md diff --git a/python/tech-interview-questions-py/longest-non-repeating-substring-from-string/README.md b/python/tech-interview-questions-py/longest-non-repeating-substring-from-string-py/README.md similarity index 77% rename from python/tech-interview-questions-py/longest-non-repeating-substring-from-string/README.md rename to python/tech-interview-questions-py/longest-non-repeating-substring-from-string-py/README.md index 4535c8f22b..086bd1fd14 100644 --- a/python/tech-interview-questions-py/longest-non-repeating-substring-from-string/README.md +++ b/python/tech-interview-questions-py/longest-non-repeating-substring-from-string-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - longest-non-repeating-substring-from-string + - longest-non-repeating-substring-from-string-py diff --git a/python/tech-interview-questions-py/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string-py.md b/python/tech-interview-questions-py/longest-non-repeating-substring-from-string-py/longest-non-repeating-substring-from-string-py.md similarity index 100% rename from python/tech-interview-questions-py/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string-py.md rename to python/tech-interview-questions-py/longest-non-repeating-substring-from-string-py/longest-non-repeating-substring-from-string-py.md diff --git a/python/tech-interview-questions-py/longest-palindrome/README.md b/python/tech-interview-questions-py/longest-palindrome-py/README.md similarity index 84% rename from python/tech-interview-questions-py/longest-palindrome/README.md rename to python/tech-interview-questions-py/longest-palindrome-py/README.md index 002fd913b9..ff4c0fa50f 100644 --- a/python/tech-interview-questions-py/longest-palindrome/README.md +++ b/python/tech-interview-questions-py/longest-palindrome-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - longest-palindrome \ No newline at end of file + - longest-palindrome-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/longest-palindrome/longest-palindrome-py.md b/python/tech-interview-questions-py/longest-palindrome-py/longest-palindrome-py.md similarity index 100% rename from python/tech-interview-questions-py/longest-palindrome/longest-palindrome-py.md rename to python/tech-interview-questions-py/longest-palindrome-py/longest-palindrome-py.md diff --git a/python/tech-interview-questions-py/most-frequent-element/README.md b/python/tech-interview-questions-py/most-frequent-element-py/README.md similarity index 80% rename from python/tech-interview-questions-py/most-frequent-element/README.md rename to python/tech-interview-questions-py/most-frequent-element-py/README.md index 6eef7524a4..a0777edbd0 100644 --- a/python/tech-interview-questions-py/most-frequent-element/README.md +++ b/python/tech-interview-questions-py/most-frequent-element-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - most-frequent-element + - most-frequent-element-py diff --git a/python/tech-interview-questions-py/most-frequent-element/most-frequent-element-py.md b/python/tech-interview-questions-py/most-frequent-element-py/most-frequent-element-py.md similarity index 100% rename from python/tech-interview-questions-py/most-frequent-element/most-frequent-element-py.md rename to python/tech-interview-questions-py/most-frequent-element-py/most-frequent-element-py.md diff --git a/python/tech-interview-questions-py/move-zeroes-to-end-of-list/README.md b/python/tech-interview-questions-py/move-zeroes-to-end-of-list-py/README.md similarity index 84% rename from python/tech-interview-questions-py/move-zeroes-to-end-of-list/README.md rename to python/tech-interview-questions-py/move-zeroes-to-end-of-list-py/README.md index 0d448465e5..fd1e4de508 100644 --- a/python/tech-interview-questions-py/move-zeroes-to-end-of-list/README.md +++ b/python/tech-interview-questions-py/move-zeroes-to-end-of-list-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - move-zeroes-to-end-of-list \ No newline at end of file + - move-zeroes-to-end-of-list-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/move-zeroes-to-end-of-list/move-zeroes-to-end-of-list-py.md b/python/tech-interview-questions-py/move-zeroes-to-end-of-list-py/move-zeroes-to-end-of-list-py.md similarity index 100% rename from python/tech-interview-questions-py/move-zeroes-to-end-of-list/move-zeroes-to-end-of-list-py.md rename to python/tech-interview-questions-py/move-zeroes-to-end-of-list-py/move-zeroes-to-end-of-list-py.md diff --git a/python/tech-interview-questions-py/nth-largest-element-from-a-list/README.md b/python/tech-interview-questions-py/nth-largest-element-from-a-list-py/README.md similarity index 74% rename from python/tech-interview-questions-py/nth-largest-element-from-a-list/README.md rename to python/tech-interview-questions-py/nth-largest-element-from-a-list-py/README.md index 0140b4a17e..c9a451a498 100644 --- a/python/tech-interview-questions-py/nth-largest-element-from-a-list/README.md +++ b/python/tech-interview-questions-py/nth-largest-element-from-a-list-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - nth-largest-element-from-a-list \ No newline at end of file + - nth-largest-element-from-a-list-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/nth-largest-element-from-a-list/nth-largest-element-from-a-list-py.md b/python/tech-interview-questions-py/nth-largest-element-from-a-list-py/nth-largest-element-from-a-list-py.md similarity index 100% rename from python/tech-interview-questions-py/nth-largest-element-from-a-list/nth-largest-element-from-a-list-py.md rename to python/tech-interview-questions-py/nth-largest-element-from-a-list-py/nth-largest-element-from-a-list-py.md diff --git a/python/tech-interview-questions-py/number-to-roman-numeral/README.md b/python/tech-interview-questions-py/number-to-roman-numeral-py/README.md similarity index 82% rename from python/tech-interview-questions-py/number-to-roman-numeral/README.md rename to python/tech-interview-questions-py/number-to-roman-numeral-py/README.md index 38743fead1..b77674708c 100644 --- a/python/tech-interview-questions-py/number-to-roman-numeral/README.md +++ b/python/tech-interview-questions-py/number-to-roman-numeral-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - number-to-roman-numeral \ No newline at end of file + - number-to-roman-numeral-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/number-to-roman-numeral/number-to-roman-numeral-py.md b/python/tech-interview-questions-py/number-to-roman-numeral-py/number-to-roman-numeral-py.md similarity index 100% rename from python/tech-interview-questions-py/number-to-roman-numeral/number-to-roman-numeral-py.md rename to python/tech-interview-questions-py/number-to-roman-numeral-py/number-to-roman-numeral-py.md diff --git a/python/tech-interview-questions-py/pascals-triangle-index-return/README.md b/python/tech-interview-questions-py/pascals-triangle-index-return-py/README.md similarity index 79% rename from python/tech-interview-questions-py/pascals-triangle-index-return/README.md rename to python/tech-interview-questions-py/pascals-triangle-index-return-py/README.md index 498d7cce7c..7562309fd4 100644 --- a/python/tech-interview-questions-py/pascals-triangle-index-return/README.md +++ b/python/tech-interview-questions-py/pascals-triangle-index-return-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - pascals-triangle-index-return \ No newline at end of file + - pascals-triangle-index-return-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/pascals-triangle-index-return/pascals-triangle-index-return-py.md b/python/tech-interview-questions-py/pascals-triangle-index-return-py/pascals-triangle-index-return-py.md similarity index 100% rename from python/tech-interview-questions-py/pascals-triangle-index-return/pascals-triangle-index-return-py.md rename to python/tech-interview-questions-py/pascals-triangle-index-return-py/pascals-triangle-index-return-py.md diff --git a/python/tech-interview-questions-py/pattern-matching/README.md b/python/tech-interview-questions-py/pattern-matching-py/README.md similarity index 87% rename from python/tech-interview-questions-py/pattern-matching/README.md rename to python/tech-interview-questions-py/pattern-matching-py/README.md index 4fcc0d1e6c..d9e29e1cc7 100644 --- a/python/tech-interview-questions-py/pattern-matching/README.md +++ b/python/tech-interview-questions-py/pattern-matching-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - pattern-matching \ No newline at end of file + - pattern-matching-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/pattern-matching/pattern-matching-py.md b/python/tech-interview-questions-py/pattern-matching-py/pattern-matching-py.md similarity index 100% rename from python/tech-interview-questions-py/pattern-matching/pattern-matching-py.md rename to python/tech-interview-questions-py/pattern-matching-py/pattern-matching-py.md diff --git a/python/tech-interview-questions-py/product-of-a-list-excluding-self/README.md b/python/tech-interview-questions-py/product-of-a-list-excluding-self-py/README.md similarity index 85% rename from python/tech-interview-questions-py/product-of-a-list-excluding-self/README.md rename to python/tech-interview-questions-py/product-of-a-list-excluding-self-py/README.md index 3842d6610b..67b682a1d8 100644 --- a/python/tech-interview-questions-py/product-of-a-list-excluding-self/README.md +++ b/python/tech-interview-questions-py/product-of-a-list-excluding-self-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - product-of-a-list-excluding-self \ No newline at end of file + - product-of-a-list-excluding-self-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/product-of-a-list-excluding-self/product-of-a-list-excluding-self-py.md b/python/tech-interview-questions-py/product-of-a-list-excluding-self-py/product-of-a-list-excluding-self-py.md similarity index 100% rename from python/tech-interview-questions-py/product-of-a-list-excluding-self/product-of-a-list-excluding-self-py.md rename to python/tech-interview-questions-py/product-of-a-list-excluding-self-py/product-of-a-list-excluding-self-py.md diff --git a/python/tech-interview-questions-py/return-the-middle-of-a-list/README.md b/python/tech-interview-questions-py/return-the-middle-of-a-list-py/README.md similarity index 79% rename from python/tech-interview-questions-py/return-the-middle-of-a-list/README.md rename to python/tech-interview-questions-py/return-the-middle-of-a-list-py/README.md index 3ce0f29c2d..6cc52d4234 100644 --- a/python/tech-interview-questions-py/return-the-middle-of-a-list/README.md +++ b/python/tech-interview-questions-py/return-the-middle-of-a-list-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - return-the-middle-of-a-list \ No newline at end of file + - return-the-middle-of-a-list-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/return-the-middle-of-a-list/return-the-middle-of-a-list-py.md b/python/tech-interview-questions-py/return-the-middle-of-a-list-py/return-the-middle-of-a-list-py.md similarity index 100% rename from python/tech-interview-questions-py/return-the-middle-of-a-list/return-the-middle-of-a-list-py.md rename to python/tech-interview-questions-py/return-the-middle-of-a-list-py/return-the-middle-of-a-list-py.md diff --git a/python/tech-interview-questions-py/reversing-a-string/README.md b/python/tech-interview-questions-py/reversing-a-string-py/README.md similarity index 83% rename from python/tech-interview-questions-py/reversing-a-string/README.md rename to python/tech-interview-questions-py/reversing-a-string-py/README.md index efb43efdc8..e9e484ce86 100644 --- a/python/tech-interview-questions-py/reversing-a-string/README.md +++ b/python/tech-interview-questions-py/reversing-a-string-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - reversing-a-string \ No newline at end of file + - reversing-a-string-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/reversing-a-string/reversing-a-string-py.md b/python/tech-interview-questions-py/reversing-a-string-py/reversing-a-string-py.md similarity index 100% rename from python/tech-interview-questions-py/reversing-a-string/reversing-a-string-py.md rename to python/tech-interview-questions-py/reversing-a-string-py/reversing-a-string-py.md diff --git a/python/tech-interview-questions-py/reversing-words-in-a-string/README.md b/python/tech-interview-questions-py/reversing-words-in-a-string-py/README.md similarity index 84% rename from python/tech-interview-questions-py/reversing-words-in-a-string/README.md rename to python/tech-interview-questions-py/reversing-words-in-a-string-py/README.md index e4af354840..bc0ba6688b 100644 --- a/python/tech-interview-questions-py/reversing-words-in-a-string/README.md +++ b/python/tech-interview-questions-py/reversing-words-in-a-string-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - reversing-words-in-a-string \ No newline at end of file + - reversing-words-in-a-string-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/reversing-words-in-a-string/reversing-words-in-a-string-py.md b/python/tech-interview-questions-py/reversing-words-in-a-string-py/reversing-words-in-a-string-py.md similarity index 100% rename from python/tech-interview-questions-py/reversing-words-in-a-string/reversing-words-in-a-string-py.md rename to python/tech-interview-questions-py/reversing-words-in-a-string-py/reversing-words-in-a-string-py.md diff --git a/python/tech-interview-questions-py/rotating-a-list/README.md b/python/tech-interview-questions-py/rotating-a-list-py/README.md similarity index 84% rename from python/tech-interview-questions-py/rotating-a-list/README.md rename to python/tech-interview-questions-py/rotating-a-list-py/README.md index ebb692c5db..e642629e5d 100644 --- a/python/tech-interview-questions-py/rotating-a-list/README.md +++ b/python/tech-interview-questions-py/rotating-a-list-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - rotating-a-list \ No newline at end of file + - rotating-a-list-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/rotating-a-list/rotating-a-list-py.md b/python/tech-interview-questions-py/rotating-a-list-py/rotating-a-list-py.md similarity index 100% rename from python/tech-interview-questions-py/rotating-a-list/rotating-a-list-py.md rename to python/tech-interview-questions-py/rotating-a-list-py/rotating-a-list-py.md diff --git a/python/tech-interview-questions-py/squares-of-sorted-lists/README.md b/python/tech-interview-questions-py/squares-of-sorted-lists-py/README.md similarity index 84% rename from python/tech-interview-questions-py/squares-of-sorted-lists/README.md rename to python/tech-interview-questions-py/squares-of-sorted-lists-py/README.md index 34011de3c9..10574a4599 100644 --- a/python/tech-interview-questions-py/squares-of-sorted-lists/README.md +++ b/python/tech-interview-questions-py/squares-of-sorted-lists-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - squares-of-sorted-lists \ No newline at end of file + - squares-of-sorted-lists-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/squares-of-sorted-lists/squares-of-sorted-lists-py.md b/python/tech-interview-questions-py/squares-of-sorted-lists-py/squares-of-sorted-lists-py.md similarity index 100% rename from python/tech-interview-questions-py/squares-of-sorted-lists/squares-of-sorted-lists-py.md rename to python/tech-interview-questions-py/squares-of-sorted-lists-py/squares-of-sorted-lists-py.md diff --git a/python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero/README.md b/python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero-py/README.md similarity index 81% rename from python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero/README.md rename to python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero-py/README.md index a1196a0e8a..cea70aa301 100644 --- a/python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero/README.md +++ b/python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - steps-to-reduce-a-num-to-zero \ No newline at end of file + - steps-to-reduce-a-num-to-zero-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero/steps-to-reduce-a-num-to-zero-py.md b/python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero-py/steps-to-reduce-a-num-to-zero-py.md similarity index 100% rename from python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero/steps-to-reduce-a-num-to-zero-py.md rename to python/tech-interview-questions-py/steps-to-reduce-a-num-to-zero-py/steps-to-reduce-a-num-to-zero-py.md diff --git a/python/tech-interview-questions-py/string-comparison/README.md b/python/tech-interview-questions-py/string-comparison-py/README.md similarity index 88% rename from python/tech-interview-questions-py/string-comparison/README.md rename to python/tech-interview-questions-py/string-comparison-py/README.md index d45d7bb3b0..bf8f76295c 100644 --- a/python/tech-interview-questions-py/string-comparison/README.md +++ b/python/tech-interview-questions-py/string-comparison-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - string-comparison \ No newline at end of file + - string-comparison-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/string-comparison/string-comparison-py.md b/python/tech-interview-questions-py/string-comparison-py/string-comparison-py.md similarity index 100% rename from python/tech-interview-questions-py/string-comparison/string-comparison-py.md rename to python/tech-interview-questions-py/string-comparison-py/string-comparison-py.md diff --git a/python/tech-interview-questions-py/string-permutation/README.md b/python/tech-interview-questions-py/string-permutation-py/README.md similarity index 88% rename from python/tech-interview-questions-py/string-permutation/README.md rename to python/tech-interview-questions-py/string-permutation-py/README.md index 0a471ada01..494e703aec 100644 --- a/python/tech-interview-questions-py/string-permutation/README.md +++ b/python/tech-interview-questions-py/string-permutation-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - string-permutation \ No newline at end of file + - string-permutation-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/string-permutation/string-permutation-py.md b/python/tech-interview-questions-py/string-permutation-py/string-permutation-py.md similarity index 100% rename from python/tech-interview-questions-py/string-permutation/string-permutation-py.md rename to python/tech-interview-questions-py/string-permutation-py/string-permutation-py.md diff --git a/python/tech-interview-questions-py/sum-of-two-strings/README.md b/python/tech-interview-questions-py/sum-of-two-strings-py/README.md similarity index 86% rename from python/tech-interview-questions-py/sum-of-two-strings/README.md rename to python/tech-interview-questions-py/sum-of-two-strings-py/README.md index 20c8d5c21f..4740efcf6b 100644 --- a/python/tech-interview-questions-py/sum-of-two-strings/README.md +++ b/python/tech-interview-questions-py/sum-of-two-strings-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - sum-of-two-strings \ No newline at end of file + - sum-of-two-strings-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/sum-of-two-strings/sum-of-two-strings-py.md b/python/tech-interview-questions-py/sum-of-two-strings-py/sum-of-two-strings-py.md similarity index 100% rename from python/tech-interview-questions-py/sum-of-two-strings/sum-of-two-strings-py.md rename to python/tech-interview-questions-py/sum-of-two-strings-py/sum-of-two-strings-py.md diff --git a/python/tech-interview-questions-py/sum-target-value-from-a-list/README.md b/python/tech-interview-questions-py/sum-target-value-from-a-list-py/README.md similarity index 85% rename from python/tech-interview-questions-py/sum-target-value-from-a-list/README.md rename to python/tech-interview-questions-py/sum-target-value-from-a-list-py/README.md index 787cd8e0b3..4e53e8d8e6 100644 --- a/python/tech-interview-questions-py/sum-target-value-from-a-list/README.md +++ b/python/tech-interview-questions-py/sum-target-value-from-a-list-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - sum-target-value-from-a-list \ No newline at end of file + - sum-target-value-from-a-list-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/sum-target-value-from-a-list/sum-target-value-from-a-list-py.md b/python/tech-interview-questions-py/sum-target-value-from-a-list-py/sum-target-value-from-a-list-py.md similarity index 100% rename from python/tech-interview-questions-py/sum-target-value-from-a-list/sum-target-value-from-a-list-py.md rename to python/tech-interview-questions-py/sum-target-value-from-a-list-py/sum-target-value-from-a-list-py.md diff --git a/python/tech-interview-questions-py/wealthiest-citizen/README.md b/python/tech-interview-questions-py/wealthiest-citizen-py/README.md similarity index 84% rename from python/tech-interview-questions-py/wealthiest-citizen/README.md rename to python/tech-interview-questions-py/wealthiest-citizen-py/README.md index 489e3e3357..fcda6dcc64 100644 --- a/python/tech-interview-questions-py/wealthiest-citizen/README.md +++ b/python/tech-interview-questions-py/wealthiest-citizen-py/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - wealthiest-citizen \ No newline at end of file + - wealthiest-citizen-py \ No newline at end of file diff --git a/python/tech-interview-questions-py/wealthiest-citizen/wealthiest-citizen-py.md b/python/tech-interview-questions-py/wealthiest-citizen-py/wealthiest-citizen-py.md similarity index 100% rename from python/tech-interview-questions-py/wealthiest-citizen/wealthiest-citizen-py.md rename to python/tech-interview-questions-py/wealthiest-citizen-py/wealthiest-citizen-py.md From ff376c67851ebbab4bc8fb13dbfdce109cbebc9a Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Fri, 16 Dec 2022 15:50:49 +0100 Subject: [PATCH 302/390] rename files with suffix js and update readmes --- .../javascript-playground-questions/README.md | 2 + .../tech-interview-exercises-js/README.md | 31 +++++ .../binary-search-exercise-js/README.md | 9 ++ .../binary-search-js.md | 74 ++++++++++++ .../coding-with-enki-js/README.md | 9 ++ .../coding-with-enki-js.md | 67 +++++++++++ .../concatenation-of-a-list-js/README.md | 10 ++ .../concatenation-of-a-list-js.md | 60 ++++++++++ .../README.md | 9 ++ .../find-the-unique-value-exercise-js.md | 59 ++++++++++ .../list-permutation-js/README.md | 9 ++ .../list-permutation-js.md | 56 +++++++++ .../README.md | 9 ++ ...-non-repeating-substring-from-string-js.md | 76 +++++++++++++ .../longest-palindrome-js/README.md | 9 ++ .../longest-palindrome-js.md | 71 ++++++++++++ .../most-frequent-element-js/README.md | 9 ++ .../most-frequent-element-js.md | 51 +++++++++ .../move-zeroes-to-end-of-list-js/README.md | 9 ++ .../move-zeroes-to-end-of-list-js.md | 58 ++++++++++ .../README.md | 9 ++ .../nth-largest-element-from-a-list-js.md | 59 ++++++++++ .../number-to-roman-numeral-js/README.md | 9 ++ .../number-to-roman-numeral-js.md | 107 ++++++++++++++++++ .../README.md | 9 ++ .../pascals-triangle-index-return-js.md | 63 +++++++++++ .../pattern-matching-js/README.md | 9 ++ .../pattern-matching-js.md | 65 +++++++++++ .../README.md | 9 ++ .../product-of-a-list-excluding-self-js.md | 60 ++++++++++ .../return-the-middle-of-a-list-js/README.md | 9 ++ .../return-the-middle-of-a-list-js.md | 60 ++++++++++ .../reversing-a-string-js/README.md | 9 ++ .../reversing-a-string-js.md | 51 +++++++++ .../reversing-words-in-a-string-js/README.md | 9 ++ .../reversing-words-in-a-string-js.md | 53 +++++++++ .../rotating-a-list-js/README.md | 9 ++ .../rotating-a-list-js/rotating-a-list-js.md | 59 ++++++++++ .../squares-of-sorted-lists-js/README.md | 9 ++ .../squares-of-sorted-lists-js.md | 54 +++++++++ .../README.md | 9 ++ .../steps-to-reduce-a-num-to-zero-js.md | 73 ++++++++++++ .../string-comparison-js/README.md | 9 ++ .../string-comparison-js.md | 74 ++++++++++++ .../string-permutation-js/README.md | 9 ++ .../string-permutation-js.md | 76 +++++++++++++ .../sum-of-two-strings-js/README.md | 9 ++ .../sum-of-two-strings-js.md | 58 ++++++++++ .../sum-target-value-from-a-list-js/README.md | 9 ++ .../sum-target-value-from-a-list-js.md | 64 +++++++++++ .../wealthiest-citizen-js/README.md | 9 ++ .../wealthiest-citizen-js.md | 61 ++++++++++ 52 files changed, 1868 insertions(+) create mode 100644 javascript/tech-interview-exercises-js/README.md create mode 100644 javascript/tech-interview-exercises-js/binary-search-exercise-js/README.md create mode 100644 javascript/tech-interview-exercises-js/binary-search-exercise-js/binary-search-js.md create mode 100644 javascript/tech-interview-exercises-js/coding-with-enki-js/README.md create mode 100644 javascript/tech-interview-exercises-js/coding-with-enki-js/coding-with-enki-js.md create mode 100644 javascript/tech-interview-exercises-js/concatenation-of-a-list-js/README.md create mode 100644 javascript/tech-interview-exercises-js/concatenation-of-a-list-js/concatenation-of-a-list-js.md create mode 100644 javascript/tech-interview-exercises-js/find-the-unique-value-exercise-js/README.md create mode 100644 javascript/tech-interview-exercises-js/find-the-unique-value-exercise-js/find-the-unique-value-exercise-js.md create mode 100644 javascript/tech-interview-exercises-js/list-permutation-js/README.md create mode 100644 javascript/tech-interview-exercises-js/list-permutation-js/list-permutation-js.md create mode 100644 javascript/tech-interview-exercises-js/longest-non-repeating-substring-from-string-js/README.md create mode 100644 javascript/tech-interview-exercises-js/longest-non-repeating-substring-from-string-js/longest-non-repeating-substring-from-string-js.md create mode 100644 javascript/tech-interview-exercises-js/longest-palindrome-js/README.md create mode 100644 javascript/tech-interview-exercises-js/longest-palindrome-js/longest-palindrome-js.md create mode 100644 javascript/tech-interview-exercises-js/most-frequent-element-js/README.md create mode 100644 javascript/tech-interview-exercises-js/most-frequent-element-js/most-frequent-element-js.md create mode 100644 javascript/tech-interview-exercises-js/move-zeroes-to-end-of-list-js/README.md create mode 100644 javascript/tech-interview-exercises-js/move-zeroes-to-end-of-list-js/move-zeroes-to-end-of-list-js.md create mode 100644 javascript/tech-interview-exercises-js/nth-largest-element-from-a-list-js/README.md create mode 100644 javascript/tech-interview-exercises-js/nth-largest-element-from-a-list-js/nth-largest-element-from-a-list-js.md create mode 100644 javascript/tech-interview-exercises-js/number-to-roman-numeral-js/README.md create mode 100644 javascript/tech-interview-exercises-js/number-to-roman-numeral-js/number-to-roman-numeral-js.md create mode 100644 javascript/tech-interview-exercises-js/pascals-triangle-index-return-js/README.md create mode 100644 javascript/tech-interview-exercises-js/pascals-triangle-index-return-js/pascals-triangle-index-return-js.md create mode 100644 javascript/tech-interview-exercises-js/pattern-matching-js/README.md create mode 100644 javascript/tech-interview-exercises-js/pattern-matching-js/pattern-matching-js.md create mode 100644 javascript/tech-interview-exercises-js/product-of-a-list-excluding-self-js/README.md create mode 100644 javascript/tech-interview-exercises-js/product-of-a-list-excluding-self-js/product-of-a-list-excluding-self-js.md create mode 100644 javascript/tech-interview-exercises-js/return-the-middle-of-a-list-js/README.md create mode 100644 javascript/tech-interview-exercises-js/return-the-middle-of-a-list-js/return-the-middle-of-a-list-js.md create mode 100644 javascript/tech-interview-exercises-js/reversing-a-string-js/README.md create mode 100644 javascript/tech-interview-exercises-js/reversing-a-string-js/reversing-a-string-js.md create mode 100644 javascript/tech-interview-exercises-js/reversing-words-in-a-string-js/README.md create mode 100644 javascript/tech-interview-exercises-js/reversing-words-in-a-string-js/reversing-words-in-a-string-js.md create mode 100644 javascript/tech-interview-exercises-js/rotating-a-list-js/README.md create mode 100644 javascript/tech-interview-exercises-js/rotating-a-list-js/rotating-a-list-js.md create mode 100644 javascript/tech-interview-exercises-js/squares-of-sorted-lists-js/README.md create mode 100644 javascript/tech-interview-exercises-js/squares-of-sorted-lists-js/squares-of-sorted-lists-js.md create mode 100644 javascript/tech-interview-exercises-js/steps-to-reduce-a-num-to-zero-js/README.md create mode 100644 javascript/tech-interview-exercises-js/steps-to-reduce-a-num-to-zero-js/steps-to-reduce-a-num-to-zero-js.md create mode 100644 javascript/tech-interview-exercises-js/string-comparison-js/README.md create mode 100644 javascript/tech-interview-exercises-js/string-comparison-js/string-comparison-js.md create mode 100644 javascript/tech-interview-exercises-js/string-permutation-js/README.md create mode 100644 javascript/tech-interview-exercises-js/string-permutation-js/string-permutation-js.md create mode 100644 javascript/tech-interview-exercises-js/sum-of-two-strings-js/README.md create mode 100644 javascript/tech-interview-exercises-js/sum-of-two-strings-js/sum-of-two-strings-js.md create mode 100644 javascript/tech-interview-exercises-js/sum-target-value-from-a-list-js/README.md create mode 100644 javascript/tech-interview-exercises-js/sum-target-value-from-a-list-js/sum-target-value-from-a-list-js.md create mode 100644 javascript/tech-interview-exercises-js/wealthiest-citizen-js/README.md create mode 100644 javascript/tech-interview-exercises-js/wealthiest-citizen-js/wealthiest-citizen-js.md diff --git a/javascript/javascript-playground-questions/README.md b/javascript/javascript-playground-questions/README.md index d00bcee255..4770c21c68 100644 --- a/javascript/javascript-playground-questions/README.md +++ b/javascript/javascript-playground-questions/README.md @@ -35,3 +35,5 @@ sections: - js-beginning-and-end-pairs - js-harmonic-series +next: + - javascript:tech-interview-exercises-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/README.md b/javascript/tech-interview-exercises-js/README.md new file mode 100644 index 0000000000..4dfca103ef --- /dev/null +++ b/javascript/tech-interview-exercises-js/README.md @@ -0,0 +1,31 @@ +name: Interview Exercises + +description: Questions to improve your coding skills. + +sections: + '0': + - binary-search-exercise-js + - list-permutation-js + - coding-with-enki-js + - concatenation-of-a-list-js + - find-the-unique-value-exercise-js + - longest-non-repeating-substring-from-string-js + - longest-palindrome-js + - move-zeroes-to-end-of-list-js + - nth-largest-element-from-a-list-js + - most-frequent-element-js + - number-to-roman-numeral-js + - wealthiest-citizen-js + - sum-target-value-from-a-list-js + - string-permutation-js + - sum-of-two-strings-js + - string-comparison-js + - steps-to-reduce-a-num-to-zero-js + - squares-of-sorted-lists-js + - rotating-a-list-js + - reversing-words-in-a-string-js + - reversing-a-string-js + - return-the-middle-of-a-list-js + - product-of-a-list-excluding-self-js + - pattern-matching-js + - pascals-triangle-index-return-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/binary-search-exercise-js/README.md b/javascript/tech-interview-exercises-js/binary-search-exercise-js/README.md new file mode 100644 index 0000000000..eb67f573b1 --- /dev/null +++ b/javascript/tech-interview-exercises-js/binary-search-exercise-js/README.md @@ -0,0 +1,9 @@ +name: Binary Search + +description: Create an algorithm that outputs the index of a number from a list using a target value. + +aspects: + - workout + +insights: + - binary-search-exercise-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/binary-search-exercise-js/binary-search-js.md b/javascript/tech-interview-exercises-js/binary-search-exercise-js/binary-search-js.md new file mode 100644 index 0000000000..dbb28906d2 --- /dev/null +++ b/javascript/tech-interview-exercises-js/binary-search-exercise-js/binary-search-js.md @@ -0,0 +1,74 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Create a function that returns the index of the given target value from a sorted numbers list. Your algorithm should use O(log n) runtime complexity. + + // Sample input list and target to use: + let numbers = [-5, -3, 1, 6, 8, 11] + let target = 6 + + // Sample output: + // The target value is on index 3 + + // Type your code here: + +--- + +# Binary Search + +--- + +## Content + +> 👩‍💻 Your task is to: **Create a function that returns the index of the given `target` value from a sorted `numbers` list. Your algorithm should use `O(log n)` runtime complexity.** + +For example, if the input list is: +```javascript +let numbers = [-5, -3, 1, 6, 8, 11] +``` + +and the target value is: +```javascript +let target = 6 +``` + +the function should return the index of the target value inside the input list: +```plain-text +3 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read this footnote[1] or review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + +--- + +## Footnotes + +[1: Hints] + +Since the input list is sorted, you can use a binary search algorithm to find the target value in the list. This algorithm has a runtime complexity of `O(log n)`, which means it can find the target value in a list of `n` elements in a time that grows logarithmically with the size of the input. + +In a binary search, you start by comparing the target value to the middle element of the list. If the target value is smaller than the middle element, you can discard the second half of the list, because the target value cannot be in that half (since the list is sorted). Otherwise, you can discard the first half of the list. + +You then repeat this process on the remaining half of the list, until you either find the target value or determine that it does not exist in the list. \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/coding-with-enki-js/README.md b/javascript/tech-interview-exercises-js/coding-with-enki-js/README.md new file mode 100644 index 0000000000..e3c1dd3ee6 --- /dev/null +++ b/javascript/tech-interview-exercises-js/coding-with-enki-js/README.md @@ -0,0 +1,9 @@ +name: Coding With Enki + +description: Write a program that generates a new string list from a numbers list using a set of rules. + +aspects: + - workout + +insights: + - coding-with-enki-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/coding-with-enki-js/coding-with-enki-js.md b/javascript/tech-interview-exercises-js/coding-with-enki-js/coding-with-enki-js.md new file mode 100644 index 0000000000..39f2300b97 --- /dev/null +++ b/javascript/tech-interview-exercises-js/coding-with-enki-js/coding-with-enki-js.md @@ -0,0 +1,67 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Write a program that generates a new string list from the given numbers list. + + // Conditions + // If a number is divisible by both 2 and 4, replace it with "I'm". + // If a number is not divisible by any number but 1 or itself (i.e. a prime number), replace it with "Enki". + // If a number is divisible by 7, replace with "with". + // If a number is divisible by both 3 and 5, replace with "coding". + + // Sample lists to use: + let numbers = [12, 21, 15, 17] + + // Type your code here: + +--- + +# Coding With Enki + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a program that generates a new string list from the given `numbers` list.** + +Conditions: + - If a number is divisible by both 2 and 4, replace it with "I'm". + - If a number is not divisible by any number but 1 or itself (i.e. a prime number), replace it with "Enki". + - If a number is divisible by 7, replace with "with". + - If a number is divisible by both 3 and 5, replace with "coding". + +For instance, if the input list was: +```javascript +let numbers = [17, 19, 23, 29] +``` + +The result would be: +```javascript +let newList = ["Enki", "Enki", "Enki", "Enki"] +``` + +Since all of these numbers satisfy the second condition. + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/javascript/tech-interview-exercises-js/concatenation-of-a-list-js/README.md b/javascript/tech-interview-exercises-js/concatenation-of-a-list-js/README.md new file mode 100644 index 0000000000..95a81c8579 --- /dev/null +++ b/javascript/tech-interview-exercises-js/concatenation-of-a-list-js/README.md @@ -0,0 +1,10 @@ +name: List Concatenation + +description: Write a function that takes in a list of numbers, concatenates it to itself, and returns it as a new list. + + +aspects: + - workout + +insights: + - concatenation-of-a-list-js diff --git a/javascript/tech-interview-exercises-js/concatenation-of-a-list-js/concatenation-of-a-list-js.md b/javascript/tech-interview-exercises-js/concatenation-of-a-list-js/concatenation-of-a-list-js.md new file mode 100644 index 0000000000..f6f8c974bf --- /dev/null +++ b/javascript/tech-interview-exercises-js/concatenation-of-a-list-js/concatenation-of-a-list-js.md @@ -0,0 +1,60 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Write a function that takes in a list of numbers, concatenates it to itself, and returns it as a new list. + + // Sample program: + let numbers = [7, 3, 7] + build_nums_list(numbers) + // [7, 3, 7, 7, 3, 7] + + // Type your code here: + +--- + +# List Concatenation + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a function that takes in a list of numbers, concatenates it to itself, and returns it as a new list.** + +For instance, if the input list is: +```javascript +let numbers = [7, 3, 7] +``` + +the function should return: + +```javascript +build_nums_list(numbers) +// [7, 3, 7, 7, 3, 7] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + + + diff --git a/javascript/tech-interview-exercises-js/find-the-unique-value-exercise-js/README.md b/javascript/tech-interview-exercises-js/find-the-unique-value-exercise-js/README.md new file mode 100644 index 0000000000..5f97062231 --- /dev/null +++ b/javascript/tech-interview-exercises-js/find-the-unique-value-exercise-js/README.md @@ -0,0 +1,9 @@ +name: Find the unique value + +description: Find the unique value in a list. + +aspects: + - workout + +insights: + - find-the-unique-value-exercise-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/find-the-unique-value-exercise-js/find-the-unique-value-exercise-js.md b/javascript/tech-interview-exercises-js/find-the-unique-value-exercise-js/find-the-unique-value-exercise-js.md new file mode 100644 index 0000000000..66d04ccbe6 --- /dev/null +++ b/javascript/tech-interview-exercises-js/find-the-unique-value-exercise-js/find-the-unique-value-exercise-js.md @@ -0,0 +1,59 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Write a function that finds the unique value from a list of numbers. The function should have linear complexity. + + // Sample program: + let numbers = [13, 13, 44, 44, 1, 1, 7, 7, 9] + find_unique(numbers) + // 9 + + // Type your code here: + +--- + +# Find the Unique Value + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a function that finds the unique value from a list of numbers. The function should have linear complexity.** + +For instance, if the input list is: + +```javascript +let numbers = [13, 13, 44, 44, 1, 1, 7, 7, 9] +``` + +the function should return `9` since it is the only element in the list that does not have a duplicate: + +```javascript +find_unique(numbers) +// 9 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + diff --git a/javascript/tech-interview-exercises-js/list-permutation-js/README.md b/javascript/tech-interview-exercises-js/list-permutation-js/README.md new file mode 100644 index 0000000000..ff6ab2abf0 --- /dev/null +++ b/javascript/tech-interview-exercises-js/list-permutation-js/README.md @@ -0,0 +1,9 @@ +name: List Permutations + +description: Write a function that finds all permutations of a list. + +aspects: + - workout + +insights: + - list-permutation-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/list-permutation-js/list-permutation-js.md b/javascript/tech-interview-exercises-js/list-permutation-js/list-permutation-js.md new file mode 100644 index 0000000000..f1325e3a64 --- /dev/null +++ b/javascript/tech-interview-exercises-js/list-permutation-js/list-permutation-js.md @@ -0,0 +1,56 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Write a function that takes in list of intengers and returns a new list of each possible permutation. + + // Sample program: + // let ints = [4, 7] + newList = [[4, 7], [7, 4]] + + // Sample list to use: + let ints = [4, 0, 1, 2, 3, 5] + + // Type your code here: + +--- + +# List Permutations + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a function that takes in list of intengers and returns a new list for each possible permutation.** + +For instance, if the input list is +```javascript +let ints = [4, 0, 7] +``` +the function should return: +```javascript +newList = [[4, 0, 7], [4, 7, 0], [0, 7, 4], [0, 4, 7], [7, 4, 0], [7, 0, 4]] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/javascript/tech-interview-exercises-js/longest-non-repeating-substring-from-string-js/README.md b/javascript/tech-interview-exercises-js/longest-non-repeating-substring-from-string-js/README.md new file mode 100644 index 0000000000..adbe26c4b0 --- /dev/null +++ b/javascript/tech-interview-exercises-js/longest-non-repeating-substring-from-string-js/README.md @@ -0,0 +1,9 @@ +name: Longest substring with no repeating characters + +description: Find the longest substring with no repeating characters from a given string. + +aspects: + - workout + +insights: + - longest-non-repeating-substring-from-string-js diff --git a/javascript/tech-interview-exercises-js/longest-non-repeating-substring-from-string-js/longest-non-repeating-substring-from-string-js.md b/javascript/tech-interview-exercises-js/longest-non-repeating-substring-from-string-js/longest-non-repeating-substring-from-string-js.md new file mode 100644 index 0000000000..4f065f4fe8 --- /dev/null +++ b/javascript/tech-interview-exercises-js/longest-non-repeating-substring-from-string-js/longest-non-repeating-substring-from-string-js.md @@ -0,0 +1,76 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Write a function that finds and returns the longest substring with no repeating characters from a given string. + + // Sample program: + let str = "asgegsagefasg" + find_longest_substring(str) + // "gef" + + // Sample strings: + let string1 = "aaaaaa" + let string2 = "asdeavfeva" + + // Type your code here: + +--- + +# Find the Longest Substring With No Repeating Letters + +--- + +## Content + +> 👩‍💻 Your task is to: **Write a function that returns the longest substring with no repeating characters from a given `string`.** + +Here is an example of how the function can be used: + +```javascript +let string1 = "asgegsagefasg" +find_longest_substring(string1) + +// "gef" + +let string2 = "abcabcbb" +find_longest_substring(string2) + +// "abc" +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read this footnote[1] or review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + + +--- + +## Footnotes + +[1: Hints] + +A substring is a contiguous sequence of characters within a string. + +For example, the substrings of the string "abcde" are: + +"a", "ab", "abc", "abcd", "abcde", "b", "bc", "bcd", "bcde", "c", "cd", "cde", "d", "de", and "e". diff --git a/javascript/tech-interview-exercises-js/longest-palindrome-js/README.md b/javascript/tech-interview-exercises-js/longest-palindrome-js/README.md new file mode 100644 index 0000000000..ba43795a86 --- /dev/null +++ b/javascript/tech-interview-exercises-js/longest-palindrome-js/README.md @@ -0,0 +1,9 @@ +name: Longest Palindrome + +description: Find and return the longest possible palindrome from a given string. + +aspects: + - workout + +insights: + - longest-palindrome-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/longest-palindrome-js/longest-palindrome-js.md b/javascript/tech-interview-exercises-js/longest-palindrome-js/longest-palindrome-js.md new file mode 100644 index 0000000000..a7540bb0df --- /dev/null +++ b/javascript/tech-interview-exercises-js/longest-palindrome-js/longest-palindrome-js.md @@ -0,0 +1,71 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Find the longest palindrome from the given letters string. + + // Sample program: + let letters = "abbbbcceeezdda" + find_longest_palindrome(letters) + // "bbbb" + + // Type your code here: + +--- + +# Longest Palindrome + +--- + +## Content + +> 👩‍💻 Your task is to: **Find the longest palindrome from the given `letters` string.** + +Sample program: +```javascript +let letters = "abbbbcceeezdda" +find_longest_palindrome(letters) + +// "bbbb" +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read this footnote[1] or review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + +--- + +## Footnotes + +[1: Hints] + +The time complexity of this task is *O(N)* where *N* is the length of our `letters` string. + +The Space complexity is *O(1)* as *s* is a fixed size of the alphabet. + +A palindrome is a word or phrase that reads the same forwards and backwards. I.e. **civic**, **level**, **madam**, and so on... + +In an even palindrome, each letter has an equal partner on the opposite side. + +In an odd palindrome, there is a single non-partnered letter in the middle of the pallindrome. + +If each letter occurs X times, we know that x // 2 * 2 is the number of letters that can be partnered. diff --git a/javascript/tech-interview-exercises-js/most-frequent-element-js/README.md b/javascript/tech-interview-exercises-js/most-frequent-element-js/README.md new file mode 100644 index 0000000000..7889cfc8b6 --- /dev/null +++ b/javascript/tech-interview-exercises-js/most-frequent-element-js/README.md @@ -0,0 +1,9 @@ +name: Most frequent element + +description: Return the most frequent element from a list. + +aspects: + - workout + +insights: + - most-frequent-element-js diff --git a/javascript/tech-interview-exercises-js/most-frequent-element-js/most-frequent-element-js.md b/javascript/tech-interview-exercises-js/most-frequent-element-js/most-frequent-element-js.md new file mode 100644 index 0000000000..d72f6abd90 --- /dev/null +++ b/javascript/tech-interview-exercises-js/most-frequent-element-js/most-frequent-element-js.md @@ -0,0 +1,51 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Return the most frequent element from a given numbers list. The time complexity should be better than O(n logn). + + // Sample lists to use: + let numbers = [1, 1, 8, 6, 4, 13, 1, 7, 8, 6] + + // Type your code here: + +--- + +# Most Frequent Element + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the most frequent element from the `numbers` list. The time complexity should be better than `O(n logn)`.** + +Sample program: +```javascript +let numbers = [1, 1, 8, 6, 4, 13, 1, 7, 8, 6] +most_frequent_element(numbers) +// 1 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can alway review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + diff --git a/javascript/tech-interview-exercises-js/move-zeroes-to-end-of-list-js/README.md b/javascript/tech-interview-exercises-js/move-zeroes-to-end-of-list-js/README.md new file mode 100644 index 0000000000..66e4c0ecc2 --- /dev/null +++ b/javascript/tech-interview-exercises-js/move-zeroes-to-end-of-list-js/README.md @@ -0,0 +1,9 @@ +name: Moving 0's to the end of a list + +description: Move all 0's to the end of the given list, whilst maintaining the relative order of other numbers. + +aspects: + - workout + +insights: + - move-zeroes-to-end-of-list-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/move-zeroes-to-end-of-list-js/move-zeroes-to-end-of-list-js.md b/javascript/tech-interview-exercises-js/move-zeroes-to-end-of-list-js/move-zeroes-to-end-of-list-js.md new file mode 100644 index 0000000000..0649a68ccd --- /dev/null +++ b/javascript/tech-interview-exercises-js/move-zeroes-to-end-of-list-js/move-zeroes-to-end-of-list-js.md @@ -0,0 +1,58 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Move all 0's to the end of the given list, whilst maintaining the relative order of other numbers. Try to solve this in-place; by not creating a new list. + + // Input + let numbers = [1, 2, 0, 3, 0, 4, 0, 5] + // Function + move_zeros(numbers) + // [1, 2, 3, 4, 5, 0, 0, 0] + + // Type your code here: + +--- + +# Move Zeroes to the End of a List + +--- + +## Content + +> 👩‍💻 Your task is to: **Move all 0's to the end of the given list, whilst maintaining the relative order of other numbers. Try to solve this in-place; by not creating a new list.** + +Sample program: +```javascript +// Input +let numbers = [1, 2, 0, 3, 0, 4, 0, 5] + +// Function +move_zeros(numbers) + +// [1, 2, 3, 4, 5, 0, 0, 0] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + diff --git a/javascript/tech-interview-exercises-js/nth-largest-element-from-a-list-js/README.md b/javascript/tech-interview-exercises-js/nth-largest-element-from-a-list-js/README.md new file mode 100644 index 0000000000..04346c2499 --- /dev/null +++ b/javascript/tech-interview-exercises-js/nth-largest-element-from-a-list-js/README.md @@ -0,0 +1,9 @@ +name: Largest Element + +description: Return the Nth Largest Element From a List + +aspects: + - workout + +insights: + - nth-largest-element-from-a-list-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/nth-largest-element-from-a-list-js/nth-largest-element-from-a-list-js.md b/javascript/tech-interview-exercises-js/nth-largest-element-from-a-list-js/nth-largest-element-from-a-list-js.md new file mode 100644 index 0000000000..8b0cb9f04b --- /dev/null +++ b/javascript/tech-interview-exercises-js/nth-largest-element-from-a-list-js/nth-largest-element-from-a-list-js.md @@ -0,0 +1,59 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Return the nth largest element from the numbers list. + + // Sample variables to use: + let numbers = [1, 4, 2, 8, 7, 5] + let n = 3 + + // nth Largest (3rd largest) + // 5 + + // Type your code here: + +--- + +# Return the Nth Largest Element From a List + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the nth largest element from a list.** + +Sample program: +```javascript +// Given list +let numbers = [1, 4, 2, 8, 7, 5] + +// Given n +let n = 3 + +// nth Largest (3rd largest) +// 5 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/javascript/tech-interview-exercises-js/number-to-roman-numeral-js/README.md b/javascript/tech-interview-exercises-js/number-to-roman-numeral-js/README.md new file mode 100644 index 0000000000..1be64cd8ab --- /dev/null +++ b/javascript/tech-interview-exercises-js/number-to-roman-numeral-js/README.md @@ -0,0 +1,9 @@ +name: Number To Roman Numeral Converter + +description: Given a list of numbers, convert them to Roman numerals. + +aspects: + - workout + +insights: + - number-to-roman-numeral-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/number-to-roman-numeral-js/number-to-roman-numeral-js.md b/javascript/tech-interview-exercises-js/number-to-roman-numeral-js/number-to-roman-numeral-js.md new file mode 100644 index 0000000000..2446d1caf1 --- /dev/null +++ b/javascript/tech-interview-exercises-js/number-to-roman-numeral-js/number-to-roman-numeral-js.md @@ -0,0 +1,107 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Generate Roman numerals from a given list of numbers. + + // Sample list to use: + let numbers = [1, 23, 44, 59, 1111, 127, 999] + + // Type your code here: + +--- + +# Number to Roman Numeral + +--- + +## Content + +> 👩‍💻 Your task is to: **Generate Roman numerals from a given list of numbers.** + +Roman numeral symbols are: + +| Roman Numeral | Integer | +|:-------------:|:-------:| +| I | 1 | +| V | 5 | +| X | 10 | +| L | 50 | +| C | 100 | +| D | 500 | +| M | 1000 | + +**Note: There are several rules Roman numerals follow. Take a look at this note[1].** + +Sample list to use: +```javascript +let numbers = [1, 23, 44, 59, 1111, 127, 999] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comment section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + +--- + +## Footnotes + +[1: Notes] + +- When a value increases, up to 3 times, the symbol is added to itself. + +If the value increases more, you subtract from the next highest numeral: + +| Roman Numeral | Integer | +|:-------------:|:-------:| +| I | 1 | +| II | 2 | +| III | 3 | +| IV | 4 | +| V | 5 | +| VI | 6 | +| VII | 7 | +| VIII | 8 | +| IX | 9 | +| X | 10 | + +- When a symbol of smaller value is after a symbol of a greater value, they are added together. If the smaller symbol is before it, they are subtracted. + +| Number | Calculation | Result | +|:------:|:-----------:|:------:| +| IV | V - I | 4 | +| VI | V + I | 6 | + +Symbols like V, L, D never repeat. That is beacuse VV is X, LL is C, DD is M. + +From symbols V and X you can only subtract I, from symbols L, C and M, you can only subtract X. + +Here's a sample of wrong vs correct way of writting numbers + +| Sample | ❌ | ✅ | +|:------:|:------:|:---:| +| 41 | XXXXI | XLI | +| 100 | LL | C | +| 59 | LVIIII | LIX | +| 7 | IIIX | VII | +| 111 | CVVI | CXI | +| 400 | CCCC | CD | \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/pascals-triangle-index-return-js/README.md b/javascript/tech-interview-exercises-js/pascals-triangle-index-return-js/README.md new file mode 100644 index 0000000000..d5b722f2be --- /dev/null +++ b/javascript/tech-interview-exercises-js/pascals-triangle-index-return-js/README.md @@ -0,0 +1,9 @@ +name: Pascals Triangles Index + +description: Return the nth row of Pascal's triangle through its index. + +aspects: + - workout + +insights: + - pascals-triangle-index-return-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/pascals-triangle-index-return-js/pascals-triangle-index-return-js.md b/javascript/tech-interview-exercises-js/pascals-triangle-index-return-js/pascals-triangle-index-return-js.md new file mode 100644 index 0000000000..1628fe005c --- /dev/null +++ b/javascript/tech-interview-exercises-js/pascals-triangle-index-return-js/pascals-triangle-index-return-js.md @@ -0,0 +1,63 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Return the nth row of the Pascal's triangle. + + // If rowIndex = 4 (5th row), you return: + // [1, 4, 6, 4, 1] + // If rowIndex = 1, you return: + // [1, 1] + + // Type your code here: + +--- + +# Pascals Triangles Index + +--- + +## Content + +> 👩‍💻 Your task is to: **Create a function that returns the nth row of the Pascal's triangle.** + +For instance, if: +```javascript +let rowIndex = 4 // (5th row) +``` + +you return: +```javascript +// [1, 4, 6, 4, 1] +``` + +> The Pascal triangle is a triangular array of binomial coefficients. + +![pascal-triangle](https://img.enkipro.com/9ca1eb25c5fc393b831db1556dcad889.png) + +Here is a gif from Wikipedia that demonstrates how each value is calculated: + +![wiki-explanation](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/javascript/tech-interview-exercises-js/pattern-matching-js/README.md b/javascript/tech-interview-exercises-js/pattern-matching-js/README.md new file mode 100644 index 0000000000..270465a9e8 --- /dev/null +++ b/javascript/tech-interview-exercises-js/pattern-matching-js/README.md @@ -0,0 +1,9 @@ +name: Pattern Match + +description: Confirm if the pattern of the given strings follows the same pattern of the `pattern` variable. + +aspects: + - workout + +insights: + - pattern-matching-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/pattern-matching-js/pattern-matching-js.md b/javascript/tech-interview-exercises-js/pattern-matching-js/pattern-matching-js.md new file mode 100644 index 0000000000..e95adbf5f2 --- /dev/null +++ b/javascript/tech-interview-exercises-js/pattern-matching-js/pattern-matching-js.md @@ -0,0 +1,65 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Confirm if the pattern of the given strings follow the same pattern of the pattern variable. + + // Sample program: + let pattern = 'aabbc' + let str1 = 'meow meow woof woof oink' + let str2 = 'meow woof oink' + + check_pattern(pattern, str1) + // True + + check_pattern(pattern, str2) + // False + + + // Type your code here: + +--- + +# Pattern Matching + +--- + +## Content + +> 👩‍💻 Your task is to: **Confirm if the pattern of the given strings follow the same pattern of the `pattern` variable.** + +Example input/output: +```javascript +let pattern = 'aabbc' +let str1 = 'meow meow woof woof oink' +let str2 = 'meow woof oink' + +check_pattern(pattern, str1) +// True + +check_pattern(pattern, str2) +// False +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read through the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/javascript/tech-interview-exercises-js/product-of-a-list-excluding-self-js/README.md b/javascript/tech-interview-exercises-js/product-of-a-list-excluding-self-js/README.md new file mode 100644 index 0000000000..326693de8e --- /dev/null +++ b/javascript/tech-interview-exercises-js/product-of-a-list-excluding-self-js/README.md @@ -0,0 +1,9 @@ +name: Product of a List Excluding Self + +description: Implement a function that returns a new list where the current element is the product of all elements in the given list excluding itself. + +aspects: + - workout + +insights: + - product-of-a-list-excluding-self-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/product-of-a-list-excluding-self-js/product-of-a-list-excluding-self-js.md b/javascript/tech-interview-exercises-js/product-of-a-list-excluding-self-js/product-of-a-list-excluding-self-js.md new file mode 100644 index 0000000000..92ddb95aa3 --- /dev/null +++ b/javascript/tech-interview-exercises-js/product-of-a-list-excluding-self-js/product-of-a-list-excluding-self-js.md @@ -0,0 +1,60 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Implement a function that returns a new list such that the current element is the product of all elements in the given list excluding itself. The function should have a runtime complexity of O(n). + + // Sample list: + let numbers = [1, 3, 4, 6, 7] + + // Sample return: + product_list(numbers) + // [504, 168, 126, 84, 72] + + // Type your code here: + +--- + +# Product of List Excluding Self + +--- + +## Content + +> 👩‍💻 Your task is to: **Implement a function that returns a new list such that the current element is the product of all elements in the `numbers` list excluding itself. The function should have a runtime complexity of `O(n)`.** + +For instance, if the input list: +```javascript +let numbers = [1, 3, 4, 6] +``` + +you would return: +```javascript +product_list(numbers) + +// [72, 24, 18, 12] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + diff --git a/javascript/tech-interview-exercises-js/return-the-middle-of-a-list-js/README.md b/javascript/tech-interview-exercises-js/return-the-middle-of-a-list-js/README.md new file mode 100644 index 0000000000..3c0e65f439 --- /dev/null +++ b/javascript/tech-interview-exercises-js/return-the-middle-of-a-list-js/README.md @@ -0,0 +1,9 @@ +name: Return the Middle Element from a List + +description: Returns the middle element of a list. + +aspects: + - workout + +insights: + - return-the-middle-of-a-list-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/return-the-middle-of-a-list-js/return-the-middle-of-a-list-js.md b/javascript/tech-interview-exercises-js/return-the-middle-of-a-list-js/return-the-middle-of-a-list-js.md new file mode 100644 index 0000000000..60ba5e3d2f --- /dev/null +++ b/javascript/tech-interview-exercises-js/return-the-middle-of-a-list-js/return-the-middle-of-a-list-js.md @@ -0,0 +1,60 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Create a function that finds and returns the middle element of a list. If the list has 2 middle elements, return the first one. + + // Sample program: + let numbers = [1, 2, 3, 4, 5, 6] + find_middle(numbers) + // 3 + + let numbers = [1, 2, 3, 4, 5, 6, 7] + find_middle(numbers) + // 4 + + // Type your code here: + +--- + +# Return the Middle of a List + +--- + +## Content + +> 👩‍💻 Your task is to: **Implement a function that returns the middle element of a `numbers` list. If the list has 2 middle elements, return the first one.** + +Sample program: +```javascript +let numbers = [1, 2, 3, 4, 5, 6] +find_middle(numbers) +// 3 + +let numbers = [1, 2, 3, 4, 5, 6, 7] +find_middle(numbers) +// 4 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/javascript/tech-interview-exercises-js/reversing-a-string-js/README.md b/javascript/tech-interview-exercises-js/reversing-a-string-js/README.md new file mode 100644 index 0000000000..c22d0a262f --- /dev/null +++ b/javascript/tech-interview-exercises-js/reversing-a-string-js/README.md @@ -0,0 +1,9 @@ +name: Reversing a String + +description: Reverse the order of characters in a given string. + +aspects: + - workout + +insights: + - reversing-a-string-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/reversing-a-string-js/reversing-a-string-js.md b/javascript/tech-interview-exercises-js/reversing-a-string-js/reversing-a-string-js.md new file mode 100644 index 0000000000..1c0f1003d3 --- /dev/null +++ b/javascript/tech-interview-exercises-js/reversing-a-string-js/reversing-a-string-js.md @@ -0,0 +1,51 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Create a function that reverses the given words string. Modify the given input string list in-place with O(1) memory. + + // Sample lists to use: + let words = ['H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'] + + // Type your code here: + +--- + +# Reverse a String + +--- + +## Content + +> 👩‍💻 Your task is to: **Create a function that reverses the given `words` string. Modify the given input string list in-place with `O(1)` memory.** + +Sample program: +```javascript +let words = ['H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'] +reverse_string(words) + +// ['d', 'l', 'r', 'o', 'w', 'o', 'l', 'l', 'e', 'H'] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/javascript/tech-interview-exercises-js/reversing-words-in-a-string-js/README.md b/javascript/tech-interview-exercises-js/reversing-words-in-a-string-js/README.md new file mode 100644 index 0000000000..8ab2125743 --- /dev/null +++ b/javascript/tech-interview-exercises-js/reversing-words-in-a-string-js/README.md @@ -0,0 +1,9 @@ +name: Reversing words in a string + +description: Reverse the order of characters in a string while preserving the space and initial order between words. + +aspects: + - workout + +insights: + - reversing-words-in-a-string-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/reversing-words-in-a-string-js/reversing-words-in-a-string-js.md b/javascript/tech-interview-exercises-js/reversing-words-in-a-string-js/reversing-words-in-a-string-js.md new file mode 100644 index 0000000000..17bb9e3385 --- /dev/null +++ b/javascript/tech-interview-exercises-js/reversing-words-in-a-string-js/reversing-words-in-a-string-js.md @@ -0,0 +1,53 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Reverse the order of characters in the given sentence while preserving the whitespace and initial order between words. + + // Sample sentence to reverse: + let sentence = "Enki is the god of knowledge, water, crafts and creation" + reverse_sentence(sentence) + + // noitaerc dna stfarc ,retaw ,egdelwonk fo dog eht si iknE + // Type your code here: + +--- + +# Reversing Words in a String + +--- + +## Content + +> 👩‍💻 Your task is to: **Reverse the order of characters in the given string while preserving the whitespace and initial order between words.** + +Sample program: +```javascript +let sentence = "You passed the test" +reverse_sentence(sentence) + +// "uoY dessap eht tset" +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/javascript/tech-interview-exercises-js/rotating-a-list-js/README.md b/javascript/tech-interview-exercises-js/rotating-a-list-js/README.md new file mode 100644 index 0000000000..5cfe716f20 --- /dev/null +++ b/javascript/tech-interview-exercises-js/rotating-a-list-js/README.md @@ -0,0 +1,9 @@ +name: Rotating a list + +description: Rotate the given list to the right by n steps. + +aspects: + - workout + +insights: + - rotating-a-list-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/rotating-a-list-js/rotating-a-list-js.md b/javascript/tech-interview-exercises-js/rotating-a-list-js/rotating-a-list-js.md new file mode 100644 index 0000000000..503cc0062e --- /dev/null +++ b/javascript/tech-interview-exercises-js/rotating-a-list-js/rotating-a-list-js.md @@ -0,0 +1,59 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Rotate the given numbers list to the right by n steps. Could you solve this in-place using O(1) extra space? + + // Sample variables to use: + let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] + let n = 4 + + // Result: + rotate_list(numbers, n) + + // [6, 7, 8, 9, 1, 2, 3, 4, 5] + + // Type your code here: + +--- + +# Find the Non-Duplicate Value + +--- + +## Content + +> 👩‍💻 Your task is to: **Rotate the given `numbers` list to the right by `n` steps. Could you solve this in-place using `O(1)` extra space?** + +Sample variables to use: +```javascript +let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] +let n = 4 + +rotate_list(numbers, n) + +// [6, 7, 8, 9, 1, 2, 3, 4, 5] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/squares-of-sorted-lists-js/README.md b/javascript/tech-interview-exercises-js/squares-of-sorted-lists-js/README.md new file mode 100644 index 0000000000..bcadb73c5b --- /dev/null +++ b/javascript/tech-interview-exercises-js/squares-of-sorted-lists-js/README.md @@ -0,0 +1,9 @@ +name: Squares of a Sorted List + +description: Create an algorithm that returns squared values for each element of the given list. + +aspects: + - workout + +insights: + - squares-of-sorted-lists-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/squares-of-sorted-lists-js/squares-of-sorted-lists-js.md b/javascript/tech-interview-exercises-js/squares-of-sorted-lists-js/squares-of-sorted-lists-js.md new file mode 100644 index 0000000000..e4d7aed740 --- /dev/null +++ b/javascript/tech-interview-exercises-js/squares-of-sorted-lists-js/squares-of-sorted-lists-js.md @@ -0,0 +1,54 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Return a list of squares from a given non-squared list of integers. The new list should be sorted in an ascending order. Try to find an O(n) solution. + + // Sample lists to use: + let numbers = [-9, -3, 0, 1, 3, 4, 9, 12] + sort_squares(numbers) + + // [0, 1, 9, 9, 16, 81, 81, 144] + + // Type your code here: +--- + +# Squares of a Sorted List + +--- + +## Content + +> 👩‍💻 Your task is to: **Return a list of squares from a given non-squared list of integers. The new list should be sorted in an ascending order. Try to find an `O(n)` solution.** + +Sample program: + +```javascript +let numbers = [-9, -3, 0, 1, 3, 4, 9, 12] +sort_squares(numbers) + +// [0, 1, 9, 9, 16, 81, 81, 144] +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/javascript/tech-interview-exercises-js/steps-to-reduce-a-num-to-zero-js/README.md b/javascript/tech-interview-exercises-js/steps-to-reduce-a-num-to-zero-js/README.md new file mode 100644 index 0000000000..32ceb1f6e1 --- /dev/null +++ b/javascript/tech-interview-exercises-js/steps-to-reduce-a-num-to-zero-js/README.md @@ -0,0 +1,9 @@ +name: Number of steps to reduce a number to zero + +description: Return the number of steps necessary to reduce a number to zero. + +aspects: + - workout + +insights: + - steps-to-reduce-a-num-to-zero-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/steps-to-reduce-a-num-to-zero-js/steps-to-reduce-a-num-to-zero-js.md b/javascript/tech-interview-exercises-js/steps-to-reduce-a-num-to-zero-js/steps-to-reduce-a-num-to-zero-js.md new file mode 100644 index 0000000000..fa8c326abc --- /dev/null +++ b/javascript/tech-interview-exercises-js/steps-to-reduce-a-num-to-zero-js/steps-to-reduce-a-num-to-zero-js.md @@ -0,0 +1,73 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Return the number of steps needed to reduce a given number to 0. + + // Rules: + // If the current number is even, you divide it by 2, + // if it is odd, you reduce it by 1. + + // Sample numbers to use: + let num1 = 314 + let num2 = 7 + let num3 = 15 + let num4 = 555 + + // Type your code here: + +--- + +# Steps to Reduce a Number to Zero + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the number of steps needed to reduce a given number to 0.** + +Rules: +- If the current number is even, you divide it by 2, +- if it is odd, you reduce it by 1. + +Sample program: +```javascript +let num1 = 314 +reduce_to_zero(num1) +// 13 + +let num2 = 7 +reduce_to_zero(num2) +// 5 + +let num3 = 15 +reduce_to_zero(num3) +// 7 + +let num4 = 555 +reduce_to_zero(num4) +// 14 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/javascript/tech-interview-exercises-js/string-comparison-js/README.md b/javascript/tech-interview-exercises-js/string-comparison-js/README.md new file mode 100644 index 0000000000..9937cdb625 --- /dev/null +++ b/javascript/tech-interview-exercises-js/string-comparison-js/README.md @@ -0,0 +1,9 @@ +name: String Comparison + +description: Given a string of characters, check if any of the given words can be constructed using those characters. + +aspects: + - workout + +insights: + - string-comparison-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/string-comparison-js/string-comparison-js.md b/javascript/tech-interview-exercises-js/string-comparison-js/string-comparison-js.md new file mode 100644 index 0000000000..82bc51a4ab --- /dev/null +++ b/javascript/tech-interview-exercises-js/string-comparison-js/string-comparison-js.md @@ -0,0 +1,74 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Return true if the characters from the given letters string can be used to construct any of the word strings; otherwise return false. You can use each letter only once. + + // Sample lists to use: + let letters = 'aaabnn' + let word1 = 'banana' + let word2 = 'apple' + let word3 = 'ban' + let word4 = 'bananas' + + print(can_construct_words(letters, word1)) + // True + print(can_construct_words(letters, word2)) + // False + print(can_construct_words(letters, word3)) + // True + print(can_construct_words(letters, word4)) + // False + + // Type your code here: + +--- + +# String Comparison + +--- + +## Content + +> 👩‍💻 Your task is to: **Check if the characters in the `letters` string can be used to construct any of the `word` strings without repeating any letters. Return `true` if any of the `word` strings can be constructed, and `false` otherwise.** + +Sample strings to use: +```javascript +let letters = 'aaabnn' +let word1 = 'banana' +let word2 = 'apple' +let word3 = 'ban' +let word4 = 'bananas' + +print(can_construct_words(letters, word1)) +// True +print(can_construct_words(letters, word2)) +// False +print(can_construct_words(letters, word3)) +// True +print(can_construct_words(letters, word4)) +// False +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/javascript/tech-interview-exercises-js/string-permutation-js/README.md b/javascript/tech-interview-exercises-js/string-permutation-js/README.md new file mode 100644 index 0000000000..c2eaa44359 --- /dev/null +++ b/javascript/tech-interview-exercises-js/string-permutation-js/README.md @@ -0,0 +1,9 @@ +name: String Permutation + +description: Given a substring and some strings, determine if any permutation of the given substring is located inside the strings. + +aspects: + - workout + +insights: + - string-permutation-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/string-permutation-js/string-permutation-js.md b/javascript/tech-interview-exercises-js/string-permutation-js/string-permutation-js.md new file mode 100644 index 0000000000..24a1dc012a --- /dev/null +++ b/javascript/tech-interview-exercises-js/string-permutation-js/string-permutation-js.md @@ -0,0 +1,76 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Return true if a permutation of the given substring is located inside the given strings. + + // Sample lists to use: + let subStr = 'ao' + let str1 = 'boat' + let str2 = 'broader' + let str3 = 'milk' + + print(has_permutation_in_string(subStr, str1)) + // True + print(has_permutation_in_string(subStr, str2)) + // True + print(has_permutation_in_string(subStr, str3)) + // False + + // Type your code here: + +--- + +# String Permutation + +--- + +## Content + +> 👩‍💻 Your task is to: **Return `true` if a permutation of the given substring can be found within any of the given strings.** + +Sample variables to use: +```javascript +let subStr = 'ao' +let str1 = 'boat' +let str2 = 'broader' +let str3 = 'milk' + +print(has_permutation_in_string(subStr, str1)) +// True +print(has_permutation_in_string(subStr, str2)) +// True +print(has_permutation_in_string(subStr, str3)) +// False +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always read this footnote[1] or review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! + +--- + +## Footnotes + +[1: Hints] + +You can sort the strings and substrings, then check if the substring is located inside the strings. \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/sum-of-two-strings-js/README.md b/javascript/tech-interview-exercises-js/sum-of-two-strings-js/README.md new file mode 100644 index 0000000000..03534262c6 --- /dev/null +++ b/javascript/tech-interview-exercises-js/sum-of-two-strings-js/README.md @@ -0,0 +1,9 @@ +name: Sum of Two Strings + +description: Return the sum of two integer values represented as strings, as a single string value. + +aspects: + - workout + +insights: + - sum-of-two-strings-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/sum-of-two-strings-js/sum-of-two-strings-js.md b/javascript/tech-interview-exercises-js/sum-of-two-strings-js/sum-of-two-strings-js.md new file mode 100644 index 0000000000..f192f445a6 --- /dev/null +++ b/javascript/tech-interview-exercises-js/sum-of-two-strings-js/sum-of-two-strings-js.md @@ -0,0 +1,58 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Return the sum of two integer values represented as strings, as a single string value. Try to solve this by not directly transforming the values with `int()`. + + // Strings to use: + let num1 = "19" + let num2 = "7" + + // Test the function + print(add_integer_strings(num1, num2)) + // "26" + + // Type your code here: + +--- + +# Sum of Two Strings + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the sum of two integer values represented as strings, as a single string value. Try to solve this by not directly transforming the values with `int()`.** + +Sample list to use: +```javascript +let num1 = "19" +let num2 = "7" + +// Test the function +print(add_integer_strings(num1, num2)) +// "26" +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/javascript/tech-interview-exercises-js/sum-target-value-from-a-list-js/README.md b/javascript/tech-interview-exercises-js/sum-target-value-from-a-list-js/README.md new file mode 100644 index 0000000000..fccad83573 --- /dev/null +++ b/javascript/tech-interview-exercises-js/sum-target-value-from-a-list-js/README.md @@ -0,0 +1,9 @@ +name: Sum Target Value From a Given List + +description: Find which two numbers of the given `numbers` list, when summed up, equal the `target` value. Return their indices. + +aspects: + - workout + +insights: + - sum-target-value-from-a-list-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/sum-target-value-from-a-list-js/sum-target-value-from-a-list-js.md b/javascript/tech-interview-exercises-js/sum-target-value-from-a-list-js/sum-target-value-from-a-list-js.md new file mode 100644 index 0000000000..d6352b63ed --- /dev/null +++ b/javascript/tech-interview-exercises-js/sum-target-value-from-a-list-js/sum-target-value-from-a-list-js.md @@ -0,0 +1,64 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Find which two numbers of the given numbers list, when summed up, equal the target value. Return their indices. + + // Sample lists to use: + let numbers = [1, 2, 4, 7, 12] + let target1 = 6 + let target2 = 11 + + print(find_indices_of_target_sum(numbers, target1)) + // (1, 2) + + print(find_indices_of_target_sum(numbers, target2)) + // (2, 3) + + // Type your code here: + +--- + +# Sum Target Value From a List + +--- + +## Content + +> 👩‍💻 Your task is to: **Find which two numbers of the given `numbers` list, when summed up, equal the `target` value. Return their indices.** + +Sample program: +```javascript +let numbers = [1, 2, 4, 7, 12] +let target1 = 6 +let target2 = 11 + +print(find_indices_of_target_sum(numbers, target1)) +// (1, 2) + +print(find_indices_of_target_sum(numbers, target2)) +// (2, 3) +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! diff --git a/javascript/tech-interview-exercises-js/wealthiest-citizen-js/README.md b/javascript/tech-interview-exercises-js/wealthiest-citizen-js/README.md new file mode 100644 index 0000000000..ca55f42495 --- /dev/null +++ b/javascript/tech-interview-exercises-js/wealthiest-citizen-js/README.md @@ -0,0 +1,9 @@ +name: Wealthiest Citizen + +description: Find the citizen with the most wealth from a list of bank accounts. + +aspects: + - workout + +insights: + - wealthiest-citizen-js \ No newline at end of file diff --git a/javascript/tech-interview-exercises-js/wealthiest-citizen-js/wealthiest-citizen-js.md b/javascript/tech-interview-exercises-js/wealthiest-citizen-js/wealthiest-citizen-js.md new file mode 100644 index 0000000000..82f3563673 --- /dev/null +++ b/javascript/tech-interview-exercises-js/wealthiest-citizen-js/wealthiest-citizen-js.md @@ -0,0 +1,61 @@ +--- +author: Stefan-Stojanovic + +tags: + - coding + +type: normal + +category: coding + +setupCode: + startingPoint: | + // Welcome to the Javascript coding playground. + // Return the wealthiest citizen from a list of bank accounts. Each person will have multiple accounts. Add their accounts together to determine their total wealth. + + // Sample accounts to use: + let accounts = [[2, 1, 7], [7, 5, -3], [12, -5, 1], [1, 0, 11]] + + print(return_wealthiest_citizen(accounts)) + + // Sample outputs: + // 12 + // [1, 0, 11] is the wealthiest citizen with total wealth = 12 + + + // Type your code here: + +--- + +# Wealthiest Citizen + +--- + +## Content + +> 👩‍💻 Your task is to: **Return the wealthiest citizen from a list of bank accounts. Each person will have multiple accounts. Add their accounts together to determine their total wealth.** + +Sample program: +```javascript +let accounts = [[2, 1, 7], [7, 5, -3], [12, -5, 1], [1, 0, 11]] + +print(return_wealthiest_citizen(accounts)) + +// Sample outputs: +// 12 +// [1, 0, 11] is the wealthiest citizen with total wealth = 12 +``` + +--- + +Give it an honest try, and feel free to share your solution! + +If you’re stuck, you can always review the comments section. + +😇 Help us build an uplifting community by leaving encouraging comments or by upvoting your favorite ones! + +> 💡 Take a look at [how you can format text using markdown](https://www.enki.com/glossary/general/markdown-formatting). + +> 💡 The guidelines above are just suggestions. Feel free to include other concepts in your solution as you see fit. The implementation is up to you. + +> 🤓 Happy learning! Open the playground and start coding! From c4c79eb675f0abd55f52549b37c22e1af2e6f3f5 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Fri, 16 Dec 2022 15:58:22 +0100 Subject: [PATCH 303/390] add changelog --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c763a7407..2cd0811f94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## December 16th 2022 + +### Added +- [JavaScript - Tech Interview Exercises - add 25 exercises](https://github.com/enkidevs/curriculum/pull/3141) + ## December 12th 2022 ### Fixed From af44697c14373f00a2f56384dd79ae767f268fd6 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Fri, 16 Dec 2022 16:06:41 +0100 Subject: [PATCH 304/390] add suffix ti for tech interview questions --- .../tech-interview-questions/README.md | 50 +++++++++---------- .../README.md | 2 +- .../binary-search-exercise-ti.md} | 0 .../README.md | 2 +- .../coding-with-enki-ti.md} | 0 .../README.md | 2 +- .../concatenation-of-a-list-ti.md} | 0 .../README.md | 2 +- .../find-the-unique-value-exercise-ti.md} | 0 .../README.md | 2 +- .../list-permutation-ti.md} | 0 .../README.md | 2 +- ...non-repeating-substring-from-string-ti.md} | 0 .../README.md | 2 +- .../longest-palindrome-ti.md} | 0 .../README.md | 2 +- .../most-frequent-element-ti.md} | 0 .../README.md | 2 +- .../move-zeroes-to-end-of-list-ti.md} | 0 .../README.md | 2 +- .../nth-largest-element-from-a-list-ti.md} | 0 .../README.md | 2 +- .../number-to-roman-numeral-ti.md} | 0 .../README.md | 2 +- .../pascals-triangle-index-return-ti.md} | 0 .../README.md | 2 +- .../pattern-matching-ti.md} | 0 .../README.md | 2 +- .../product-of-a-list-excluding-self-ti.md} | 0 .../README.md | 2 +- .../return-the-middle-of-a-list-ti.md} | 0 .../README.md | 2 +- .../reversing-a-string-ti.md} | 0 .../README.md | 2 +- .../reversing-words-in-a-string-ti.md} | 0 .../README.md | 2 +- .../rotating-a-list-ti.md} | 0 .../README.md | 2 +- .../squares-of-sorted-lists-ti.md} | 0 .../README.md | 2 +- .../steps-to-reduce-a-num-to-zero-ti.md} | 0 .../README.md | 2 +- .../string-comparison-ti.md} | 0 .../README.md | 2 +- .../string-permutation-ti.md} | 0 .../README.md | 2 +- .../sum-of-two-strings-ti.md} | 0 .../README.md | 2 +- .../sum-target-value-from-a-list-ti-ti.md} | 0 .../README.md | 2 +- .../wealthiest-citizen-ti-ti.md} | 0 51 files changed, 50 insertions(+), 50 deletions(-) rename tech-interviews/tech-interview-questions/{binary-search-exercise => binary-search-exercise-ti}/README.md (84%) rename tech-interviews/tech-interview-questions/{binary-search-exercise/binary-search-exercise.md => binary-search-exercise-ti/binary-search-exercise-ti.md} (100%) rename tech-interviews/tech-interview-questions/{coding-with-enki => coding-with-enki-ti}/README.md (87%) rename tech-interviews/tech-interview-questions/{coding-with-enki/coding-with-enki.md => coding-with-enki-ti/coding-with-enki-ti.md} (100%) rename tech-interviews/tech-interview-questions/{concatenation-of-a-list => concatenation-of-a-list-ti}/README.md (85%) rename tech-interviews/tech-interview-questions/{concatenation-of-a-list/concatenation-of-a-list.md => concatenation-of-a-list-ti/concatenation-of-a-list-ti.md} (100%) rename tech-interviews/tech-interview-questions/{find-the-unique-value-exercise => find-the-unique-value-exercise-ti}/README.md (74%) rename tech-interviews/tech-interview-questions/{find-the-unique-value-exercise/find-the-unique-value-exercise.md => find-the-unique-value-exercise-ti/find-the-unique-value-exercise-ti.md} (100%) rename tech-interviews/tech-interview-questions/{list-permutation => list-permutation-ti}/README.md (84%) rename tech-interviews/tech-interview-questions/{list-permutation/list-permutation.md => list-permutation-ti/list-permutation-ti.md} (100%) rename tech-interviews/tech-interview-questions/{longest-non-repeating-substring-from-string => longest-non-repeating-substring-from-string-ti}/README.md (77%) rename tech-interviews/tech-interview-questions/{longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string.md => longest-non-repeating-substring-from-string-ti/longest-non-repeating-substring-from-string-ti.md} (100%) rename tech-interviews/tech-interview-questions/{longest-palindrome => longest-palindrome-ti}/README.md (84%) rename tech-interviews/tech-interview-questions/{longest-palindrome/longest-palindrome.md => longest-palindrome-ti/longest-palindrome-ti.md} (100%) rename tech-interviews/tech-interview-questions/{most-frequent-element => most-frequent-element-ti}/README.md (80%) rename tech-interviews/tech-interview-questions/{most-frequent-element/most-frequent-element.md => most-frequent-element-ti/most-frequent-element-ti.md} (100%) rename tech-interviews/tech-interview-questions/{move-zeroes-to-end-of-list => move-zeroes-to-end-of-list-ti}/README.md (84%) rename tech-interviews/tech-interview-questions/{move-zeroes-to-end-of-list/move-zeroes-to-end-of-list.md => move-zeroes-to-end-of-list-ti/move-zeroes-to-end-of-list-ti.md} (100%) rename tech-interviews/tech-interview-questions/{nth-largest-element-from-a-list => nth-largest-element-from-a-list-ti}/README.md (74%) rename tech-interviews/tech-interview-questions/{nth-largest-element-from-a-list/nth-largest-element-from-a-list.md => nth-largest-element-from-a-list-ti/nth-largest-element-from-a-list-ti.md} (100%) rename tech-interviews/tech-interview-questions/{number-to-roman-numeral => number-to-roman-numeral-ti}/README.md (82%) rename tech-interviews/tech-interview-questions/{number-to-roman-numeral/number-to-roman-numeral.md => number-to-roman-numeral-ti/number-to-roman-numeral-ti.md} (100%) rename tech-interviews/tech-interview-questions/{pascals-triangle-index-return => pascals-triangle-index-return-ti}/README.md (79%) rename tech-interviews/tech-interview-questions/{pascals-triangle-index-return/pascals-triangle-index-return.md => pascals-triangle-index-return-ti/pascals-triangle-index-return-ti.md} (100%) rename tech-interviews/tech-interview-questions/{pattern-matching => pattern-matching-ti}/README.md (87%) rename tech-interviews/tech-interview-questions/{pattern-matching/pattern-matching.md => pattern-matching-ti/pattern-matching-ti.md} (100%) rename tech-interviews/tech-interview-questions/{product-of-a-list-excluding-self => product-of-a-list-excluding-self-ti}/README.md (85%) rename tech-interviews/tech-interview-questions/{product-of-a-list-excluding-self/product-of-a-list-excluding-self.md => product-of-a-list-excluding-self-ti/product-of-a-list-excluding-self-ti.md} (100%) rename tech-interviews/tech-interview-questions/{return-the-middle-of-a-list => return-the-middle-of-a-list-ti}/README.md (79%) rename tech-interviews/tech-interview-questions/{return-the-middle-of-a-list/return-the-middle-of-a-list.md => return-the-middle-of-a-list-ti/return-the-middle-of-a-list-ti.md} (100%) rename tech-interviews/tech-interview-questions/{reversing-a-string => reversing-a-string-ti}/README.md (83%) rename tech-interviews/tech-interview-questions/{reversing-a-string/reversing-a-string.md => reversing-a-string-ti/reversing-a-string-ti.md} (100%) rename tech-interviews/tech-interview-questions/{reversing-words-in-a-string => reversing-words-in-a-string-ti}/README.md (84%) rename tech-interviews/tech-interview-questions/{reversing-words-in-a-string/reversing-words-in-a-string.md => reversing-words-in-a-string-ti/reversing-words-in-a-string-ti.md} (100%) rename tech-interviews/tech-interview-questions/{rotating-a-list => rotating-a-list-ti}/README.md (84%) rename tech-interviews/tech-interview-questions/{rotating-a-list/rotating-a-list.md => rotating-a-list-ti/rotating-a-list-ti.md} (100%) rename tech-interviews/tech-interview-questions/{squares-of-sorted-lists => squares-of-sorted-lists-ti}/README.md (84%) rename tech-interviews/tech-interview-questions/{squares-of-sorted-lists/squares-of-sorted-lists.md => squares-of-sorted-lists-ti/squares-of-sorted-lists-ti.md} (100%) rename tech-interviews/tech-interview-questions/{steps-to-reduce-a-num-to-zero => steps-to-reduce-a-num-to-zero-ti}/README.md (81%) rename tech-interviews/tech-interview-questions/{steps-to-reduce-a-num-to-zero/steps-to-reduce-a-num-to-zero.md => steps-to-reduce-a-num-to-zero-ti/steps-to-reduce-a-num-to-zero-ti.md} (100%) rename tech-interviews/tech-interview-questions/{string-comparison => string-comparison-ti}/README.md (88%) rename tech-interviews/tech-interview-questions/{string-comparison/string-comparison.md => string-comparison-ti/string-comparison-ti.md} (100%) rename tech-interviews/tech-interview-questions/{string-permutation => string-permutation-ti}/README.md (88%) rename tech-interviews/tech-interview-questions/{string-permutation/string-permutation.md => string-permutation-ti/string-permutation-ti.md} (100%) rename tech-interviews/tech-interview-questions/{sum-of-two-strings => sum-of-two-strings-ti}/README.md (86%) rename tech-interviews/tech-interview-questions/{sum-of-two-strings/sum-of-two-strings.md => sum-of-two-strings-ti/sum-of-two-strings-ti.md} (100%) rename tech-interviews/tech-interview-questions/{sum-target-value-from-a-list => sum-target-value-from-a-list-ti}/README.md (85%) rename tech-interviews/tech-interview-questions/{sum-target-value-from-a-list/sum-target-value-from-a-list.md => sum-target-value-from-a-list-ti/sum-target-value-from-a-list-ti-ti.md} (100%) rename tech-interviews/tech-interview-questions/{wealthiest-citizen => wealthiest-citizen-ti}/README.md (84%) rename tech-interviews/tech-interview-questions/{wealthiest-citizen/wealthiest-citizen.md => wealthiest-citizen-ti/wealthiest-citizen-ti-ti.md} (100%) diff --git a/tech-interviews/tech-interview-questions/README.md b/tech-interviews/tech-interview-questions/README.md index 6fd41cfba0..1bed7bd885 100644 --- a/tech-interviews/tech-interview-questions/README.md +++ b/tech-interviews/tech-interview-questions/README.md @@ -4,28 +4,28 @@ description: Questions to improve your coding skills. sections: '0': - - binary-search-exercise - - list-permutation - - coding-with-enki - - concatenation-of-a-list - - find-the-unique-value-exercise - - longest-non-repeating-substring-from-string - - longest-palindrome - - move-zeroes-to-end-of-list - - nth-largest-element-from-a-list - - most-frequent-element - - number-to-roman-numeral - - wealthiest-citizen - - sum-target-value-from-a-list - - string-permutation - - sum-of-two-strings - - string-comparison - - steps-to-reduce-a-num-to-zero - - squares-of-sorted-lists - - rotating-a-list - - reversing-words-in-a-string - - reversing-a-string - - return-the-middle-of-a-list - - product-of-a-list-excluding-self - - pattern-matching - - pascals-triangle-index-return \ No newline at end of file + - binary-search-exercise-ti + - list-permutation-ti + - coding-with-enki-ti + - concatenation-of-a-list-ti + - find-the-unique-value-exercise-ti + - longest-non-repeating-substring-from-string-ti + - longest-palindrome-ti + - move-zeroes-to-end-of-list-ti + - nth-largest-element-from-a-list-ti + - most-frequent-element-ti + - number-to-roman-numeral-ti + - wealthiest-citizen-ti + - sum-target-value-from-a-list-ti + - string-permutation-ti + - sum-of-two-strings-ti + - string-comparison-ti + - steps-to-reduce-a-num-to-zero-ti + - squares-of-sorted-lists-ti + - rotating-a-list-ti + - reversing-words-in-a-string-ti + - reversing-a-string-ti + - return-the-middle-of-a-list-ti + - product-of-a-list-excluding-self-ti + - pattern-matching-ti + - pascals-triangle-index-return-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/binary-search-exercise/README.md b/tech-interviews/tech-interview-questions/binary-search-exercise-ti/README.md similarity index 84% rename from tech-interviews/tech-interview-questions/binary-search-exercise/README.md rename to tech-interviews/tech-interview-questions/binary-search-exercise-ti/README.md index 196c401a1a..897da46755 100644 --- a/tech-interviews/tech-interview-questions/binary-search-exercise/README.md +++ b/tech-interviews/tech-interview-questions/binary-search-exercise-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - binary-search-exercise \ No newline at end of file + - binary-search-exercise-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/binary-search-exercise/binary-search-exercise.md b/tech-interviews/tech-interview-questions/binary-search-exercise-ti/binary-search-exercise-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/binary-search-exercise/binary-search-exercise.md rename to tech-interviews/tech-interview-questions/binary-search-exercise-ti/binary-search-exercise-ti.md diff --git a/tech-interviews/tech-interview-questions/coding-with-enki/README.md b/tech-interviews/tech-interview-questions/coding-with-enki-ti/README.md similarity index 87% rename from tech-interviews/tech-interview-questions/coding-with-enki/README.md rename to tech-interviews/tech-interview-questions/coding-with-enki-ti/README.md index 7e220e8399..c15849c2a9 100644 --- a/tech-interviews/tech-interview-questions/coding-with-enki/README.md +++ b/tech-interviews/tech-interview-questions/coding-with-enki-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - coding-with-enki \ No newline at end of file + - coding-with-enki-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md b/tech-interviews/tech-interview-questions/coding-with-enki-ti/coding-with-enki-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/coding-with-enki/coding-with-enki.md rename to tech-interviews/tech-interview-questions/coding-with-enki-ti/coding-with-enki-ti.md diff --git a/tech-interviews/tech-interview-questions/concatenation-of-a-list/README.md b/tech-interviews/tech-interview-questions/concatenation-of-a-list-ti/README.md similarity index 85% rename from tech-interviews/tech-interview-questions/concatenation-of-a-list/README.md rename to tech-interviews/tech-interview-questions/concatenation-of-a-list-ti/README.md index e95e232591..fe6342e752 100644 --- a/tech-interviews/tech-interview-questions/concatenation-of-a-list/README.md +++ b/tech-interviews/tech-interview-questions/concatenation-of-a-list-ti/README.md @@ -7,4 +7,4 @@ aspects: - workout insights: - - concatenation-of-a-list + - concatenation-of-a-list-ti diff --git a/tech-interviews/tech-interview-questions/concatenation-of-a-list/concatenation-of-a-list.md b/tech-interviews/tech-interview-questions/concatenation-of-a-list-ti/concatenation-of-a-list-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/concatenation-of-a-list/concatenation-of-a-list.md rename to tech-interviews/tech-interview-questions/concatenation-of-a-list-ti/concatenation-of-a-list-ti.md diff --git a/tech-interviews/tech-interview-questions/find-the-unique-value-exercise/README.md b/tech-interviews/tech-interview-questions/find-the-unique-value-exercise-ti/README.md similarity index 74% rename from tech-interviews/tech-interview-questions/find-the-unique-value-exercise/README.md rename to tech-interviews/tech-interview-questions/find-the-unique-value-exercise-ti/README.md index 0097225ef8..99a95ab27a 100644 --- a/tech-interviews/tech-interview-questions/find-the-unique-value-exercise/README.md +++ b/tech-interviews/tech-interview-questions/find-the-unique-value-exercise-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - find-the-unique-value-exercise \ No newline at end of file + - find-the-unique-value-exercise-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/find-the-unique-value-exercise/find-the-unique-value-exercise.md b/tech-interviews/tech-interview-questions/find-the-unique-value-exercise-ti/find-the-unique-value-exercise-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/find-the-unique-value-exercise/find-the-unique-value-exercise.md rename to tech-interviews/tech-interview-questions/find-the-unique-value-exercise-ti/find-the-unique-value-exercise-ti.md diff --git a/tech-interviews/tech-interview-questions/list-permutation/README.md b/tech-interviews/tech-interview-questions/list-permutation-ti/README.md similarity index 84% rename from tech-interviews/tech-interview-questions/list-permutation/README.md rename to tech-interviews/tech-interview-questions/list-permutation-ti/README.md index bc13f9095c..f9ccdc079d 100644 --- a/tech-interviews/tech-interview-questions/list-permutation/README.md +++ b/tech-interviews/tech-interview-questions/list-permutation-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - list-permutation \ No newline at end of file + - list-permutation-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/list-permutation/list-permutation.md b/tech-interviews/tech-interview-questions/list-permutation-ti/list-permutation-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/list-permutation/list-permutation.md rename to tech-interviews/tech-interview-questions/list-permutation-ti/list-permutation-ti.md diff --git a/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/README.md b/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string-ti/README.md similarity index 77% rename from tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/README.md rename to tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string-ti/README.md index 4535c8f22b..d686d13c44 100644 --- a/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/README.md +++ b/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - longest-non-repeating-substring-from-string + - longest-non-repeating-substring-from-string-ti diff --git a/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string.md b/tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string-ti/longest-non-repeating-substring-from-string-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string/longest-non-repeating-substring-from-string.md rename to tech-interviews/tech-interview-questions/longest-non-repeating-substring-from-string-ti/longest-non-repeating-substring-from-string-ti.md diff --git a/tech-interviews/tech-interview-questions/longest-palindrome/README.md b/tech-interviews/tech-interview-questions/longest-palindrome-ti/README.md similarity index 84% rename from tech-interviews/tech-interview-questions/longest-palindrome/README.md rename to tech-interviews/tech-interview-questions/longest-palindrome-ti/README.md index 002fd913b9..e6330a9ced 100644 --- a/tech-interviews/tech-interview-questions/longest-palindrome/README.md +++ b/tech-interviews/tech-interview-questions/longest-palindrome-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - longest-palindrome \ No newline at end of file + - longest-palindrome-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/longest-palindrome/longest-palindrome.md b/tech-interviews/tech-interview-questions/longest-palindrome-ti/longest-palindrome-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/longest-palindrome/longest-palindrome.md rename to tech-interviews/tech-interview-questions/longest-palindrome-ti/longest-palindrome-ti.md diff --git a/tech-interviews/tech-interview-questions/most-frequent-element/README.md b/tech-interviews/tech-interview-questions/most-frequent-element-ti/README.md similarity index 80% rename from tech-interviews/tech-interview-questions/most-frequent-element/README.md rename to tech-interviews/tech-interview-questions/most-frequent-element-ti/README.md index 6eef7524a4..6179ae49fc 100644 --- a/tech-interviews/tech-interview-questions/most-frequent-element/README.md +++ b/tech-interviews/tech-interview-questions/most-frequent-element-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - most-frequent-element + - most-frequent-element-ti diff --git a/tech-interviews/tech-interview-questions/most-frequent-element/most-frequent-element.md b/tech-interviews/tech-interview-questions/most-frequent-element-ti/most-frequent-element-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/most-frequent-element/most-frequent-element.md rename to tech-interviews/tech-interview-questions/most-frequent-element-ti/most-frequent-element-ti.md diff --git a/tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list/README.md b/tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list-ti/README.md similarity index 84% rename from tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list/README.md rename to tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list-ti/README.md index 0d448465e5..31b9a81555 100644 --- a/tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list/README.md +++ b/tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - move-zeroes-to-end-of-list \ No newline at end of file + - move-zeroes-to-end-of-list-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list/move-zeroes-to-end-of-list.md b/tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list-ti/move-zeroes-to-end-of-list-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list/move-zeroes-to-end-of-list.md rename to tech-interviews/tech-interview-questions/move-zeroes-to-end-of-list-ti/move-zeroes-to-end-of-list-ti.md diff --git a/tech-interviews/tech-interview-questions/nth-largest-element-from-a-list/README.md b/tech-interviews/tech-interview-questions/nth-largest-element-from-a-list-ti/README.md similarity index 74% rename from tech-interviews/tech-interview-questions/nth-largest-element-from-a-list/README.md rename to tech-interviews/tech-interview-questions/nth-largest-element-from-a-list-ti/README.md index 0140b4a17e..b3b4a7da71 100644 --- a/tech-interviews/tech-interview-questions/nth-largest-element-from-a-list/README.md +++ b/tech-interviews/tech-interview-questions/nth-largest-element-from-a-list-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - nth-largest-element-from-a-list \ No newline at end of file + - nth-largest-element-from-a-list-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/nth-largest-element-from-a-list/nth-largest-element-from-a-list.md b/tech-interviews/tech-interview-questions/nth-largest-element-from-a-list-ti/nth-largest-element-from-a-list-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/nth-largest-element-from-a-list/nth-largest-element-from-a-list.md rename to tech-interviews/tech-interview-questions/nth-largest-element-from-a-list-ti/nth-largest-element-from-a-list-ti.md diff --git a/tech-interviews/tech-interview-questions/number-to-roman-numeral/README.md b/tech-interviews/tech-interview-questions/number-to-roman-numeral-ti/README.md similarity index 82% rename from tech-interviews/tech-interview-questions/number-to-roman-numeral/README.md rename to tech-interviews/tech-interview-questions/number-to-roman-numeral-ti/README.md index 38743fead1..990f0efaf6 100644 --- a/tech-interviews/tech-interview-questions/number-to-roman-numeral/README.md +++ b/tech-interviews/tech-interview-questions/number-to-roman-numeral-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - number-to-roman-numeral \ No newline at end of file + - number-to-roman-numeral-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/number-to-roman-numeral/number-to-roman-numeral.md b/tech-interviews/tech-interview-questions/number-to-roman-numeral-ti/number-to-roman-numeral-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/number-to-roman-numeral/number-to-roman-numeral.md rename to tech-interviews/tech-interview-questions/number-to-roman-numeral-ti/number-to-roman-numeral-ti.md diff --git a/tech-interviews/tech-interview-questions/pascals-triangle-index-return/README.md b/tech-interviews/tech-interview-questions/pascals-triangle-index-return-ti/README.md similarity index 79% rename from tech-interviews/tech-interview-questions/pascals-triangle-index-return/README.md rename to tech-interviews/tech-interview-questions/pascals-triangle-index-return-ti/README.md index 498d7cce7c..31c57e3434 100644 --- a/tech-interviews/tech-interview-questions/pascals-triangle-index-return/README.md +++ b/tech-interviews/tech-interview-questions/pascals-triangle-index-return-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - pascals-triangle-index-return \ No newline at end of file + - pascals-triangle-index-return-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/pascals-triangle-index-return/pascals-triangle-index-return.md b/tech-interviews/tech-interview-questions/pascals-triangle-index-return-ti/pascals-triangle-index-return-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/pascals-triangle-index-return/pascals-triangle-index-return.md rename to tech-interviews/tech-interview-questions/pascals-triangle-index-return-ti/pascals-triangle-index-return-ti.md diff --git a/tech-interviews/tech-interview-questions/pattern-matching/README.md b/tech-interviews/tech-interview-questions/pattern-matching-ti/README.md similarity index 87% rename from tech-interviews/tech-interview-questions/pattern-matching/README.md rename to tech-interviews/tech-interview-questions/pattern-matching-ti/README.md index 4fcc0d1e6c..3697aa2965 100644 --- a/tech-interviews/tech-interview-questions/pattern-matching/README.md +++ b/tech-interviews/tech-interview-questions/pattern-matching-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - pattern-matching \ No newline at end of file + - pattern-matching-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/pattern-matching/pattern-matching.md b/tech-interviews/tech-interview-questions/pattern-matching-ti/pattern-matching-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/pattern-matching/pattern-matching.md rename to tech-interviews/tech-interview-questions/pattern-matching-ti/pattern-matching-ti.md diff --git a/tech-interviews/tech-interview-questions/product-of-a-list-excluding-self/README.md b/tech-interviews/tech-interview-questions/product-of-a-list-excluding-self-ti/README.md similarity index 85% rename from tech-interviews/tech-interview-questions/product-of-a-list-excluding-self/README.md rename to tech-interviews/tech-interview-questions/product-of-a-list-excluding-self-ti/README.md index 3842d6610b..f528a6a3fe 100644 --- a/tech-interviews/tech-interview-questions/product-of-a-list-excluding-self/README.md +++ b/tech-interviews/tech-interview-questions/product-of-a-list-excluding-self-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - product-of-a-list-excluding-self \ No newline at end of file + - product-of-a-list-excluding-self-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/product-of-a-list-excluding-self/product-of-a-list-excluding-self.md b/tech-interviews/tech-interview-questions/product-of-a-list-excluding-self-ti/product-of-a-list-excluding-self-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/product-of-a-list-excluding-self/product-of-a-list-excluding-self.md rename to tech-interviews/tech-interview-questions/product-of-a-list-excluding-self-ti/product-of-a-list-excluding-self-ti.md diff --git a/tech-interviews/tech-interview-questions/return-the-middle-of-a-list/README.md b/tech-interviews/tech-interview-questions/return-the-middle-of-a-list-ti/README.md similarity index 79% rename from tech-interviews/tech-interview-questions/return-the-middle-of-a-list/README.md rename to tech-interviews/tech-interview-questions/return-the-middle-of-a-list-ti/README.md index 3ce0f29c2d..9fd53ad337 100644 --- a/tech-interviews/tech-interview-questions/return-the-middle-of-a-list/README.md +++ b/tech-interviews/tech-interview-questions/return-the-middle-of-a-list-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - return-the-middle-of-a-list \ No newline at end of file + - return-the-middle-of-a-list-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/return-the-middle-of-a-list/return-the-middle-of-a-list.md b/tech-interviews/tech-interview-questions/return-the-middle-of-a-list-ti/return-the-middle-of-a-list-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/return-the-middle-of-a-list/return-the-middle-of-a-list.md rename to tech-interviews/tech-interview-questions/return-the-middle-of-a-list-ti/return-the-middle-of-a-list-ti.md diff --git a/tech-interviews/tech-interview-questions/reversing-a-string/README.md b/tech-interviews/tech-interview-questions/reversing-a-string-ti/README.md similarity index 83% rename from tech-interviews/tech-interview-questions/reversing-a-string/README.md rename to tech-interviews/tech-interview-questions/reversing-a-string-ti/README.md index efb43efdc8..69773ae2bf 100644 --- a/tech-interviews/tech-interview-questions/reversing-a-string/README.md +++ b/tech-interviews/tech-interview-questions/reversing-a-string-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - reversing-a-string \ No newline at end of file + - reversing-a-string-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/reversing-a-string/reversing-a-string.md b/tech-interviews/tech-interview-questions/reversing-a-string-ti/reversing-a-string-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/reversing-a-string/reversing-a-string.md rename to tech-interviews/tech-interview-questions/reversing-a-string-ti/reversing-a-string-ti.md diff --git a/tech-interviews/tech-interview-questions/reversing-words-in-a-string/README.md b/tech-interviews/tech-interview-questions/reversing-words-in-a-string-ti/README.md similarity index 84% rename from tech-interviews/tech-interview-questions/reversing-words-in-a-string/README.md rename to tech-interviews/tech-interview-questions/reversing-words-in-a-string-ti/README.md index e4af354840..43f9a84de2 100644 --- a/tech-interviews/tech-interview-questions/reversing-words-in-a-string/README.md +++ b/tech-interviews/tech-interview-questions/reversing-words-in-a-string-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - reversing-words-in-a-string \ No newline at end of file + - reversing-words-in-a-string-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/reversing-words-in-a-string/reversing-words-in-a-string.md b/tech-interviews/tech-interview-questions/reversing-words-in-a-string-ti/reversing-words-in-a-string-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/reversing-words-in-a-string/reversing-words-in-a-string.md rename to tech-interviews/tech-interview-questions/reversing-words-in-a-string-ti/reversing-words-in-a-string-ti.md diff --git a/tech-interviews/tech-interview-questions/rotating-a-list/README.md b/tech-interviews/tech-interview-questions/rotating-a-list-ti/README.md similarity index 84% rename from tech-interviews/tech-interview-questions/rotating-a-list/README.md rename to tech-interviews/tech-interview-questions/rotating-a-list-ti/README.md index ebb692c5db..86cd6390fc 100644 --- a/tech-interviews/tech-interview-questions/rotating-a-list/README.md +++ b/tech-interviews/tech-interview-questions/rotating-a-list-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - rotating-a-list \ No newline at end of file + - rotating-a-list-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/rotating-a-list/rotating-a-list.md b/tech-interviews/tech-interview-questions/rotating-a-list-ti/rotating-a-list-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/rotating-a-list/rotating-a-list.md rename to tech-interviews/tech-interview-questions/rotating-a-list-ti/rotating-a-list-ti.md diff --git a/tech-interviews/tech-interview-questions/squares-of-sorted-lists/README.md b/tech-interviews/tech-interview-questions/squares-of-sorted-lists-ti/README.md similarity index 84% rename from tech-interviews/tech-interview-questions/squares-of-sorted-lists/README.md rename to tech-interviews/tech-interview-questions/squares-of-sorted-lists-ti/README.md index 34011de3c9..fce3a15a20 100644 --- a/tech-interviews/tech-interview-questions/squares-of-sorted-lists/README.md +++ b/tech-interviews/tech-interview-questions/squares-of-sorted-lists-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - squares-of-sorted-lists \ No newline at end of file + - squares-of-sorted-lists-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/squares-of-sorted-lists/squares-of-sorted-lists.md b/tech-interviews/tech-interview-questions/squares-of-sorted-lists-ti/squares-of-sorted-lists-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/squares-of-sorted-lists/squares-of-sorted-lists.md rename to tech-interviews/tech-interview-questions/squares-of-sorted-lists-ti/squares-of-sorted-lists-ti.md diff --git a/tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero/README.md b/tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero-ti/README.md similarity index 81% rename from tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero/README.md rename to tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero-ti/README.md index a1196a0e8a..8115a73936 100644 --- a/tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero/README.md +++ b/tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - steps-to-reduce-a-num-to-zero \ No newline at end of file + - steps-to-reduce-a-num-to-zero-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero/steps-to-reduce-a-num-to-zero.md b/tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero-ti/steps-to-reduce-a-num-to-zero-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero/steps-to-reduce-a-num-to-zero.md rename to tech-interviews/tech-interview-questions/steps-to-reduce-a-num-to-zero-ti/steps-to-reduce-a-num-to-zero-ti.md diff --git a/tech-interviews/tech-interview-questions/string-comparison/README.md b/tech-interviews/tech-interview-questions/string-comparison-ti/README.md similarity index 88% rename from tech-interviews/tech-interview-questions/string-comparison/README.md rename to tech-interviews/tech-interview-questions/string-comparison-ti/README.md index d45d7bb3b0..378cccb002 100644 --- a/tech-interviews/tech-interview-questions/string-comparison/README.md +++ b/tech-interviews/tech-interview-questions/string-comparison-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - string-comparison \ No newline at end of file + - string-comparison-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/string-comparison/string-comparison.md b/tech-interviews/tech-interview-questions/string-comparison-ti/string-comparison-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/string-comparison/string-comparison.md rename to tech-interviews/tech-interview-questions/string-comparison-ti/string-comparison-ti.md diff --git a/tech-interviews/tech-interview-questions/string-permutation/README.md b/tech-interviews/tech-interview-questions/string-permutation-ti/README.md similarity index 88% rename from tech-interviews/tech-interview-questions/string-permutation/README.md rename to tech-interviews/tech-interview-questions/string-permutation-ti/README.md index 0a471ada01..c0b100667f 100644 --- a/tech-interviews/tech-interview-questions/string-permutation/README.md +++ b/tech-interviews/tech-interview-questions/string-permutation-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - string-permutation \ No newline at end of file + - string-permutation-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/string-permutation/string-permutation.md b/tech-interviews/tech-interview-questions/string-permutation-ti/string-permutation-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/string-permutation/string-permutation.md rename to tech-interviews/tech-interview-questions/string-permutation-ti/string-permutation-ti.md diff --git a/tech-interviews/tech-interview-questions/sum-of-two-strings/README.md b/tech-interviews/tech-interview-questions/sum-of-two-strings-ti/README.md similarity index 86% rename from tech-interviews/tech-interview-questions/sum-of-two-strings/README.md rename to tech-interviews/tech-interview-questions/sum-of-two-strings-ti/README.md index 20c8d5c21f..e1f4fe4982 100644 --- a/tech-interviews/tech-interview-questions/sum-of-two-strings/README.md +++ b/tech-interviews/tech-interview-questions/sum-of-two-strings-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - sum-of-two-strings \ No newline at end of file + - sum-of-two-strings-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/sum-of-two-strings/sum-of-two-strings.md b/tech-interviews/tech-interview-questions/sum-of-two-strings-ti/sum-of-two-strings-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/sum-of-two-strings/sum-of-two-strings.md rename to tech-interviews/tech-interview-questions/sum-of-two-strings-ti/sum-of-two-strings-ti.md diff --git a/tech-interviews/tech-interview-questions/sum-target-value-from-a-list/README.md b/tech-interviews/tech-interview-questions/sum-target-value-from-a-list-ti/README.md similarity index 85% rename from tech-interviews/tech-interview-questions/sum-target-value-from-a-list/README.md rename to tech-interviews/tech-interview-questions/sum-target-value-from-a-list-ti/README.md index 787cd8e0b3..9988b63a5a 100644 --- a/tech-interviews/tech-interview-questions/sum-target-value-from-a-list/README.md +++ b/tech-interviews/tech-interview-questions/sum-target-value-from-a-list-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - sum-target-value-from-a-list \ No newline at end of file + - sum-target-value-from-a-list-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/sum-target-value-from-a-list/sum-target-value-from-a-list.md b/tech-interviews/tech-interview-questions/sum-target-value-from-a-list-ti/sum-target-value-from-a-list-ti-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/sum-target-value-from-a-list/sum-target-value-from-a-list.md rename to tech-interviews/tech-interview-questions/sum-target-value-from-a-list-ti/sum-target-value-from-a-list-ti-ti.md diff --git a/tech-interviews/tech-interview-questions/wealthiest-citizen/README.md b/tech-interviews/tech-interview-questions/wealthiest-citizen-ti/README.md similarity index 84% rename from tech-interviews/tech-interview-questions/wealthiest-citizen/README.md rename to tech-interviews/tech-interview-questions/wealthiest-citizen-ti/README.md index 489e3e3357..f4006f5d61 100644 --- a/tech-interviews/tech-interview-questions/wealthiest-citizen/README.md +++ b/tech-interviews/tech-interview-questions/wealthiest-citizen-ti/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - wealthiest-citizen \ No newline at end of file + - wealthiest-citizen-ti \ No newline at end of file diff --git a/tech-interviews/tech-interview-questions/wealthiest-citizen/wealthiest-citizen.md b/tech-interviews/tech-interview-questions/wealthiest-citizen-ti/wealthiest-citizen-ti-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/wealthiest-citizen/wealthiest-citizen.md rename to tech-interviews/tech-interview-questions/wealthiest-citizen-ti/wealthiest-citizen-ti-ti.md From 6b7808de460ecbc2fdfe218d4d7a98a5245c06eb Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Dec 2022 16:08:30 +0100 Subject: [PATCH 305/390] Update README.md --- .../binary-search-exercise-js/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/tech-interview-exercises-js/binary-search-exercise-js/README.md b/javascript/tech-interview-exercises-js/binary-search-exercise-js/README.md index eb67f573b1..de33b13078 100644 --- a/javascript/tech-interview-exercises-js/binary-search-exercise-js/README.md +++ b/javascript/tech-interview-exercises-js/binary-search-exercise-js/README.md @@ -6,4 +6,4 @@ aspects: - workout insights: - - binary-search-exercise-js \ No newline at end of file + - binary-search-js From 2c94a14714471a3b8b05fb7cf43dfa728a4a81df Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Fri, 16 Dec 2022 16:09:19 +0100 Subject: [PATCH 306/390] rename 2 files --- ...ue-from-a-list-ti-ti.md => sum-target-value-from-a-list-ti.md} | 0 .../{wealthiest-citizen-ti-ti.md => wealthiest-citizen-ti.md} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename tech-interviews/tech-interview-questions/sum-target-value-from-a-list-ti/{sum-target-value-from-a-list-ti-ti.md => sum-target-value-from-a-list-ti.md} (100%) rename tech-interviews/tech-interview-questions/wealthiest-citizen-ti/{wealthiest-citizen-ti-ti.md => wealthiest-citizen-ti.md} (100%) diff --git a/tech-interviews/tech-interview-questions/sum-target-value-from-a-list-ti/sum-target-value-from-a-list-ti-ti.md b/tech-interviews/tech-interview-questions/sum-target-value-from-a-list-ti/sum-target-value-from-a-list-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/sum-target-value-from-a-list-ti/sum-target-value-from-a-list-ti-ti.md rename to tech-interviews/tech-interview-questions/sum-target-value-from-a-list-ti/sum-target-value-from-a-list-ti.md diff --git a/tech-interviews/tech-interview-questions/wealthiest-citizen-ti/wealthiest-citizen-ti-ti.md b/tech-interviews/tech-interview-questions/wealthiest-citizen-ti/wealthiest-citizen-ti.md similarity index 100% rename from tech-interviews/tech-interview-questions/wealthiest-citizen-ti/wealthiest-citizen-ti-ti.md rename to tech-interviews/tech-interview-questions/wealthiest-citizen-ti/wealthiest-citizen-ti.md From 2179b2af3292263d0a5002b61b3bd0b7caa1ffa8 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Dec 2022 16:23:45 +0100 Subject: [PATCH 307/390] Update README.md --- tech-interviews/tech-interviews-core/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tech-interviews/tech-interviews-core/README.md b/tech-interviews/tech-interviews-core/README.md index a50cd7e4a6..6abf4aa6af 100644 --- a/tech-interviews/tech-interviews-core/README.md +++ b/tech-interviews/tech-interviews-core/README.md @@ -12,4 +12,6 @@ sections: - what-is-big-o - big-o-tips - arrays-and-maps - - array-and-map-tips \ No newline at end of file + - array-and-map-tips + +next:tech-interview-questions From bd30e2a2c85d4e95723ccdde52a22936761bd33d Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Dec 2022 16:25:08 +0100 Subject: [PATCH 308/390] Update README.md --- tech-interviews/tech-interviews-core/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tech-interviews/tech-interviews-core/README.md b/tech-interviews/tech-interviews-core/README.md index 6abf4aa6af..0ae9e7648c 100644 --- a/tech-interviews/tech-interviews-core/README.md +++ b/tech-interviews/tech-interviews-core/README.md @@ -14,4 +14,5 @@ sections: - arrays-and-maps - array-and-map-tips -next:tech-interview-questions +next: + - tech-interviews:tech-interview-questions From 5f1b41391c0a2312f8eaee966908f25a91e4da74 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Dec 2022 16:26:37 +0100 Subject: [PATCH 309/390] Update CHANGELOG.md --- CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 71e0264e38..9307240a0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,7 +48,10 @@ Types of change: ### Fixed -## December 13th 2022 +## December 16th 2022 + +### Fixed +- [Tech Interviews - Tech Interview Exercises - Make exercises go after the preparation course](https://github.com/enkidevs/curriculum/pull/3142) ### Added - [Tech Interviews - Tech Interview Exercises - Add 25 exercises](https://github.com/enkidevs/curriculum/pull/3139) From 7a46fbef5856279127b1a38d71a3c872473b2990 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Dec 2022 18:17:22 +0100 Subject: [PATCH 310/390] Update README.md --- tech-interviews/tech-interview-questions/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tech-interviews/tech-interview-questions/README.md b/tech-interviews/tech-interview-questions/README.md index 1bed7bd885..f145bdf81b 100644 --- a/tech-interviews/tech-interview-questions/README.md +++ b/tech-interviews/tech-interview-questions/README.md @@ -1,4 +1,4 @@ -name: Tech Interview Exercises +name: Exercises description: Questions to improve your coding skills. @@ -28,4 +28,4 @@ sections: - return-the-middle-of-a-list-ti - product-of-a-list-excluding-self-ti - pattern-matching-ti - - pascals-triangle-index-return-ti \ No newline at end of file + - pascals-triangle-index-return-ti From 0854385ee160894f1d1c1fdd13633a03f527f832 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 16 Dec 2022 18:18:35 +0100 Subject: [PATCH 311/390] Update CHANGELOG.md --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9307240a0a..34a9d40618 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,9 @@ Types of change: ## December 16th 2022 +### Changed +- [Tech Interviews - Tech Interview Exercises - Change name](https://github.com/enkidevs/curriculum/pull/3143) + ### Fixed - [Tech Interviews - Tech Interview Exercises - Make exercises go after the preparation course](https://github.com/enkidevs/curriculum/pull/3142) From 5d69c113888519db121d8eba7897af60e54767ec Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 20 Dec 2022 10:44:13 +0100 Subject: [PATCH 312/390] Update altering-format-string-output-by-changing-a-format-specifier-s-argument-index.md Remove type in the gap so whitespace doesn't make the answer incorrect. Also update answers to have whitespace in them: --- ...by-changing-a-format-specifier-s-argument-index.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/java/data-management/strings-iii/altering-format-string-output-by-changing-a-format-specifier-s-argument-index.md b/java/data-management/strings-iii/altering-format-string-output-by-changing-a-format-specifier-s-argument-index.md index ba2c59b52a..51ee797e65 100644 --- a/java/data-management/strings-iii/altering-format-string-output-by-changing-a-format-specifier-s-argument-index.md +++ b/java/data-management/strings-iii/altering-format-string-output-by-changing-a-format-specifier-s-argument-index.md @@ -12,7 +12,6 @@ notes: 'Gamified insight. Static Workout. ' revisionQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone --- @@ -71,8 +70,8 @@ result = String.format( // result = ??? ``` -- `bca` -- `abc` -- `aaa` -- `cab` -- `bac` +- `b c a` +- `a b c` +- `a a a` +- `c a b` +- `b a c` From 72950870f2be2476e9f7ba27ad66e65db6b84445 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 20 Dec 2022 10:48:42 +0100 Subject: [PATCH 313/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 34a9d40618..ad5a7af187 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## December 20th 2022 + +### Changed +- [Java - altering format string output by changing a format specifiers argument index - update question](https://github.com/enkidevs/curriculum/pull/3144) + ## December 16th 2022 ### Changed From a826813249157aa2c52addae92f5608ad169e53b Mon Sep 17 00:00:00 2001 From: nishmamehta <121473459+nishmamehta@users.noreply.github.com> Date: Thu, 29 Dec 2022 12:39:05 +0530 Subject: [PATCH 314/390] Upload nft topic --- intro-to-nfts/README.md | 13 ++++ intro-to-nfts/intro-to-nfts/README.md | 11 +++ .../buy-create-and-sell-nfts/README.md | 11 +++ .../buy-create-and-sell-nfts/buy-nfts.md | 43 ++++++++++++ .../buy-create-and-sell-nfts/create-nfts.md | 47 +++++++++++++ .../buy-create-and-sell-nfts/sell-nfts.md | 43 ++++++++++++ .../fundamentals-of-nfts/README.md | 11 +++ .../how-are-nfts-valuable.md | 65 +++++++++++++++++ .../fundamentals-of-nfts/nf-in-nfts.md | 67 ++++++++++++++++++ .../fundamentals-of-nfts/t-in-nfts.md | 36 ++++++++++ .../intro-to-nfts/nft-use-cases/README.md | 13 ++++ .../nft-use-cases/digital-artwork.md | 34 +++++++++ .../nft-use-cases/introduction.md | 23 ++++++ .../intro-to-nfts/nft-use-cases/nft-gaming.md | 22 ++++++ .../why-are-nfts-interesting-1.md | 70 +++++++++++++++++++ .../why-are-nfts-interesting-2.md | 64 +++++++++++++++++ 16 files changed, 573 insertions(+) create mode 100644 intro-to-nfts/README.md create mode 100644 intro-to-nfts/intro-to-nfts/README.md create mode 100644 intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/README.md create mode 100644 intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/buy-nfts.md create mode 100644 intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/create-nfts.md create mode 100644 intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/sell-nfts.md create mode 100644 intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/README.md create mode 100644 intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/how-are-nfts-valuable.md create mode 100644 intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/nf-in-nfts.md create mode 100644 intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/t-in-nfts.md create mode 100644 intro-to-nfts/intro-to-nfts/nft-use-cases/README.md create mode 100644 intro-to-nfts/intro-to-nfts/nft-use-cases/digital-artwork.md create mode 100644 intro-to-nfts/intro-to-nfts/nft-use-cases/introduction.md create mode 100644 intro-to-nfts/intro-to-nfts/nft-use-cases/nft-gaming.md create mode 100644 intro-to-nfts/intro-to-nfts/nft-use-cases/why-are-nfts-interesting-1.md create mode 100644 intro-to-nfts/intro-to-nfts/nft-use-cases/why-are-nfts-interesting-2.md diff --git a/intro-to-nfts/README.md b/intro-to-nfts/README.md new file mode 100644 index 0000000000..2282bcb74a --- /dev/null +++ b/intro-to-nfts/README.md @@ -0,0 +1,13 @@ +name: Intro to NFTs + +icon: 'https://img.enkipro.com/db79b7f9f0366f0c0e4183480a71fb91.png' + +color: 'ffe0a6' + +description: Fundamental Guide to NFTs for Beginners + +language: python + +availableAspects: + - introduction + - workout \ No newline at end of file diff --git a/intro-to-nfts/intro-to-nfts/README.md b/intro-to-nfts/intro-to-nfts/README.md new file mode 100644 index 0000000000..dd833db6ed --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/README.md @@ -0,0 +1,11 @@ +name: Intro to NFTs + +description: Fundamental Guide to NFTs for Beginners + +core: true + +sections: + '0': + - nft-use-cases + - fundamentals-of-nfts + - buy-create-and-sell-nfts \ No newline at end of file diff --git a/intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/README.md b/intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/README.md new file mode 100644 index 0000000000..fa5a79ffd0 --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/README.md @@ -0,0 +1,11 @@ +name: Buy, Create and Sell NFTs + +description: Methods for buying, creating, and selling NFTs + +insights: + - buy-nfts + - create-nfts + - sell-nfts + +aspects: + - workout diff --git a/intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/buy-nfts.md b/intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/buy-nfts.md new file mode 100644 index 0000000000..4446cb78ad --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/buy-nfts.md @@ -0,0 +1,43 @@ +--- +author: nishma +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +links: + - '[OpenSea Marketplace](https://opensea.io/){website}' + - '[Rarible Marketplace](https://rarible.com/){website}' + - '[Foundation](https://foundation.app/){website}' + - '[Nifty Gateway](https://www.niftygateway.com/){website}' + +--- +# How to Buy NFTs + +--- +## Content + +Before learning how to buy NFT tokens, there are a few things worth considering: + - What marketplace do you intend to use? + - Which cryptocurrency will be needed to make the purchase? + - Are the NFTs only available at a certain time, like during an NFT drop? + +For example, someone who wants to buy an NBA Top Shot pack of virtual trading cards must open an account with NBA Top Shot and create a Dapper wallet. + +Once you've connected your wallet to the NFT marketplace, you can start browsing the marketplace's offerings and make a purchase. + +NFT marketplaces include OpenSea, Rarible, Foundation, Nifty Gateway, Reddit, Instagram etc. + +![OpenSea marketplace interface](https://img.enkipro.com/9e553fbb82dc029bc98cfc4b5b880d64.jpeg) + +--- +## Practice +Which platforms can NFTs be purchased on? + +??? + +- NFT Marketplaces like Opensea +- The stock Market +- On Amazon +- bricks and mortar stores \ No newline at end of file diff --git a/intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/create-nfts.md b/intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/create-nfts.md new file mode 100644 index 0000000000..35a678c86a --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/create-nfts.md @@ -0,0 +1,47 @@ +--- +author: nishma +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- +# Create NFTs + +--- +## Content + +### Create a Piece of Art + +You first need to create a piece of art that you’ll want to turn into an NFT. You may decide to make a digital image, audio production, or video[1]. + +### Choose a Blockchain + +A creator must figure out which blockchain they want to issue their NFTs on. + +Ethereum is the most popular blockchain at this time, but a variety of other blockchains are gaining popularity, such as: Cosmos, Tezos, Polkadot, Flow, Binance Smart Chain, etc. + +### Get a Wallet + +You’ll need to set up a cryptocurrency wallet to pay a marketplace’s fees and receive payment once you start selling your NFTs such as: Coinbase Wallet, MetaMask, Trust Wallet, Enjin, and D’Cent. + +![NFT wallet screenshot](https://img.enkipro.com/3f0ad01ca85fa0cc999e4bd4f067601c.png) + +--- +## Practice +Which of these is NOT an NFT Marketplace? + +??? + +- Amazon +- OpenSea +- Rarible +- Nifty Gateway + +--- +## Footnotes + +[1: NFT file types] +Most marketplaces support NFTs that represent JPEG, MP3, MP4, TXT, and other digital files. \ No newline at end of file diff --git a/intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/sell-nfts.md b/intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/sell-nfts.md new file mode 100644 index 0000000000..c97352c10d --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/buy-create-and-sell-nfts/sell-nfts.md @@ -0,0 +1,43 @@ +--- +author: nishma +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +--- +# How to Sell NFTs + +--- +## Content + +### Find a Marketplace + +Depending on your art and interests, you may choose a curated marketplace that specializes in specific kinds of art or a general open marketplace. + +### Minting an NFT + +NFT marketplaces offer a step-by-step guide for uploading your digital file to their platform. That process will enable you to turn your digital art into a marketable NFT by adding it to the blockchain, known as minting an NFT. + +### Sell your NFT + +Once you’ve minted your NFT, you can choose to sell it. There are generally three ways to sell your NFT: + + - Fixed price: This allows you to set a price for the NFT and sell it instantly if a buyer is willing to buy the NFT at that price. + + - Timed auction: A timed auction will give those interested in your NFT a time limit to submit bids. + + - Unlimited auction: There is no set time limit with an unlimited auction. Instead, the seller can choose to end the auction whenever they want. + +--- +## Practice + +What does "minting an NFT" mean? + +??? + +- Adding an NFT on blockchain +- Buying an NFT on Marketplace +- Investing in NFT on Marketplace +- Transferring an NFT on Marketplace \ No newline at end of file diff --git a/intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/README.md b/intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/README.md new file mode 100644 index 0000000000..2276c2256d --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/README.md @@ -0,0 +1,11 @@ +name: Fundamentals of NFTs + +description: Detailed explanation and understanding of concepts underlying NFTs + +insights: + - nf-in-nfts + - t-in-nfts + - how-are-nfts-valuable + +aspects: + - introduction diff --git a/intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/how-are-nfts-valuable.md b/intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/how-are-nfts-valuable.md new file mode 100644 index 0000000000..0a82f16648 --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/how-are-nfts-valuable.md @@ -0,0 +1,65 @@ +--- +author: nishma +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- +# How are NFTs valuable? + +--- +## Content + +NFTs have no fixed value, and just like most goods, it's entirely based on demand. + +![Demand and Supply graph for nfts](https://img.enkipro.com/85dc965cfeffb53cfe595efd88be12a5.png) + +The general aim, similar to any collectible, is to trade NFTs for income or own them for status. + +### Income + +You can earn NFTs by playing games, or you can buy them on NFT marketplaces. + +To earn money, you can sell them at a higher price - therefore making a profit. + +### Status + +You might buy a desirable NFT from a famous collection like BAYC or made by a famous artist like Beeple. + +You could also buy and keep NFTs from artists you really like. + + +### Custom features + +Artists can add royalties into their NFTs. + +This means that, whenever the NFT changes hands, the artist automatically receives a percentage of the sale value. + +--- +## Practice + +Which of these is NOT a valid use case for an NFT? + +??? + +- replacing a $100 bill +- earned as a reward in a game +- obtained as a receipt for purchase +- used as an artist's autograph + +--- +## Revision + +Artists can set up ??? on NFTs to receive a percentage of each sale value. + +- royalties +- tokens +- rewards +- penalties \ No newline at end of file diff --git a/intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/nf-in-nfts.md b/intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/nf-in-nfts.md new file mode 100644 index 0000000000..f52d86cfe5 --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/nf-in-nfts.md @@ -0,0 +1,67 @@ +--- +author: nishma +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- +# The NF in NFT = Non-Fungible + +--- +## Content + +What is the NF in NFT? Non-fungible! + +Non-fungible loosely means non-replaceable. There is only one of them. + +Suppose you wish to purchase a specific pair of green pants from Zara. When you order them, you wouldn't care about which exact pair is delivered. + +![New Zara green pants](https://img.enkipro.com/a287333484594ac5ff6f307642db3545.jpeg) + +Zara will most likely manufacture thousands of the same pants in your size and send them to stores and people like you. Thus, these pants would be fungible - they’re replaceable. + +However, let’s talk about a pair of green pants you’ve had for many years. Even if you try to buy the same thing online, it won't be the exact same pair of green pants you've owned. + +![Old Zara green pants](https://img.enkipro.com/0a5dddcade9665c80a5bdea872dbf819.png) + +They would be irreplaceable, and hence, non-fungible. The only one on the planet that exists. They have emotional value and significance because they're scarce. + +> 💡 Everything in our economy is either fungible or non-fungible.[1] + +--- +## Practice + +A dollar bill is non-fungible. + +??? + +- False +- True + +--- +## Revision + +Non-Fungible means: + +??? + +- A: Unique +- B: Replaceable +- C: Of Value +- D: Plastic money + +--- +## Footnotes +[1: Fungible and Non-fungible] + +A pack of Trader Joe’s tortillas — fungible; the Mona Lisa — non-fungible. +![Fungible and Non-fungible example](https://img.enkipro.com/138e0a4045b0bb487d291d6b3b610fc0.gif) + +Unsurprisingly, non-fungible things are way more valuable than fungible things. diff --git a/intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/t-in-nfts.md b/intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/t-in-nfts.md new file mode 100644 index 0000000000..786eeda6ca --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/fundamentals-of-nfts/t-in-nfts.md @@ -0,0 +1,36 @@ +--- +author: nishma +type: normal +category: must-know +links: + - '[Grimes Digital Art Sells for $5.8M](https://www.vanityfair.com/style/2021/03/grimes-art-sold-nft-cryptocurrency-auction-elon-musk-warnymph){website}' + - '[Jack Dorseys First Tweet went on sale for $48M](https://www.coindesk.com/business/2022/04/13/jack-dorseys-first-tweet-nft-went-on-sale-for-48m-it-ended-with-a-top-bid-of-just-280/){website}' + +--- +# The T in NFT (Token) + +--- +## Content + +What are Tokens? + +On a high-level, a token is a digital asset that exists on the blockchain and can only be owned by one account (i.e. one blockchain address). + +For example, you can't replace the Vengeful war babies images[1] with Jack Dorsey’s First Tweet[2] becaucse blockchain data can't be changed. + +Hence, non-fungible token (irreplaceable digital asset). + +The most well-known NFTs currently exist on the Ethereum Blockchain, but they’re represented in different ways than coins, using the ERC-721 standard [3], which states: + +> 💡 “A non-fungible token (NFT) is used to identify something or someone in a unique way. This type of token is perfect to be used on platforms that offer collectible items, access keys, lottery tickets, numbered seats for concerts and sports matches, etc.” + +--- +## Footnotes +[1: Vengeful war babibes images] +‘WarNymph’, a digital artwork collection by Canadian musician and artist Claire Elise Boucher (also known as Grimes), which depicts babies with swords and wings guarding Mars, sold in 20 minutes for $5.8M in an auction on Nifty Gateway. + +[2: Jack Dorsey's First Tweet] +Jack Dorsey, CEO of Twitter and Square, sold his first tweet as an NFT for over $2.9 million when bidding ended on the “Valuables” platform, which is run by Cent, a blockchain-powered social media network. The tweet, which says, “just setting up my twttr,” was first posted by Dorsey on March 21, 2006. + +[3: ERC-721 Standard] +Firstly, ERC-721 is a type of standard — a template or format that other developers agree to follow. Following the same standards makes writing code easier, more predictable, and reusable. ERC-721 is a token standard on Ethereum for non-fungible tokens (NFTs). \ No newline at end of file diff --git a/intro-to-nfts/intro-to-nfts/nft-use-cases/README.md b/intro-to-nfts/intro-to-nfts/nft-use-cases/README.md new file mode 100644 index 0000000000..783a05a831 --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/nft-use-cases/README.md @@ -0,0 +1,13 @@ +name: NFT Use Cases + +description: NFT ecosystem and use cases such as digital art, collectibles, and others + +insights: + - introduction + - why-are-nfts-interesting-1 + - why-are-nfts-interesting-2 + - digital-artwork + - nft-gaming + +aspects: + - introduction \ No newline at end of file diff --git a/intro-to-nfts/intro-to-nfts/nft-use-cases/digital-artwork.md b/intro-to-nfts/intro-to-nfts/nft-use-cases/digital-artwork.md new file mode 100644 index 0000000000..52b9d93d50 --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/nft-use-cases/digital-artwork.md @@ -0,0 +1,34 @@ +--- +author: nishma +type: normal +category: must-know +--- +# Digital Artwork + +--- +## Content + +A common question about digital artwork NFTs is: what can you do with it? + +These works can be exhibited in galleries, museums, online collections, as well as virtual worlds. + +![NFT exhibitions](https://img.enkipro.com/b6b5c8aae8d5b7355638b0da04b78847.jpeg) + +A common skepticism is that someone can just take a screenshot of an NFT making it not really scarce. + +The same argument could apply to physical items. Anyone can take a photo of the Mona Lisa or create a replica of it, but it still isn’t the real item from the artist. + +See? + +![Mona Lisa image](https://img.enkipro.com/e9da0632fa3043bf9aae6c0ff5673e91.jpeg) + +People are willing to pay a premium for original work, and NFTs (via a blockchain) make it trivial to verify authenticity. + +> 💡 It's the authenticity and scarcity that is giving an NFT its value, not just its visual appearance.[1] + +--- +## Footnotes +[1: Salvador Dali example] + +For instance, Salvador Dali used to pay for his meals by signing napkins for restaurant owners, so even if you create an exact replica of a Dali-signed napkin it’s still not the original. +![Napkin with Salvador Dali autograph](https://img.enkipro.com/067231228531b196a3f36f0318667a20.png) \ No newline at end of file diff --git a/intro-to-nfts/intro-to-nfts/nft-use-cases/introduction.md b/intro-to-nfts/intro-to-nfts/nft-use-cases/introduction.md new file mode 100644 index 0000000000..e0ed9bccf4 --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/nft-use-cases/introduction.md @@ -0,0 +1,23 @@ +--- +author: nishma +type: normal +category: must-know +--- +# Introduction + +--- +## Content + +Remember back in the early 2000s when you would buy a pack of Pokemon cards? + +Many people are now, similarly, buying tweets, jpegs, NBA game highlights, GIFs, and all sorts of other previously non-buyable things. + +![NFT-meme](https://img.enkipro.com/c6d117f4f2373c4bb2999fe440d767eb.jpeg) + +At first, this was an experiment with new technology. Then it became a way for artists to take ownership of their work to control its value. And now major brands and celebrities have joined in. + +"So… what is going on here?" you might ask. Stay tuned with us to find out! + +Enki's NFT workouts will give you a high-level overview of what NFTs are, their use cases, and how to buy/ sell them. + +Let's get started! \ No newline at end of file diff --git a/intro-to-nfts/intro-to-nfts/nft-use-cases/nft-gaming.md b/intro-to-nfts/intro-to-nfts/nft-use-cases/nft-gaming.md new file mode 100644 index 0000000000..dbc7dd27dd --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/nft-use-cases/nft-gaming.md @@ -0,0 +1,22 @@ +--- +author: nishma +type: normal +category: must-know +--- +# NFT Gaming + +--- +## Content + +NFT in gaming is the source of earning money by purchasing and trading in-game items on the cryptocurrency market. + +An example of such play-to-earn NFT game is Axie Infinity. The game rewards players with Smooth Love Potion (SLP) tokens and NFTs known as Axies. The SLP token is listed on major exchanges like Binance. + +For the first time, gamers can trade their in-game rewards on the open market. + +![NFT gaming](https://img.enkipro.com/89ac7ac25f429dd60e40b6c7faeb2e6d.png) + +NFT games offer benefits that can't be found in traditional games: +- you own your in-game purchases (and not the game company) +- you can monetize and trade them on any NFT marketplace +- you don't need to fear losing the assets to duplication or bad behavior by the game maker \ No newline at end of file diff --git a/intro-to-nfts/intro-to-nfts/nft-use-cases/why-are-nfts-interesting-1.md b/intro-to-nfts/intro-to-nfts/nft-use-cases/why-are-nfts-interesting-1.md new file mode 100644 index 0000000000..52579b26ed --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/nft-use-cases/why-are-nfts-interesting-1.md @@ -0,0 +1,70 @@ +--- +author: nishma +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone +links: + - '[Fractional NFTs Explained](https://www.coindesk.com/learn/how-can-you-share-an-nft-fractional-nfts-explained/){website}' + +--- +# Part 1: Why are NFTs interesting? + +--- +## Content + +The acronym "NFT" stands for non-fungible token. On a high level, NFTs are irreplaceable digital assets traded on a blockchain. [1] + +### Transfer of Ownership + +NFT are interoperable, which means that they can be connected, exchanged, or traded over different platforms that operate on the blockchain. + +For example, two games that are created and designed on the Ethereum blockchain[2] can easily support the same in-game collectibles like vehicles, weapons, armor, or even entire characters.[3] + +### Transparency + +As NFT operates on the blockchain, the presence and history of ownership are unalterable and accessible to the public. + +--- +## Practice + +Two games that are created and designed on the Ethereum network can support the same in-game collectibles like vehicles, weapons, armor, or even entire characters. + +??? + +- True +- False + +--- +## Revision + +NFT stands for ??? + +- Non-Fungible Token +- Non-Fungible Trade +- Non-Financial Token +- Non-Financial Trade + +--- +## Footnotes +[1: NFTs as collectibles] + +People love collectibles, and NFTs combined with other financial building blocks enabled by a blockchain, allow anyone to issue, own, and trade them. + +[2: Ethereum] + +At its core, Ethereum is a decentralized global software platform powered by blockchain technology. It is most commonly known for its native cryptocurrency, ether (EH). + +Ethereum can be used by anyone to create any secured digital technology. It has a token designed to pay for work done supporting the blockchain, but participants can also use it to pay for tangible goods and services if accepted. + +[3: NFT can do much more] + +NFT activity can go well past trading and include actions like being able to borrow and lend, support fractional ownership (e.g. NIFTEX), or use it as collateral in taking out a loan (e.g. NFTfi). + +NFT fractionalization is simply the act of dividing the ownership of an NFT into smaller fractions. This makes it possible for several people to own a single NFT. \ No newline at end of file diff --git a/intro-to-nfts/intro-to-nfts/nft-use-cases/why-are-nfts-interesting-2.md b/intro-to-nfts/intro-to-nfts/nft-use-cases/why-are-nfts-interesting-2.md new file mode 100644 index 0000000000..9ed3f827db --- /dev/null +++ b/intro-to-nfts/intro-to-nfts/nft-use-cases/why-are-nfts-interesting-2.md @@ -0,0 +1,64 @@ +--- +author: nishma +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- +# Part 2: Why are NFTs interesting? + +--- +## Content + +### Social Tokens + +NFTs can be used to represent anything from a person's time to specialized access to a community's shared ownership, similar to how stocks work. + +You own X units of something and can vote on how that something is used, or what it does, or trade your X units with someone.[2] + +### Licenses and Certifications + +As NFTs contain unique codes, they can also be used to tokenize documentation such as degrees, academic certificates, or licenses. + +Because they're on the public immutable[1] blockchain, it's straightforward to confirm both the existence and authenticity of tokenized documents. + +--- +## Practice + +Maria, an admin at University of Chicago, can issue NFTs as certificates for a proof of degree completion. + +??? + +- True +- False + +--- +## Revision + +NFTs can only represent digital artwork and in-game collectibles. + +??? + +- False +- True + +--- +## Footnotes + +[1: Blockchains are immutable] + +Once a piece of data is added to the blockchain, it cannot be tampered with. + +This means that, blockchains work great for storing factual data whos authenticity needs to be verified. + +[2: Social Tokens example] + +For example, Reuben Bramanathan, who previously worked on legal and product at Coinbase, tokenized his time where 1 $CSNL token equaled 1 hour of his time and was freely traded. + From 1dde2d92bccc1e25a9a2e4bb0074e9b55d120dc0 Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic <n.stojanovic035@gmail.com> Date: Tue, 3 Jan 2023 15:40:07 +0100 Subject: [PATCH 315/390] Typo --- sql/ddl/create/check-constraint.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sql/ddl/create/check-constraint.md b/sql/ddl/create/check-constraint.md index fb2c617468..baa798f7c3 100644 --- a/sql/ddl/create/check-constraint.md +++ b/sql/ddl/create/check-constraint.md @@ -32,7 +32,7 @@ CREATE TABLE voters ( ); ``` -Now, if you were to insert a record which had a value for the `age` column less that 18, you would get an error. +Now, if you were to insert a record which had a value for the `age` column less than 18, you would get an error. What if you wanted to constrain the value of two columns at the same time? This is possible by creating a table check constraint. Let's say that for some reason you also want only names that start with `'T'`. In this case, your table definition would look like: From 46216a14364ff7af0fb5ea964f95a0da337d5f0a Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 3 Jan 2023 15:43:56 +0100 Subject: [PATCH 316/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 34a9d40618..344e9f8f6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## January 3rd 2023 + +### Fixed +- [SQL - Check constraint - Fix typo](https://github.com/enkidevs/curriculum/pull/3148) + ## December 16th 2022 ### Changed From d1f4c073c065515ffda0dab33cce3aed6d861303 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 3 Jan 2023 15:55:05 +0100 Subject: [PATCH 317/390] Update dijkstras-algorithm.md --- .../graph-algorithms/dijkstras-algorithm.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/comp-sci/data-structures-and-algorithms/graph-algorithms/dijkstras-algorithm.md b/comp-sci/data-structures-and-algorithms/graph-algorithms/dijkstras-algorithm.md index 44639b7530..bc5a852712 100644 --- a/comp-sci/data-structures-and-algorithms/graph-algorithms/dijkstras-algorithm.md +++ b/comp-sci/data-structures-and-algorithms/graph-algorithms/dijkstras-algorithm.md @@ -4,8 +4,9 @@ type: normal category: must-know links: - >- - [Step-by-step, interactive Dijkstra`s algorithm - application](https://www-m9.ma.tum.de/graph-algorithms/spp-dijkstra/index_en.html){website} + [Dijkstra's algorithm](https://algorithms.discrete.ma.tum.de/graph-algorithms/spp-dijkstra/index_en.html){website} + - >- + [Dijkstra's algorithm video](https://www.youtube.com/watch?v=GazC3A4OQTE){video} revisionQuestion: formats: - fill-in-the-gap From c031a380e6afd7900a35ca77797400452984451a Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Tue, 3 Jan 2023 20:39:37 +0100 Subject: [PATCH 318/390] draft --- r/r-core/intro-to-r/1 copy 2.md | 90 ++++++++++++++ r/r-core/intro-to-r/1 copy 3.md | 90 ++++++++++++++ r/r-core/intro-to-r/1 copy 4.md | 90 ++++++++++++++ r/r-core/intro-to-r/1 copy 5.md | 90 ++++++++++++++ r/r-core/intro-to-r/assignment-operators-r.md | 73 +++++++++++ r/r-core/intro-to-r/basic-data-types-r.md | 90 ++++++++++++++ .../intro-to-r/combining-variables-in-r.md | 92 ++++++++++++++ .../intro-to-r/creating-a-program-in-r.md | 99 +++++++++++++++ .../creating-and-storing-variables-in-r.md | 58 +++++++++ .../intro-to-r/function-methods-in-r-ii.md | 91 ++++++++++++++ r/r-core/intro-to-r/function-methods-in-r.md | 87 +++++++++++++ r/r-core/intro-to-r/functions-in-r.md | 89 ++++++++++++++ .../global-environment-variables-in-r.md | 92 ++++++++++++++ r/r-core/intro-to-r/local-variables-in-r.md | 105 ++++++++++++++++ .../local-vs-global-variables-in-r.md | 85 +++++++++++++ .../printing-and-storing-variables-in-r.md | 74 +++++++++++ r/r-core/intro-to-r/what-is-r.md | 65 ++++++++++ r/r-core/intro-to-r/why-learn-r.md | 70 +++++++++++ .../dictionary-methods-in-r-ii.md | 116 ++++++++++++++++++ .../dictionary-methods-in-r.md | 104 ++++++++++++++++ .../intro-to-dictionaries-r.md | 78 ++++++++++++ 21 files changed, 1828 insertions(+) create mode 100644 r/r-core/intro-to-r/1 copy 2.md create mode 100644 r/r-core/intro-to-r/1 copy 3.md create mode 100644 r/r-core/intro-to-r/1 copy 4.md create mode 100644 r/r-core/intro-to-r/1 copy 5.md create mode 100644 r/r-core/intro-to-r/assignment-operators-r.md create mode 100644 r/r-core/intro-to-r/basic-data-types-r.md create mode 100644 r/r-core/intro-to-r/combining-variables-in-r.md create mode 100644 r/r-core/intro-to-r/creating-a-program-in-r.md create mode 100644 r/r-core/intro-to-r/creating-and-storing-variables-in-r.md create mode 100644 r/r-core/intro-to-r/function-methods-in-r-ii.md create mode 100644 r/r-core/intro-to-r/function-methods-in-r.md create mode 100644 r/r-core/intro-to-r/functions-in-r.md create mode 100644 r/r-core/intro-to-r/global-environment-variables-in-r.md create mode 100644 r/r-core/intro-to-r/local-variables-in-r.md create mode 100644 r/r-core/intro-to-r/local-vs-global-variables-in-r.md create mode 100644 r/r-core/intro-to-r/printing-and-storing-variables-in-r.md create mode 100644 r/r-core/intro-to-r/what-is-r.md create mode 100644 r/r-core/intro-to-r/why-learn-r.md create mode 100644 r/r-core/unordered-data-types-r/dictionary-methods-in-r-ii.md create mode 100644 r/r-core/unordered-data-types-r/dictionary-methods-in-r.md create mode 100644 r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md diff --git a/r/r-core/intro-to-r/1 copy 2.md b/r/r-core/intro-to-r/1 copy 2.md new file mode 100644 index 0000000000..ca0f62ce75 --- /dev/null +++ b/r/r-core/intro-to-r/1 copy 2.md @@ -0,0 +1,90 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +**R** has several basic data types, including: + +`character`: characters, such as "hello" or "goodbye" +```r +greeting <- "hello" +print(greeting) +# "hello" +``` + +`numeric`: numbers, either integers or decimals + +```r +numbers <- c(1, 2, 3, 4, 5) +print(numbers) +# 1 2 3 4 5 + +decimals <- c(1.1, 2.2, 3.3) +print(decimals) +# 1.1 2.2 3.3 +``` + +`logical`: boolean values, either `TRUE` or `FALSE`: + +```r +booleans <- c(TRUE, FALSE, TRUE, FALSE) +print(booleans) +# TRUE FALSE TRUE FALSE +``` + +`factor`: categorical variables +```r +cities <- factor(c("New York", "Chicago", "San Francisco", "New York")) +print(cities) +# New York Chicago San Francisco New York +# Levels: Chicago New York San Francisco +``` + +`NULL`: represents an empty object +```r +empty <- NULL +print(empty) +# NULL +``` + +--- +## Practice + +Which of the following is a basic data type in R? + +??? + +- `numeric` +- `integer` +- `matrix` +- `function` +- `data frame` + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/intro-to-r/1 copy 3.md b/r/r-core/intro-to-r/1 copy 3.md new file mode 100644 index 0000000000..ca0f62ce75 --- /dev/null +++ b/r/r-core/intro-to-r/1 copy 3.md @@ -0,0 +1,90 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +**R** has several basic data types, including: + +`character`: characters, such as "hello" or "goodbye" +```r +greeting <- "hello" +print(greeting) +# "hello" +``` + +`numeric`: numbers, either integers or decimals + +```r +numbers <- c(1, 2, 3, 4, 5) +print(numbers) +# 1 2 3 4 5 + +decimals <- c(1.1, 2.2, 3.3) +print(decimals) +# 1.1 2.2 3.3 +``` + +`logical`: boolean values, either `TRUE` or `FALSE`: + +```r +booleans <- c(TRUE, FALSE, TRUE, FALSE) +print(booleans) +# TRUE FALSE TRUE FALSE +``` + +`factor`: categorical variables +```r +cities <- factor(c("New York", "Chicago", "San Francisco", "New York")) +print(cities) +# New York Chicago San Francisco New York +# Levels: Chicago New York San Francisco +``` + +`NULL`: represents an empty object +```r +empty <- NULL +print(empty) +# NULL +``` + +--- +## Practice + +Which of the following is a basic data type in R? + +??? + +- `numeric` +- `integer` +- `matrix` +- `function` +- `data frame` + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/intro-to-r/1 copy 4.md b/r/r-core/intro-to-r/1 copy 4.md new file mode 100644 index 0000000000..ca0f62ce75 --- /dev/null +++ b/r/r-core/intro-to-r/1 copy 4.md @@ -0,0 +1,90 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +**R** has several basic data types, including: + +`character`: characters, such as "hello" or "goodbye" +```r +greeting <- "hello" +print(greeting) +# "hello" +``` + +`numeric`: numbers, either integers or decimals + +```r +numbers <- c(1, 2, 3, 4, 5) +print(numbers) +# 1 2 3 4 5 + +decimals <- c(1.1, 2.2, 3.3) +print(decimals) +# 1.1 2.2 3.3 +``` + +`logical`: boolean values, either `TRUE` or `FALSE`: + +```r +booleans <- c(TRUE, FALSE, TRUE, FALSE) +print(booleans) +# TRUE FALSE TRUE FALSE +``` + +`factor`: categorical variables +```r +cities <- factor(c("New York", "Chicago", "San Francisco", "New York")) +print(cities) +# New York Chicago San Francisco New York +# Levels: Chicago New York San Francisco +``` + +`NULL`: represents an empty object +```r +empty <- NULL +print(empty) +# NULL +``` + +--- +## Practice + +Which of the following is a basic data type in R? + +??? + +- `numeric` +- `integer` +- `matrix` +- `function` +- `data frame` + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/intro-to-r/1 copy 5.md b/r/r-core/intro-to-r/1 copy 5.md new file mode 100644 index 0000000000..ca0f62ce75 --- /dev/null +++ b/r/r-core/intro-to-r/1 copy 5.md @@ -0,0 +1,90 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +**R** has several basic data types, including: + +`character`: characters, such as "hello" or "goodbye" +```r +greeting <- "hello" +print(greeting) +# "hello" +``` + +`numeric`: numbers, either integers or decimals + +```r +numbers <- c(1, 2, 3, 4, 5) +print(numbers) +# 1 2 3 4 5 + +decimals <- c(1.1, 2.2, 3.3) +print(decimals) +# 1.1 2.2 3.3 +``` + +`logical`: boolean values, either `TRUE` or `FALSE`: + +```r +booleans <- c(TRUE, FALSE, TRUE, FALSE) +print(booleans) +# TRUE FALSE TRUE FALSE +``` + +`factor`: categorical variables +```r +cities <- factor(c("New York", "Chicago", "San Francisco", "New York")) +print(cities) +# New York Chicago San Francisco New York +# Levels: Chicago New York San Francisco +``` + +`NULL`: represents an empty object +```r +empty <- NULL +print(empty) +# NULL +``` + +--- +## Practice + +Which of the following is a basic data type in R? + +??? + +- `numeric` +- `integer` +- `matrix` +- `function` +- `data frame` + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/intro-to-r/assignment-operators-r.md b/r/r-core/intro-to-r/assignment-operators-r.md new file mode 100644 index 0000000000..3e15ce475f --- /dev/null +++ b/r/r-core/intro-to-r/assignment-operators-r.md @@ -0,0 +1,73 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Assignment Operators in R + +--- + +## Content + +In R, you can use assignment operators to assign values to variables. + +The most common assignment operator is the <- operator, which is used to assign a value to a variable: +```r +x <- 5 +y <- 10 + +print(x) +# 5 + +print(y) +# 10 +``` + +You can also use the = operator for assignment: +```r +x = 5 +y = 10 + +print(x) +# 5 + +print(y) +# 10 +``` + + +--- +## Practice + +Which of the following is a basic data type in R? + +??? + +- `numeric` +- `integer` +- `matrix` +- `function` +- `data frame` + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/intro-to-r/basic-data-types-r.md b/r/r-core/intro-to-r/basic-data-types-r.md new file mode 100644 index 0000000000..ca0f62ce75 --- /dev/null +++ b/r/r-core/intro-to-r/basic-data-types-r.md @@ -0,0 +1,90 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +**R** has several basic data types, including: + +`character`: characters, such as "hello" or "goodbye" +```r +greeting <- "hello" +print(greeting) +# "hello" +``` + +`numeric`: numbers, either integers or decimals + +```r +numbers <- c(1, 2, 3, 4, 5) +print(numbers) +# 1 2 3 4 5 + +decimals <- c(1.1, 2.2, 3.3) +print(decimals) +# 1.1 2.2 3.3 +``` + +`logical`: boolean values, either `TRUE` or `FALSE`: + +```r +booleans <- c(TRUE, FALSE, TRUE, FALSE) +print(booleans) +# TRUE FALSE TRUE FALSE +``` + +`factor`: categorical variables +```r +cities <- factor(c("New York", "Chicago", "San Francisco", "New York")) +print(cities) +# New York Chicago San Francisco New York +# Levels: Chicago New York San Francisco +``` + +`NULL`: represents an empty object +```r +empty <- NULL +print(empty) +# NULL +``` + +--- +## Practice + +Which of the following is a basic data type in R? + +??? + +- `numeric` +- `integer` +- `matrix` +- `function` +- `data frame` + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/intro-to-r/combining-variables-in-r.md b/r/r-core/intro-to-r/combining-variables-in-r.md new file mode 100644 index 0000000000..ec38eda46c --- /dev/null +++ b/r/r-core/intro-to-r/combining-variables-in-r.md @@ -0,0 +1,92 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Combining Variables in R + +--- + +## Content + +In **R**, you can use the `c()` function to combine variables into a vector. Here is a function that takes in a sequence of values and returns a vector: +```r +x <- 5 +y <- 10 + +z <- c(x, y) +print(z) +# 5 10 +``` + +You can also use the `cbind()` function to combine variables horizontally (i.e., side by side) into a matrix. For example: +```r +x <- 5 +y <- 10 +z <- 10 + +matrix1 <- cbind(x, y) +print(matrix1) +# x y +# [1,] 5 10 + +matrix2 <- cbind(z, y) +print(matrix2) +# z y +# [1,] 5 10 +# [2,]10 10 +``` + +Alternatively, you can use the `rbind()` function to combine variables vertically (i.e., one on top of the other) into a matrix. For example: +```r +x <- 5 +y <- 10 +z <- 5 + +matrix3 <- rbind(x, y) +print(matrix3) +# [,1] +# x 5 +# y 10 + +matrix4 <- rbind(z, y) +print(matrix4) +# [,1] +# z 5 +# y 10 +``` + + +--- +## Practice + +Which of the following is **NOT** a way to combine variables in **R**? + +??? + +- `vector = merge(x, y)` +- `z = c(x, y)` +- `matrix1 = bind(x, y)` +- `matrix2 = rbind(z, y)` + +--- +## Revision + +Which function can be used to combine variables vertically into a matrix in **R**? + +??? + +- `rbind()` +- `cbind()` +- `combine()` +- `merge()` \ No newline at end of file diff --git a/r/r-core/intro-to-r/creating-a-program-in-r.md b/r/r-core/intro-to-r/creating-a-program-in-r.md new file mode 100644 index 0000000000..effa81f9a3 --- /dev/null +++ b/r/r-core/intro-to-r/creating-a-program-in-r.md @@ -0,0 +1,99 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +In this tutorial, we will write a simple program in R that calculates the area of a rectangle. + +First, we will define a function calculate_area() that takes in two arguments: length and width. The function will return the area of the rectangle, which is calculated by multiplying the length and width. +```r +calculate_area <- function(length, width) { + return(length * width) +} +``` + +Next, we will prompt the user to enter the length and width of the rectangle using the readline() function. +```r +length <- readline("Enter the length of the rectangle: ") +width <- readline("Enter the width of the rectangle: ") +``` + +Note that the input entered by the user will be stored as a character string, so we need to convert it to a numeric value using the as.numeric() function. +```r +length <- as.numeric(length) +width <- as.numeric(width) +``` + +Finally, we will call the calculate_area() function and print the result. +```r +area <- calculate_area(length, width) + +print(paste("The area of the rectangle is", area)) +``` + +The complete program would look like this: +```r +calculate_area <- function(length, width) { + return(length * width) +} + +length <- readline("Enter the length of the rectangle: ") +width <- readline("Enter the width of the rectangle: ") + +length <- as.numeric(length) +width <- as.numeric(width) + +area <- calculate_area(length, width) + +print(paste("The area of the rectangle is", area)) +``` + +--- +## Practice + +Complete the code to finish the program: + +```r +calculate_area <- function(length, width) { + return(length * width) +} + +length <- 8 +width <- 5 + +area <- calculate_area(length, width) + +print(paste("The area of the rectangle is", area)) +``` + + + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/intro-to-r/creating-and-storing-variables-in-r.md b/r/r-core/intro-to-r/creating-and-storing-variables-in-r.md new file mode 100644 index 0000000000..fcb21ad4f9 --- /dev/null +++ b/r/r-core/intro-to-r/creating-and-storing-variables-in-r.md @@ -0,0 +1,58 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Creating and Storing Variables in R + +--- + +## Content + +In **R**, you can create variables using the `<-` operator. For example: +```r +x <- 5 +y <- 10 +``` + +You can also use the `=` operator, but it is generally recommended to use `<-` as it is easier to read and less prone to errors. + +To access the value of a variable, you can type the name of the variable inside a `print()`: +```r +print(x) +# 5 + +print(y) +# 10 +``` + +You can also use the `assign()` function to create a variable and store it in the global environment: +```r +assign("z", c(x, y)) +print(z) +# 5 10 +``` + + + +--- +## Practice + +Which of the following is **NOT** a way to create a variable in **R**? + +??? + +-``a <=` +-`x = 5` +-`y <- 10` +-`z = c(x, y)` \ No newline at end of file diff --git a/r/r-core/intro-to-r/function-methods-in-r-ii.md b/r/r-core/intro-to-r/function-methods-in-r-ii.md new file mode 100644 index 0000000000..eb064f1d4f --- /dev/null +++ b/r/r-core/intro-to-r/function-methods-in-r-ii.md @@ -0,0 +1,91 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# More Function Methods + +--- + +## Content + +In **R**, there are many more function methods that you can use to manipulate functions. + +The `args()` function returns a list of the formal arguments of a function: +```r +add <- function(x, y) { + x + y +} + +args(add) +# x, y +``` + +The `source()` function reads in the source code of a function and returns it as a character string: +```r +add <- function(x, y) { + x + y +} + +deparse(add) +# "function (x, y) +# { +# x + y +# }" +``` + +The `deparse()` function returns a character string representation of an object: +```r +add <- function(x, y) { + x + y +} + +deparse(add) +# "function (x, y) +# { +# x + y +# }" +``` + +The `is.primitive()` function returns `TRUE` if an object is a primitive function and `FALSE` otherwise: +```r +is.primitive(mean) +# TRUE + +is.primitive(add) +# FALSE +``` + +--- +## Practice + +Which function can be used to return a character string representation of an object in **R**? + +??? + +- `deparse()` +- `args()` +- `source()` +- `is.primitive()` + +--- +## Revision + +Which function returns `TRUE` if an object is a primitive function and FALSE otherwise in **R**? + +??? + +- `is.primitive()` +- `args()` +- `source()` +- `deparse()` \ No newline at end of file diff --git a/r/r-core/intro-to-r/function-methods-in-r.md b/r/r-core/intro-to-r/function-methods-in-r.md new file mode 100644 index 0000000000..9c3cabe850 --- /dev/null +++ b/r/r-core/intro-to-r/function-methods-in-r.md @@ -0,0 +1,87 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Function Methods in R + +--- + +## Content + +In **R**, you can use function methods to manipulate functions. + +The `formals()` function returns a list of the arguments of a function: +```r +add <- function(x, y) { + x + y +} + +formals(add) +# $x +# $y +``` + +The `body()` function returns the body of a function as an expression: +```r +add <- function(x, y) { + x + y +} + +body(add) +# x + y +``` + +The `environment()` function returns the environment in which a function was defined: +```r +add <- function(x, y) { + x + y +} + +environment(add) +# <environment: R_GlobalEnv> +``` + +You can use the `call()` function to call a function with a list of arguments: +```r +add <- function(x, y) { + x + y +} + +args <- list(5, 10) +call(add, args) +# 15 +``` + +--- +## Practice + +Which function can be used to return the body of a function as an expression in **R**? + +??? + +- `body()` +- `formals()` +- `environment()` +- `call()` + +--- +## Revision + +Which function can be used to call a function with a list of arguments in **R**? + +??? + +- `call()` +- `formals()` +- `body()` \ No newline at end of file diff --git a/r/r-core/intro-to-r/functions-in-r.md b/r/r-core/intro-to-r/functions-in-r.md new file mode 100644 index 0000000000..30d6329ea4 --- /dev/null +++ b/r/r-core/intro-to-r/functions-in-r.md @@ -0,0 +1,89 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Functions in R + +--- + +## Content + +In **R**, a function is a reusable block of code that performs a specific task. Functions can take in arguments and return values. + +You can define a function using the `function` keyword, followed by the function `name` and a pair of parentheses `()`. The arguments go inside the parentheses, separated by commas. The function body goes inside curly braces `{}`. + +Here is an example of a function that adds two numbers: +```r +add <- function(x, y) { + x + y +} + +result <- add(5, 10) +print(result) +# 15 +``` + +You can use the `return()` function to specify the value that the function should return: +```r +add <- function(x, y) { + return(x + y) +} + +result <- add(5, 10) +print(result) +# 15 +``` + +You can also specify default values for the arguments using the `=` operator: +```r +add <- function(x = 1, y = 2) { + return(x + y) +} + +result <- add() +print(result) +# 3 + +result <- add(5) +print(result) +# 7 + +result <- add(y = 10) +print(result) +# 11 +``` + +--- +## Practice + +Which of the following is **NOT** a way to define a function in **R**? + +??? + +- `add <- function(x, y) {x + y}` +- `add(x, y) => {x + y}` +- `function add(x, y) {x + y}` +- `def add(x, y): return x + y` + +--- +## Revision + +Which function can be used to specify the value that a function should return in **R**? + +??? + +- `return()` +- `result()` +- `output()` +- `value()` \ No newline at end of file diff --git a/r/r-core/intro-to-r/global-environment-variables-in-r.md b/r/r-core/intro-to-r/global-environment-variables-in-r.md new file mode 100644 index 0000000000..1acce1ce72 --- /dev/null +++ b/r/r-core/intro-to-r/global-environment-variables-in-r.md @@ -0,0 +1,92 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Global Environment Variables in R + +--- + +## Content + +In **R**, a global environment is a place where all the objects you create are stored. When you start an **R** session, a global environment is created automatically. + +You can use the `ls()` function to list the objects in the global environment: +```r +x <- 5 +y <- 10 + +ls() +# "x" "y" +``` + +You can also use the `objects()` function to list the objects in the global environment: + +```r +objects() +# [1] "x" "y" +``` + +To access the value of a global environment variable, you can type the name of the variable: + +```r +print(x) +# 5 + +print(y) +# 10 +``` + +You can also use the `get()` function to access the value of a global environment variable: +```r +get("x") +# 5 + +get("y") +# 10 +``` + +To remove a global environment variable, you can use the `rm()` function: +```r +rm(x) + +ls() +# "y" + +objects() +# [1] "y" +``` + +--- +## Practice + +Which of the following is **NOT** a way to list all objects in the global environment in **R**? + +??? + +- `get()` +- `ls()` +- `objects()` + + +--- +## Revision + +What function can be used to remove a global environment variable in R? + +??? + +- `rm()` +- `delete()` +- `remove()` +- `erase()` \ No newline at end of file diff --git a/r/r-core/intro-to-r/local-variables-in-r.md b/r/r-core/intro-to-r/local-variables-in-r.md new file mode 100644 index 0000000000..9e8f729768 --- /dev/null +++ b/r/r-core/intro-to-r/local-variables-in-r.md @@ -0,0 +1,105 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Local Variables in R + +--- + +## Content + +In **R**, a local environment is a place where the objects you create within a function are stored. When you define a function, a local environment is created automatically. + +To create a local variable within a function, you can use the `<-` operator. For example: + +```r +add <- function(x, y) { + z <- x + y + print(z) +} + +add(5, 10) +# 15 +``` + +You can also use the `assign()` function to create a local variable and store it in the local environment: + +```r +add <- function(x, y) { + assign("z", x + y) + print(z) +} + +add(5, 10) +# 15 +``` + +To access the value of a local variable, you can type the name of the variable: + +```r +add <- function(x, y) { + z <- x + y + print(z) +} + +add(5, 10) +# 15 +``` + +You can also use the `get()` function to access the value of a local variable: +```r +add <- function(x, y) { + assign("z", x + y) + print(get("z")) +} + +add(5, 10) +# 15 +``` + +To remove a local variable, you can use the `rm()` function: +```r +add <- function(x, y) { + z <- x + y + rm(z) + print(z) +} + +add(5, 10) +# Error: object 'z' not found +``` + +--- +## Practice + +Which of the following is **NOT** a way to create a local variable in a function in **R**? + +??? + +- `z <- x + y` +- `assign("z", x + y)` +- `get("z") <- x + y` +- `rm("z", x + y)` + +--- +## Revision + +What function can be used to remove a local variable in a function in **R**? + +??? + +- `delete()` +- `remove()` +- `erase()` +- `rm()` \ No newline at end of file diff --git a/r/r-core/intro-to-r/local-vs-global-variables-in-r.md b/r/r-core/intro-to-r/local-vs-global-variables-in-r.md new file mode 100644 index 0000000000..75c3b4daa9 --- /dev/null +++ b/r/r-core/intro-to-r/local-vs-global-variables-in-r.md @@ -0,0 +1,85 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +In **R**, a global environment is a place where all the objects you create are stored. When you start an **R** session, a global environment is created automatically. + +On the other hand, a local environment is a place where the objects you create within a function are stored. When you define a function, a local environment is created automatically. + +Global variables can be accessed from anywhere in your **R** session, while local variables can only be accessed within the function where they are defined. + +Here is an example that illustrates the difference between global and local variables: + +```r +x <- 5 + +add <- function(y) { + z <- x + y + print(z) +} + +add(10) +# 15 + +print(z) +# Error: object 'z' not found +``` + +In this example, `x` is a global variable, while `z` is a local variable. The `add()` function uses both variables, but `z` is only defined within the function and is not accessible outside of it. + +You can use the `<<-` operator to create a global variable within a function: +```r +add <- function(y) { + z <<- x + y + print(z) +} + +add(10) +# 15 + +print(z) +# 15 +``` + +Note that the use of the `<<-` operator is generally discouraged as it can lead to confusing and hard-to-debug code. + +--- +## Practice + +Which of the following is **NOT** true about global and local variables in **R**? + +??? + +- The <<- operator is generally recommended for creating global variables in **R**. +- The <<- operator can be used to create a global variable within a function. +- Local variables can only be accessed within the function where they are defined. +- Global variables can be accessed from anywhere in your **R** session. + +--- +## Revision + +Which of the following is **NOT** a way to access the value of a global environment variable in **R**? + +??? + +- `rm("x")` +- `print(x)` +- `get("x")` +- `x[1]` \ No newline at end of file diff --git a/r/r-core/intro-to-r/printing-and-storing-variables-in-r.md b/r/r-core/intro-to-r/printing-and-storing-variables-in-r.md new file mode 100644 index 0000000000..2d61a3ec4f --- /dev/null +++ b/r/r-core/intro-to-r/printing-and-storing-variables-in-r.md @@ -0,0 +1,74 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Printing and Storing Variables in R + +--- + +## Content + +In this lesson, you'll learn how to print messages and store variables in **R**. + + +### Printing Messages +--- + +To print a message to the console in **R**, you can use the `print()` function. For example: +```r +print("Hello, world!") +``` + +You can also use the `cat()` function to print a message. The `cat()` function is similar to `print()`, but it does not add a newline after the message. For example: +```r +cat("Hello, world!") +``` + +### Storing Variables +--- + +To store a value in a variable in **R**, you can use the assignment operator `<-`. For example: +```r +x <- 10 +y <- 20 +z <- x + y +``` + +You can also use the `=` operator to store a value in a variable, but it is generally recommended to use `<-` as it is more readable and less prone to errors. + + +> 💬 Why are you interested in **R**? +> +> Leave a comment or view some of the other comments for inspiration before moving on. + +--- +## Practice + +Which of the following is the correct way to store the value `5` in a variable `x`? + +??? + +- x <- 5 +- x = 5 +- x < 5 +- x =< 5 + +--- +## Footnotes + +[1: Printing] +Printing messages in **R** is useful for debugging and for communicating information to the user. + +[2: Variables] +Variables are used to store values in a program, making it easier to reuse those values and perform operations on them. \ No newline at end of file diff --git a/r/r-core/intro-to-r/what-is-r.md b/r/r-core/intro-to-r/what-is-r.md new file mode 100644 index 0000000000..d8ddbabf93 --- /dev/null +++ b/r/r-core/intro-to-r/what-is-r.md @@ -0,0 +1,65 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# R Intro + +--- + +## Content + +**R** is a popular programming language and software environment for statistical computing[1] and graphics[2]. It is widely used among statisticians, data scientists, and researchers in academia and industry. + +**R** is a high-level language, which means it has a relatively simple syntax that is easy to read and write. Here's an example of how you might plot a line graph in **R**: + +```r +x <- c(1, 2, 3, 4, 5) +y <- c(1, 4, 9, 16, 25) +plot(x, y) +``` + +**R** also has a vast community of users and developers, which has led to the creation of a large number of packages that extend its functionality. This means that **R** is capable of handling a wide range of tasks, from data manipulation and visualization to machine learning and data analysis. + +> 💬 Why are you interested in **R**? +> +> Leave a comment or view some of the other comments for inspiration before moving on. + +--- +## Practice + +Let's try some **R** code! Do you remember how to print a message to the console? + +Don't worry; this is to get you comfortable with code. +You'll learn all about how this works in the upcoming lessons. + + +```r +message <- "Hello, world!" +???(message) +``` + +- print +- write +- output +- cat + +--- +## Footnotes + + +[1: Statistical Computing] +**R** is primarily used for statistical computing, which involves the use of statistical techniques to analyze data and make inferences about it. This includes tasks such as fitting statistical models to data, estimating parameters, and testing hypotheses. + +[2: Graphics] +In addition to its capabilities for statistical computing, **R** is also known for its powerful graphics capabilities. It includes a variety of functions for creating plots and charts, which can be used to visualize and communicate data effectively. \ No newline at end of file diff --git a/r/r-core/intro-to-r/why-learn-r.md b/r/r-core/intro-to-r/why-learn-r.md new file mode 100644 index 0000000000..6d8b96d78d --- /dev/null +++ b/r/r-core/intro-to-r/why-learn-r.md @@ -0,0 +1,70 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion + +type: normal + +category: must-know + +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Why It's Good to Learn R + +--- + +## Content + + +**R** is a powerful and popular programming language that is widely used in data science, statistics, and research. Here are a few reasons why it's a good idea to learn **R**: + +It's widely used in academia and industry: **R** is a popular choice for statistical analysis and data visualization in many fields, including economics, biology, psychology, and finance. This means that learning **R** can make you a valuable asset to employers and can open up career opportunities in a variety of industries. + +It has a large and active community: **R** has a large and active community of users and developers, which means that there is a wealth of resources and support available for learning and using **R**. There are numerous forums, blogs, and online communities where you can ask questions, get help, and share your knowledge with others. + +It has a wide range of packages and tools: **R** has a vast collection of packages and tools that extend its functionality and make it suitable for a wide range of tasks. For example, there are packages for machine learning, data manipulation, data visualization, and more. + +It's a good foundation for learning other languages: Many other programming languages, such as Python and Java, share some similarities with **R**. Learning **R** can therefore be a good foundation for learning these other languages, making it easier to pick up new skills in the future. + +> 💬 What motivates you to learn **R**? +> +> Leave a comment or view some of the other comments for inspiration before moving on. + +--- + +## Practice + +Let's try some **R** code! Can you write a function that takes a vector of numbers and returns the sum of the squares of those numbers? + +```r +sum_of_squares <- function(x) { + ??? +} + +``` + +- sum(x^2) +- x^2 %>% sum +- reduce(x, +, x^2) +- x %>% sapply(function(n) n^2) %>% sum + + +--- + +## Footnotes + +[1: Data Science] +**R** is widely used in data science, which is the field that deals with the extraction of insights and knowledge from data. This includes tasks such as data cleaning, analysis, and visualization. + +[2: Statistics] +**R** is also used in statistical analysis, which involves the use of statistical methods to analyze data and make inferences about it. This includes tasks such as hypothesis testing, regression analysis, and statistical modeling. + +[3: Research] +**R** is commonly used in research, particularly in fields such as biology, psychology, and economics. It is often used to analyze and visualize data, as well as to perform statistical analyses and simulations. \ No newline at end of file diff --git a/r/r-core/unordered-data-types-r/dictionary-methods-in-r-ii.md b/r/r-core/unordered-data-types-r/dictionary-methods-in-r-ii.md new file mode 100644 index 0000000000..1a12ac3d2e --- /dev/null +++ b/r/r-core/unordered-data-types-r/dictionary-methods-in-r-ii.md @@ -0,0 +1,116 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# More about Dictionaries in R + +--- + +## Content + +In addition to accessing elements in a dictionary (or list) as shown in the previous insight, you can also add and remove elements. + +To add an element to a list, you can use the `[[<-]]` or `[<-]` operators: +```r +fruits <- list(apple = "red", orange = "orange") +fruits[[4]] <- "green" +fruits["banana"] <- "yellow" + +print(fruits) +# $apple +# [1] "red" +# +# $orange +# [1] "orange" +# +# $banana +# [1] "yellow" +# +# $`4` +# [1] "green" +``` + +You can also use the `$<-` operator to add an element with a specific key: +```r +fruits$kiwi <- "brown" + +print(fruits) +# $apple +# [1] "red" +# +# $orange +# [1] "orange" +# +# $banana +# [1] "yellow" +# +# $`4` +# [1] "green" +# +# $kiwi +# [1] "brown" + +``` + +To remove an element from a list, you can use the `-` operator: +```r +fruits <- list(apple = "red", orange = "orange", banana = "yellow") +fruits <- fruits[-2] + +print(fruits) +# $apple +# [1] "red" +# +# $banana +# [1] "yellow" +``` + +You can also use the rm() function to remove an element by its key: +```r +fruits <- list(apple = "red", orange = "orange", banana = "yellow") +rm(fruits$orange) + +print(fruits) +# $apple +# [1] "red" +# +# $banana +# [1] "yellow" +``` + + +--- +## Practice + +Which of the following is **NOT** a way to add an element to a list in **R**? + +??? + +- `list.key <- value` +- `list[[<-]]` +- `list[<-]` +- `list$<-` + + +--- +## Revision + +What function can be used to remove an element from a list by its key in **R**? + +??? + +- `rm()` +- `remove()` +- `delete()` +- `erase()` \ No newline at end of file diff --git a/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md b/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md new file mode 100644 index 0000000000..1606102afa --- /dev/null +++ b/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md @@ -0,0 +1,104 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Dictionary Methods in R + +--- + +## Content + +`R` has several functions for working with dictionaries. Here are some of the most commonly used ones: + +Consider the following dictionary: +```r +square_numbers <- list( + 1: 1, + 2: 4, + 3: 9, + 4: 16, + 5: 25 +) +``` + +`rm()` removes all items from the dictionary +```r +rm(square_numbers) + +print(square_numbers) +# NULL +``` + +`duplicate()` returns a copy of the dictionary +```r +new_squares <- duplicate(square_numbers) + +print(new_squares) +# 1: 1 +# 2: 4 +# 3: 9 +# 4: 16 +# 5: 25 + +``` + +names() returns the names of the elements in the dictionary as a character vector + +```r +names(square_numbers) + +print(names(square_numbers)) +# "1" "2" "3" "4" "5" + +``` + + +--- +## Practice + +Complete the following code snippet to make a duplicate of the variable `my_house` called `new_house`: + +```r +my_house <- list(bedrooms: 2, bathrooms: 2, garden: TRUE) + +new_house <- ???.??? +``` + +- my_house +- duplicate() +- clone() +- copy() +- duplicate + +--- +## Revision + +What function can be used to return the names of the elements in a dictionary as a character vector? + + +```r +english_to_french <- list(apple: 'pomme', orange: 'orange') + +english_to_french.??? +# "orange" "apple" +``` + +- names() +- keys() +- contents() +- items() + +--- +## Footnotes + diff --git a/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md b/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md new file mode 100644 index 0000000000..5b1a6bd401 --- /dev/null +++ b/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md @@ -0,0 +1,78 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Introduction to Dictionaries in R + +--- + +## Content + +In `R`, dictionaries are known as lists. A list is an ordered collection of elements, where each element can be of a different data type. Lists are created using the `list()` function. + +Here is an example of a list: +```r +fruits <- list(apple = "red", orange = "orange", banana = "yellow") +``` + +The elements in a list are called components, and each component has a name and a value. The names are called keys, and the values are called the elements of the list. + +To access an element in a list, you can use either the `[[]]`, `[]` or the `$` operator. + +For example: +```r +fruits[[1]] +# "red" + +fruits[1] +# "red" + +fruits$apple +# "red" +``` + +You can also use the `names()` function to get a character vector of the names of the elements in a list: +```r +names(fruits) +# "apple" "orange" "banana" +``` + +And the `length()` function to get the number of elements in a list: +```r +length(fruits) +# 3 +``` + + +--- +## Practice + +Which of the following is **NOT** a way to access an element in a list in **R**? + +- `list.key` +- `list[[1]]` +- `list$key` +- `list[1]` + +--- +## Revision + +What function can be used to get the number of elements in a list in R? + +??? + +- `length()` +- `size()` +- `count()` +- `lengths()` \ No newline at end of file From b59daccad9f59361d1c39df6fda285c9d72cfa5e Mon Sep 17 00:00:00 2001 From: nishmamehta <121473459+nishmamehta@users.noreply.github.com> Date: Wed, 4 Jan 2023 18:54:25 +0530 Subject: [PATCH 319/390] Update intro-to-nfts/intro-to-nfts/README.md Co-authored-by: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> --- intro-to-nfts/intro-to-nfts/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/intro-to-nfts/intro-to-nfts/README.md b/intro-to-nfts/intro-to-nfts/README.md index dd833db6ed..301b8fbbfd 100644 --- a/intro-to-nfts/intro-to-nfts/README.md +++ b/intro-to-nfts/intro-to-nfts/README.md @@ -1,4 +1,4 @@ -name: Intro to NFTs +name: Introduction description: Fundamental Guide to NFTs for Beginners From bfbd639c2b4a7936a52c5339027a8b1c0866f985 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 4 Jan 2023 14:57:21 +0100 Subject: [PATCH 320/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 34a9d40618..6e8afae510 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## January 4th 2023 + +### Added +- [Intro to NFT - Topic - Add new topic](https://github.com/enkidevs/curriculum/pull/3147) + ## December 16th 2022 ### Changed From 32f3d757432c7c3f695cf8eb2dd8ebe31af9d951 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 4 Jan 2023 15:39:17 +0100 Subject: [PATCH 321/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 34a9d40618..59d9d95ae3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## January 4th 2023 + +### Fixed +- [Comp Sci - Dijkstras Algorithm - Remove broken link and add new ones](https://github.com/enkidevs/curriculum/pull/3149) + ## December 16th 2022 ### Changed From 4af59a22c339483ab4dc62bf03963e3fedb7058e Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Wed, 4 Jan 2023 18:31:22 +0100 Subject: [PATCH 322/390] draf 2 --- r/README.md | 15 ++ r/r-core/README.md | 18 ++ .../if-else-in-r.md | 100 +++++++++++ .../if-statements-in-r.md | 79 +++++++++ .../nesting-if-else-statements-in-r.md | 157 ++++++++++++++++++ .../switch-statements-in-r.md | 108 ++++++++++++ .../what-are-conditional-statements-r.md | 29 ++++ .../global-environment-variables-in-r.md | 0 .../local-variables-in-r.md | 0 .../local-vs-global-variables-in-r.md | 9 +- .../function-methods-in-r-ii.md | 0 .../function-methods-in-r.md | 0 .../functions-in-r.md | 0 r/r-core/intro-to-r/1 copy 2.md | 90 ---------- r/r-core/intro-to-r/1 copy 3.md | 90 ---------- r/r-core/intro-to-r/1 copy 4.md | 90 ---------- r/r-core/intro-to-r/1 copy 5.md | 90 ---------- .../creating-and-storing-variables-in-r.md | 58 ------- .../intro-to-r/first-program-hello-world.md | 61 +++++++ r/r-core/intro-to-r/installing-r-locally.md | 63 +++++++ r/r-core/intro-to-r/what-is-r.md | 2 +- r/r-core/intro-to-r/why-learn-r.md | 49 ++---- .../looping-techniques-in-r/apply-function.md | 105 ++++++++++++ .../looping-techniques-in-r.md | 27 +++ .../math-functions-for-vectorization-in-r.md | 108 ++++++++++++ ...stical-functions-for-vectorization-in-r.md | 104 ++++++++++++ .../the-lapply-and-sapply-functions-in-r.md | 82 +++++++++ .../what-is-vectorization.md | 93 +++++++++++ r/r-core/loops-in-r/break-and-next-in-r.md | 101 +++++++++++ r/r-core/loops-in-r/for-loops-in-r.md | 72 ++++++++ r/r-core/loops-in-r/intro-to-loops-in-r.md | 95 +++++++++++ r/r-core/loops-in-r/nesting-loops-in-r.md | 48 ++++++ r/r-core/loops-in-r/repeat-loops-in-r.md | 121 ++++++++++++++ r/r-core/loops-in-r/while-loops-in-r.md | 118 +++++++++++++ r/r-core/programs-in-r/1 copy 5.md | 108 ++++++++++++ r/r-core/programs-in-r/1 copy.md | 84 ++++++++++ r/r-core/programs-in-r/1.md | 108 ++++++++++++ r/r-core/programs-in-r/2.md | 69 ++++++++ r/r-core/programs-in-r/3.md | 28 ++++ r/r-core/programs-in-r/4.md | 68 ++++++++ .../creating-a-program-in-r.md | 0 .../open-and-close-a-file.md | 99 +++++++++++ .../readline-in-r.md | 51 ++++++ .../the-file-function.md | 72 ++++++++ .../the-paste-function-in-r-ii.md | 51 ++++++ .../the-paste-function-in-r.md | 75 +++++++++ .../writelines-in-r.md | 65 ++++++++ ...another-way-to-create-dictionaries-in-r.md | 92 ++++++++++ .../dictionary-methods-in-r.md | 16 +- .../intro-to-dictionaries-r.md | 24 ++- .../unordered-data-types-in-r-ii.md | 86 ++++++++++ .../unoredered-data-types-in-r.md | 96 +++++++++++ .../assignment-operators-r.md | 0 .../basic-data-types-r.md | 0 .../combining-variables-in-r.md | 0 .../creating-a-program-in-r.md | 99 +++++++++++ .../creating-and-storing-variables-in-r.md | 84 ++++++++++ .../printing-and-storing-variables-in-r.md | 9 +- 58 files changed, 3075 insertions(+), 491 deletions(-) create mode 100644 r/README.md create mode 100644 r/r-core/README.md create mode 100644 r/r-core/conditional-statements-in-r/if-else-in-r.md create mode 100644 r/r-core/conditional-statements-in-r/if-statements-in-r.md create mode 100644 r/r-core/conditional-statements-in-r/nesting-if-else-statements-in-r.md create mode 100644 r/r-core/conditional-statements-in-r/switch-statements-in-r.md create mode 100644 r/r-core/conditional-statements-in-r/what-are-conditional-statements-r.md rename r/r-core/{intro-to-r => environment-variables-in-r}/global-environment-variables-in-r.md (100%) rename r/r-core/{intro-to-r => environment-variables-in-r}/local-variables-in-r.md (100%) rename r/r-core/{intro-to-r => environment-variables-in-r}/local-vs-global-variables-in-r.md (73%) rename r/r-core/{intro-to-r => functions-in-r}/function-methods-in-r-ii.md (100%) rename r/r-core/{intro-to-r => functions-in-r}/function-methods-in-r.md (100%) rename r/r-core/{intro-to-r => functions-in-r}/functions-in-r.md (100%) delete mode 100644 r/r-core/intro-to-r/1 copy 2.md delete mode 100644 r/r-core/intro-to-r/1 copy 3.md delete mode 100644 r/r-core/intro-to-r/1 copy 4.md delete mode 100644 r/r-core/intro-to-r/1 copy 5.md delete mode 100644 r/r-core/intro-to-r/creating-and-storing-variables-in-r.md create mode 100644 r/r-core/intro-to-r/first-program-hello-world.md create mode 100644 r/r-core/intro-to-r/installing-r-locally.md create mode 100644 r/r-core/looping-techniques-in-r/apply-function.md create mode 100644 r/r-core/looping-techniques-in-r/looping-techniques-in-r.md create mode 100644 r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md create mode 100644 r/r-core/looping-techniques-in-r/statistical-functions-for-vectorization-in-r.md create mode 100644 r/r-core/looping-techniques-in-r/the-lapply-and-sapply-functions-in-r.md create mode 100644 r/r-core/looping-techniques-in-r/what-is-vectorization.md create mode 100644 r/r-core/loops-in-r/break-and-next-in-r.md create mode 100644 r/r-core/loops-in-r/for-loops-in-r.md create mode 100644 r/r-core/loops-in-r/intro-to-loops-in-r.md create mode 100644 r/r-core/loops-in-r/nesting-loops-in-r.md create mode 100644 r/r-core/loops-in-r/repeat-loops-in-r.md create mode 100644 r/r-core/loops-in-r/while-loops-in-r.md create mode 100644 r/r-core/programs-in-r/1 copy 5.md create mode 100644 r/r-core/programs-in-r/1 copy.md create mode 100644 r/r-core/programs-in-r/1.md create mode 100644 r/r-core/programs-in-r/2.md create mode 100644 r/r-core/programs-in-r/3.md create mode 100644 r/r-core/programs-in-r/4.md rename r/r-core/{intro-to-r => programs-in-r}/creating-a-program-in-r.md (100%) create mode 100644 r/r-core/reading-and-writting-data-to-and-from-files/open-and-close-a-file.md create mode 100644 r/r-core/reading-and-writting-data-to-and-from-files/readline-in-r.md create mode 100644 r/r-core/reading-and-writting-data-to-and-from-files/the-file-function.md create mode 100644 r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r-ii.md create mode 100644 r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r.md create mode 100644 r/r-core/reading-and-writting-data-to-and-from-files/writelines-in-r.md create mode 100644 r/r-core/unordered-data-types-r/another-way-to-create-dictionaries-in-r.md create mode 100644 r/r-core/unordered-data-types-r/unordered-data-types-in-r-ii.md create mode 100644 r/r-core/unordered-data-types-r/unoredered-data-types-in-r.md rename r/r-core/{intro-to-r => variables-and-data-types}/assignment-operators-r.md (100%) rename r/r-core/{intro-to-r => variables-and-data-types}/basic-data-types-r.md (100%) rename r/r-core/{intro-to-r => variables-and-data-types}/combining-variables-in-r.md (100%) create mode 100644 r/r-core/variables-and-data-types/creating-a-program-in-r.md create mode 100644 r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md rename r/r-core/{intro-to-r => variables-and-data-types}/printing-and-storing-variables-in-r.md (91%) diff --git a/r/README.md b/r/README.md new file mode 100644 index 0000000000..66f0acb1d0 --- /dev/null +++ b/r/README.md @@ -0,0 +1,15 @@ +name: R + +description: A programming language for statistical computing and graphics. + +color: D2FFA6 + +icon: https://img.enkipro.com/1422996b1142be465484e6ee505547be.png + +language: r + +availableAspects: + - introduction + - workout + - deep + - obscura diff --git a/r/r-core/README.md b/r/r-core/README.md new file mode 100644 index 0000000000..47d0c66b50 --- /dev/null +++ b/r/r-core/README.md @@ -0,0 +1,18 @@ +name: Core + +description: The fundamentals of Python. No skin shedding needed. + +core: true + +sections: + '0': + - intro-to-r + - variables-and-data-types + - unordered-data-types-r + - conditional-statements-in-r + - functions-in-r + - loops-in-r + - looping-techniques-in-r + - environment-variables-in-r + - reading-and-writting-data-to-and-from-files + - programs-in-r diff --git a/r/r-core/conditional-statements-in-r/if-else-in-r.md b/r/r-core/conditional-statements-in-r/if-else-in-r.md new file mode 100644 index 0000000000..c23cfa28c7 --- /dev/null +++ b/r/r-core/conditional-statements-in-r/if-else-in-r.md @@ -0,0 +1,100 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# ifelse Statements + +--- + +## Content + +Previously we learned about the `if` statement; now let's learn about the `ifelse` statement. + +--- +### ifelse Statement + +`ifelse` statements are similar to `if` statements, but they allow you to specify a value to return based on whether a condition is `TRUE` or `FALSE`. + +Here's the syntax for the `ifelse`: +```r +result <- ifelse(condition, value_if_true, value_if_false) +``` + +Here's how you would use it to check if one number is bigger than another: +```r +x <- 5 +y <- 3 + +result <- ifelse(x > y, "x is larger", "y is larger") +print(result) +# "x is larger" +``` + +Another way to use `if-else` statements is via blocks of code; like most other languages: +```r +x <- 10 + +if (x > 0) { + print("x is positive") +} else { + print("x is not positive") +} + +# "x is positive +``` + + +--- +## Practice + +Add the missing pieces of code for the `ifelse` statement: + +```r +x <- 5 +y <- 3 + +result <- ???(??? > y, "True", "False") +print(result) +# "True" +``` + +- `ifelse` +- `if` +- `else` +- `x` + +--- +## Revision + +Complete the gaps for the code to work. + +```r +x <- 10 + +??? (x > 0) { + print("x is positive") +} ??? { + print("x is not positive") +} + +# "x is positive +``` + +??? + +- `if` +- `else` +- `ifelse` +- `elseif` \ No newline at end of file diff --git a/r/r-core/conditional-statements-in-r/if-statements-in-r.md b/r/r-core/conditional-statements-in-r/if-statements-in-r.md new file mode 100644 index 0000000000..5c7ed61c1b --- /dev/null +++ b/r/r-core/conditional-statements-in-r/if-statements-in-r.md @@ -0,0 +1,79 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# What Are Flow Control Statements? + +--- + +## Content + +The first conditional statement we will learn is `if`. + +--- +### if Statements + +`if` statements are used to execute a code block if a condition is `TRUE`. The basic syntax of an `if` statement is as follows: +```r +if (condition) { + # Code to execute if condition is TRUE +} +``` + +Here's an example where we check if a number is bigger than 3: +```r +x <- 5 +if (x > 3) { + print('it is greater!') +} + +# "it is greater!" +``` + +--- +## Practice + +Add the missing pieces of code for the `if` statement: +```r +x <- 5 +y <- 3 +if (???) { + print('x is greater than y') +} +``` + +- `x > y` +- `x < y` +- `x` +- `y` + +--- +## Revision + +What will the following code output? + +```r +x <- 10 +y <- 20 +if (x > y) { + print('x is greater than y') +} +``` + +??? + +- Nothing as the condition wasn't TRUE +- x is greater than y +- it will error \ No newline at end of file diff --git a/r/r-core/conditional-statements-in-r/nesting-if-else-statements-in-r.md b/r/r-core/conditional-statements-in-r/nesting-if-else-statements-in-r.md new file mode 100644 index 0000000000..0e5d4649c7 --- /dev/null +++ b/r/r-core/conditional-statements-in-r/nesting-if-else-statements-in-r.md @@ -0,0 +1,157 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Nesting ifelse Statements + +--- + +## Content + +Have you ever wanted to execute different actions in your R code based on multiple conditions? One way to do this is by using nested `ifelse` statements. + +Nested `ifelse` statements are `ifelse` statements that are placed inside another `ifelse` statement. This allows you to create code that can execute different actions based on multiple conditions. + +Here is an example of a nested ifelse statement in R: +```r +x <- 10 +y <- 20 + +result <- ifelse(x > y, "x is greater than y", + ifelse(x < y, "x is less than y", "x is equal to y")) +print(result) +``` + +In this example, the ifelse function first checks whether x is greater than y. If it is, the string "x is greater than y" is returned. If it is not, the ifelse function moves on to the next condition, which checks whether x is less than y. If it is, the string "x is less than y" is returned. If it is not, the final condition is evaluated, and the string "x is equal to y" is returned. + + +### When to use nested ifelse statements +--- + +Nested ifelse statements can be useful when you have multiple conditions to check and you want to execute different actions based on the results of those conditions. However, it is important to be careful when using nested ifelse statements, as they can quickly become difficult to read and maintain if you have too many levels of nesting. + +### Conclusion +--- + +In summary, nesting ifelse statements in R allows you to create complex conditions and execute different actions based on those conditions. However, it is important to use them wisely to avoid making your code hard to read and maintain. + + + + + +--- +### What are nested ifelse statements? + + +<!-- +In R, you can nest `ifelse` statements to create more complex conditions. This allows you to create code that can execute different actions based on multiple conditions. + +Here is an example of how to nest `ifelse` statements in R: +```r +x <- 10 +y <- 20 + +result <- ifelse(x > y, "x is greater than y", ifelse(x < y, "x is less than y", "x is equal to y")) +print(result) +``` + + +In this example, the `ifelse` function first checks whether `x` is greater than `y`. If it is, the string `"x is greater than y"` is returned. If it is not, the `ifelse` function moves on to the next condition, which checks whether `x` is less than `y`. If it is, the string `"x is less than y"` is returned. If it is not, the final condition is evaluated, and the string "x is equal to y" is returned. + +Nesting `ifelse` statements can be useful when you have multiple conditions to check and you want to execute different actions based on the results of those conditions. + +However, it is important to be careful when using nested `ifelse` statements, as they can quickly become difficult to read and maintain if you have too many levels of nesting. --> + + +--- +## Practice + +Which of the following is a valid way to nest ifelse statements in R? + +A) + +```r +x <- 10 +y <- 20 + +result <- ifelse(x > y, "x is greater than y") else { + ifelse(x < y, "x is less than y") else { + "x is equal to y" + } +} +print(result) +``` + +B) + +```r +x <- 10 +y <- 20 + +result <- ifelse(x > y) { + "x is greater than y" +} else { + ifelse(x < y) { + "x is less than y" + } else { + "x is equal to y" + } +} +print(result) +``` + +C) +```r +x <- 10 +y <- 20 + +result <- ifelse(x > y) { + "x is greater than y" +} +ifelse(x < y) { + "x is less than y" +} +ifelse(x == y) { + "x is equal to y" +} +print(result) +``` + +D) +```r +x <- 10 +y <- 20 + +result <- ifelse(x > y) { + "x is greater than y" +} else { + ifelse(x < y) { + "x is less than y" + } else { + "x is equal to y" + } +} +print(result) +``` + +??? + +- `B)` +- `A)` +- `C)` +- `D)` + +--- +## Revision diff --git a/r/r-core/conditional-statements-in-r/switch-statements-in-r.md b/r/r-core/conditional-statements-in-r/switch-statements-in-r.md new file mode 100644 index 0000000000..111757c9e8 --- /dev/null +++ b/r/r-core/conditional-statements-in-r/switch-statements-in-r.md @@ -0,0 +1,108 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Switch Statements + +--- + +## Content + +The last, but not least, conditional statement in **R** is the `switch` statement. + +--- +### Switch + +The `switch` statement is a control flow statement in **R** that allows you to choose one of several code blocks to execute based on a value. It is similar to the `if` and `ifelse` statements, but it can be more efficient and easier to read when you have many conditions to check. + +Here is an example of how to use the `switch` statement in **R**: +```r +x <- "A" +switch(x, + "A" = print("You selected A"), + "B" = print("You selected B"), + "C" = print("You selected C")) +``` + +In this example, the code block associated with the value `"A"` is executed, and the message `"You selected A"` is printed to the console. + +--- +## Practice + +What does the `switch` statement do? + +```plain-text +a) Select one of several code blocks to execute based on a value +b) Return a value based on a condition +c) Iterate over a sequence of values +d) None of the above +``` + +??? + +- `a)` +- `b)` +- `c)` +- `d)` + +--- +## Revision + +Which of the following is a valid way to use the switch statement in R? + +A) +```r +x <- "A" +switch(x) { + "A" = print("You selected A") + "B" = print("You selected B") + "C" = print("You selected C") +} +``` + +B) +```r +x <- "A" +switch(x) + case "A": print("You selected A") + case "B": print("You selected B") + case "C": print("You selected C") +``` + +C) +```r +x <- "A" +switch(x) { + "A": print("You selected A") + "B": print("You selected B") + "C": print("You selected C") +} +``` + +D) +```r +x <- "A" +switch(x) + print("You selected A") if x == "A" + print("You selected B") if x == "B" + print("You selected C") if x == "C" +``` + +??? + +- `A)` +- `B)` +- `C)` +- `D)` \ No newline at end of file diff --git a/r/r-core/conditional-statements-in-r/what-are-conditional-statements-r.md b/r/r-core/conditional-statements-in-r/what-are-conditional-statements-r.md new file mode 100644 index 0000000000..7430e77d85 --- /dev/null +++ b/r/r-core/conditional-statements-in-r/what-are-conditional-statements-r.md @@ -0,0 +1,29 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# What Are Flow Control Statements? + +--- + +## Content + +Flow Control statements are an important part of any programming language, and **R** is no exception. Flow Control, also called **Conditional** statements allow you to execute different code blocks based on whether a condition is `TRUE` or `FALSE`. + +There are three types of conditional statements in **R**: `if`, `if-else`, and `switch` statements. + +These conditional statements are an important tool for controlling the flow of your program. They allow you to specify different code paths to execute based on different conditions, and make it possible to write programs that can adapt to different inputs and situations. + +For example, you could use a conditional statement to check whether a user has entered a valid password before allowing them to log in to your program, or to check whether a file exists before trying to read or write to it. \ No newline at end of file diff --git a/r/r-core/intro-to-r/global-environment-variables-in-r.md b/r/r-core/environment-variables-in-r/global-environment-variables-in-r.md similarity index 100% rename from r/r-core/intro-to-r/global-environment-variables-in-r.md rename to r/r-core/environment-variables-in-r/global-environment-variables-in-r.md diff --git a/r/r-core/intro-to-r/local-variables-in-r.md b/r/r-core/environment-variables-in-r/local-variables-in-r.md similarity index 100% rename from r/r-core/intro-to-r/local-variables-in-r.md rename to r/r-core/environment-variables-in-r/local-variables-in-r.md diff --git a/r/r-core/intro-to-r/local-vs-global-variables-in-r.md b/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md similarity index 73% rename from r/r-core/intro-to-r/local-vs-global-variables-in-r.md rename to r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md index 75c3b4daa9..649b49951e 100644 --- a/r/r-core/intro-to-r/local-vs-global-variables-in-r.md +++ b/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md @@ -13,15 +13,12 @@ practiceQuestion: --- -# Basic Data Types in R +# Local vs Global Variables --- ## Content -In **R**, a global environment is a place where all the objects you create are stored. When you start an **R** session, a global environment is created automatically. - -On the other hand, a local environment is a place where the objects you create within a function are stored. When you define a function, a local environment is created automatically. Global variables can be accessed from anywhere in your **R** session, while local variables can only be accessed within the function where they are defined. @@ -67,8 +64,8 @@ Which of the following is **NOT** true about global and local variables in **R** ??? -- The <<- operator is generally recommended for creating global variables in **R**. -- The <<- operator can be used to create a global variable within a function. +- The `<<-` operator is generally recommended for creating global variables in **R**. +- The `<<-` operator can be used to create a global variable within a function. - Local variables can only be accessed within the function where they are defined. - Global variables can be accessed from anywhere in your **R** session. diff --git a/r/r-core/intro-to-r/function-methods-in-r-ii.md b/r/r-core/functions-in-r/function-methods-in-r-ii.md similarity index 100% rename from r/r-core/intro-to-r/function-methods-in-r-ii.md rename to r/r-core/functions-in-r/function-methods-in-r-ii.md diff --git a/r/r-core/intro-to-r/function-methods-in-r.md b/r/r-core/functions-in-r/function-methods-in-r.md similarity index 100% rename from r/r-core/intro-to-r/function-methods-in-r.md rename to r/r-core/functions-in-r/function-methods-in-r.md diff --git a/r/r-core/intro-to-r/functions-in-r.md b/r/r-core/functions-in-r/functions-in-r.md similarity index 100% rename from r/r-core/intro-to-r/functions-in-r.md rename to r/r-core/functions-in-r/functions-in-r.md diff --git a/r/r-core/intro-to-r/1 copy 2.md b/r/r-core/intro-to-r/1 copy 2.md deleted file mode 100644 index ca0f62ce75..0000000000 --- a/r/r-core/intro-to-r/1 copy 2.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -author: Stefan-Stojanovic - -tags: - - introduction - - discussion -type: normal -category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - context: standalone - ---- - -# Basic Data Types in R - ---- - -## Content - -**R** has several basic data types, including: - -`character`: characters, such as "hello" or "goodbye" -```r -greeting <- "hello" -print(greeting) -# "hello" -``` - -`numeric`: numbers, either integers or decimals - -```r -numbers <- c(1, 2, 3, 4, 5) -print(numbers) -# 1 2 3 4 5 - -decimals <- c(1.1, 2.2, 3.3) -print(decimals) -# 1.1 2.2 3.3 -``` - -`logical`: boolean values, either `TRUE` or `FALSE`: - -```r -booleans <- c(TRUE, FALSE, TRUE, FALSE) -print(booleans) -# TRUE FALSE TRUE FALSE -``` - -`factor`: categorical variables -```r -cities <- factor(c("New York", "Chicago", "San Francisco", "New York")) -print(cities) -# New York Chicago San Francisco New York -# Levels: Chicago New York San Francisco -``` - -`NULL`: represents an empty object -```r -empty <- NULL -print(empty) -# NULL -``` - ---- -## Practice - -Which of the following is a basic data type in R? - -??? - -- `numeric` -- `integer` -- `matrix` -- `function` -- `data frame` - ---- -## Revision - -What is the basic data type for a vector of categorical variables in R? - -??? - -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file diff --git a/r/r-core/intro-to-r/1 copy 3.md b/r/r-core/intro-to-r/1 copy 3.md deleted file mode 100644 index ca0f62ce75..0000000000 --- a/r/r-core/intro-to-r/1 copy 3.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -author: Stefan-Stojanovic - -tags: - - introduction - - discussion -type: normal -category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - context: standalone - ---- - -# Basic Data Types in R - ---- - -## Content - -**R** has several basic data types, including: - -`character`: characters, such as "hello" or "goodbye" -```r -greeting <- "hello" -print(greeting) -# "hello" -``` - -`numeric`: numbers, either integers or decimals - -```r -numbers <- c(1, 2, 3, 4, 5) -print(numbers) -# 1 2 3 4 5 - -decimals <- c(1.1, 2.2, 3.3) -print(decimals) -# 1.1 2.2 3.3 -``` - -`logical`: boolean values, either `TRUE` or `FALSE`: - -```r -booleans <- c(TRUE, FALSE, TRUE, FALSE) -print(booleans) -# TRUE FALSE TRUE FALSE -``` - -`factor`: categorical variables -```r -cities <- factor(c("New York", "Chicago", "San Francisco", "New York")) -print(cities) -# New York Chicago San Francisco New York -# Levels: Chicago New York San Francisco -``` - -`NULL`: represents an empty object -```r -empty <- NULL -print(empty) -# NULL -``` - ---- -## Practice - -Which of the following is a basic data type in R? - -??? - -- `numeric` -- `integer` -- `matrix` -- `function` -- `data frame` - ---- -## Revision - -What is the basic data type for a vector of categorical variables in R? - -??? - -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file diff --git a/r/r-core/intro-to-r/1 copy 4.md b/r/r-core/intro-to-r/1 copy 4.md deleted file mode 100644 index ca0f62ce75..0000000000 --- a/r/r-core/intro-to-r/1 copy 4.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -author: Stefan-Stojanovic - -tags: - - introduction - - discussion -type: normal -category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - context: standalone - ---- - -# Basic Data Types in R - ---- - -## Content - -**R** has several basic data types, including: - -`character`: characters, such as "hello" or "goodbye" -```r -greeting <- "hello" -print(greeting) -# "hello" -``` - -`numeric`: numbers, either integers or decimals - -```r -numbers <- c(1, 2, 3, 4, 5) -print(numbers) -# 1 2 3 4 5 - -decimals <- c(1.1, 2.2, 3.3) -print(decimals) -# 1.1 2.2 3.3 -``` - -`logical`: boolean values, either `TRUE` or `FALSE`: - -```r -booleans <- c(TRUE, FALSE, TRUE, FALSE) -print(booleans) -# TRUE FALSE TRUE FALSE -``` - -`factor`: categorical variables -```r -cities <- factor(c("New York", "Chicago", "San Francisco", "New York")) -print(cities) -# New York Chicago San Francisco New York -# Levels: Chicago New York San Francisco -``` - -`NULL`: represents an empty object -```r -empty <- NULL -print(empty) -# NULL -``` - ---- -## Practice - -Which of the following is a basic data type in R? - -??? - -- `numeric` -- `integer` -- `matrix` -- `function` -- `data frame` - ---- -## Revision - -What is the basic data type for a vector of categorical variables in R? - -??? - -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file diff --git a/r/r-core/intro-to-r/1 copy 5.md b/r/r-core/intro-to-r/1 copy 5.md deleted file mode 100644 index ca0f62ce75..0000000000 --- a/r/r-core/intro-to-r/1 copy 5.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -author: Stefan-Stojanovic - -tags: - - introduction - - discussion -type: normal -category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - context: standalone - ---- - -# Basic Data Types in R - ---- - -## Content - -**R** has several basic data types, including: - -`character`: characters, such as "hello" or "goodbye" -```r -greeting <- "hello" -print(greeting) -# "hello" -``` - -`numeric`: numbers, either integers or decimals - -```r -numbers <- c(1, 2, 3, 4, 5) -print(numbers) -# 1 2 3 4 5 - -decimals <- c(1.1, 2.2, 3.3) -print(decimals) -# 1.1 2.2 3.3 -``` - -`logical`: boolean values, either `TRUE` or `FALSE`: - -```r -booleans <- c(TRUE, FALSE, TRUE, FALSE) -print(booleans) -# TRUE FALSE TRUE FALSE -``` - -`factor`: categorical variables -```r -cities <- factor(c("New York", "Chicago", "San Francisco", "New York")) -print(cities) -# New York Chicago San Francisco New York -# Levels: Chicago New York San Francisco -``` - -`NULL`: represents an empty object -```r -empty <- NULL -print(empty) -# NULL -``` - ---- -## Practice - -Which of the following is a basic data type in R? - -??? - -- `numeric` -- `integer` -- `matrix` -- `function` -- `data frame` - ---- -## Revision - -What is the basic data type for a vector of categorical variables in R? - -??? - -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file diff --git a/r/r-core/intro-to-r/creating-and-storing-variables-in-r.md b/r/r-core/intro-to-r/creating-and-storing-variables-in-r.md deleted file mode 100644 index fcb21ad4f9..0000000000 --- a/r/r-core/intro-to-r/creating-and-storing-variables-in-r.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -author: Stefan-Stojanovic - -tags: - - introduction - - discussion -type: normal -category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - context: standalone - ---- - -# Creating and Storing Variables in R - ---- - -## Content - -In **R**, you can create variables using the `<-` operator. For example: -```r -x <- 5 -y <- 10 -``` - -You can also use the `=` operator, but it is generally recommended to use `<-` as it is easier to read and less prone to errors. - -To access the value of a variable, you can type the name of the variable inside a `print()`: -```r -print(x) -# 5 - -print(y) -# 10 -``` - -You can also use the `assign()` function to create a variable and store it in the global environment: -```r -assign("z", c(x, y)) -print(z) -# 5 10 -``` - - - ---- -## Practice - -Which of the following is **NOT** a way to create a variable in **R**? - -??? - --``a <=` --`x = 5` --`y <- 10` --`z = c(x, y)` \ No newline at end of file diff --git a/r/r-core/intro-to-r/first-program-hello-world.md b/r/r-core/intro-to-r/first-program-hello-world.md new file mode 100644 index 0000000000..0e9f09977f --- /dev/null +++ b/r/r-core/intro-to-r/first-program-hello-world.md @@ -0,0 +1,61 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Let’s Create Our First Program + +--- + +## Content + +"Hello, World!" is a simple program that prints the text "Hello, World!" to the screen. It is often used as a starting point when learning a new programming language. + +In **R**, you can print text to the screen using the `print()` function. Here is an example of a "Hello, World!" program in **R**: +```r +print("Hello, World!") +``` + +To run the program, you can write the code into the **R** console, or you can save it to a script file with the `.R` extension and run it using the `source()` function. +```r +# Save the code to a file called "hello.R" + +# In the R console, type: +source("hello.R") +``` + +You should see the text "Hello, World!" printed to the screen. + +--- +## Practice + +Which function is used to print text to the screen in R? + +??? + +- `print()` +- `printout()` +- `echo()` +- `display()` + +--- +## Revision + +Which function is used to run a script file in R? + +??? + +- `source()` +- `run()` +- `execute()` +- `eval()` \ No newline at end of file diff --git a/r/r-core/intro-to-r/installing-r-locally.md b/r/r-core/intro-to-r/installing-r-locally.md new file mode 100644 index 0000000000..0e32065a76 --- /dev/null +++ b/r/r-core/intro-to-r/installing-r-locally.md @@ -0,0 +1,63 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Installing R Locally + + +--- + +## Content + +**R** is a free, open-source programming language for statistical computing and graphics. You can install **R** locally on your computer to use it for data analysis, visualization, and more. + +To install **R**, you can follow these steps: + +- Download the latest version of **R** from the [official website](https://cran.r-project.org/). +- Run the installation file and follow the prompts to install **R**. +- Once the installation is complete, you can start using **R** by opening the **R** console or writing **R** scripts. + +You can also install **R** on a server[1] or in the cloud, such as on [Amazon Web Services](https://aws.amazon.com/blogs/opensource/getting-started-with-r-on-amazon-web-services/) or [Google Cloud Platform](https://cloud.google.com/architecture/data-science-with-r-on-gcp-eda#ai_platform_notebooks). + +--- +## Practice + +Which of the following is a basic data type in R? + +??? + +- `numeric` +- `integer` +- `matrix` +- `function` +- `data frame` + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` + +--- +## Footnotes + +[1: Server] +A server is a computer that provides resources, data, or services to other computers or devices on a network. \ No newline at end of file diff --git a/r/r-core/intro-to-r/what-is-r.md b/r/r-core/intro-to-r/what-is-r.md index d8ddbabf93..a31677f9ef 100644 --- a/r/r-core/intro-to-r/what-is-r.md +++ b/r/r-core/intro-to-r/what-is-r.md @@ -21,7 +21,7 @@ practiceQuestion: **R** is a popular programming language and software environment for statistical computing[1] and graphics[2]. It is widely used among statisticians, data scientists, and researchers in academia and industry. -**R** is a high-level language, which means it has a relatively simple syntax that is easy to read and write. Here's an example of how you might plot a line graph in **R**: +**R** is a high-level language, which means it has a relatively simple syntax. Here's an example of how you might plot a line graph in **R**: ```r x <- c(1, 2, 3, 4, 5) diff --git a/r/r-core/intro-to-r/why-learn-r.md b/r/r-core/intro-to-r/why-learn-r.md index 6d8b96d78d..610d7da564 100644 --- a/r/r-core/intro-to-r/why-learn-r.md +++ b/r/r-core/intro-to-r/why-learn-r.md @@ -22,49 +22,26 @@ practiceQuestion: ## Content +**R** is a popular programming language for data analysis and statistical computing. It is widely used in various fields[1] such as finance, biology, and psychology. -**R** is a powerful and popular programming language that is widely used in data science, statistics, and research. Here are a few reasons why it's a good idea to learn **R**: +There are several reasons why learning **R** can be beneficial: -It's widely used in academia and industry: **R** is a popular choice for statistical analysis and data visualization in many fields, including economics, biology, psychology, and finance. This means that learning **R** can make you a valuable asset to employers and can open up career opportunities in a variety of industries. - -It has a large and active community: **R** has a large and active community of users and developers, which means that there is a wealth of resources and support available for learning and using **R**. There are numerous forums, blogs, and online communities where you can ask questions, get help, and share your knowledge with others. - -It has a wide range of packages and tools: **R** has a vast collection of packages and tools that extend its functionality and make it suitable for a wide range of tasks. For example, there are packages for machine learning, data manipulation, data visualization, and more. - -It's a good foundation for learning other languages: Many other programming languages, such as Python and Java, share some similarities with **R**. Learning **R** can therefore be a good foundation for learning these other languages, making it easier to pick up new skills in the future. - -> 💬 What motivates you to learn **R**? -> -> Leave a comment or view some of the other comments for inspiration before moving on. - ---- - -## Practice - -Let's try some **R** code! Can you write a function that takes a vector of numbers and returns the sum of the squares of those numbers? - -```r -sum_of_squares <- function(x) { - ??? -} - -``` - -- sum(x^2) -- x^2 %>% sum -- reduce(x, +, x^2) -- x %>% sapply(function(n) n^2) %>% sum +- **R** is open-source and free to use, making it accessible to anyone who wants to learn it. +- **R** has a large community of users who contribute to its development and share their knowledge and resources online. +- **R** has a wide range of packages and libraries available for various data analysis tasks[2], such as data visualization, machine learning, and statistical modeling[3]. +- **R** is widely used in academia and industry, making it a valuable skill to have on your resume. +Overall, learning **R** can open up new opportunities for data analysis and help you make informed decisions based on data. Whether you are a beginner or an experienced programmer, **R** is a powerful tool to add to your toolkit. --- ## Footnotes -[1: Data Science] -**R** is widely used in data science, which is the field that deals with the extraction of insights and knowledge from data. This includes tasks such as data cleaning, analysis, and visualization. +[1: Research] +**R** is commonly used in research, particularly in fields such as biology, psychology, and economics. It is often used to analyze and visualize data, as well as to perform statistical analyses and simulations. -[2: Statistics] -**R** is also used in statistical analysis, which involves the use of statistical methods to analyze data and make inferences about it. This includes tasks such as hypothesis testing, regression analysis, and statistical modeling. +[2: Data Science] +**R** is widely used in data science, which is the field that deals with the extraction of insights and knowledge from data. This includes tasks such as data cleaning, analysis, and visualization. -[3: Research] -**R** is commonly used in research, particularly in fields such as biology, psychology, and economics. It is often used to analyze and visualize data, as well as to perform statistical analyses and simulations. \ No newline at end of file +[3: Statistics] +**R** is also used in statistical analysis, which involves the use of statistical methods to analyze data and make inferences about it. This includes tasks such as hypothesis testing, regression analysis, and statistical modeling. \ No newline at end of file diff --git a/r/r-core/looping-techniques-in-r/apply-function.md b/r/r-core/looping-techniques-in-r/apply-function.md new file mode 100644 index 0000000000..6d3370b3b1 --- /dev/null +++ b/r/r-core/looping-techniques-in-r/apply-function.md @@ -0,0 +1,105 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# apply Function + +--- + +## Content + +The `apply` function is a powerful and flexible function in R that allows you to apply a function to a matrix or array, and return a vector, matrix, or array with the results. This can be faster than looping through the elements one at a time, because it allows the computer to perform the operations in parallel. + +Here is the basic syntax of the `apply` function: +```r +apply(X, MARGIN, FUN, ...) +``` + +- `X` is the matrix or array that you want to apply the function to. +- `MARGIN` is an integer that specifies which dimension of the matrix or array you want to apply the function to. If `MARGIN` is `1`, the function is applied to each row of the matrix or array. If `MARGIN` is `2`, the function is applied to each column of the matrix or array. If `MARGIN` is `c(1, 2)`, the function is applied to all elements of the matrix or array. +- `FUN` is the function that you want to apply to the matrix or array. +- `...` are any additional arguments that you want to pass to the function. + +Here is an example of how to use the `apply` function to apply a function to each row of a matrix: +```r +matrix <- matrix(1:9, 3, 3) +print(matrix) +# [,1] [,2] [,3] +# [1,] 1 4 7 +# [2,] 2 5 8 +# [3,] 3 6 9 + + +apply(matrix, 1, sum) +# 12 15 18 +``` + +Here is an example of how to use the `apply` function to apply a function to each column of a matrix: +```r +matrix <- matrix(1:9, 3, 3) +print(matrix) +# [,1] [,2] [,3] +# [1,] 1 4 7 +# [2,] 2 5 8 +# [3,] 3 6 9 + +apply(matrix, 2, sum) +# 6 15 24 +``` + +Here is an example of how to use the `apply` function to apply a function to all elements of a matrix: +```r +matrix <- matrix(1:9, 3, 3) +print(matrix) +# [,1] [,2] [,3] +# [1,] 1 4 7 +# [2,] 2 5 8 +# [3,] 3 6 9 + + +apply(matrix, c(1, 2), sum) +# 45 +``` + + +**Note**: you should be careful when using the `apply` function, because it can result in code that is less readable and more difficult to debug. + +You should consider using the `apply` function only when it is significantly faster than alternative approaches, such as looping through the elements one at a time. + + +--- +## Practice + +Which of the following is a basic data type in R? + +??? + +- `numeric` +- `integer` +- `matrix` +- `function` +- `data frame` + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/looping-techniques-in-r/looping-techniques-in-r.md b/r/r-core/looping-techniques-in-r/looping-techniques-in-r.md new file mode 100644 index 0000000000..c09702cbfc --- /dev/null +++ b/r/r-core/looping-techniques-in-r/looping-techniques-in-r.md @@ -0,0 +1,27 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Looping Techniques in R + +--- + +## Content + +There are several techniques you can use to loop through data in R. These techniques allow you to process data more efficiently, and make your code more concise and readable. + +Some of these are: +- Vectorization +- the apply Functions +- the lapply and sapply Functions \ No newline at end of file diff --git a/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md b/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md new file mode 100644 index 0000000000..700d98b688 --- /dev/null +++ b/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md @@ -0,0 +1,108 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Mathematical Functions that Support Vectorization + +--- + +## Content + +R has many built-in mathematical functions. Here are some that support vectorization in R: +```r +vector <- 10 +abs(vector) +sqrt(vector) +log(vector) +exp(vector) +``` + +`abs`: Returns the absolute value of a number or array. +```r +abs(-1) +# 1 +abs(-1:10) +# 1 2 3 4 5 6 7 8 9 10 +``` + +`sqrt`: Returns the square root of a number or array. +```r +sqrt(4) +# 2 +sqrt(1:5) +# 1 1.4142136 1.7320508 2 2.236068 +``` + +`log`: Returns the natural logarithm (base e) of a number or array. +```r +log(2.71828) +# 1 +log(1:5) +# 0 0.69314718 1.0986123 1.3862944 1.6094379 +``` + +`exp`: Returns the exponent (e^x) of a number or array. + + +```r +exp(1) +# 2.71828 +exp(1:9) +# 2.7182818 7.389056 20.085537 54.59815 148.4132 403.4287 1096.6332 2980.958 8103.084 +``` + +You can use these mathematical functions to perform mathematical operations on arrays or vectors, rather than looping through the elements one at a time. This can be faster, especially when working with large data sets, because it allows the computer to perform the operations in parallel, rather than sequentially. + +However, you should be careful when using vectorization, because it can result in code that is less readable and more difficult to debug. + +--- +## Practice + +Complete the following code snippet to double the elements of the `vector` variable: + +```r +vector <- 1:10 +vector <- ??? ??? 2 +``` + +- `vector` +- `*` +- `matrix` +- `/` + +--- +## Revision + +What is the output of the following code? + +```r +vector <- 1:10 +vector <- vector * 2 + 1 +``` + +??? + +- `3 5 7 9 11 13 15 17 19 21` +- `1 3 5 7 9 11 13 15 17 19` +- `2 4 6 8 10 12 14 16 18 20` +- `1 2 3 4 5 6 7 8 9 10` + +--- +## Footnotes + +[1: Parallel Processing] +Parallel processing is the ability of a computer to perform multiple operations at the same time, using multiple processors or cores. Vectorization allows you to take advantage of parallel processing, because it allows the computer to perform the operations in parallel, rather than sequentially. This can significantly reduce the processing time, especially when working with large data sets. + +[2: Sequential Processing] +Sequential processing is the ability of a computer to perform one operation at a time, in a specified order. Looping through elements one at a time is an example of sequential processing, because the computer processes each element one at a time, in the order that they appear. Vectorization allows you to perform operations on arrays or vectors, rather than looping through the elements one at a time, which can be faster because it allows the computer to perform the operations in parallel. \ No newline at end of file diff --git a/r/r-core/looping-techniques-in-r/statistical-functions-for-vectorization-in-r.md b/r/r-core/looping-techniques-in-r/statistical-functions-for-vectorization-in-r.md new file mode 100644 index 0000000000..d2154a29cf --- /dev/null +++ b/r/r-core/looping-techniques-in-r/statistical-functions-for-vectorization-in-r.md @@ -0,0 +1,104 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Statistical Functions + +--- + +## Content + +R has many built-in statistical functions that support vectorization. + +Here are some common ones: +```r +vector <- 1:10 +max(vector) +min(vector) +mean(vector) +median(vector) +sd(vector) +``` + +`max`: Returns the maximum value of an array or vector. +```r +max(1:10) +# 10 +max(c(1, 3, 5, 7, 9)) +# 9 +``` + +`min`: Returns the minimum value of an array or vector. +```r +min(1:10) +# 1 +min(c(1, 3, 5, 7, 9)) +# 1 +``` + +`mean`: Returns the mean (average) value of an array or vector. +```r +mean(1:10) +# 5.5 +mean(c(1, 3, 5, 7, 9)) +# 5 +``` + +`median`: Returns the median value of an array or vector. +```r +median(1:10) +# 5.5 +median(c(1, 3, 5, 7, 9)) +# 5 +``` + +`sd`: Returns the standard deviation of an array or vector. +```r +sd(1:10) +# 3.02765 +sd(c(1, 3, 5, 7, 9)) +# 3.162278 +``` + +--- +## Practice + +Complete the following code snippet to calculate the standard deviation of the scores variable: +```r +scores <- c(100, 90, 80, 70, 60) +??? +``` + +- `sd(scores)` +- `mean(scores)` +- `median(scores)` +- `max(scores)` + + +--- +## Revision + +What is the output of the following code? + +```r +scores <- c(100, 90, 80, 70, 60) +mean(scores) +``` + +??? + +- `80` +- `85` +- `90` +- `95` diff --git a/r/r-core/looping-techniques-in-r/the-lapply-and-sapply-functions-in-r.md b/r/r-core/looping-techniques-in-r/the-lapply-and-sapply-functions-in-r.md new file mode 100644 index 0000000000..6751f8b549 --- /dev/null +++ b/r/r-core/looping-techniques-in-r/the-lapply-and-sapply-functions-in-r.md @@ -0,0 +1,82 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# The lapply and sapply Functions + +--- + +## Content + +The `lapply` and `sapply` functions are two closely related functions in R that allow you to apply a function to a list or vector, and return a list or vector with the results. These functions are faster than looping through the elements one at a time, because they allow the computer to perform the operations in parallel, rather than sequentially. + +Here are the basic syntaxes of the `lapply` and `sapply` functions: +```r +lapply(X, FUN, ...) +sapply(X, FUN, ...) +``` + +- `X` is the list or vector that you want to apply the function to. +- `FUN` is the function that you want to apply to the list or vector. +- `...` are any additional arguments that you want to pass to the function. + + +Here is an example of how to use the `lapply` function to apply a function to a list: +```r +my_list <- list(1:3, 4:6, 7:9) +lapply(my_list, sum) +# 6 15 24 +``` + +The `lapply` function returns a list with the results of the function applied to each element of the input list. + +The `sapply` function is similar to the `lapply` function, but it returns a vector with the results, rather than a list. This can be useful when you want to simplify the output of the function, or when you want to store the results in a variable for further processing. + +Here is and example of the `sapply` function: +```r +vector <- 1:9 +sapply(vector, sqrt) +# 1 1.4142136 1.7320508 2 2.236068 2.4494898 2.6457513 2.8284271 3 +``` + +--- +## Practice + +Complete the following code snippet to apply the mean function to each element of the scores list: +```r +scores <- list(c(100, 90, 80), c(70, 60, 50)) +lapply(??? , mean) +``` + +- `scores` +- `c(100, 90, 80)` +- `c(70, 60, 50)` +- `c(100, 90, 80, 70, 60, 50)` + +--- +## Revision + +What is the output of the following code? + +```r +scores <- list(c(100, 90, 80), c(70, 60, 50)) +sapply(scores, mean) +``` + +??? + +- `[90 60]` +- `[6, 15, 24]` +- `[85, 55]` +- `[1, 4, 7]` \ No newline at end of file diff --git a/r/r-core/looping-techniques-in-r/what-is-vectorization.md b/r/r-core/looping-techniques-in-r/what-is-vectorization.md new file mode 100644 index 0000000000..92e5caa7cd --- /dev/null +++ b/r/r-core/looping-techniques-in-r/what-is-vectorization.md @@ -0,0 +1,93 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Vectorization in R + +--- + +## Content + +Vectorization is a technique for performing operations on **arrays** or **vectors**, rather than looping through the elements one at a time. Vectorization can be faster than looping, because it allows the computer to perform the operations in parallel[1], rather than sequentially[2]. + +Here is an example of a loop that adds 1 to each element of a vector: +```r +vector <- 1:10 +for (i in 1:length(vector)) { + vector[i] <- vector[i] + 1 +} +``` + +You can achieve the same result using vectorization: +```r +vector <- 1:10 +vector <- vector + 1 +``` + +Vectorization can be especially useful when working with large data sets, because it can significantly reduce the processing time. + +`+`, `-`, `*`, `/`, `^`: These arithmetic operators support vectorization, allowing you to perform arithmetic operations on arrays or vectors. +```r +vector <- 1:10 +vector + 1 +vector - 1 +vector * 2 +vector / 2 +vector ^ 2 +``` + + +You can use vectorization to improve the performance of your R code, especially when working with large data sets. However, you should be careful when using vectorization, because it can result in code that is less readable and more difficult to debug. + + +--- +## Practice + +Complete the following code snippet to double the elements of the `vector` variable: + +```r +vector <- 1:10 +vector <- ??? ??? 2 +``` + +- `vector` +- `*` +- `matrix` +- `/` + +--- +## Revision + +What is the output of the following code? + +```r +vector <- 1:10 +vector <- vector * 2 + 1 +``` + +??? + +- `3 5 7 9 11 13 15 17 19 21` +- `1 3 5 7 9 11 13 15 17 19` +- `2 4 6 8 10 12 14 16 18 20` +- `1 2 3 4 5 6 7 8 9 10` + +--- +## Footnotes + +[1: Parallel Processing] +Parallel processing is the ability of a computer to perform multiple operations at the same time, using multiple processors or cores. Vectorization allows you to take advantage of parallel processing, because it allows the computer to perform the operations in parallel, rather than sequentially. This can significantly reduce the processing time, especially when working with large data sets. + +[2: Sequential Processing] +Sequential processing is the ability of a computer to perform one operation at a time, in a specified order. Looping through elements one at a time is an example of sequential processing, because the computer processes each element one at a time, in the order that they appear. Vectorization allows you to perform operations on arrays or vectors, rather than looping through the elements one at a time, which can be faster because it allows the computer to perform the operations in parallel. \ No newline at end of file diff --git a/r/r-core/loops-in-r/break-and-next-in-r.md b/r/r-core/loops-in-r/break-and-next-in-r.md new file mode 100644 index 0000000000..d9f9bcdcd7 --- /dev/null +++ b/r/r-core/loops-in-r/break-and-next-in-r.md @@ -0,0 +1,101 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# For loops in R + +--- + +## Content + +You can use the `break` and `next` statements to control the flow of the `for` loop. The `break` statement breaks out of the loop and terminates it, while the `next` statement skips the rest of the current iteration and continues with the next one. + +Here is an example of a `for` loop that uses the `break` statement to exit the loop when the value of `i` is `5`: + +```r +# Print the numbers from 1 to 10, but skip 5 +for (i in 1:10) { + if (i == 5) { + break + } + print(i) +} +``` + +Here is an example of a `for` loop that uses the `next` statement to skip the iteration when the value of `i` is `even`: +```r +for (i in 1:10) { + if (i %% 2 == 0) { + next + } + print(i) +} +``` + +You can use the `break` and ``next`` statements together to create more complex loops. + +For example, you can use a `break` statement to exit the loop when a certain condition is met, and use a ``next`` statement to skip certain iterations. +```r +for (i in 1:10) { + if (i == 5) { + break + } + if (i %% 2 == 0) { + next + } + print(i) +} +``` + + +--- +## Practice + +What is the output ofthe following code? + +```r +for (i in 1:10) { + if (i == 5) { + next + } + print(i) +} +``` + +- `1 2 3 4 6 7 8 9 10` +- `1 2 3 4 5 6 7 8 9 10` +- `1 2 3 4` +- `1 2 3 4 5` + +--- +## Revision + +Complete the following code snippet to print the elements of the `fruits` vector: + +```r +fruits <- c("apple", "banana", "cherry") +for (fruit in ???) { + print(???) +} +``` + + +- `fruits` +- `fruit` +- `banana` +- `vector` \ No newline at end of file diff --git a/r/r-core/loops-in-r/for-loops-in-r.md b/r/r-core/loops-in-r/for-loops-in-r.md new file mode 100644 index 0000000000..765b2e8fb4 --- /dev/null +++ b/r/r-core/loops-in-r/for-loops-in-r.md @@ -0,0 +1,72 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# For loops in R + +--- + +## Content + +A `for` loop in **R** allows you to iterate over a sequence of values or elements. You can use a `for` loop to execute a block of code for each value or element in the sequence. + +Here is the basic syntax of a for loop in **R**: +```r +for (variable in sequence) { + # code to be executed +} +``` + +The `variable` is a placeholder for the current value or element in the sequence. The sequence can be any object that can be iterated over, such as a vector, list, or data frame. + +Here is an example of a for loop that prints the numbers from 1 to 10: +```r +for (i in 1:10) { + print(i) +} +``` + +You can also use a for loop to iterate over the elements of a character vector: +```r +for (word in c("apple", "banana", "cherry")) { + print(word) +} +``` + +--- +## Practice + +Finish the code to create a `for` loop that itterates over a `vegetables` sequence using `veg` as a variable: + +```r +for (??? in ???) { + # code to be executed +} +``` + +- `veg` +- `vegetables` + +--- +## Revision + +What is the basic data type for a vector of categorical variables in **R**? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/loops-in-r/intro-to-loops-in-r.md b/r/r-core/loops-in-r/intro-to-loops-in-r.md new file mode 100644 index 0000000000..5b081efe4e --- /dev/null +++ b/r/r-core/loops-in-r/intro-to-loops-in-r.md @@ -0,0 +1,95 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +Loops are a fundamental programming concept that allow you to repeat a block of code multiple times. + +In **R**, you can use loops to perform tasks such as iterating over the elements of an array, data frame, or list, or to execute a block of code until a certain condition is met. + +There are three types of loops in **R**: `for` loops, `while` loops, and `repeat` loops. + +### For + +A `for` loop allows you to iterate over a sequence of values or elements. You can use a for loop to execute a block of code for each value or element in the sequence. For example: +```r +# Print the numbers from 1 to 10 +for (i in 1:10) { + print(i) +} + +# Print the elements of a character vector +for (word in c("apple", "banana", "cherry")) { + print(word) +} +``` + +A while loop allows you to execute a block of code as long as a certain condition is TRUE. You can use a while loop to perform an action until a certain condition is met, or to perform an action indefinitely. For example: +```r +# Print the numbers from 1 to 10 +i <- 1 +while (i <= 10) { + print(i) + i <- i + 1 +} + +# Print "Hello, World!" indefinitely +while (TRUE) { + print("Hello, World!") +} +``` +A repeat loop is similar to a while loop, but the condition is checked at the end of the loop instead of at the beginning. You can use a repeat loop to perform an action indefinitely or until a certain condition is met. For example: +```r +# Print the numbers from 1 to 10 +i <- 1 +repeat { + print(i) + i <- i + 1 + if (i > 10) { + break + } +``` + + + +--- +## Practice + +Which of the following is a basic data type in **R**? + +??? + +- `numeric` +- `integer` +- `matrix` +- `function` +- `data frame` + +--- +## Revision + +What is the basic data type for a vector of categorical variables in **R**? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/loops-in-r/nesting-loops-in-r.md b/r/r-core/loops-in-r/nesting-loops-in-r.md new file mode 100644 index 0000000000..eddfd84763 --- /dev/null +++ b/r/r-core/loops-in-r/nesting-loops-in-r.md @@ -0,0 +1,48 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Nesting ifelse Statements + +--- + +## Content + +Nesting refers to the practice of placing one control flow statement inside another. This allows you to create more complex programs that can make decisions based on multiple conditions. + +In R, you can nest if statements, for loops, and other control flow statements inside each other to create more advanced programs. + +Here is an example of how to nest an if statement inside a for loop in R: +```r +for (i in 1:5) { + if (i %% 2 == 0) { + print(paste("i is even:", i)) + } else { + print(paste("i is odd:", i)) + } +} +``` + + + + + + +--- +## Practice + + +--- +## Revision diff --git a/r/r-core/loops-in-r/repeat-loops-in-r.md b/r/r-core/loops-in-r/repeat-loops-in-r.md new file mode 100644 index 0000000000..34a8a90dd1 --- /dev/null +++ b/r/r-core/loops-in-r/repeat-loops-in-r.md @@ -0,0 +1,121 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +A `repeat` loop allows you to execute a block of code indefinitely in **R**, until a `break` statement is encountered. You can use a `repeat` loop to perform an action indefinitely, or to perform an action until a certain condition is met. + +Here is the syntax for a `repeat` loop in R: +```r +repeat { + # code to be executed +} +``` + +The code in the loop is executed repeatedly until a `break` statement is encountered. + +Here is an example of a `repeat` loop that prints the numbers from `1` to `10`: +```r +i <- 1 +repeat { + if (i > 10) { + break + } + print(i) + i <- i + 1 +} +``` +You can use the `break` and `next` statements to control the flow of a repeat loop. The `break` statement breaks out of the loop and terminates it, while the `next` statement skips the rest of the current iteration and goes to the next one. + +Here is an example of a repeat loop that uses the `break` statement to exit the loop when the value of `i` is `5`: +```r +i <- 1 +repeat { + if (i == 5) { + break + } + print(i) + i <- i + 1 +} +``` + +Here is an example of a `repeat` loop that uses the `next` statement to skip the iteration when the value of `i` is `even`: +```r +i <- 1 +repeat { + if (i > 10) { + break + } + if (i %% 2 == 0) { + i <- i + 1 + next + } + print(i) + i <- i + 1 +} +``` + +--- +## Practice + +Complete the following code snippet to print the numbers from 1 to 10: + +```r +i <- 1 +repeat { + if (??? ??? 10) { + break + } + print(i) + i <- i + 1 +} +``` + +- `i` +- `>` +- `i + 1` +- `<` +- `i - 1` + +--- +## Revision + +What is the output of the following code? + +```r +i <- 1 +repeat { + if (i > 10) { + break + } + if (i %% 2 == 0) { + i <- i + 1 + next + } + print(i) + i <- i + 1 +} +``` + +??? + +- `1 3 5 7 9` +- `1 2 3 4 5 6 7 8 9 10` +- `2 4 6 8 10` +- `1 2 4 6 8 10` \ No newline at end of file diff --git a/r/r-core/loops-in-r/while-loops-in-r.md b/r/r-core/loops-in-r/while-loops-in-r.md new file mode 100644 index 0000000000..cd148d7e9e --- /dev/null +++ b/r/r-core/loops-in-r/while-loops-in-r.md @@ -0,0 +1,118 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +A while loop allows you to execute a block of code as long as a certain condition is TRUE in R. You can use a while loop to perform an action until a certain condition is met, or to perform an action indefinitely. +Here is the syntax for a while loop in R: +```r +while (condition) { + # code to be executed +} +``` +The condition is an expression that is evaluated before each iteration of the loop. If the condition is TRUE, the code in the loop is executed. If the condition is FALSE, the loop is terminated. + +Here is an example of a while loop that prints the numbers from 1 to 10: +```r +i <- 1 +while (i <= 10) { + print(i) + i <- i + 1 +} +``` + +You can use the break and next statements to control the flow of a while loop. The break statement breaks out of the loop and terminates it, while the next statement skips the rest of the current iteration and goes to the next one. + +Here is an example of a while loop that uses the break statement to exit the loop when the value of i is 5: +```r +i <- 1 +while (TRUE) { + if (i == 5) { + break + } + print(i) + i <- i + 1 +} +``` +Here is an example of a while loop that uses the next statement to skip the iteration when the value of i is even: +```r +i <- 1 +while (i <= 10) { + if (i %% 2 == 0) { + i <- i + 1 + next + } + print(i) + i <- i + 1 +} +``` + +You can use the break and next statements together to create more complex loops. For example, you can use a break statement to exit the loop when a certain condition is met, and use a next statement to skip certain iterations. +```r +i <- 1 +while (i <= 10) { + if (i == 5) { + break + } + if (i %% 2 == 0) { + i <- i + 1 + next + } + print(i) + i <- i + 1 +} +``` + +--- +## Practice + +Complete the following code snippet to print the numbers from 1 to 10: + +```r +i <- 1 +while (??? <= 10) { + print(i) + i <- i + 1 +} +``` + +- `i` +- `integer` +- `I` +- `for` + +--- +## Revision + +What is the output of the following code? + +```r +i <- 1 +while (i <= 10) { + print(i) + i <- i + 2 +} + +# ??? +``` + +- `1 3 5 7 9` +- `1 2 3 4 5 6 7 8 9 10` +- `2 4 6 8 10` +- `1 2 4 6 8 10` \ No newline at end of file diff --git a/r/r-core/programs-in-r/1 copy 5.md b/r/r-core/programs-in-r/1 copy 5.md new file mode 100644 index 0000000000..c0cac2aa47 --- /dev/null +++ b/r/r-core/programs-in-r/1 copy 5.md @@ -0,0 +1,108 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +In this workout, we will create a calculator program. + +Creating a calculator program in R requires only a few lines of code. This tutorial will show you how to create a basic calculator program that can perform addition, subtraction, multiplication, and division. + +To create a calculator program in R, we will do the following in a couple of insights: + +1. Define a function that takes two numbers as arguments and returns the result of the desired calculation. For example, to create a function that performs addition, you could use the following code: +```r +add <- function(x, y) { + return(x + y) +} +``` + +2. Define similar functions for the other calculations that you want to support (e.g. subtraction, multiplication, division). + +3. Use the readline function to read user input from the command line. This function reads a line of text from the standard input stream, and returns it as a character string. + +4. Use the as.numeric function to convert the user input from a character string to a numeric value. + +5. Use an if statement or a switch statement to determine which calculation to perform based on the user's input. + +6. Call the appropriate function to perform the calculation, and print the result to the command line using the print function. + +Here is an example of a complete calculator program in R: +```r +# Define the calculator functions +add <- function(x, y) { + return(x + y) +} +subtract <- function(x, y) { + return(x - y) +} +multiply <- function(x, y) { + return(x * y) +} +divide <- function(x, y) { + return(x / y) +} + +# Read the user input +input <- readline("Enter an operation (+, -, *, /) and two numbers: ") + +# Split the input into tokens +tokens <- strsplit(input, " ")[[1]] + +# Extract the operation and the numbers +operation <- tokens[1] +x <- as.numeric(tokens[2]) +y <- as + +``` + + + +--- +## Practice + +Complete the code to finish the program: + +```r +calculate_area <- function(length, width) { + return(length * width) +} + +length <- 8 +width <- 5 + +area <- calculate_area(length, width) + +print(paste("The area of the rectangle is", area)) +``` + + + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/programs-in-r/1 copy.md b/r/r-core/programs-in-r/1 copy.md new file mode 100644 index 0000000000..873c0be72c --- /dev/null +++ b/r/r-core/programs-in-r/1 copy.md @@ -0,0 +1,84 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +```r +# Function to perform arithmetic operations +calculator <- function(x, y, op) { + if (op == "+") { + return(x + y) + } else if (op == "-") { + return(x - y) + } else if (op == "*") { + return(x * y) + } else if (op == "/") { + return(x / y) + } else { + return("Invalid operator") + } +} + +# Test the calculator function +print(calculator(2, 3, "+")) # 5 +print(calculator(2, 3, "-")) # -1 +print(calculator(2, 3, "*")) # 6 +print(calculator(2, 3, "/")) # 0.6666666666666666 +print(calculator(2, 3, "^")) # Invalid operator +``` + + +This program defines a calculator function that takes three arguments: `x` and `y` are the operands, and `op` is the operator. The function uses an `if-else` statement to check the value of `op` and perform the appropriate arithmetic operation on `x` and `y`. If the operator is invalid, the function returns the string `"Invalid operator"`. + +To test the calculator function, we call it with different values of `x`, `y`, and `op` and print the results. + + +--- +## Practice + +Complete the code to finish the program: + +```r +calculate_area <- function(length, width) { + return(length * width) +} + +length <- 8 +width <- 5 + +area <- calculate_area(length, width) + +print(paste("The area of the rectangle is", area)) +``` + + + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/programs-in-r/1.md b/r/r-core/programs-in-r/1.md new file mode 100644 index 0000000000..c0cac2aa47 --- /dev/null +++ b/r/r-core/programs-in-r/1.md @@ -0,0 +1,108 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +In this workout, we will create a calculator program. + +Creating a calculator program in R requires only a few lines of code. This tutorial will show you how to create a basic calculator program that can perform addition, subtraction, multiplication, and division. + +To create a calculator program in R, we will do the following in a couple of insights: + +1. Define a function that takes two numbers as arguments and returns the result of the desired calculation. For example, to create a function that performs addition, you could use the following code: +```r +add <- function(x, y) { + return(x + y) +} +``` + +2. Define similar functions for the other calculations that you want to support (e.g. subtraction, multiplication, division). + +3. Use the readline function to read user input from the command line. This function reads a line of text from the standard input stream, and returns it as a character string. + +4. Use the as.numeric function to convert the user input from a character string to a numeric value. + +5. Use an if statement or a switch statement to determine which calculation to perform based on the user's input. + +6. Call the appropriate function to perform the calculation, and print the result to the command line using the print function. + +Here is an example of a complete calculator program in R: +```r +# Define the calculator functions +add <- function(x, y) { + return(x + y) +} +subtract <- function(x, y) { + return(x - y) +} +multiply <- function(x, y) { + return(x * y) +} +divide <- function(x, y) { + return(x / y) +} + +# Read the user input +input <- readline("Enter an operation (+, -, *, /) and two numbers: ") + +# Split the input into tokens +tokens <- strsplit(input, " ")[[1]] + +# Extract the operation and the numbers +operation <- tokens[1] +x <- as.numeric(tokens[2]) +y <- as + +``` + + + +--- +## Practice + +Complete the code to finish the program: + +```r +calculate_area <- function(length, width) { + return(length * width) +} + +length <- 8 +width <- 5 + +area <- calculate_area(length, width) + +print(paste("The area of the rectangle is", area)) +``` + + + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/programs-in-r/2.md b/r/r-core/programs-in-r/2.md new file mode 100644 index 0000000000..141186c416 --- /dev/null +++ b/r/r-core/programs-in-r/2.md @@ -0,0 +1,69 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +Next you need to define similar functions for the other calculations that you want to support (e.g. subtraction, multiplication, division). +```r +subtract <- function(x, y) { + return(x - y) +} +multiply <- function(x, y) { + return(x * y) +} +divide <- function(x, y) { + return(x / y) +} +``` + + + +--- +## Practice + +Complete the code to finish the program: + +```r +calculate_area <- function(length, width) { + return(length * width) +} + +length <- 8 +width <- 5 + +area <- calculate_area(length, width) + +print(paste("The area of the rectangle is", area)) +``` + + + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/programs-in-r/3.md b/r/r-core/programs-in-r/3.md new file mode 100644 index 0000000000..74acf69d8a --- /dev/null +++ b/r/r-core/programs-in-r/3.md @@ -0,0 +1,28 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +Next we are going to use the readline function to read user input from the command line. This function reads a line of text from the standard input stream, and returns it as a character string. +```r +# Read the user input +input <- readline("Enter an operation (+, -, *, /) and two numbers: ") +``` + diff --git a/r/r-core/programs-in-r/4.md b/r/r-core/programs-in-r/4.md new file mode 100644 index 0000000000..514825bb68 --- /dev/null +++ b/r/r-core/programs-in-r/4.md @@ -0,0 +1,68 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +Then we are going to use the as.numeric function to convert the user input from a character string to a numeric value. +```r +# Split the input into tokens +tokens <- strsplit(input, " ")[[1]] + +# Extract the operation and the numbers +operation <- tokens[1] +x <- as.numeric(tokens[2]) +y <- as + +``` + + + +--- +## Practice + +Complete the code to finish the program: + +```r +calculate_area <- function(length, width) { + return(length * width) +} + +length <- 8 +width <- 5 + +area <- calculate_area(length, width) + +print(paste("The area of the rectangle is", area)) +``` + + + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/intro-to-r/creating-a-program-in-r.md b/r/r-core/programs-in-r/creating-a-program-in-r.md similarity index 100% rename from r/r-core/intro-to-r/creating-a-program-in-r.md rename to r/r-core/programs-in-r/creating-a-program-in-r.md diff --git a/r/r-core/reading-and-writting-data-to-and-from-files/open-and-close-a-file.md b/r/r-core/reading-and-writting-data-to-and-from-files/open-and-close-a-file.md new file mode 100644 index 0000000000..ef82e6c943 --- /dev/null +++ b/r/r-core/reading-and-writting-data-to-and-from-files/open-and-close-a-file.md @@ -0,0 +1,99 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# The open & close Functions + +--- + +## Content + +The `open` and close functions are useful functions in **R** that allow you to open and close files, respectively. These functions are used in conjunction with other functions, such as readline and writeLines, to read and write data to files in **R**. + +Here is the basic syntax of the `open` function: +```r +open(file, mode = "r", blocking = TRUE) +``` + +- `file` is the name of the file to open. +- `mode` is an optional argument that specifies the mode in which to open the file. The possible values are `"r"` for reading, `"w"` for writing, and `"a"` for appending. The default value is `"r"`. +- `blocking` is an optional argument that specifies whether to open the file in blocking or non-blocking mode. The default value is `TRUE`. + +The `open` function returns a file object that you can use to read or write data to the file. + +Here is the basic syntax of the close function: +```r +close(connection) +``` + +- `connection` is the file object to close. + +The `close` function closes the specified file object, and frees up any resources that were being used by the file. + +Here is an example of how to use the `open` and `close` functions to read a file in **R**: +```r +# Open the file for reading +file <- open("test.txt", "r") + +# Read and process the file line by line +while (length(line <- readline(file)) > 0) { + # Process the line here +} + +# Close the file +close(file) +``` + +In this example, we use the `open` function to open the file `test.txt` for reading, and store the file object in the variable `file`. We then use the `readline` function to read a line of text from the file, and store it in the variable `line`. We use a `while` loop to read and process the file line by line, until the end of the file is reached. Finally, we use the `close` function to close the file. + +The `open` and `close` functions are important tools for reading and writing data to files in **R**. You should always remember to close a file when you are done with it, to free up resources and ensure that the file is properly saved. + +--- +## Practice + +To open a file for writing, you should use the `open` function with the mode argument set to ???. + +True or false? + +"The open function returns a file object that you can use to read or write data to the file." + +??? + + +- `"w"` +- `true` +- `false` +- `"r"` +- `"a"` + +--- +## Revision + +To close a file, you should use the close function with the file object ??? as an argument." + +True or false? + +"The close function closes the specified file object and frees up resources being used by the file." + +??? + +- `connection` +- `true` +- `false` +- `handle` +- `file` + + + diff --git a/r/r-core/reading-and-writting-data-to-and-from-files/readline-in-r.md b/r/r-core/reading-and-writting-data-to-and-from-files/readline-in-r.md new file mode 100644 index 0000000000..3825b5ab2e --- /dev/null +++ b/r/r-core/reading-and-writting-data-to-and-from-files/readline-in-r.md @@ -0,0 +1,51 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# The readline Function + +--- + +## Content + +The `readline` function is a useful function in **R** that allows you to read a line of text from the console, or from a file. This can be useful for creating interactive programs that allow the user to enter input, or for reading data from a file. + +Here is the basic syntax of the `readline` function: +```r +readline(prompt = "") +``` + +- `prompt` is an optional argument that specifies the prompt to display to the user. + + +Here is an example of how to use the `readline` function to read a line of text from the console: +```r +name <- readline("Enter your name: ") +print(paste("Hello, ", name)) + +# Hello Stefan +``` + +In this example, we use the `readline` function to read a line of text from the console, and store it in the variable `name`. We then print a greeting using the `paste` function, which concatenates the string `"Hello, "` with the value of the `name` variable. + +--- +## Practice + + + + +--- +## Revision + diff --git a/r/r-core/reading-and-writting-data-to-and-from-files/the-file-function.md b/r/r-core/reading-and-writting-data-to-and-from-files/the-file-function.md new file mode 100644 index 0000000000..78cf09dec2 --- /dev/null +++ b/r/r-core/reading-and-writting-data-to-and-from-files/the-file-function.md @@ -0,0 +1,72 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# The file Function + +--- + +## Content + +The `file` function is a useful function in R that allows you to create a file object for reading or writing data to a file. This function is typically used in conjunction with other functions, such as `readline` and `writeLines`, to read and write data to files in R. + +Here is the basic syntax of the `file` function: +```r +file(description, open = "", blocking = TRUE) +``` + +- `description` is a character string that specifies the name of the file to open, or a connection object to reuse. +- `open` is an optional argument that specifies the mode in which to open the file. The possible values are `"r"` for reading, `"w"` for writing, and `"a"` for appending. The default value is `""`, which means that the file is opened in the default mode for the specified description. +- `blocking` is an optional argument that specifies whether to open the file in blocking or non-blocking mode. The default value is `TRUE`. + +The `file` function returns a file object that you can use to read or write data to the file. + +Here is an example of how to use the file function to open a file for reading: +```r +file <- file("test.txt", "r") +``` + +Here's another example with the use of the `readline` function to read a line of text from a file. +```r +file <- file("test.txt", "r") +line <- readline(file) +close(file) +``` + +In this example, we open the file `"test.txt"` for reading using the `file` function, and store the file object in the variable `file`. We then use the `readline` function to read a line of text from the file, and store it in the variable `line`. Finally, we close the file using the `close` function. + + + +--- +## Practice + +To open a file for reading, you can use the file function with the open argument set to ???." + +??? + +- `"r"` +- `"w"` +- `"a"` + +--- +## Revision + +"To open a file for writing, you can use the file function with the open argument set to ???." + +??? + +- `"w"` +- `"r"` +- `"a"` \ No newline at end of file diff --git a/r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r-ii.md b/r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r-ii.md new file mode 100644 index 0000000000..0dc3334414 --- /dev/null +++ b/r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r-ii.md @@ -0,0 +1,51 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# More on the paste Function + +--- + +## Content + +The `paste` function has several optional arguments that allow you to customize the output. For example, you can use the collapse argument to specify a separator to use between the elements of a vector: +```r +z <- c("red", "green", "blue") +paste(z, collapse = ", ") +# "red, green, blue" +``` + +You can also use the sep and collapse arguments together to specify different separators for different levels of the input: +```r +z <- list(c("red", "green"), "blue") +paste(z, sep = ":", collapse = ", ") +# "red:green, blue" +``` + +Finally, you can use the quote argument to specify whether or not to surround the output with quotation marks: + +```r +paste("Hello", "world!", quote = TRUE) +# "\"Hello\" \"world!\"" +paste("Hello", "world!", quote = FALSE) +# "Hello world!" +``` + + + + + + + diff --git a/r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r.md b/r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r.md new file mode 100644 index 0000000000..252a53d2bd --- /dev/null +++ b/r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r.md @@ -0,0 +1,75 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# paste Function + +--- + +## Content + +The `paste` function in **R** is a versatile tool that allows you to combine or concatenate strings, variables, and other objects. In this insight, we will take a look at some examples of how to use the `paste` function in **R**. + +The most basic usage of the paste function is to combine two or more strings into a single string. Here is an example: +```r +paste("Hello", "world!") # "Hello world!" +``` + +You can also specify a separator to use between the strings: +```r +paste("Hello", "world!", sep = " ") # "Hello world!" +paste("Hello", "world!", sep = "-") # "Hello-world!" +``` + +The paste function can also combine variables, such as numbers or vectors: +```r +x <- 10 +y <- 20 +paste("The sum of x and y is", x + y) # "The sum of x and y is 30" + +z <- c("red", "green", "blue") +paste("The colors are", z) # "The colors are red green blue" +``` + + + + +------------------------------------- +The paste function has several optional arguments that allow you to customize the output. For example, you can use the collapse argument to specify a separator to use between the elements of a vector: +```r +z <- c("red", "green", "blue") +paste(z, collapse = ", ") # "red, green, blue" +``` + +You can also use the sep and collapse arguments together to specify different separators for different levels of the input: +```r +z <- list(c("red", "green"), "blue") +paste(z, sep = ":", collapse = ", ") # "red:green, blue" +``` + +Finally, you can use the quote argument to specify whether or not to surround the output with quotation marks: + + +```r +paste("Hello", "world!", quote = TRUE) # "\"Hello\" \"world!\"" +paste("Hello", "world!", quote = FALSE) # "Hello world!" +``` + + + + + + + diff --git a/r/r-core/reading-and-writting-data-to-and-from-files/writelines-in-r.md b/r/r-core/reading-and-writting-data-to-and-from-files/writelines-in-r.md new file mode 100644 index 0000000000..174ee8e3c9 --- /dev/null +++ b/r/r-core/reading-and-writting-data-to-and-from-files/writelines-in-r.md @@ -0,0 +1,65 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# The writelines Function + +--- + +## Content + +The `writeLines` function is a useful function in R that allows you to write data to a file. This function is typically used in conjunction with the file function, which creates a file object for reading or writing data to a file. + +Here is the basic syntax of the `writeLines` function: +```r +writeLines(text, con = stdout(), sep = "\n", useBytes = FALSE) +``` + +- `text` is a character vector that specifies the data to write to the file. +- `con` is an optional argument that specifies the connection to use for writing. The default value is `stdout()`, which means that the data is written to the standard output stream. +- `sep` is an optional argument that specifies the character to use as the line separator. The default value is `"\n"`, which means that each element of text is written on a new line. +- `useBytes` is an optional argument that specifies whether to use bytes or characters for the output. The default value is `FALSE`, which means that characters are used. + + +The `writeLines` function writes the specified data to the specified file or connection. + +Here is an example of how to use it: +```r +file <- file("test.txt", "w") +writeLines(c("Hello", "World"), file) +close(file) +``` + +In this example, we use the `file` function to open the file `test.txt` for writing, and store the file object in the variable `file`. We then use the `writeLines` function to write the character vector `c("Hello", "World")` to the file, using the `file` object as the connection. Finally, we use the `close` function to close the file and free up resources. + +The `writeLines` function is a useful function for writing data to files in R. You should always remember to close a file when you are done with it, using the `close` function, to free up resources and ensure that the file is properly saved. + +--- +## Practice + +To write data to a file using the `writeLines` function, you need to specify the data to write as the ??? argument. + +- `"text"` +- `"data"` +- `"output"` + +--- +## Revision + +To write data to a file using the `writeLines` function, you need to specify the connection to use for writing as the ??? argument. + +- `"con"` +- `"file"` +- `"connection"` \ No newline at end of file diff --git a/r/r-core/unordered-data-types-r/another-way-to-create-dictionaries-in-r.md b/r/r-core/unordered-data-types-r/another-way-to-create-dictionaries-in-r.md new file mode 100644 index 0000000000..2f39b04e3c --- /dev/null +++ b/r/r-core/unordered-data-types-r/another-way-to-create-dictionaries-in-r.md @@ -0,0 +1,92 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Another Way to Create Dictionaries + +--- + +## Content + +You can create a dictionary in R using the `dictionary()` function from the `purrr` package, or the `dict()` function from the `hash` package. For example: + +```r +# Install the purrr and hash packages +install.packages(c("purrr", "hash")) + +# Load the purrr and hash packages +library(purrr) +library(hash) + +# Create a dictionary using the dictionary() function +my_dict1 <- dictionary( + a = 1, + b = 2, + c = 3 +) + +# Create a dictionary using the dict() function +my_dict2 <- dict( + a = 1, + b = 2, + c = 3 +) +``` + +You can access the values in a dictionary using their keys, like this: +```r +my_dict1$a # value for key "a" +my_dict2[["b"]] # value for key "b" +``` + +You can add, modify, or remove key-value pairs from a dictionary using assignment operators or the `insert()` function. For example: +```r +# Add a key-value pair +my_dict1$d <- 4 + +# Modify a value +my_dict2[["c"]] <- 5 + +# Remove a key-value pair +my_dict2 <- remove(my_dict2, "b") +``` + +You can also loop over the key-value pairs in a dictionary using the map() function from the purrr package, like this: +```r +map(my_dict1, print) # prints the key-value pairs in my_dict1 +``` + + + +--- +## Practice + +Which of the following is **NOT** a way to access an element in a list in **R**? + +- `list.key` +- `list[[1]]` +- `list$key` +- `list[1]` + +--- +## Revision + +What function can be used to get the number of elements in a list in R? + +??? + +- `length()` +- `size()` +- `count()` +- `lengths()` \ No newline at end of file diff --git a/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md b/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md index 1606102afa..32e5cddb15 100644 --- a/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md +++ b/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md @@ -23,7 +23,7 @@ practiceQuestion: Consider the following dictionary: ```r -square_numbers <- list( +square_numbers <- c( 1: 1, 2: 4, 3: 9, @@ -40,19 +40,6 @@ print(square_numbers) # NULL ``` -`duplicate()` returns a copy of the dictionary -```r -new_squares <- duplicate(square_numbers) - -print(new_squares) -# 1: 1 -# 2: 4 -# 3: 9 -# 4: 16 -# 5: 25 - -``` - names() returns the names of the elements in the dictionary as a character vector ```r @@ -60,7 +47,6 @@ names(square_numbers) print(names(square_numbers)) # "1" "2" "3" "4" "5" - ``` diff --git a/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md b/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md index 5b1a6bd401..6313c4c690 100644 --- a/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md +++ b/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md @@ -19,16 +19,19 @@ practiceQuestion: ## Content -In `R`, dictionaries are known as lists. A list is an ordered collection of elements, where each element can be of a different data type. Lists are created using the `list()` function. -Here is an example of a list: +In **R**, a dictionary is a collection of key-value pairs, similar to a **map** or **hash** table in other programming languages. You can use dictionaries to store data that you want to access by a unique identifier (the key) rather than an index. + +In `R`, you can create dictionaries similarly to lists. + +Here is an example of a dictionary: ```r -fruits <- list(apple = "red", orange = "orange", banana = "yellow") +fruits <- c(apple = "red", orange = "orange", banana = "yellow") ``` -The elements in a list are called components, and each component has a name and a value. The names are called keys, and the values are called the elements of the list. +Difference between a dictionary and a list in R is that elements in a Dictionary have a name (key). -To access an element in a list, you can use either the `[[]]`, `[]` or the `$` operator. +To access an element in a dictionary, you can use either the `[[]]` or `[]` operator for indices or the key. For example: ```r @@ -36,9 +39,14 @@ fruits[[1]] # "red" fruits[1] +# apple # "red" -fruits$apple +fruits["apple"] +# apple +# "red" + +fruits[["apple"]] # "red" ``` @@ -62,13 +70,13 @@ Which of the following is **NOT** a way to access an element in a list in **R**? - `list.key` - `list[[1]]` -- `list$key` +- `list[["pear"]]` - `list[1]` --- ## Revision -What function can be used to get the number of elements in a list in R? +What function can be used to get the number of elements in a list in **R**? ??? diff --git a/r/r-core/unordered-data-types-r/unordered-data-types-in-r-ii.md b/r/r-core/unordered-data-types-r/unordered-data-types-in-r-ii.md new file mode 100644 index 0000000000..664d3ec7be --- /dev/null +++ b/r/r-core/unordered-data-types-r/unordered-data-types-in-r-ii.md @@ -0,0 +1,86 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# More Unordered Data Types + +--- +## Content + +In the previous insight we learned what **vectors** are. Now we will learn about **lists**. + +--- +### Lists + +A list is an ordered collection of objects, which can be of different types. You can create a list using the `list()` function. For example: + +```r +# list with elements of different types +w <- list(1, "a", TRUE) +``` +Just like *vectors*, you can access the elements of a list using their indices, which start at 1. For example: + +```r +# 1st element of w +w[1] +# 1 + +# 2nd element of w +w[2] +# a + +# 3rd element of w +w[3] +# TRUE +``` + +You can also use negative indexing to access the elements of a list in reverse order. +```r +# Access the last element of a vector +w[-1] +# TRUE +``` + + +--- +## Practice + +Finish the code to create a `skills` list containing three skills: +```r +??? <- ???("Pilot", "Doctor", "Programmer") +``` + +- `skills` +- `list` +- `people` +- `create` + + +--- +## Revision + +Finish the code to create a *numeric* list called `numbers`: +```r +??? <- ???( + 1, 2, 3, 4, 5 +) + +print(numbers) +# 1 2 3 4 5 +``` + +- `numbers` +- `list` +- `numeric` +- `output` \ No newline at end of file diff --git a/r/r-core/unordered-data-types-r/unoredered-data-types-in-r.md b/r/r-core/unordered-data-types-r/unoredered-data-types-in-r.md new file mode 100644 index 0000000000..ca42959b84 --- /dev/null +++ b/r/r-core/unordered-data-types-r/unoredered-data-types-in-r.md @@ -0,0 +1,96 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Unordered Data Types in R + +--- +## Content + +In **R**, there are two types of unordered data structures: **vectors** and **lists**. + +--- +### Vectors + +A vector is a one-dimensional array of data elements of the same type, such as *numeric*, *character*, or *logical*. You can create a vector using the `c()` function, which stands for "concatenate." For example: + +```r +# Create a numeric vector +numeric_vector <- c(1, 2, 3, 4, 5) + +# Create a character vector +character_vector <- c("a", "b", "c", "d", "e") + +# Create a logical vector +logical_vector <- c(TRUE, FALSE, TRUE, TRUE, FALSE) +``` +You can access the elements of a vector using indexing, which starts at 1 for the first element. + +```r +# Access the second element of a vector +numeric_vector[2] +# 2 + +character_vector[2] +# "b" + +logical_vector[2] +# FALSE +``` + +You can also use negative indexing to access the elements of a vector in reverse order. +```r +# Access the last element of a vector +numeric_vector[-1] +# 5 + +character_vector[-1] +# "e" + +logical_vector[-1] +# FALSE +``` + + +--- +## Practice + +A ??? is a ??? array of data elements of ??? data type. + +??? + +- `vector` +- `one-dimensional` +- `the same` +- `different` +- `list` +- `two-dimensional` + +--- +## Revision + +Finish the code to create a *numeric* vector called `numers`: +```r +??? <- ???( + 1, 2, 3, 4, 5 +) + +print(numbers) +# [1] 1 2 3 4 5 +``` + +- `numbers` +- `c` +- `numeric` +- `output` \ No newline at end of file diff --git a/r/r-core/intro-to-r/assignment-operators-r.md b/r/r-core/variables-and-data-types/assignment-operators-r.md similarity index 100% rename from r/r-core/intro-to-r/assignment-operators-r.md rename to r/r-core/variables-and-data-types/assignment-operators-r.md diff --git a/r/r-core/intro-to-r/basic-data-types-r.md b/r/r-core/variables-and-data-types/basic-data-types-r.md similarity index 100% rename from r/r-core/intro-to-r/basic-data-types-r.md rename to r/r-core/variables-and-data-types/basic-data-types-r.md diff --git a/r/r-core/intro-to-r/combining-variables-in-r.md b/r/r-core/variables-and-data-types/combining-variables-in-r.md similarity index 100% rename from r/r-core/intro-to-r/combining-variables-in-r.md rename to r/r-core/variables-and-data-types/combining-variables-in-r.md diff --git a/r/r-core/variables-and-data-types/creating-a-program-in-r.md b/r/r-core/variables-and-data-types/creating-a-program-in-r.md new file mode 100644 index 0000000000..effa81f9a3 --- /dev/null +++ b/r/r-core/variables-and-data-types/creating-a-program-in-r.md @@ -0,0 +1,99 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +In this tutorial, we will write a simple program in R that calculates the area of a rectangle. + +First, we will define a function calculate_area() that takes in two arguments: length and width. The function will return the area of the rectangle, which is calculated by multiplying the length and width. +```r +calculate_area <- function(length, width) { + return(length * width) +} +``` + +Next, we will prompt the user to enter the length and width of the rectangle using the readline() function. +```r +length <- readline("Enter the length of the rectangle: ") +width <- readline("Enter the width of the rectangle: ") +``` + +Note that the input entered by the user will be stored as a character string, so we need to convert it to a numeric value using the as.numeric() function. +```r +length <- as.numeric(length) +width <- as.numeric(width) +``` + +Finally, we will call the calculate_area() function and print the result. +```r +area <- calculate_area(length, width) + +print(paste("The area of the rectangle is", area)) +``` + +The complete program would look like this: +```r +calculate_area <- function(length, width) { + return(length * width) +} + +length <- readline("Enter the length of the rectangle: ") +width <- readline("Enter the width of the rectangle: ") + +length <- as.numeric(length) +width <- as.numeric(width) + +area <- calculate_area(length, width) + +print(paste("The area of the rectangle is", area)) +``` + +--- +## Practice + +Complete the code to finish the program: + +```r +calculate_area <- function(length, width) { + return(length * width) +} + +length <- 8 +width <- 5 + +area <- calculate_area(length, width) + +print(paste("The area of the rectangle is", area)) +``` + + + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md b/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md new file mode 100644 index 0000000000..9ee03006e9 --- /dev/null +++ b/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md @@ -0,0 +1,84 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Creating and Storing Variables + +--- + +## Content + +Variables are a fundamental concept in programming, and **R** is no exception. A variable is a named location in memory that you can store a value in, and later retrieve and use that value. Variables are a way to store and manipulate data in a program. + +In **R**, you can create variables using the `<-` operator. For example: +```r +x <- 5 +y <- 10 +``` + +You can also use the `=` operator, but it is generally recommended to use `<-` as it is easier to read and less prone to errors. + +To access the value of a variable, you can type the name of the variable inside a `print()`: +```r +print(x) +# 5 + +print(y) +# 10 +``` + +You can also use the `assign()` function to create and store a variable: +```r +assign("z", c(x, y)) +print(z) +# 5 10 +``` + +Or you can create variables using other variables: +```r +a <- x + y +print(a) +# 15 +``` + +--- +## Practice + +Which of the following is **NOT** a way to create a variable in **R**? + +??? + +- `a <=` +- `x = 5` +- `y <- 10` +- `z = c(x, y)` + +--- +## Practice + +Finish the code to create a new variable called `z` by summing the values of the `x` and `y` variables. Print the new variable. +```r +x <- 5 +y <- 5 +??? <- x ??? y + +???(z) +# 10 +``` + +- `z` +- `+` +- `print` +- `output` +- `plus` diff --git a/r/r-core/intro-to-r/printing-and-storing-variables-in-r.md b/r/r-core/variables-and-data-types/printing-and-storing-variables-in-r.md similarity index 91% rename from r/r-core/intro-to-r/printing-and-storing-variables-in-r.md rename to r/r-core/variables-and-data-types/printing-and-storing-variables-in-r.md index 2d61a3ec4f..488cb2c517 100644 --- a/r/r-core/intro-to-r/printing-and-storing-variables-in-r.md +++ b/r/r-core/variables-and-data-types/printing-and-storing-variables-in-r.md @@ -22,8 +22,8 @@ practiceQuestion: In this lesson, you'll learn how to print messages and store variables in **R**. -### Printing Messages --- +### Printing Messages To print a message to the console in **R**, you can use the `print()` function. For example: ```r @@ -35,8 +35,8 @@ You can also use the `cat()` function to print a message. The `cat()` function i cat("Hello, world!") ``` -### Storing Variables --- +### Storing Variables To store a value in a variable in **R**, you can use the assignment operator `<-`. For example: ```r @@ -47,11 +47,6 @@ z <- x + y You can also use the `=` operator to store a value in a variable, but it is generally recommended to use `<-` as it is more readable and less prone to errors. - -> 💬 Why are you interested in **R**? -> -> Leave a comment or view some of the other comments for inspiration before moving on. - --- ## Practice From 14614f3933b605c1eed6245f2ad7c7bb55f71c68 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Thu, 5 Jan 2023 12:27:48 +0100 Subject: [PATCH 323/390] add first draft of intro to R topic --- r/r-core/README.md | 7 +- .../conditional-statements-in-r/README.md | 14 ++ .../nesting-if-else-in-r.md | 99 +++++++++++ .../nesting-if-else-statements-in-r.md | 157 ------------------ r/r-core/data-type-conversion-in-r/README.md | 14 ++ .../as-double-and-character-r.md | 96 +++++++++++ .../as-logical-and-vector-r.md | 114 +++++++++++++ .../data-type-conversion-in-r/as-matrix-r.md | 97 +++++++++++ .../as-numeric-and-integer-r.md | 98 +++++++++++ .../data-type-conversion.md | 74 +++++++++ r/r-core/environment-variables-in-r/README.md | 12 ++ r/r-core/functions-in-r/README.md | 16 ++ .../functions-in-r/the-matrix-funtion-r.md | 97 +++++++++++ .../the-paste-function-in-r-ii.md | 73 ++++++++ .../the-paste-function-in-r.md | 34 ++-- r/r-core/intro-to-r/README.md | 13 ++ ...orld.md => first-program-hello-world-r.md} | 0 r/r-core/looping-techniques-in-r/README.md | 15 ++ r/r-core/loops-in-r/README.md | 15 ++ r/r-core/loops-in-r/for-loops-in-r.md | 25 ++- r/r-core/loops-in-r/intro-to-loops-in-r.md | 37 ++--- r/r-core/loops-in-r/nesting-loops-in-r.md | 106 ++++++++++-- r/r-core/programs-in-r/1 copy.md | 84 ---------- r/r-core/programs-in-r/1.md | 108 ------------ r/r-core/programs-in-r/3.md | 28 ---- r/r-core/programs-in-r/4.md | 68 -------- r/r-core/programs-in-r/README.md | 16 ++ ...ogram-in-r.md => area-of-a-rectangle-r.md} | 12 +- .../{1 copy 5.md => calculator-r.md} | 39 +---- r/r-core/programs-in-r/factorial-r.md | 44 +++++ .../{2.md => fibonacci-sequence-r.md} | 32 +++- r/r-core/programs-in-r/fizz-buzz-r.md | 43 +++++ .../programs-in-r/prime-number-checker-r.md | 50 ++++++ r/r-core/programs-in-r/reverse-a-string-r.md | 45 +++++ .../README.md | 14 ++ .../as-numeric.md | 88 ++++++++++ .../open-and-close-a-file.md | 0 .../readline-in-r.md | 17 ++ .../the-file-function.md | 0 .../writelines-in-r.md | 0 .../the-paste-function-in-r-ii.md | 51 ------ r/r-core/unordered-data-types-r/README.md | 16 ++ r/r-core/variables-and-data-types/README.md | 14 ++ .../assignment-operators-r.md | 5 +- .../creating-a-program-in-r.md | 99 ----------- .../creating-and-storing-variables-in-r.md | 2 - ...les-in-r.md => printing-variables-in-r.md} | 25 +-- 47 files changed, 1379 insertions(+), 734 deletions(-) create mode 100644 r/r-core/conditional-statements-in-r/README.md create mode 100644 r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md delete mode 100644 r/r-core/conditional-statements-in-r/nesting-if-else-statements-in-r.md create mode 100644 r/r-core/data-type-conversion-in-r/README.md create mode 100644 r/r-core/data-type-conversion-in-r/as-double-and-character-r.md create mode 100644 r/r-core/data-type-conversion-in-r/as-logical-and-vector-r.md create mode 100644 r/r-core/data-type-conversion-in-r/as-matrix-r.md create mode 100644 r/r-core/data-type-conversion-in-r/as-numeric-and-integer-r.md create mode 100644 r/r-core/data-type-conversion-in-r/data-type-conversion.md create mode 100644 r/r-core/environment-variables-in-r/README.md create mode 100644 r/r-core/functions-in-r/README.md create mode 100644 r/r-core/functions-in-r/the-matrix-funtion-r.md create mode 100644 r/r-core/functions-in-r/the-paste-function-in-r-ii.md rename r/r-core/{reading-and-writting-data-to-and-from-files => functions-in-r}/the-paste-function-in-r.md (58%) create mode 100644 r/r-core/intro-to-r/README.md rename r/r-core/intro-to-r/{first-program-hello-world.md => first-program-hello-world-r.md} (100%) create mode 100644 r/r-core/looping-techniques-in-r/README.md create mode 100644 r/r-core/loops-in-r/README.md delete mode 100644 r/r-core/programs-in-r/1 copy.md delete mode 100644 r/r-core/programs-in-r/1.md delete mode 100644 r/r-core/programs-in-r/3.md delete mode 100644 r/r-core/programs-in-r/4.md create mode 100644 r/r-core/programs-in-r/README.md rename r/r-core/programs-in-r/{creating-a-program-in-r.md => area-of-a-rectangle-r.md} (73%) rename r/r-core/programs-in-r/{1 copy 5.md => calculator-r.md} (82%) create mode 100644 r/r-core/programs-in-r/factorial-r.md rename r/r-core/programs-in-r/{2.md => fibonacci-sequence-r.md} (60%) create mode 100644 r/r-core/programs-in-r/fizz-buzz-r.md create mode 100644 r/r-core/programs-in-r/prime-number-checker-r.md create mode 100644 r/r-core/programs-in-r/reverse-a-string-r.md create mode 100644 r/r-core/reading-and-writing-data-to-and-from-files/README.md create mode 100644 r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md rename r/r-core/{reading-and-writting-data-to-and-from-files => reading-and-writing-data-to-and-from-files}/open-and-close-a-file.md (100%) rename r/r-core/{reading-and-writting-data-to-and-from-files => reading-and-writing-data-to-and-from-files}/readline-in-r.md (69%) rename r/r-core/{reading-and-writting-data-to-and-from-files => reading-and-writing-data-to-and-from-files}/the-file-function.md (100%) rename r/r-core/{reading-and-writting-data-to-and-from-files => reading-and-writing-data-to-and-from-files}/writelines-in-r.md (100%) delete mode 100644 r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r-ii.md create mode 100644 r/r-core/unordered-data-types-r/README.md create mode 100644 r/r-core/variables-and-data-types/README.md delete mode 100644 r/r-core/variables-and-data-types/creating-a-program-in-r.md rename r/r-core/variables-and-data-types/{printing-and-storing-variables-in-r.md => printing-variables-in-r.md} (50%) diff --git a/r/r-core/README.md b/r/r-core/README.md index 47d0c66b50..327f345c7e 100644 --- a/r/r-core/README.md +++ b/r/r-core/README.md @@ -1,6 +1,6 @@ name: Core -description: The fundamentals of Python. No skin shedding needed. +description: The fundamentals of R. core: true @@ -9,10 +9,11 @@ sections: - intro-to-r - variables-and-data-types - unordered-data-types-r + - data-type-conversions - conditional-statements-in-r - functions-in-r + - environment-variables-in-r - loops-in-r - looping-techniques-in-r - - environment-variables-in-r - - reading-and-writting-data-to-and-from-files + - reading-and-writing-data-to-and-from-files - programs-in-r diff --git a/r/r-core/conditional-statements-in-r/README.md b/r/r-core/conditional-statements-in-r/README.md new file mode 100644 index 0000000000..e115365bb0 --- /dev/null +++ b/r/r-core/conditional-statements-in-r/README.md @@ -0,0 +1,14 @@ +name: Control Flow + +description: Learn about conditional statements in R. + +insights: + - what-are-conditional-statements-r + - if-statements-in-r + - if-else-in-r + - nesting-if-else-in-r + - switch-statements-in-r + +aspects: + - workout + - deep \ No newline at end of file diff --git a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md new file mode 100644 index 0000000000..b4ee65d252 --- /dev/null +++ b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md @@ -0,0 +1,99 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Nesting ifelse Statements + +--- + +## Content + +Have you ever wanted to execute different actions in your R code based on multiple conditions? One way to do this is by using nested `ifelse` statements. + +To nest `ifelse` statements, you place one `ifelse` statement inside the `then` clause of another `ifelse` statement. Here is an example of how to do this: + +Here is an example of a nested ifelse statement in R: +```r +# Initialize variable x +x <- 3 + +# Nest ifelse statements +result <- ifelse(x > 0, ifelse(x > 2, "x is greater than 2", "x is 1 or 2"), "x is 0 or negative") + +# Print the result +print(result) + +``` + +In this example, we use an `ifelse` statement to check if `x` is greater than `0`. +```r +ifelse(x > 0 +``` + +If it is, then we use another `ifelse` statement to check if `x` is greater than 2: +```r +ifelse(x > 0, ifelse(x > 2, +``` + + +If it is, then we print "x is greater than 2". +```r +ifelse(x > 0, ifelse(x > 2, "x is greater than 2" +``` + + +If it is not, then we print "x is 1 or 2": +```r +ifelse(x > 0, ifelse(x > 2, "x is greater than 2", "x is 1 or 2"), + +``` + + +Finally, If `x` is not greater than `0`, then we print "x is 0 or negative": +```r +ifelse(x > 0, ifelse(x > 2, "x is greater than 2", "x is 1 or 2"), "x is 0 or negative") +``` + +As a result of this code, the output will be "x is greater than 2". + + +### When to use nested ifelse statements +--- + +Nested `ifelse` statements can be useful when you have multiple conditions to check and you want to execute different actions based on the results of those conditions. + +However, it is important to be careful when using nested `ifelse` statements, as they can quickly become difficult to read and maintain if you have too many levels of nesting. + +--- +## Practice + +What is the result of the following nested `ifelse`? + +```r +# Initialize variable x +x <- 5 + +# Nest ifelse statements +result <- ifelse(x > 0, ifelse(x > 10, "x is greater than 10", "x is between 1 and 10"), "x is 0 or negative") + +# Print the result +print(result) +# ??? +``` + +- `"x is between 1 and 10"` +- `"x is greater than 10"` +- `"x is 0 or negative"` +- `Error` \ No newline at end of file diff --git a/r/r-core/conditional-statements-in-r/nesting-if-else-statements-in-r.md b/r/r-core/conditional-statements-in-r/nesting-if-else-statements-in-r.md deleted file mode 100644 index 0e5d4649c7..0000000000 --- a/r/r-core/conditional-statements-in-r/nesting-if-else-statements-in-r.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -author: Stefan-Stojanovic - -tags: - - introduction - - discussion -type: normal -category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone - ---- - -# Nesting ifelse Statements - ---- - -## Content - -Have you ever wanted to execute different actions in your R code based on multiple conditions? One way to do this is by using nested `ifelse` statements. - -Nested `ifelse` statements are `ifelse` statements that are placed inside another `ifelse` statement. This allows you to create code that can execute different actions based on multiple conditions. - -Here is an example of a nested ifelse statement in R: -```r -x <- 10 -y <- 20 - -result <- ifelse(x > y, "x is greater than y", - ifelse(x < y, "x is less than y", "x is equal to y")) -print(result) -``` - -In this example, the ifelse function first checks whether x is greater than y. If it is, the string "x is greater than y" is returned. If it is not, the ifelse function moves on to the next condition, which checks whether x is less than y. If it is, the string "x is less than y" is returned. If it is not, the final condition is evaluated, and the string "x is equal to y" is returned. - - -### When to use nested ifelse statements ---- - -Nested ifelse statements can be useful when you have multiple conditions to check and you want to execute different actions based on the results of those conditions. However, it is important to be careful when using nested ifelse statements, as they can quickly become difficult to read and maintain if you have too many levels of nesting. - -### Conclusion ---- - -In summary, nesting ifelse statements in R allows you to create complex conditions and execute different actions based on those conditions. However, it is important to use them wisely to avoid making your code hard to read and maintain. - - - - - ---- -### What are nested ifelse statements? - - -<!-- -In R, you can nest `ifelse` statements to create more complex conditions. This allows you to create code that can execute different actions based on multiple conditions. - -Here is an example of how to nest `ifelse` statements in R: -```r -x <- 10 -y <- 20 - -result <- ifelse(x > y, "x is greater than y", ifelse(x < y, "x is less than y", "x is equal to y")) -print(result) -``` - - -In this example, the `ifelse` function first checks whether `x` is greater than `y`. If it is, the string `"x is greater than y"` is returned. If it is not, the `ifelse` function moves on to the next condition, which checks whether `x` is less than `y`. If it is, the string `"x is less than y"` is returned. If it is not, the final condition is evaluated, and the string "x is equal to y" is returned. - -Nesting `ifelse` statements can be useful when you have multiple conditions to check and you want to execute different actions based on the results of those conditions. - -However, it is important to be careful when using nested `ifelse` statements, as they can quickly become difficult to read and maintain if you have too many levels of nesting. --> - - ---- -## Practice - -Which of the following is a valid way to nest ifelse statements in R? - -A) - -```r -x <- 10 -y <- 20 - -result <- ifelse(x > y, "x is greater than y") else { - ifelse(x < y, "x is less than y") else { - "x is equal to y" - } -} -print(result) -``` - -B) - -```r -x <- 10 -y <- 20 - -result <- ifelse(x > y) { - "x is greater than y" -} else { - ifelse(x < y) { - "x is less than y" - } else { - "x is equal to y" - } -} -print(result) -``` - -C) -```r -x <- 10 -y <- 20 - -result <- ifelse(x > y) { - "x is greater than y" -} -ifelse(x < y) { - "x is less than y" -} -ifelse(x == y) { - "x is equal to y" -} -print(result) -``` - -D) -```r -x <- 10 -y <- 20 - -result <- ifelse(x > y) { - "x is greater than y" -} else { - ifelse(x < y) { - "x is less than y" - } else { - "x is equal to y" - } -} -print(result) -``` - -??? - -- `B)` -- `A)` -- `C)` -- `D)` - ---- -## Revision diff --git a/r/r-core/data-type-conversion-in-r/README.md b/r/r-core/data-type-conversion-in-r/README.md new file mode 100644 index 0000000000..52d95ce9b1 --- /dev/null +++ b/r/r-core/data-type-conversion-in-r/README.md @@ -0,0 +1,14 @@ +name: Data Conversion + +description: Learn how to convert data from one data type into another. + +insights: + - data-type-conversion-r + - as-numeric-and-integer-r + - as-double-and-character-r + - as-logical-and-vector-r + - as-matrix-r + +aspects: + - workout + - deep \ No newline at end of file diff --git a/r/r-core/data-type-conversion-in-r/as-double-and-character-r.md b/r/r-core/data-type-conversion-in-r/as-double-and-character-r.md new file mode 100644 index 0000000000..5a119aca2c --- /dev/null +++ b/r/r-core/data-type-conversion-in-r/as-double-and-character-r.md @@ -0,0 +1,96 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# as.character & as.double + +--- + +## Content + + +### as.double +--- + +The `as.double` converts an object to double (floating point) type. +```r +# Convert a number to a double +x <- 123 +x <- as.double(x) +print(x) +# 123.0 + +# Convert a vector of numbers to a vector of doubles +v <- c(1, 2, 3) +v <- as.double(v) +print(v) +# 1.0 2.0 3.0 +``` + + +### as.character +--- + +The `as.character` converts an object to character (string) type. + +```r +# Convert a number to a string +x <- 123 +x <- as.character(x) +print(x) +# "123" + +# Convert a vector of numbers to a vector of strings +v <- c(1, 2, 3) +v <- as.character(v) +print(v) +# "1" "2" "3" +``` + + +--- +## Practice + +Convert the following logical vector to a character vector using the `as.character` function: + +```r +x <- c(TRUE, FALSE, TRUE, TRUE) + +x <- as.???(???) +print(x) +# "TRUE" "FALSE" "TRUE" "TRUE +``` + +- `character` +- `x` +- `y` +- `number` + +--- +## Revision + +Convert the following character vector to a double type using the `as.double` function: + +```r +x <- c(1,2, 345) + +x <- ??? +print(x) +# 1.0 2.0 345.0 +``` + +- `as.double(x)` +- `as a double` +- `x.as.double` diff --git a/r/r-core/data-type-conversion-in-r/as-logical-and-vector-r.md b/r/r-core/data-type-conversion-in-r/as-logical-and-vector-r.md new file mode 100644 index 0000000000..58a946ae5b --- /dev/null +++ b/r/r-core/data-type-conversion-in-r/as-logical-and-vector-r.md @@ -0,0 +1,114 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# as.logical & as.vector + +--- + +## Content + + +### as.logical + +The `as.logical` converts an object to logical (TRUE/FALSE) type. + +```r +# Convert a string to a logical value +x <- "TRUE" +x <- as.logical(x) +print(x) +# TRUE + +# Convert a vector of strings to a vector of logical values +v <- c("TRUE", "FALSE", "TRUE") +v <- as.logical(v) +print(v) +# TRUE FALSE TRUE + +# Convert a matrix of characters to a matrix of logical values +m <- matrix(c("TRUE", "FALSE", "TRUE", "FALSE"), nrow = 2) +m <- as.logical(m) +print(m) +# TRUE FALSE TRUE FALSE +``` + + +### as.vector + +The `as.vector` converts an object to vector type. + +```r +# Convert a number to a vector +x <- 123 +x <- as.vector(x) +print(x) +# 123 + +# Convert a matrix to a vector +m <- matrix(1:4, nrow = 2) +v <- as.vector(m) +print(v) +# 1 3 2 4 +``` + + +--- +## Practice + +Which of the following will create a logical vector from a character vector? + +```r +# A) +v <- as.vector(c(TRUE, FALSE, TRUE)) + +# B) +v <- as.logical(c(TRUE, FALSE, TRUE)) + +# C) +v <- as.vector(c("True", "False", "True")) + +# D) +v <- as.logical(c("True", "False", "True")) +``` + +- `D)` +- `A)` +- `B)` +- `C)` + +--- +## Revision + +Which of the following will create a character vector from a logical vector? + +```r +# A) +v <- as.character(c(TRUE, FALSE, TRUE)) + +# B) +v <- as.vector(c("True", "False", "True")) + +# C) +v <- as.character(c(1, 0, 1)) + +# D) +v <- as.vector(c(1, 0, 1)) +``` + +- `A)` +- `D)` +- `B)` +- `C)` diff --git a/r/r-core/data-type-conversion-in-r/as-matrix-r.md b/r/r-core/data-type-conversion-in-r/as-matrix-r.md new file mode 100644 index 0000000000..353476a418 --- /dev/null +++ b/r/r-core/data-type-conversion-in-r/as-matrix-r.md @@ -0,0 +1,97 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# as.matrix + +--- + +## Content + + +### as.matrix + +The `as.matrix` converts an object to matrix type. + +```r +# Convert a vector to a matrix +v <- c(1, 2, 3, 4) +m <- as.matrix(v) +print(m) +# [,1] +# [1,] 1 +# [2,] 2 +# [3,] 3 +# [4,] 4 + +# Convert a list to a matrix +l <- list(c(1, 2), c(3, 4)) +m <- as.matrix(l) +print(m) +# [,1] [,2] +# [1,] 1 2 +# [2,] 3 4 +``` + +--- +## Practice + +Which of the following will create a 3x3 matrix from a numeric vector? + + +```r +# A) +m <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3) + +# B) +m <- as.matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3) + +# C) +m <- as.matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 2, ncol = 4) + +# D) +m <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 2, ncol = 4) +``` + +- `B)` +- `A)` +- `C)` +- `D)` + + + +--- +## Revision + +Which of the following will create a 2x4 matrix from a character vector? + +```r +# A) +m <- matrix(c("a", "b", "c", "d", "e", "f", "g", "h"), nrow = 2, ncol = 4) + +# B) +m <- as.matrix(c("a", "b", "c", "d", "e", "f", "g", "h"), nrow = 2, ncol = 4) + +# C) +m <- matrix(c("a", "b", "c", "d", "e", "f", "g", "h"), nrow = 2, ncol = 4) + +# D) +m <- matrix(c("a", "b", "c", "d", "e", "f", "g", "h"), nrow = 4, ncol = 2) +``` + +- `B)` +- `A)` +- `C)` +- `D)` diff --git a/r/r-core/data-type-conversion-in-r/as-numeric-and-integer-r.md b/r/r-core/data-type-conversion-in-r/as-numeric-and-integer-r.md new file mode 100644 index 0000000000..a045ea516e --- /dev/null +++ b/r/r-core/data-type-conversion-in-r/as-numeric-and-integer-r.md @@ -0,0 +1,98 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# as.numeric & as.integer + +--- + +## Content + + +### as.numeric +--- + +The `as.numeric` function converts an object to numeric (integer or double) type. + +Here's an example +```r +# Convert a string to a number +x <- "123" +x <- as.numeric(x) +print(x) +# 123 + +# Convert a vector of strings to a vector of numbers +v <- c("1", "2", "3") +v <- as.numeric(v) +print(v) +# 1 2 3 +``` + + +### as.integer +--- + +`as.integer`: Converts an object to integer type. + +```r +# Convert a number to an integer +x <- 123.45 +x <- as.integer(x) +print(x) +# 123 + +# Convert a vector of numbers to a vector of integers +v <- c(1.5, 2.5, 3.5) +v <- as.integer(v) +print(v) +# 1 2 3 +``` + + +--- +## Practice + +Convert the following character vector to a numeric vector using the `as.numeric` function: + +```r +x <- c("1", "2", "3", "4", "5") + +x <- as.???(???) +print(x) +# 1 2 3 4 5 +``` + +- `numeric` +- `x` +- `y` +- `number` + +--- +## Revision + +Convert the following character vector to a integer type using the `as.integer` function: + +```r +x <- c("1", "2", "3", "4", "5") + +x <- ??? +print(x) +# 1 2 3 4 5 +``` + +- `as.integer(x)` +- `as an integer` +- `x.asInteger` diff --git a/r/r-core/data-type-conversion-in-r/data-type-conversion.md b/r/r-core/data-type-conversion-in-r/data-type-conversion.md new file mode 100644 index 0000000000..75af7ef984 --- /dev/null +++ b/r/r-core/data-type-conversion-in-r/data-type-conversion.md @@ -0,0 +1,74 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Data Type Conversion + +--- + +## Content + +In **R**, it is often necessary to convert data from one type to another. For example, you may need to convert a string to a number, or a vector to a matrix. Here are some common functions for converting data types in **R**: + + +- `as.numeric`: Converts an object to numeric (integer or double) type. +- `as.integer`: Converts an object to integer type. +- `as.double`: Converts an object to double (floating point) type. +- `as.character`: Converts an object to character (string) type. +- `as.logical`: Converts an object to logical (TRUE/FALSE) type. +- `as.vector`: Converts an object to vector type. +- `as.matrix`: Converts an object to matrix type. + +Note: Each of these methods has an `is.name` methods. For instance, `is.numeric`, `is.double` and so on. They are used to check if the value is the appropriate type. + +They return `TRUE` or `FALSE`. + +Another way to check which data type a value has is with the `typeof()` method. + +We will discuss some examples on how to use them in the following insights. + + +--- +## Practice + +Complete the code to finish the program: + +```r +calculate_area <- function(length, width) { + return(length * width) +} + +length <- 8 +width <- 5 + +area <- calculate_area(length, width) + +print(paste("The area of the rectangle is", area)) +``` + + + +--- +## Revision + +What is the basic data type for a vector of categorical variables in R? + +??? + +- `factor` +- `character` +- `numeric` +- `logical` +- `NULL` \ No newline at end of file diff --git a/r/r-core/environment-variables-in-r/README.md b/r/r-core/environment-variables-in-r/README.md new file mode 100644 index 0000000000..8b7bb8defb --- /dev/null +++ b/r/r-core/environment-variables-in-r/README.md @@ -0,0 +1,12 @@ +name: Environment Variables + +description: Learn about the local and global environment variables. + +insights: + - global-environment-variables-in-r + - local-variables-in-r + - local-vs-global-variables-in-r + +aspects: + - workout + - deep \ No newline at end of file diff --git a/r/r-core/functions-in-r/README.md b/r/r-core/functions-in-r/README.md new file mode 100644 index 0000000000..e06dd2b08e --- /dev/null +++ b/r/r-core/functions-in-r/README.md @@ -0,0 +1,16 @@ +name: Intro to Functions + +description: Function basics. + +insights: + - functions-in-r + - function-methods-in-r + - function-methods-in-r-ii + - the-paste-function-in-r + - the-paste-function-in-r-ii + - the-matrix-function-r + + +aspects: + - workout + - deep \ No newline at end of file diff --git a/r/r-core/functions-in-r/the-matrix-funtion-r.md b/r/r-core/functions-in-r/the-matrix-funtion-r.md new file mode 100644 index 0000000000..9358763b2a --- /dev/null +++ b/r/r-core/functions-in-r/the-matrix-funtion-r.md @@ -0,0 +1,97 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# The matrix Function + +--- + +## Content + + +The `matrix` function is a useful function in R that allows you to create a matrix, or a two-dimensional array, of data. Matrices are useful for storing and manipulating tabular data, and are often used for statistical and mathematical operations. + +Here is the basic syntax of the `matrix` function: +```r +matrix(data, nrow, ncol, byrow = FALSE, dimnames = NULL) +``` + +- `data` is a vector of data that will be converted into a matrix. +- `nrow` is the number of rows in the matrix. +- `ncol` is the number of columns in the matrix. +- `byrow` is a logical argument that specifies whether the data should be filled by row (`TRUE`) or by column (`FALSE`, the default). +- `dimnames` is a list of length 2 containing the row and column names of the matrix. + +Here is an example of how to use the matrix function to create a matrix of data: +```r +# Create a 3x3 matrix of data +m <- matrix(1:9, nrow = 3, ncol = 3) +print(m) +# [,1] [,2] [,3] +# [1,] 1 4 7 +# [2,] 2 5 8 +# [3,] 3 6 9 +``` + + +In this example, we use the `matrix` function to create a 3x3 matrix of data, using the values `1:9` as the data. The `nrow` and `ncol` arguments specify the dimensions of the matrix, and the `byrow` argument specifies that the data should be filled by row. The resulting matrix is then printed to the console. + +--- +## Practice + +Which of the following will create a 2x3 matrix with the data in `x` filled by column? + +```r +x <- c(1, 2, 3, 4, 5, 6) +``` + +```r +# A) +m <- matrix(x, nrow = 2, ncol = 3, byrow = FALSE) + +# B) +m <- matrix(x, nrow = 3, ncol = 2, byrow = TRUE) + +# C) +m <- matrix(x, nrow = 2, ncol = 3, byrow = TRUE) + +# D) +m <- matrix(x, nrow = 3, ncol = 2, byrow = FALSE) +``` + +??? + +- `A)` +- `B)` +- `C)` +- `D)` + + + +--- +## Revision + +True or false? + +The following code will create a 3x3 matrix of characters: + +```r +x <- c("a", "b", "c", "d", "e", "f", "g", "h", "i") +m <- matrix(x, nrow = 3, ncol = 3, byrow = TRUE) +``` + +??? + +- `True` +- `False` \ No newline at end of file diff --git a/r/r-core/functions-in-r/the-paste-function-in-r-ii.md b/r/r-core/functions-in-r/the-paste-function-in-r-ii.md new file mode 100644 index 0000000000..1eb6bcf8a5 --- /dev/null +++ b/r/r-core/functions-in-r/the-paste-function-in-r-ii.md @@ -0,0 +1,73 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# More on the paste Function + +--- + +## Content + +The `paste` function has several optional arguments that allow you to customize the output. For example, you can use the `collapse` argument to specify a separator to use between the elements of a vector: +```r +z <- c("red", "green", "blue") +paste(z, collapse = ", ") +# "red, green, blue" +``` + +You can also use the `sep` and `collapse` arguments together to specify different separators for different levels of the input: +```r +z <- list(c("red", "green"), "blue") +paste(z, sep = ":", collapse = ", ") +# "red:green, blue" +``` + +Finally, you can use the `quote` argument to specify whether or not to surround the output with quotation marks: + +```r +paste("Hello", "world!", quote = TRUE) +# "\"Hello\" \"world!\"" +paste("Hello", "world!", quote = FALSE) +# "Hello world!" +``` + +--- +## Practice + +Fill in the gap to combine the elements of the vector `c("red", "green", "blue")` into a single string, separated by a comma and a space: + +```r +z <- c("red", "green", "blue") +paste(z, ??? = ", ") +# "red, green, blue" +``` + +- `sep` +- `collapse` +- `quote` +- `combine` + + +--- +## Revision + +Which of the following lines of code will combine the elements of the list `list(c("red", "green"), "blue")` into a single string, using colons as separators within the elements and commas as separators between the elements? + +??? + +- `paste(list(c("red", "green"), "blue"), sep = ":", collapse = ", ")` +- `paste(list(c("red", "green"), "blue"), sep = ",", collapse = ": ")` +- `paste(list(c("red", "green"), "blue"), sep = ",", collapse = ":")` +- `paste(list(c("red", "green"), "blue"), sep = ":", collapse = " ")` \ No newline at end of file diff --git a/r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r.md b/r/r-core/functions-in-r/the-paste-function-in-r.md similarity index 58% rename from r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r.md rename to r/r-core/functions-in-r/the-paste-function-in-r.md index 252a53d2bd..8404ba5c81 100644 --- a/r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r.md +++ b/r/r-core/functions-in-r/the-paste-function-in-r.md @@ -45,31 +45,37 @@ paste("The colors are", z) # "The colors are red green blue" +--- +## Practice -------------------------------------- -The paste function has several optional arguments that allow you to customize the output. For example, you can use the collapse argument to specify a separator to use between the elements of a vector: -```r -z <- c("red", "green", "blue") -paste(z, collapse = ", ") # "red, green, blue" -``` +Fill in the gap to combine the strings `"Hello"` and `"world!"` into a single string: -You can also use the sep and collapse arguments together to specify different separators for different levels of the input: ```r -z <- list(c("red", "green"), "blue") -paste(z, sep = ":", collapse = ", ") # "red:green, blue" +paste(???, ???) # "Hello world!" ``` -Finally, you can use the quote argument to specify whether or not to surround the output with quotation marks: +- `"Hello"` +- `"world!"` +- `"Hello!", "world"` +- `"Hi", "world!"` -```r -paste("Hello", "world!", quote = TRUE) # "\"Hello\" \"world!\"" -paste("Hello", "world!", quote = FALSE) # "Hello world!" -``` +--- +## Revision + + +Which of the following lines of code will combine the strings `"Hello"` and `"world!"` into a single string, separated by a space? +```r +??? +``` +- `paste("Hello", "world!", sep = " ")` +- `paste("Hello", "world!", sep = "-")` +- `paste("Hello", "world!", sep = ",")` +- `paste("Hello", "world!", sep = ":")` diff --git a/r/r-core/intro-to-r/README.md b/r/r-core/intro-to-r/README.md new file mode 100644 index 0000000000..ab2251f0a9 --- /dev/null +++ b/r/r-core/intro-to-r/README.md @@ -0,0 +1,13 @@ +name: Intro to R + +description: Get familiar with R. + +insights: + - what-is-r + - why-learn-r + - installing-r-locally + - first-program-hello-world-r + +aspects: + - workout + - deep \ No newline at end of file diff --git a/r/r-core/intro-to-r/first-program-hello-world.md b/r/r-core/intro-to-r/first-program-hello-world-r.md similarity index 100% rename from r/r-core/intro-to-r/first-program-hello-world.md rename to r/r-core/intro-to-r/first-program-hello-world-r.md diff --git a/r/r-core/looping-techniques-in-r/README.md b/r/r-core/looping-techniques-in-r/README.md new file mode 100644 index 0000000000..e7ccd961bb --- /dev/null +++ b/r/r-core/looping-techniques-in-r/README.md @@ -0,0 +1,15 @@ +name: Looping Techniques + +description: Learn about some looping techniques you can use in R. + +insights: + - looping-techniques-in-r + - what-is-vectorization + - statistical-functions-for-vectorization-in-r + - math-functions-for-vectorization-in-r + - apply-function + - the-lapply-and-sapply-functions-in-r + +aspects: + - workout + - deep \ No newline at end of file diff --git a/r/r-core/loops-in-r/README.md b/r/r-core/loops-in-r/README.md new file mode 100644 index 0000000000..566eba55e9 --- /dev/null +++ b/r/r-core/loops-in-r/README.md @@ -0,0 +1,15 @@ +name: Loops + +description: Learn what loops are and how to use them. + +insights: + - intro-to-loops-in-r + - for-loops-in-r + - break-and-next-in-r + - while-loops-in-r + - repeat-loops-in-r + - nesting-loops-in-r + +aspects: + - workout + - deep \ No newline at end of file diff --git a/r/r-core/loops-in-r/for-loops-in-r.md b/r/r-core/loops-in-r/for-loops-in-r.md index 765b2e8fb4..166b3d048d 100644 --- a/r/r-core/loops-in-r/for-loops-in-r.md +++ b/r/r-core/loops-in-r/for-loops-in-r.md @@ -30,14 +30,14 @@ for (variable in sequence) { The `variable` is a placeholder for the current value or element in the sequence. The sequence can be any object that can be iterated over, such as a vector, list, or data frame. -Here is an example of a for loop that prints the numbers from 1 to 10: +Here is an example of a `for` loop that prints the numbers from 1 to 10: ```r for (i in 1:10) { print(i) } ``` -You can also use a for loop to iterate over the elements of a character vector: +You can also use a `for` loop to iterate over the elements of a character vector: ```r for (word in c("apple", "banana", "cherry")) { print(word) @@ -61,12 +61,21 @@ for (??? in ???) { --- ## Revision -What is the basic data type for a vector of categorical variables in **R**? +What is the output of the following code? + + +```r +for (word in c("apple", "banana", "cherry")) { + print(word) +} + +# ??? +# ??? +# ??? +``` ??? -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file +- `"apple"` +- `"banana"` +- `"cherry"` diff --git a/r/r-core/loops-in-r/intro-to-loops-in-r.md b/r/r-core/loops-in-r/intro-to-loops-in-r.md index 5b081efe4e..a475ea333b 100644 --- a/r/r-core/loops-in-r/intro-to-loops-in-r.md +++ b/r/r-core/loops-in-r/intro-to-loops-in-r.md @@ -13,7 +13,7 @@ practiceQuestion: --- -# Basic Data Types in R +# Intro to Loops --- @@ -40,7 +40,9 @@ for (word in c("apple", "banana", "cherry")) { } ``` -A while loop allows you to execute a block of code as long as a certain condition is TRUE. You can use a while loop to perform an action until a certain condition is met, or to perform an action indefinitely. For example: +### While + +A `while` loop allows you to execute a block of code as long as a certain condition is TRUE. You can use a while loop to perform an action until a certain condition is met, or to perform an action indefinitely. For example: ```r # Print the numbers from 1 to 10 i <- 1 @@ -54,7 +56,10 @@ while (TRUE) { print("Hello, World!") } ``` -A repeat loop is similar to a while loop, but the condition is checked at the end of the loop instead of at the beginning. You can use a repeat loop to perform an action indefinitely or until a certain condition is met. For example: + +### Repeat + +A `repeat` loop is similar to a while loop, but the condition is checked at the end of the loop instead of at the beginning. You can use a `repeat` loop to perform an action indefinitely or until a certain condition is met. For example: ```r # Print the numbers from 1 to 10 i <- 1 @@ -66,30 +71,14 @@ repeat { } ``` - - --- ## Practice -Which of the following is a basic data type in **R**? - -??? - -- `numeric` -- `integer` -- `matrix` -- `function` -- `data frame` - ---- -## Revision - -What is the basic data type for a vector of categorical variables in **R**? +Which of these is not a loop type in R? ??? -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file +- `until` +- `repeat` +- `for` +- `while` diff --git a/r/r-core/loops-in-r/nesting-loops-in-r.md b/r/r-core/loops-in-r/nesting-loops-in-r.md index eddfd84763..157ca7fc87 100644 --- a/r/r-core/loops-in-r/nesting-loops-in-r.md +++ b/r/r-core/loops-in-r/nesting-loops-in-r.md @@ -14,35 +14,119 @@ practiceQuestion: --- -# Nesting ifelse Statements +# Nesting Loops --- ## Content -Nesting refers to the practice of placing one control flow statement inside another. This allows you to create more complex programs that can make decisions based on multiple conditions. +It is possible to nest loops in **R**, which means placing one loop inside another. This can be useful for performing tasks that require multiple levels of iteration. -In R, you can nest if statements, for loops, and other control flow statements inside each other to create more advanced programs. - -Here is an example of how to nest an if statement inside a for loop in R: +Here is an example of one: ```r -for (i in 1:5) { - if (i %% 2 == 0) { - print(paste("i is even:", i)) - } else { - print(paste("i is odd:", i)) +# Initialize variables +i <- 1 +j <- 1 + +# Outer loop +for (i in 1:3) { + + # Inner loop + for (j in 1:3) { + + # Print the current values of i and j + print(paste("i =", i, "j =", j)) } } -``` +# Output: +# i = 1 j = 1 +# i = 1 j = 2 +# i = 1 j = 3 +# i = 2 j = 1 +# i = 2 j = 2 +# i = 2 j = 3 +# i = 3 j = 1 +# i = 3 j = 2 +# i = 3 j = 3 +``` +In this example, we have an outer loop that iterates over the values `1` to `3`, and an inner loop that also iterates over the values `1` to `3`. The inner loop is executed `3` times for each iteration of the outer loop, resulting in a total of `9` iterations. +We can also use `if` statements to control the flow of a loop. Here is an example of a nested loop that only prints the values of `i` and `j` when `i` is greater than `j`: +```r +# Outer loop +for (i in 1:3) { + + # Inner loop + for (j in 1:3) { + + # Only print the current values of i and j if i > j + if (i > j) { + print(paste("i =", i, "j =", j)) + } + } +} +# Output: +# i = 2 j = 1 +# i = 3 j = 1 +# i = 3 j = 2 +``` --- ## Practice +Finish the code for the output to be correct. + +```r +for (??? in 1:2) { + + # Inner loop + for (j in 1:???) { + + # Print the current values of i and j + print(paste("i =", i, "j =", j)) + } +} + +# "i = 1 j = 1" +# "i = 1 j = 2" +# "i = 2 j = 1" +# "i = 2 j = 2" +``` + +- `i` +- `2` +- `j` +- `3` --- ## Revision + +Finish the code for the output to be correct. + +```r +for (??? in 1:2) { + + # Inner loop + for (j in 1:???) { + + # Print the current values of i and j + ???(paste("i =", i, "j =", j)) + } +} + +# "i = 1 j = 1" +# "i = 1 j = 2" +# "i = 2 j = 1" +# "i = 2 j = 2" +``` + +- `i` +- `2` +- `print` +- `output` +- `j` +- `3` \ No newline at end of file diff --git a/r/r-core/programs-in-r/1 copy.md b/r/r-core/programs-in-r/1 copy.md deleted file mode 100644 index 873c0be72c..0000000000 --- a/r/r-core/programs-in-r/1 copy.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -author: Stefan-Stojanovic - -tags: - - introduction - - discussion -type: normal -category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone - ---- - -# Basic Data Types in R - ---- - -## Content - -```r -# Function to perform arithmetic operations -calculator <- function(x, y, op) { - if (op == "+") { - return(x + y) - } else if (op == "-") { - return(x - y) - } else if (op == "*") { - return(x * y) - } else if (op == "/") { - return(x / y) - } else { - return("Invalid operator") - } -} - -# Test the calculator function -print(calculator(2, 3, "+")) # 5 -print(calculator(2, 3, "-")) # -1 -print(calculator(2, 3, "*")) # 6 -print(calculator(2, 3, "/")) # 0.6666666666666666 -print(calculator(2, 3, "^")) # Invalid operator -``` - - -This program defines a calculator function that takes three arguments: `x` and `y` are the operands, and `op` is the operator. The function uses an `if-else` statement to check the value of `op` and perform the appropriate arithmetic operation on `x` and `y`. If the operator is invalid, the function returns the string `"Invalid operator"`. - -To test the calculator function, we call it with different values of `x`, `y`, and `op` and print the results. - - ---- -## Practice - -Complete the code to finish the program: - -```r -calculate_area <- function(length, width) { - return(length * width) -} - -length <- 8 -width <- 5 - -area <- calculate_area(length, width) - -print(paste("The area of the rectangle is", area)) -``` - - - ---- -## Revision - -What is the basic data type for a vector of categorical variables in R? - -??? - -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file diff --git a/r/r-core/programs-in-r/1.md b/r/r-core/programs-in-r/1.md deleted file mode 100644 index c0cac2aa47..0000000000 --- a/r/r-core/programs-in-r/1.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -author: Stefan-Stojanovic - -tags: - - introduction - - discussion -type: normal -category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone - ---- - -# Basic Data Types in R - ---- - -## Content - -In this workout, we will create a calculator program. - -Creating a calculator program in R requires only a few lines of code. This tutorial will show you how to create a basic calculator program that can perform addition, subtraction, multiplication, and division. - -To create a calculator program in R, we will do the following in a couple of insights: - -1. Define a function that takes two numbers as arguments and returns the result of the desired calculation. For example, to create a function that performs addition, you could use the following code: -```r -add <- function(x, y) { - return(x + y) -} -``` - -2. Define similar functions for the other calculations that you want to support (e.g. subtraction, multiplication, division). - -3. Use the readline function to read user input from the command line. This function reads a line of text from the standard input stream, and returns it as a character string. - -4. Use the as.numeric function to convert the user input from a character string to a numeric value. - -5. Use an if statement or a switch statement to determine which calculation to perform based on the user's input. - -6. Call the appropriate function to perform the calculation, and print the result to the command line using the print function. - -Here is an example of a complete calculator program in R: -```r -# Define the calculator functions -add <- function(x, y) { - return(x + y) -} -subtract <- function(x, y) { - return(x - y) -} -multiply <- function(x, y) { - return(x * y) -} -divide <- function(x, y) { - return(x / y) -} - -# Read the user input -input <- readline("Enter an operation (+, -, *, /) and two numbers: ") - -# Split the input into tokens -tokens <- strsplit(input, " ")[[1]] - -# Extract the operation and the numbers -operation <- tokens[1] -x <- as.numeric(tokens[2]) -y <- as - -``` - - - ---- -## Practice - -Complete the code to finish the program: - -```r -calculate_area <- function(length, width) { - return(length * width) -} - -length <- 8 -width <- 5 - -area <- calculate_area(length, width) - -print(paste("The area of the rectangle is", area)) -``` - - - ---- -## Revision - -What is the basic data type for a vector of categorical variables in R? - -??? - -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file diff --git a/r/r-core/programs-in-r/3.md b/r/r-core/programs-in-r/3.md deleted file mode 100644 index 74acf69d8a..0000000000 --- a/r/r-core/programs-in-r/3.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -author: Stefan-Stojanovic - -tags: - - introduction - - discussion -type: normal -category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone - ---- - -# Basic Data Types in R - ---- - -## Content - -Next we are going to use the readline function to read user input from the command line. This function reads a line of text from the standard input stream, and returns it as a character string. -```r -# Read the user input -input <- readline("Enter an operation (+, -, *, /) and two numbers: ") -``` - diff --git a/r/r-core/programs-in-r/4.md b/r/r-core/programs-in-r/4.md deleted file mode 100644 index 514825bb68..0000000000 --- a/r/r-core/programs-in-r/4.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -author: Stefan-Stojanovic - -tags: - - introduction - - discussion -type: normal -category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone - ---- - -# Basic Data Types in R - ---- - -## Content - -Then we are going to use the as.numeric function to convert the user input from a character string to a numeric value. -```r -# Split the input into tokens -tokens <- strsplit(input, " ")[[1]] - -# Extract the operation and the numbers -operation <- tokens[1] -x <- as.numeric(tokens[2]) -y <- as - -``` - - - ---- -## Practice - -Complete the code to finish the program: - -```r -calculate_area <- function(length, width) { - return(length * width) -} - -length <- 8 -width <- 5 - -area <- calculate_area(length, width) - -print(paste("The area of the rectangle is", area)) -``` - - - ---- -## Revision - -What is the basic data type for a vector of categorical variables in R? - -??? - -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file diff --git a/r/r-core/programs-in-r/README.md b/r/r-core/programs-in-r/README.md new file mode 100644 index 0000000000..3b65f8988b --- /dev/null +++ b/r/r-core/programs-in-r/README.md @@ -0,0 +1,16 @@ +name: Programs in R + +description: This workout contains several useful programs like a Calculator, Prime number checker, and more. + +insights: + - area-of-a-rectangle-r + - fizz-buzz-r + - calculator-r + - fibonacci-sequence-in-r + - prime-number-checker-r + - factorial-r + - reverse-a-string-r + +aspects: + - workout + - deep \ No newline at end of file diff --git a/r/r-core/programs-in-r/creating-a-program-in-r.md b/r/r-core/programs-in-r/area-of-a-rectangle-r.md similarity index 73% rename from r/r-core/programs-in-r/creating-a-program-in-r.md rename to r/r-core/programs-in-r/area-of-a-rectangle-r.md index effa81f9a3..57f633d225 100644 --- a/r/r-core/programs-in-r/creating-a-program-in-r.md +++ b/r/r-core/programs-in-r/area-of-a-rectangle-r.md @@ -14,34 +14,34 @@ practiceQuestion: --- -# Basic Data Types in R +# Area of a rectangle --- ## Content -In this tutorial, we will write a simple program in R that calculates the area of a rectangle. +In this tutorial, we will write a program in R that calculates the area of a rectangle. -First, we will define a function calculate_area() that takes in two arguments: length and width. The function will return the area of the rectangle, which is calculated by multiplying the length and width. +First, we will define a function `calculate_area()` that takes in two arguments: `length` and `width`. The function will return the area of the rectangle, which is calculated by multiplying the `length` and `width`. ```r calculate_area <- function(length, width) { return(length * width) } ``` -Next, we will prompt the user to enter the length and width of the rectangle using the readline() function. +Next, we will prompt the user to enter the `length` and `width` of the rectangle using the `readline()` function: ```r length <- readline("Enter the length of the rectangle: ") width <- readline("Enter the width of the rectangle: ") ``` -Note that the input entered by the user will be stored as a character string, so we need to convert it to a numeric value using the as.numeric() function. +Note that the input entered by the user will be stored as a character string, so we need to convert it to a numeric value using the `as.numeric()` function. ```r length <- as.numeric(length) width <- as.numeric(width) ``` -Finally, we will call the calculate_area() function and print the result. +Finally, we will call the `calculate_area()` function and print the result. ```r area <- calculate_area(length, width) diff --git a/r/r-core/programs-in-r/1 copy 5.md b/r/r-core/programs-in-r/calculator-r.md similarity index 82% rename from r/r-core/programs-in-r/1 copy 5.md rename to r/r-core/programs-in-r/calculator-r.md index c0cac2aa47..b1d07a05bf 100644 --- a/r/r-core/programs-in-r/1 copy 5.md +++ b/r/r-core/programs-in-r/calculator-r.md @@ -14,7 +14,7 @@ practiceQuestion: --- -# Basic Data Types in R +# Calculator Functions --- @@ -70,39 +70,4 @@ operation <- tokens[1] x <- as.numeric(tokens[2]) y <- as -``` - - - ---- -## Practice - -Complete the code to finish the program: - -```r -calculate_area <- function(length, width) { - return(length * width) -} - -length <- 8 -width <- 5 - -area <- calculate_area(length, width) - -print(paste("The area of the rectangle is", area)) -``` - - - ---- -## Revision - -What is the basic data type for a vector of categorical variables in R? - -??? - -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file +``` \ No newline at end of file diff --git a/r/r-core/programs-in-r/factorial-r.md b/r/r-core/programs-in-r/factorial-r.md new file mode 100644 index 0000000000..c5ff7a7bed --- /dev/null +++ b/r/r-core/programs-in-r/factorial-r.md @@ -0,0 +1,44 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +This program calculates the factorial of a number `n`, which is the product of all positive integers from `1` to `n`. +```r +# function to calculate the factorial of a number +factorial <- function(n) { + # initialize result to 1 + result <- 1 + + # loop from 1 to n + for (i in 1:n) { + # multiply result by i + result <- result * i + } + + # return result + return(result) +} + +# test the function with different values of n +print(factorial(1)) # 1 +print(factorial(5)) # 120 +print(factorial(10)) # 3628800 +``` diff --git a/r/r-core/programs-in-r/2.md b/r/r-core/programs-in-r/fibonacci-sequence-r.md similarity index 60% rename from r/r-core/programs-in-r/2.md rename to r/r-core/programs-in-r/fibonacci-sequence-r.md index 141186c416..01435250f6 100644 --- a/r/r-core/programs-in-r/2.md +++ b/r/r-core/programs-in-r/fibonacci-sequence-r.md @@ -20,21 +20,35 @@ practiceQuestion: ## Content -Next you need to define similar functions for the other calculations that you want to support (e.g. subtraction, multiplication, division). +This program generates the Fibonacci sequence up to a given number of terms: ```r -subtract <- function(x, y) { - return(x - y) -} -multiply <- function(x, y) { - return(x * y) -} -divide <- function(x, y) { - return(x / y) +# Read the number of terms from the user +n <- readline("Enter the number of terms: ") +n <- as.numeric(n) + +# Initialize the first two terms +a <- 0 +b <- 1 + +# Print the first two terms +print(a) +print(b) + +# Loop through the remaining terms +for (i in 3:n) { + # Calculate the next term + c <- a + b + # Print the term + print(c) + # Shift the variables + a <- b + b <- c } ``` + --- ## Practice diff --git a/r/r-core/programs-in-r/fizz-buzz-r.md b/r/r-core/programs-in-r/fizz-buzz-r.md new file mode 100644 index 0000000000..974002a483 --- /dev/null +++ b/r/r-core/programs-in-r/fizz-buzz-r.md @@ -0,0 +1,43 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# FizzBuzz + +--- + +## Content + +This program prints the numbers from 1 to 100, but for multiples of three it prints "Fizz" instead of the number, and for multiples of five it prints "Buzz". For numbers which are multiples of both three and five it prints "FizzBuzz": +```r +# Loop through the numbers from 1 to 100 +for (i in 1:100) { + + # Print "Fizz" for multiples of three + if (i %% 3 == 0) { + print("Fizz") + } + + # Print "Buzz" for multiples of five + if (i %% 5 == 0) { + print("Buzz") + } + + # Print the number if it is not a multiple of three or five + if (i %% 3 != 0 && i %% 5 != 0) { + print(i) + } +} +``` diff --git a/r/r-core/programs-in-r/prime-number-checker-r.md b/r/r-core/programs-in-r/prime-number-checker-r.md new file mode 100644 index 0000000000..6149984331 --- /dev/null +++ b/r/r-core/programs-in-r/prime-number-checker-r.md @@ -0,0 +1,50 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Prime Number Checker + +--- + +## Content + +```r +# Read the number from the user +n <- readline("Enter a number: ") +n <- as.numeric(n) + +# Initialize a flag to track whether the number is prime +is_prime <- TRUE + +# Check for divisibility by 2 and 3 +if (n %% 2 == 0 || n %% 3 == 0) { + is_prime <- FALSE +} + +# Check for divisibility by the numbers from 5 to sqrt(n) +for (i in 5:floor(sqrt(n))) { + if (n %% i == 0) { + is_prime <- FALSE + break + } +} + +# Print the result +if (is_prime) { + print("The number is prime.") +} else { + print("The number is not prime.") +} +``` \ No newline at end of file diff --git a/r/r-core/programs-in-r/reverse-a-string-r.md b/r/r-core/programs-in-r/reverse-a-string-r.md new file mode 100644 index 0000000000..99719f3189 --- /dev/null +++ b/r/r-core/programs-in-r/reverse-a-string-r.md @@ -0,0 +1,45 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Basic Data Types in R + +--- + +## Content + +This program takes a string as input and returns the reversed string. + +```r +# function to reverse a string +reverse_string <- function(string) { + # initialize result to an empty string + result <- "" + + # loop through the string in reverse order + for (i in seq_along(string)[length(string):1]) { + # append the character at index i to result + result <- paste(result, substr(string, i, i), sep="") + } + + # return result + return(result) +} + +# test the function with different strings +print(reverse_string("Hello")) # "olleH" +print(reverse_string("abcdefg")) # "gfedcba" +print(reverse_string("")) # "" +``` \ No newline at end of file diff --git a/r/r-core/reading-and-writing-data-to-and-from-files/README.md b/r/r-core/reading-and-writing-data-to-and-from-files/README.md new file mode 100644 index 0000000000..802684b75b --- /dev/null +++ b/r/r-core/reading-and-writing-data-to-and-from-files/README.md @@ -0,0 +1,14 @@ +name: Reading & Writing + +description: Learn how to read from or write data to a file or console. + +insights: + - readline-in-r + - as-numeric + - open-and-close-a-file + - the-file-function + - writelines-in-r + +aspects: + - workout + - deep \ No newline at end of file diff --git a/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md b/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md new file mode 100644 index 0000000000..d4477ca82b --- /dev/null +++ b/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md @@ -0,0 +1,88 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# as.numeric Function + +--- + +## Content + +The `as.numeric` function is a useful function that converts an object to a numeric data type. + +You can use the `readline` function in combination with the `as.numeric` function to read a number from the console, or from a file. Here is an example of how to do this: +```r +x <- readline("Enter a number: ") +x <- as.numeric(x) +print(x + 1) +``` + +In this example, we use the `readline` function to read a line of text from the console, and store it in the `x` variable. We then use the `as.numeric` function to convert the `x` variable to a numeric data type. Finally, we print the value of `x + 1`. + +If the user enters the number `5`, the program will print `6`. + + +--- +## Practice + +Fill in the gap to read a line of text from the console then convert it into a number and store it inside the same variable: + +```r +x <- readline("Enter a number: ") +??? <-???(x) +print(x * x) +``` + +- `x` +- ` as.numeric` +- `y` +- `toNumber` +- `convert` + +--- +## Revision + +Which of the following lines of code will read a line of text from the console, store it in the `y` variable, then convert it to a number? + +A) +```r +y <- readline("Enter a number: ") +y <- toNumber(y) +``` + +B) +```r +y <- readline("Enter a number: ") +y <- as.number(y) +``` + +C) +```r +y <- readline("Enter a number: ") +y <- as.numeric(y) +``` + +D) +```r +y <- writeline("Enter a number: ") +y <- as.numeric(y) +``` + +??? + +- `C)` +- `A)` +- `B)` +- `D)` \ No newline at end of file diff --git a/r/r-core/reading-and-writting-data-to-and-from-files/open-and-close-a-file.md b/r/r-core/reading-and-writing-data-to-and-from-files/open-and-close-a-file.md similarity index 100% rename from r/r-core/reading-and-writting-data-to-and-from-files/open-and-close-a-file.md rename to r/r-core/reading-and-writing-data-to-and-from-files/open-and-close-a-file.md diff --git a/r/r-core/reading-and-writting-data-to-and-from-files/readline-in-r.md b/r/r-core/reading-and-writing-data-to-and-from-files/readline-in-r.md similarity index 69% rename from r/r-core/reading-and-writting-data-to-and-from-files/readline-in-r.md rename to r/r-core/reading-and-writing-data-to-and-from-files/readline-in-r.md index 3825b5ab2e..c7837365e0 100644 --- a/r/r-core/reading-and-writting-data-to-and-from-files/readline-in-r.md +++ b/r/r-core/reading-and-writing-data-to-and-from-files/readline-in-r.md @@ -43,9 +43,26 @@ In this example, we use the `readline` function to read a line of text from the --- ## Practice +Fill in the gap to read a line of text from the console and store it inside the `x` variable: +```r +??? <- ???("Enter a value for x: ") +``` +- `x` +- `readline` +- `y` +- `input` +- `scan` --- ## Revision +Which of the following lines of code will read a line of text from the console and store it in the `y` variable, with the prompt `"Enter a value for y: "`? + +??? + +- `y <- readline("Enter a value for y: ")` +- `y <- read("Enter a value for y: ")` +- `y <- scan("Enter a value for y: ")` +- `y <- input("Enter a value for y: ")` \ No newline at end of file diff --git a/r/r-core/reading-and-writting-data-to-and-from-files/the-file-function.md b/r/r-core/reading-and-writing-data-to-and-from-files/the-file-function.md similarity index 100% rename from r/r-core/reading-and-writting-data-to-and-from-files/the-file-function.md rename to r/r-core/reading-and-writing-data-to-and-from-files/the-file-function.md diff --git a/r/r-core/reading-and-writting-data-to-and-from-files/writelines-in-r.md b/r/r-core/reading-and-writing-data-to-and-from-files/writelines-in-r.md similarity index 100% rename from r/r-core/reading-and-writting-data-to-and-from-files/writelines-in-r.md rename to r/r-core/reading-and-writing-data-to-and-from-files/writelines-in-r.md diff --git a/r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r-ii.md b/r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r-ii.md deleted file mode 100644 index 0dc3334414..0000000000 --- a/r/r-core/reading-and-writting-data-to-and-from-files/the-paste-function-in-r-ii.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -author: Stefan-Stojanovic - -tags: - - introduction - - discussion -type: normal -category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone - ---- - -# More on the paste Function - ---- - -## Content - -The `paste` function has several optional arguments that allow you to customize the output. For example, you can use the collapse argument to specify a separator to use between the elements of a vector: -```r -z <- c("red", "green", "blue") -paste(z, collapse = ", ") -# "red, green, blue" -``` - -You can also use the sep and collapse arguments together to specify different separators for different levels of the input: -```r -z <- list(c("red", "green"), "blue") -paste(z, sep = ":", collapse = ", ") -# "red:green, blue" -``` - -Finally, you can use the quote argument to specify whether or not to surround the output with quotation marks: - -```r -paste("Hello", "world!", quote = TRUE) -# "\"Hello\" \"world!\"" -paste("Hello", "world!", quote = FALSE) -# "Hello world!" -``` - - - - - - - diff --git a/r/r-core/unordered-data-types-r/README.md b/r/r-core/unordered-data-types-r/README.md new file mode 100644 index 0000000000..ed0ec0a88a --- /dev/null +++ b/r/r-core/unordered-data-types-r/README.md @@ -0,0 +1,16 @@ +name: Unordered Data Types + +description: Learn about different data types R has to offer. + +insights: + - unoredered-data-types-in-r + - unoredered-data-types-in-r-ii + - intro-to-dictionaries-r + - dictionary-methods-in-r + - dictionary-methods-in-r-ii + - another-way-to-create-dictionaries-in-r + + +aspects: + - workout + - deep \ No newline at end of file diff --git a/r/r-core/variables-and-data-types/README.md b/r/r-core/variables-and-data-types/README.md new file mode 100644 index 0000000000..ca8960074a --- /dev/null +++ b/r/r-core/variables-and-data-types/README.md @@ -0,0 +1,14 @@ +name: Variables & Data Types + +description: Learn about variables and basic data types in R. + +insights: + - creating-and-storing-variables-in-r + - assignment-operators-r + - combining-variables-in-r + - basic-data-types-r + - printing-variables-in-r + +aspects: + - workout + - deep \ No newline at end of file diff --git a/r/r-core/variables-and-data-types/assignment-operators-r.md b/r/r-core/variables-and-data-types/assignment-operators-r.md index 3e15ce475f..213ce09816 100644 --- a/r/r-core/variables-and-data-types/assignment-operators-r.md +++ b/r/r-core/variables-and-data-types/assignment-operators-r.md @@ -21,7 +21,7 @@ practiceQuestion: In R, you can use assignment operators to assign values to variables. -The most common assignment operator is the <- operator, which is used to assign a value to a variable: +The most common assignment operator is the `<-` operator, which is used to assign a value to a variable: ```r x <- 5 y <- 10 @@ -33,7 +33,8 @@ print(y) # 10 ``` -You can also use the = operator for assignment: +You can also use the `=` operator, but it is generally recommended to use `<-` as it is easier to read and less prone to errors. + ```r x = 5 y = 10 diff --git a/r/r-core/variables-and-data-types/creating-a-program-in-r.md b/r/r-core/variables-and-data-types/creating-a-program-in-r.md deleted file mode 100644 index effa81f9a3..0000000000 --- a/r/r-core/variables-and-data-types/creating-a-program-in-r.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -author: Stefan-Stojanovic - -tags: - - introduction - - discussion -type: normal -category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone - ---- - -# Basic Data Types in R - ---- - -## Content - -In this tutorial, we will write a simple program in R that calculates the area of a rectangle. - -First, we will define a function calculate_area() that takes in two arguments: length and width. The function will return the area of the rectangle, which is calculated by multiplying the length and width. -```r -calculate_area <- function(length, width) { - return(length * width) -} -``` - -Next, we will prompt the user to enter the length and width of the rectangle using the readline() function. -```r -length <- readline("Enter the length of the rectangle: ") -width <- readline("Enter the width of the rectangle: ") -``` - -Note that the input entered by the user will be stored as a character string, so we need to convert it to a numeric value using the as.numeric() function. -```r -length <- as.numeric(length) -width <- as.numeric(width) -``` - -Finally, we will call the calculate_area() function and print the result. -```r -area <- calculate_area(length, width) - -print(paste("The area of the rectangle is", area)) -``` - -The complete program would look like this: -```r -calculate_area <- function(length, width) { - return(length * width) -} - -length <- readline("Enter the length of the rectangle: ") -width <- readline("Enter the width of the rectangle: ") - -length <- as.numeric(length) -width <- as.numeric(width) - -area <- calculate_area(length, width) - -print(paste("The area of the rectangle is", area)) -``` - ---- -## Practice - -Complete the code to finish the program: - -```r -calculate_area <- function(length, width) { - return(length * width) -} - -length <- 8 -width <- 5 - -area <- calculate_area(length, width) - -print(paste("The area of the rectangle is", area)) -``` - - - ---- -## Revision - -What is the basic data type for a vector of categorical variables in R? - -??? - -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file diff --git a/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md b/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md index 9ee03006e9..4e2d55d623 100644 --- a/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md +++ b/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md @@ -27,8 +27,6 @@ x <- 5 y <- 10 ``` -You can also use the `=` operator, but it is generally recommended to use `<-` as it is easier to read and less prone to errors. - To access the value of a variable, you can type the name of the variable inside a `print()`: ```r print(x) diff --git a/r/r-core/variables-and-data-types/printing-and-storing-variables-in-r.md b/r/r-core/variables-and-data-types/printing-variables-in-r.md similarity index 50% rename from r/r-core/variables-and-data-types/printing-and-storing-variables-in-r.md rename to r/r-core/variables-and-data-types/printing-variables-in-r.md index 488cb2c517..4bdc87d43a 100644 --- a/r/r-core/variables-and-data-types/printing-and-storing-variables-in-r.md +++ b/r/r-core/variables-and-data-types/printing-variables-in-r.md @@ -13,19 +13,13 @@ practiceQuestion: --- -# Printing and Storing Variables in R +# print & cat --- ## Content -In this lesson, you'll learn how to print messages and store variables in **R**. - - ---- -### Printing Messages - -To print a message to the console in **R**, you can use the `print()` function. For example: +To print[1] a message to the console in **R**, you can use the `print()` function. For example: ```r print("Hello, world!") ``` @@ -35,18 +29,6 @@ You can also use the `cat()` function to print a message. The `cat()` function i cat("Hello, world!") ``` ---- -### Storing Variables - -To store a value in a variable in **R**, you can use the assignment operator `<-`. For example: -```r -x <- 10 -y <- 20 -z <- x + y -``` - -You can also use the `=` operator to store a value in a variable, but it is generally recommended to use `<-` as it is more readable and less prone to errors. - --- ## Practice @@ -64,6 +46,3 @@ Which of the following is the correct way to store the value `5` in a variable ` [1: Printing] Printing messages in **R** is useful for debugging and for communicating information to the user. - -[2: Variables] -Variables are used to store values in a program, making it easier to reuse those values and perform operations on them. \ No newline at end of file From 19f50d60a3795e3c5b63b1f76ae7fee018f463b6 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Thu, 5 Jan 2023 13:07:49 +0100 Subject: [PATCH 324/390] make some changes --- r/r-core/README.md | 1 + .../if-else-in-r.md | 5 ++ .../if-statements-in-r.md | 4 + .../nesting-if-else-in-r.md | 8 +- .../switch-statements-in-r.md | 6 +- .../as-double-and-character-r.md | 5 ++ .../as-logical-and-vector-r.md | 10 ++- .../data-type-conversion-in-r/as-matrix-r.md | 10 ++- .../as-numeric-and-integer-r.md | 5 ++ .../data-type-conversion.md | 39 -------- .../global-environment-variables-in-r.md | 5 ++ .../local-variables-in-r.md | 4 + .../local-vs-global-variables-in-r.md | 4 + r/r-core/functions-in-r-ii/README.md | 13 +++ .../the-matrix-funtion-r.md | 5 +- .../the-reduce-function-r.md | 58 ++++++++++++ .../functions-in-r-ii/the-sum-function-r.md | 88 +++++++++++++++++++ r/r-core/functions-in-r/README.md | 1 - .../function-methods-in-r-ii.md | 4 + .../functions-in-r/function-methods-in-r.md | 5 ++ r/r-core/functions-in-r/functions-in-r.md | 5 ++ .../the-paste-function-in-r-ii.md | 4 + .../functions-in-r/the-paste-function-in-r.md | 27 +++--- .../intro-to-r/first-program-hello-world-r.md | 4 + r/r-core/intro-to-r/installing-r-locally.md | 30 ------- r/r-core/intro-to-r/what-is-r.md | 3 +- .../looping-techniques-in-r/apply-function.md | 29 +++--- .../looping-techniques-in-r.md | 4 - .../math-functions-for-vectorization-in-r.md | 5 ++ ...stical-functions-for-vectorization-in-r.md | 4 + .../the-lapply-and-sapply-functions-in-r.md | 4 + .../what-is-vectorization.md | 5 ++ r/r-core/loops-in-r/for-loops-in-r.md | 5 ++ r/r-core/loops-in-r/nesting-loops-in-r.md | 5 ++ r/r-core/loops-in-r/repeat-loops-in-r.md | 5 ++ r/r-core/loops-in-r/while-loops-in-r.md | 5 ++ .../programs-in-r/area-of-a-rectangle-r.md | 41 +-------- r/r-core/programs-in-r/calculator-r.md | 5 -- r/r-core/programs-in-r/factorial-r.md | 5 -- .../programs-in-r/fibonacci-sequence-r.md | 43 +-------- r/r-core/programs-in-r/fizz-buzz-r.md | 5 -- .../programs-in-r/prime-number-checker-r.md | 5 -- r/r-core/programs-in-r/reverse-a-string-r.md | 5 -- .../as-numeric.md | 4 + .../open-and-close-a-file.md | 5 +- .../readline-in-r.md | 4 + .../the-file-function.md | 29 +++--- .../writelines-in-r.md | 5 +- ...another-way-to-create-dictionaries-in-r.md | 44 +++++++--- .../dictionary-methods-in-r-ii.md | 6 +- .../dictionary-methods-in-r.md | 37 ++++---- .../intro-to-dictionaries-r.md | 6 +- .../unordered-data-types-in-r-ii.md | 6 ++ .../unoredered-data-types-in-r.md | 12 ++- .../assignment-operators-r.md | 5 +- .../basic-data-types-r.md | 5 +- .../combining-variables-in-r.md | 4 + .../creating-and-storing-variables-in-r.md | 5 ++ .../printing-variables-in-r.md | 13 ++- 59 files changed, 442 insertions(+), 281 deletions(-) create mode 100644 r/r-core/functions-in-r-ii/README.md rename r/r-core/{functions-in-r => functions-in-r-ii}/the-matrix-funtion-r.md (96%) create mode 100644 r/r-core/functions-in-r-ii/the-reduce-function-r.md create mode 100644 r/r-core/functions-in-r-ii/the-sum-function-r.md diff --git a/r/r-core/README.md b/r/r-core/README.md index 327f345c7e..6cf3519ffd 100644 --- a/r/r-core/README.md +++ b/r/r-core/README.md @@ -12,6 +12,7 @@ sections: - data-type-conversions - conditional-statements-in-r - functions-in-r + - functions-in-r-ii - environment-variables-in-r - loops-in-r - looping-techniques-in-r diff --git a/r/r-core/conditional-statements-in-r/if-else-in-r.md b/r/r-core/conditional-statements-in-r/if-else-in-r.md index c23cfa28c7..fc273d72cd 100644 --- a/r/r-core/conditional-statements-in-r/if-else-in-r.md +++ b/r/r-core/conditional-statements-in-r/if-else-in-r.md @@ -11,6 +11,11 @@ practiceQuestion: - fill-in-the-gap - type-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- diff --git a/r/r-core/conditional-statements-in-r/if-statements-in-r.md b/r/r-core/conditional-statements-in-r/if-statements-in-r.md index 5c7ed61c1b..cb50c6fabd 100644 --- a/r/r-core/conditional-statements-in-r/if-statements-in-r.md +++ b/r/r-core/conditional-statements-in-r/if-statements-in-r.md @@ -11,6 +11,10 @@ practiceQuestion: - fill-in-the-gap - type-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- diff --git a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md index b4ee65d252..3a4e44a1f8 100644 --- a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md +++ b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md @@ -90,10 +90,10 @@ result <- ifelse(x > 0, ifelse(x > 10, "x is greater than 10", "x is between 1 a # Print the result print(result) -# ??? +# "???" ``` -- `"x is between 1 and 10"` -- `"x is greater than 10"` -- `"x is 0 or negative"` +- `x is between 1 and 10` +- `x is greater than 10` +- `x is 0 or negative` - `Error` \ No newline at end of file diff --git a/r/r-core/conditional-statements-in-r/switch-statements-in-r.md b/r/r-core/conditional-statements-in-r/switch-statements-in-r.md index 111757c9e8..dc289df4ad 100644 --- a/r/r-core/conditional-statements-in-r/switch-statements-in-r.md +++ b/r/r-core/conditional-statements-in-r/switch-statements-in-r.md @@ -9,9 +9,11 @@ category: must-know practiceQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone - +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- # Switch Statements diff --git a/r/r-core/data-type-conversion-in-r/as-double-and-character-r.md b/r/r-core/data-type-conversion-in-r/as-double-and-character-r.md index 5a119aca2c..0e77ba8c23 100644 --- a/r/r-core/data-type-conversion-in-r/as-double-and-character-r.md +++ b/r/r-core/data-type-conversion-in-r/as-double-and-character-r.md @@ -11,6 +11,11 @@ practiceQuestion: - fill-in-the-gap - type-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- diff --git a/r/r-core/data-type-conversion-in-r/as-logical-and-vector-r.md b/r/r-core/data-type-conversion-in-r/as-logical-and-vector-r.md index 58a946ae5b..6597f1007e 100644 --- a/r/r-core/data-type-conversion-in-r/as-logical-and-vector-r.md +++ b/r/r-core/data-type-conversion-in-r/as-logical-and-vector-r.md @@ -11,7 +11,11 @@ practiceQuestion: - fill-in-the-gap - type-in-the-gap context: standalone - +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- # as.logical & as.vector @@ -84,6 +88,8 @@ v <- as.vector(c("True", "False", "True")) v <- as.logical(c("True", "False", "True")) ``` +??? + - `D)` - `A)` - `B)` @@ -108,6 +114,8 @@ v <- as.character(c(1, 0, 1)) v <- as.vector(c(1, 0, 1)) ``` +??? + - `A)` - `D)` - `B)` diff --git a/r/r-core/data-type-conversion-in-r/as-matrix-r.md b/r/r-core/data-type-conversion-in-r/as-matrix-r.md index 353476a418..77b6303976 100644 --- a/r/r-core/data-type-conversion-in-r/as-matrix-r.md +++ b/r/r-core/data-type-conversion-in-r/as-matrix-r.md @@ -11,6 +11,11 @@ practiceQuestion: - fill-in-the-gap - type-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- @@ -50,7 +55,6 @@ print(m) Which of the following will create a 3x3 matrix from a numeric vector? - ```r # A) m <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3) @@ -65,6 +69,8 @@ m <- as.matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 2, ncol = 4) m <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 2, ncol = 4) ``` +??? + - `B)` - `A)` - `C)` @@ -91,6 +97,8 @@ m <- matrix(c("a", "b", "c", "d", "e", "f", "g", "h"), nrow = 2, ncol = 4) m <- matrix(c("a", "b", "c", "d", "e", "f", "g", "h"), nrow = 4, ncol = 2) ``` +??? + - `B)` - `A)` - `C)` diff --git a/r/r-core/data-type-conversion-in-r/as-numeric-and-integer-r.md b/r/r-core/data-type-conversion-in-r/as-numeric-and-integer-r.md index a045ea516e..a11269ef82 100644 --- a/r/r-core/data-type-conversion-in-r/as-numeric-and-integer-r.md +++ b/r/r-core/data-type-conversion-in-r/as-numeric-and-integer-r.md @@ -11,6 +11,11 @@ practiceQuestion: - fill-in-the-gap - type-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- diff --git a/r/r-core/data-type-conversion-in-r/data-type-conversion.md b/r/r-core/data-type-conversion-in-r/data-type-conversion.md index 75af7ef984..823fdfb6b7 100644 --- a/r/r-core/data-type-conversion-in-r/data-type-conversion.md +++ b/r/r-core/data-type-conversion-in-r/data-type-conversion.md @@ -6,11 +6,6 @@ tags: - discussion type: normal category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone --- @@ -22,7 +17,6 @@ practiceQuestion: In **R**, it is often necessary to convert data from one type to another. For example, you may need to convert a string to a number, or a vector to a matrix. Here are some common functions for converting data types in **R**: - - `as.numeric`: Converts an object to numeric (integer or double) type. - `as.integer`: Converts an object to integer type. - `as.double`: Converts an object to double (floating point) type. @@ -39,36 +33,3 @@ Another way to check which data type a value has is with the `typeof()` method. We will discuss some examples on how to use them in the following insights. - ---- -## Practice - -Complete the code to finish the program: - -```r -calculate_area <- function(length, width) { - return(length * width) -} - -length <- 8 -width <- 5 - -area <- calculate_area(length, width) - -print(paste("The area of the rectangle is", area)) -``` - - - ---- -## Revision - -What is the basic data type for a vector of categorical variables in R? - -??? - -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file diff --git a/r/r-core/environment-variables-in-r/global-environment-variables-in-r.md b/r/r-core/environment-variables-in-r/global-environment-variables-in-r.md index 1acce1ce72..6a37ae98ac 100644 --- a/r/r-core/environment-variables-in-r/global-environment-variables-in-r.md +++ b/r/r-core/environment-variables-in-r/global-environment-variables-in-r.md @@ -10,6 +10,11 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- diff --git a/r/r-core/environment-variables-in-r/local-variables-in-r.md b/r/r-core/environment-variables-in-r/local-variables-in-r.md index 9e8f729768..a48e3a1129 100644 --- a/r/r-core/environment-variables-in-r/local-variables-in-r.md +++ b/r/r-core/environment-variables-in-r/local-variables-in-r.md @@ -10,6 +10,10 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- diff --git a/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md b/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md index 649b49951e..ecec6695b8 100644 --- a/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md +++ b/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md @@ -10,6 +10,10 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- diff --git a/r/r-core/functions-in-r-ii/README.md b/r/r-core/functions-in-r-ii/README.md new file mode 100644 index 0000000000..0b63e89fae --- /dev/null +++ b/r/r-core/functions-in-r-ii/README.md @@ -0,0 +1,13 @@ +name: Intro to Functions + +description: Function basics. + +insights: + - the-matrix-function-r + - the-sum-function-r + - the-reduce-function-r + + +aspects: + - workout + - deep \ No newline at end of file diff --git a/r/r-core/functions-in-r/the-matrix-funtion-r.md b/r/r-core/functions-in-r-ii/the-matrix-funtion-r.md similarity index 96% rename from r/r-core/functions-in-r/the-matrix-funtion-r.md rename to r/r-core/functions-in-r-ii/the-matrix-funtion-r.md index 9358763b2a..fc00b518ec 100644 --- a/r/r-core/functions-in-r/the-matrix-funtion-r.md +++ b/r/r-core/functions-in-r-ii/the-matrix-funtion-r.md @@ -10,6 +10,10 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- @@ -19,7 +23,6 @@ practiceQuestion: ## Content - The `matrix` function is a useful function in R that allows you to create a matrix, or a two-dimensional array, of data. Matrices are useful for storing and manipulating tabular data, and are often used for statistical and mathematical operations. Here is the basic syntax of the `matrix` function: diff --git a/r/r-core/functions-in-r-ii/the-reduce-function-r.md b/r/r-core/functions-in-r-ii/the-reduce-function-r.md new file mode 100644 index 0000000000..89f4270ced --- /dev/null +++ b/r/r-core/functions-in-r-ii/the-reduce-function-r.md @@ -0,0 +1,58 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# The reduce Function + +--- + +## Content + +The reduce function is a useful function in R that allows you to apply a function to a list or vector, and return a single value that is the result of the function applied to the elements of the list or vector. This can be useful for reducing a large dataset to a single summary statistic, or for applying a function to a list of values one element at a time. + +Here is the basic syntax of the reduce function: +```r +reduce(x, f, init, right = FALSE, accumulate = FALSE) +``` + +- `x` is the list or vector that you want to apply the function to. +- `f` is the function that you want to apply to the list or vector. +- `init` is an optional argument that specifies the initial value for the function. If `init` is not specified, the function is applied to the first two elements of the list or vector. +- `right` is an optional argument that specifies whether the function should be applied from left to right (if `right = FALSE`) or from right to left (`if right = TRUE`). +- `accumulate` is an optional argument that specifies whether the function should return a single value (`if accumulate = FALSE`) or a vector of intermediate results (`if accumulate = TRUE`). + +Here is an example of how to use the `reduce` function to apply a function to a list of values one element at a time: +```r +x <- list(1, 2, 3, 4, 5) +f <- function(x, y) x + y +reduce(x, f) +# 15 +``` + + +--- +## Practice + +In the following code snippet, what is the final value of result? + +```r +x <- c(1, 2, 3, 4, 5) +result <- reduce(x, `*`) +# ??? +``` + +- `120` +- `15` +- `5` +- `1` diff --git a/r/r-core/functions-in-r-ii/the-sum-function-r.md b/r/r-core/functions-in-r-ii/the-sum-function-r.md new file mode 100644 index 0000000000..75e459e05e --- /dev/null +++ b/r/r-core/functions-in-r-ii/the-sum-function-r.md @@ -0,0 +1,88 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# The sum Function + +--- + +## Content + +The `sum` function is a basic function in **R** that calculates the `sum` of a vector or array of numbers. It is often used in conjunction with other functions, such as `apply`, to perform operations on matrices or arrays. + +Here is the basic syntax of the `sum` function: +```r +sum(x, na.rm = FALSE, ...) +``` + +- `x` is the vector or array of numbers that you want to sum. +- `na.rm` is an optional argument that specifies whether to remove missing values (NA) from the calculation. If `na.rm` is `TRUE`, missing values are removed. If `na.rm` is `FALSE`, missing values are treated as zero. +- `...` are any additional arguments that you want to pass to the function. + +Here is an example of how to use the sum function to calculate the sum of a vector: +```r +vector <- c(1, 2, 3, 4, 5) +print(sum(vector)) +# 15 +``` + +Here is an example of how to use the sum function to calculate the sum of a matrix: +```r +matrix <- matrix(1:9, 3, 3) +print(matrix) +# [,1] [,2] [,3] +# [1,] 1 4 7 +# [2,] 2 5 8 +# [3,] 3 6 9 + +print(sum(matrix)) +# 45 +``` + +Note: the `sum` function is not vectorized, which means that it cannot operate on multiple vectors or arrays at the same time. If you want to calculate the `sum` of multiple vectors or arrays, you should use the Reduce function or loop through the elements one at a time. + + +--- +## Practice + +Which of the following statements is true about the `sum` function in **R**? + +- All of the above. +- The sum function returns the sum of all elements in an input vector. +- The sum function only works on vectors of numeric data. +- The sum function ignores NA values in the input vector. + +--- +## Revision + +What is the output of the following code? +```r +vec1 <- c(1, 2, 3) +vec2 <- c(4, 5, 6) +vec3 <- c(7, 8, 9) + +print(sum(vec1, vec2, vec3)) +# ??? +``` + + +- `45` +- `21` +- `15` +- `Error: invalid 'type' (list) of argument` \ No newline at end of file diff --git a/r/r-core/functions-in-r/README.md b/r/r-core/functions-in-r/README.md index e06dd2b08e..a33895746f 100644 --- a/r/r-core/functions-in-r/README.md +++ b/r/r-core/functions-in-r/README.md @@ -8,7 +8,6 @@ insights: - function-methods-in-r-ii - the-paste-function-in-r - the-paste-function-in-r-ii - - the-matrix-function-r aspects: diff --git a/r/r-core/functions-in-r/function-methods-in-r-ii.md b/r/r-core/functions-in-r/function-methods-in-r-ii.md index eb064f1d4f..2a92ede17c 100644 --- a/r/r-core/functions-in-r/function-methods-in-r-ii.md +++ b/r/r-core/functions-in-r/function-methods-in-r-ii.md @@ -10,6 +10,10 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- diff --git a/r/r-core/functions-in-r/function-methods-in-r.md b/r/r-core/functions-in-r/function-methods-in-r.md index 9c3cabe850..e060752f07 100644 --- a/r/r-core/functions-in-r/function-methods-in-r.md +++ b/r/r-core/functions-in-r/function-methods-in-r.md @@ -10,6 +10,11 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- diff --git a/r/r-core/functions-in-r/functions-in-r.md b/r/r-core/functions-in-r/functions-in-r.md index 30d6329ea4..c122b7dd98 100644 --- a/r/r-core/functions-in-r/functions-in-r.md +++ b/r/r-core/functions-in-r/functions-in-r.md @@ -10,6 +10,11 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- diff --git a/r/r-core/functions-in-r/the-paste-function-in-r-ii.md b/r/r-core/functions-in-r/the-paste-function-in-r-ii.md index 1eb6bcf8a5..76dce66aff 100644 --- a/r/r-core/functions-in-r/the-paste-function-in-r-ii.md +++ b/r/r-core/functions-in-r/the-paste-function-in-r-ii.md @@ -11,6 +11,10 @@ practiceQuestion: - fill-in-the-gap - type-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- diff --git a/r/r-core/functions-in-r/the-paste-function-in-r.md b/r/r-core/functions-in-r/the-paste-function-in-r.md index 8404ba5c81..1e4965573d 100644 --- a/r/r-core/functions-in-r/the-paste-function-in-r.md +++ b/r/r-core/functions-in-r/the-paste-function-in-r.md @@ -11,6 +11,10 @@ practiceQuestion: - fill-in-the-gap - type-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- @@ -24,23 +28,28 @@ The `paste` function in **R** is a versatile tool that allows you to combine or The most basic usage of the paste function is to combine two or more strings into a single string. Here is an example: ```r -paste("Hello", "world!") # "Hello world!" +paste("Hello", "world!") +# "Hello world!" ``` You can also specify a separator to use between the strings: ```r -paste("Hello", "world!", sep = " ") # "Hello world!" -paste("Hello", "world!", sep = "-") # "Hello-world!" +paste("Hello", "world!", sep = " ") +# "Hello world!" +paste("Hello", "world!", sep = "-") +# "Hello-world!" ``` The paste function can also combine variables, such as numbers or vectors: ```r x <- 10 y <- 20 -paste("The sum of x and y is", x + y) # "The sum of x and y is 30" +paste("The sum of x and y is", x + y) +# "The sum of x and y is 30" z <- c("red", "green", "blue") -paste("The colors are", z) # "The colors are red green blue" +paste("The colors are", z) +# "The colors are red green blue" ``` @@ -51,7 +60,8 @@ paste("The colors are", z) # "The colors are red green blue" Fill in the gap to combine the strings `"Hello"` and `"world!"` into a single string: ```r -paste(???, ???) # "Hello world!" +paste(???, ???) +# "Hello world!" ``` - `"Hello"` @@ -59,20 +69,15 @@ paste(???, ???) # "Hello world!" - `"Hello!", "world"` - `"Hi", "world!"` - - --- ## Revision - Which of the following lines of code will combine the strings `"Hello"` and `"world!"` into a single string, separated by a space? - ```r ??? ``` - - `paste("Hello", "world!", sep = " ")` - `paste("Hello", "world!", sep = "-")` - `paste("Hello", "world!", sep = ",")` diff --git a/r/r-core/intro-to-r/first-program-hello-world-r.md b/r/r-core/intro-to-r/first-program-hello-world-r.md index 0e9f09977f..c949a1376d 100644 --- a/r/r-core/intro-to-r/first-program-hello-world-r.md +++ b/r/r-core/intro-to-r/first-program-hello-world-r.md @@ -10,6 +10,10 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- diff --git a/r/r-core/intro-to-r/installing-r-locally.md b/r/r-core/intro-to-r/installing-r-locally.md index 0e32065a76..5c7912c5ae 100644 --- a/r/r-core/intro-to-r/installing-r-locally.md +++ b/r/r-core/intro-to-r/installing-r-locally.md @@ -6,10 +6,6 @@ tags: - discussion type: normal category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - context: standalone --- @@ -30,32 +26,6 @@ To install **R**, you can follow these steps: You can also install **R** on a server[1] or in the cloud, such as on [Amazon Web Services](https://aws.amazon.com/blogs/opensource/getting-started-with-r-on-amazon-web-services/) or [Google Cloud Platform](https://cloud.google.com/architecture/data-science-with-r-on-gcp-eda#ai_platform_notebooks). ---- -## Practice - -Which of the following is a basic data type in R? - -??? - -- `numeric` -- `integer` -- `matrix` -- `function` -- `data frame` - ---- -## Revision - -What is the basic data type for a vector of categorical variables in R? - -??? - -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` - --- ## Footnotes diff --git a/r/r-core/intro-to-r/what-is-r.md b/r/r-core/intro-to-r/what-is-r.md index a31677f9ef..b159378a19 100644 --- a/r/r-core/intro-to-r/what-is-r.md +++ b/r/r-core/intro-to-r/what-is-r.md @@ -38,12 +38,11 @@ plot(x, y) --- ## Practice -Let's try some **R** code! Do you remember how to print a message to the console? +Let's try some **R** code! Do you know how to print a message to the console? Don't worry; this is to get you comfortable with code. You'll learn all about how this works in the upcoming lessons. - ```r message <- "Hello, world!" ???(message) diff --git a/r/r-core/looping-techniques-in-r/apply-function.md b/r/r-core/looping-techniques-in-r/apply-function.md index 6d3370b3b1..7f900c7200 100644 --- a/r/r-core/looping-techniques-in-r/apply-function.md +++ b/r/r-core/looping-techniques-in-r/apply-function.md @@ -10,7 +10,11 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone - +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + --- # apply Function @@ -77,29 +81,26 @@ apply(matrix, c(1, 2), sum) You should consider using the `apply` function only when it is significantly faster than alternative approaches, such as looping through the elements one at a time. - --- ## Practice -Which of the following is a basic data type in R? +Which of the following is the correct syntax for the apply function? ??? -- `numeric` -- `integer` -- `matrix` -- `function` -- `data frame` +- `apply(X, MARGIN, FUN, ...)` +- `apply(X, FUN, MARGIN, ...)` +- `apply(MARGIN, X, FUN, ...)` +- `apply(X, MARGIN, ..., FUN)` --- ## Revision -What is the basic data type for a vector of categorical variables in R? +Which of the following will apply the `sum` function to each row of the matrix matrix? ??? -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file +- `apply(matrix, 1, sum)` +- `apply(matrix, 2, sum)` +- `apply(matrix, c(1, 2), sum)` +- `apply(matrix, c(2, 1), sum)` \ No newline at end of file diff --git a/r/r-core/looping-techniques-in-r/looping-techniques-in-r.md b/r/r-core/looping-techniques-in-r/looping-techniques-in-r.md index c09702cbfc..04c06feba6 100644 --- a/r/r-core/looping-techniques-in-r/looping-techniques-in-r.md +++ b/r/r-core/looping-techniques-in-r/looping-techniques-in-r.md @@ -6,10 +6,6 @@ tags: - discussion type: normal category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - context: standalone --- diff --git a/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md b/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md index 700d98b688..9718fac177 100644 --- a/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md +++ b/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md @@ -7,6 +7,11 @@ tags: type: normal category: must-know practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone +revisionQuestion: formats: - fill-in-the-gap context: standalone diff --git a/r/r-core/looping-techniques-in-r/statistical-functions-for-vectorization-in-r.md b/r/r-core/looping-techniques-in-r/statistical-functions-for-vectorization-in-r.md index d2154a29cf..2e8e6fe724 100644 --- a/r/r-core/looping-techniques-in-r/statistical-functions-for-vectorization-in-r.md +++ b/r/r-core/looping-techniques-in-r/statistical-functions-for-vectorization-in-r.md @@ -10,6 +10,10 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- diff --git a/r/r-core/looping-techniques-in-r/the-lapply-and-sapply-functions-in-r.md b/r/r-core/looping-techniques-in-r/the-lapply-and-sapply-functions-in-r.md index 6751f8b549..050a2cb060 100644 --- a/r/r-core/looping-techniques-in-r/the-lapply-and-sapply-functions-in-r.md +++ b/r/r-core/looping-techniques-in-r/the-lapply-and-sapply-functions-in-r.md @@ -10,6 +10,10 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- diff --git a/r/r-core/looping-techniques-in-r/what-is-vectorization.md b/r/r-core/looping-techniques-in-r/what-is-vectorization.md index 92e5caa7cd..7c8ee51324 100644 --- a/r/r-core/looping-techniques-in-r/what-is-vectorization.md +++ b/r/r-core/looping-techniques-in-r/what-is-vectorization.md @@ -7,6 +7,11 @@ tags: type: normal category: must-know practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone +revisionQuestion: formats: - fill-in-the-gap context: standalone diff --git a/r/r-core/loops-in-r/for-loops-in-r.md b/r/r-core/loops-in-r/for-loops-in-r.md index 166b3d048d..3735abf2fd 100644 --- a/r/r-core/loops-in-r/for-loops-in-r.md +++ b/r/r-core/loops-in-r/for-loops-in-r.md @@ -7,6 +7,11 @@ tags: type: normal category: must-know practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone +revisionQuestion: formats: - fill-in-the-gap context: standalone diff --git a/r/r-core/loops-in-r/nesting-loops-in-r.md b/r/r-core/loops-in-r/nesting-loops-in-r.md index 157ca7fc87..8b80346447 100644 --- a/r/r-core/loops-in-r/nesting-loops-in-r.md +++ b/r/r-core/loops-in-r/nesting-loops-in-r.md @@ -11,6 +11,11 @@ practiceQuestion: - fill-in-the-gap - type-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- diff --git a/r/r-core/loops-in-r/repeat-loops-in-r.md b/r/r-core/loops-in-r/repeat-loops-in-r.md index 34a8a90dd1..05a2dcc27b 100644 --- a/r/r-core/loops-in-r/repeat-loops-in-r.md +++ b/r/r-core/loops-in-r/repeat-loops-in-r.md @@ -7,6 +7,11 @@ tags: type: normal category: must-know practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone +revisionQuestion: formats: - fill-in-the-gap context: standalone diff --git a/r/r-core/loops-in-r/while-loops-in-r.md b/r/r-core/loops-in-r/while-loops-in-r.md index cd148d7e9e..2f1951d275 100644 --- a/r/r-core/loops-in-r/while-loops-in-r.md +++ b/r/r-core/loops-in-r/while-loops-in-r.md @@ -7,6 +7,11 @@ tags: type: normal category: must-know practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone +revisionQuestion: formats: - fill-in-the-gap context: standalone diff --git a/r/r-core/programs-in-r/area-of-a-rectangle-r.md b/r/r-core/programs-in-r/area-of-a-rectangle-r.md index 57f633d225..90adfec96a 100644 --- a/r/r-core/programs-in-r/area-of-a-rectangle-r.md +++ b/r/r-core/programs-in-r/area-of-a-rectangle-r.md @@ -6,12 +6,6 @@ tags: - discussion type: normal category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone - --- # Area of a rectangle @@ -63,37 +57,4 @@ width <- as.numeric(width) area <- calculate_area(length, width) print(paste("The area of the rectangle is", area)) -``` - ---- -## Practice - -Complete the code to finish the program: - -```r -calculate_area <- function(length, width) { - return(length * width) -} - -length <- 8 -width <- 5 - -area <- calculate_area(length, width) - -print(paste("The area of the rectangle is", area)) -``` - - - ---- -## Revision - -What is the basic data type for a vector of categorical variables in R? - -??? - -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file +``` \ No newline at end of file diff --git a/r/r-core/programs-in-r/calculator-r.md b/r/r-core/programs-in-r/calculator-r.md index b1d07a05bf..e29c141a59 100644 --- a/r/r-core/programs-in-r/calculator-r.md +++ b/r/r-core/programs-in-r/calculator-r.md @@ -6,11 +6,6 @@ tags: - discussion type: normal category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone --- diff --git a/r/r-core/programs-in-r/factorial-r.md b/r/r-core/programs-in-r/factorial-r.md index c5ff7a7bed..760d122c97 100644 --- a/r/r-core/programs-in-r/factorial-r.md +++ b/r/r-core/programs-in-r/factorial-r.md @@ -6,11 +6,6 @@ tags: - discussion type: normal category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone --- diff --git a/r/r-core/programs-in-r/fibonacci-sequence-r.md b/r/r-core/programs-in-r/fibonacci-sequence-r.md index 01435250f6..fd8e780a0b 100644 --- a/r/r-core/programs-in-r/fibonacci-sequence-r.md +++ b/r/r-core/programs-in-r/fibonacci-sequence-r.md @@ -6,11 +6,6 @@ tags: - discussion type: normal category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone --- @@ -44,40 +39,4 @@ for (i in 3:n) { a <- b b <- c } -``` - - - - ---- -## Practice - -Complete the code to finish the program: - -```r -calculate_area <- function(length, width) { - return(length * width) -} - -length <- 8 -width <- 5 - -area <- calculate_area(length, width) - -print(paste("The area of the rectangle is", area)) -``` - - - ---- -## Revision - -What is the basic data type for a vector of categorical variables in R? - -??? - -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file +``` \ No newline at end of file diff --git a/r/r-core/programs-in-r/fizz-buzz-r.md b/r/r-core/programs-in-r/fizz-buzz-r.md index 974002a483..c7fe74126d 100644 --- a/r/r-core/programs-in-r/fizz-buzz-r.md +++ b/r/r-core/programs-in-r/fizz-buzz-r.md @@ -6,11 +6,6 @@ tags: - discussion type: normal category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone --- diff --git a/r/r-core/programs-in-r/prime-number-checker-r.md b/r/r-core/programs-in-r/prime-number-checker-r.md index 6149984331..657dd2edc8 100644 --- a/r/r-core/programs-in-r/prime-number-checker-r.md +++ b/r/r-core/programs-in-r/prime-number-checker-r.md @@ -6,11 +6,6 @@ tags: - discussion type: normal category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone --- diff --git a/r/r-core/programs-in-r/reverse-a-string-r.md b/r/r-core/programs-in-r/reverse-a-string-r.md index 99719f3189..aacf58a058 100644 --- a/r/r-core/programs-in-r/reverse-a-string-r.md +++ b/r/r-core/programs-in-r/reverse-a-string-r.md @@ -6,11 +6,6 @@ tags: - discussion type: normal category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone --- diff --git a/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md b/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md index d4477ca82b..d256a1f244 100644 --- a/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md +++ b/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md @@ -11,6 +11,10 @@ practiceQuestion: - fill-in-the-gap - type-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- diff --git a/r/r-core/reading-and-writing-data-to-and-from-files/open-and-close-a-file.md b/r/r-core/reading-and-writing-data-to-and-from-files/open-and-close-a-file.md index ef82e6c943..ae7a949df5 100644 --- a/r/r-core/reading-and-writing-data-to-and-from-files/open-and-close-a-file.md +++ b/r/r-core/reading-and-writing-data-to-and-from-files/open-and-close-a-file.md @@ -9,7 +9,10 @@ category: must-know practiceQuestion: formats: - fill-in-the-gap - - type-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap context: standalone --- diff --git a/r/r-core/reading-and-writing-data-to-and-from-files/readline-in-r.md b/r/r-core/reading-and-writing-data-to-and-from-files/readline-in-r.md index c7837365e0..0efb1a05cc 100644 --- a/r/r-core/reading-and-writing-data-to-and-from-files/readline-in-r.md +++ b/r/r-core/reading-and-writing-data-to-and-from-files/readline-in-r.md @@ -11,6 +11,10 @@ practiceQuestion: - fill-in-the-gap - type-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- diff --git a/r/r-core/reading-and-writing-data-to-and-from-files/the-file-function.md b/r/r-core/reading-and-writing-data-to-and-from-files/the-file-function.md index 78cf09dec2..1ec8f748ba 100644 --- a/r/r-core/reading-and-writing-data-to-and-from-files/the-file-function.md +++ b/r/r-core/reading-and-writing-data-to-and-from-files/the-file-function.md @@ -11,6 +11,11 @@ practiceQuestion: - fill-in-the-gap - type-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- @@ -33,7 +38,7 @@ file(description, open = "", blocking = TRUE) The `file` function returns a file object that you can use to read or write data to the file. -Here is an example of how to use the file function to open a file for reading: +Here is an example of how to use the `file` function to open a file for reading: ```r file <- file("test.txt", "r") ``` @@ -47,26 +52,20 @@ close(file) In this example, we open the file `"test.txt"` for reading using the `file` function, and store the file object in the variable `file`. We then use the `readline` function to read a line of text from the file, and store it in the variable `line`. Finally, we close the file using the `close` function. - - --- ## Practice -To open a file for reading, you can use the file function with the open argument set to ???." +To open a file for reading, you can use the `file` function with the `open` argument set to "???". -??? - -- `"r"` -- `"w"` -- `"a"` +- `r` +- `w` +- `a` --- ## Revision -"To open a file for writing, you can use the file function with the open argument set to ???." - -??? +To open a file for writing, you can use the `file` function with the `open` argument set to "???". -- `"w"` -- `"r"` -- `"a"` \ No newline at end of file +- `w` +- `r` +- `a` \ No newline at end of file diff --git a/r/r-core/reading-and-writing-data-to-and-from-files/writelines-in-r.md b/r/r-core/reading-and-writing-data-to-and-from-files/writelines-in-r.md index 174ee8e3c9..00971017b9 100644 --- a/r/r-core/reading-and-writing-data-to-and-from-files/writelines-in-r.md +++ b/r/r-core/reading-and-writing-data-to-and-from-files/writelines-in-r.md @@ -9,7 +9,10 @@ category: must-know practiceQuestion: formats: - fill-in-the-gap - - type-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap context: standalone --- diff --git a/r/r-core/unordered-data-types-r/another-way-to-create-dictionaries-in-r.md b/r/r-core/unordered-data-types-r/another-way-to-create-dictionaries-in-r.md index 2f39b04e3c..a746566651 100644 --- a/r/r-core/unordered-data-types-r/another-way-to-create-dictionaries-in-r.md +++ b/r/r-core/unordered-data-types-r/another-way-to-create-dictionaries-in-r.md @@ -10,7 +10,11 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone - +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- # Another Way to Create Dictionaries @@ -67,26 +71,38 @@ You can also loop over the key-value pairs in a dictionary using the map() funct map(my_dict1, print) # prints the key-value pairs in my_dict1 ``` - - --- ## Practice -Which of the following is **NOT** a way to access an element in a list in **R**? +Create a dictionary using the `dictionary()` method from the "purrr" package: -- `list.key` -- `list[[1]]` -- `list$key` -- `list[1]` +```r +my_dict ??? ???( + a = 1, + b = 2, + c = 3 +) +``` + +- `<-` +- `dictionary` +- `dictionary(` +- `<--` --- ## Revision -What function can be used to get the number of elements in a list in R? +Create a dictionary using the `dict()` method from the "hash": -??? +```r +my_dict ??? ???( + a = 1, + b = 2, + c = 3 +) +``` -- `length()` -- `size()` -- `count()` -- `lengths()` \ No newline at end of file +- `<-` +- `dict` +- `dict(` +- `<--` \ No newline at end of file diff --git a/r/r-core/unordered-data-types-r/dictionary-methods-in-r-ii.md b/r/r-core/unordered-data-types-r/dictionary-methods-in-r-ii.md index 1a12ac3d2e..229c387fdb 100644 --- a/r/r-core/unordered-data-types-r/dictionary-methods-in-r-ii.md +++ b/r/r-core/unordered-data-types-r/dictionary-methods-in-r-ii.md @@ -10,7 +10,11 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone - +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- # More about Dictionaries in R diff --git a/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md b/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md index 32e5cddb15..2d6e203344 100644 --- a/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md +++ b/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md @@ -9,6 +9,12 @@ category: must-know practiceQuestion: formats: - fill-in-the-gap + - type-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap context: standalone --- @@ -49,30 +55,29 @@ print(names(square_numbers)) # "1" "2" "3" "4" "5" ``` - --- ## Practice -Complete the following code snippet to make a duplicate of the variable `my_house` called `new_house`: +Complete the following code snippet remove all elements from the variable `my_house`: ```r -my_house <- list(bedrooms: 2, bathrooms: 2, garden: TRUE) +???(my_house) -new_house <- ???.??? +print(my_house) +# NULL ``` -- my_house -- duplicate() -- clone() -- copy() -- duplicate +- `rm` +- `remove` +- `clone` +- `copy` +- `delete` --- ## Revision What function can be used to return the names of the elements in a dictionary as a character vector? - ```r english_to_french <- list(apple: 'pomme', orange: 'orange') @@ -80,11 +85,7 @@ english_to_french.??? # "orange" "apple" ``` -- names() -- keys() -- contents() -- items() - ---- -## Footnotes - +- `names()` +- `keys()` +- `contents()` +- `items()` \ No newline at end of file diff --git a/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md b/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md index 6313c4c690..a4c27788d3 100644 --- a/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md +++ b/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md @@ -10,7 +10,11 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone - +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- # Introduction to Dictionaries in R diff --git a/r/r-core/unordered-data-types-r/unordered-data-types-in-r-ii.md b/r/r-core/unordered-data-types-r/unordered-data-types-in-r-ii.md index 664d3ec7be..a708ec73e7 100644 --- a/r/r-core/unordered-data-types-r/unordered-data-types-in-r-ii.md +++ b/r/r-core/unordered-data-types-r/unordered-data-types-in-r-ii.md @@ -9,6 +9,12 @@ category: must-know practiceQuestion: formats: - fill-in-the-gap + - type-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap context: standalone --- diff --git a/r/r-core/unordered-data-types-r/unoredered-data-types-in-r.md b/r/r-core/unordered-data-types-r/unoredered-data-types-in-r.md index ca42959b84..80e29767bf 100644 --- a/r/r-core/unordered-data-types-r/unoredered-data-types-in-r.md +++ b/r/r-core/unordered-data-types-r/unoredered-data-types-in-r.md @@ -10,7 +10,11 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone - +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- # Unordered Data Types in R @@ -80,14 +84,14 @@ A ??? is a ??? array of data elements of ??? data type. --- ## Revision -Finish the code to create a *numeric* vector called `numers`: +Finish the code to create a *character* vector called `numers`: ```r ??? <- ???( - 1, 2, 3, 4, 5 + "1", "2", "3", "4", "5" ) print(numbers) -# [1] 1 2 3 4 5 +# "1" "2" "3" "4" "5" ``` - `numbers` diff --git a/r/r-core/variables-and-data-types/assignment-operators-r.md b/r/r-core/variables-and-data-types/assignment-operators-r.md index 213ce09816..76ca9e0e2d 100644 --- a/r/r-core/variables-and-data-types/assignment-operators-r.md +++ b/r/r-core/variables-and-data-types/assignment-operators-r.md @@ -10,7 +10,10 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone - +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- # Assignment Operators in R diff --git a/r/r-core/variables-and-data-types/basic-data-types-r.md b/r/r-core/variables-and-data-types/basic-data-types-r.md index ca0f62ce75..85e813b7e9 100644 --- a/r/r-core/variables-and-data-types/basic-data-types-r.md +++ b/r/r-core/variables-and-data-types/basic-data-types-r.md @@ -10,7 +10,10 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone - +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- # Basic Data Types in R diff --git a/r/r-core/variables-and-data-types/combining-variables-in-r.md b/r/r-core/variables-and-data-types/combining-variables-in-r.md index ec38eda46c..af53506118 100644 --- a/r/r-core/variables-and-data-types/combining-variables-in-r.md +++ b/r/r-core/variables-and-data-types/combining-variables-in-r.md @@ -10,6 +10,10 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone --- diff --git a/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md b/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md index 4e2d55d623..9020b35e20 100644 --- a/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md +++ b/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md @@ -10,6 +10,11 @@ practiceQuestion: formats: - fill-in-the-gap context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone --- diff --git a/r/r-core/variables-and-data-types/printing-variables-in-r.md b/r/r-core/variables-and-data-types/printing-variables-in-r.md index 4bdc87d43a..0527bf95c1 100644 --- a/r/r-core/variables-and-data-types/printing-variables-in-r.md +++ b/r/r-core/variables-and-data-types/printing-variables-in-r.md @@ -32,14 +32,13 @@ cat("Hello, world!") --- ## Practice -Which of the following is the correct way to store the value `5` in a variable `x`? - -??? +Print a message to the console without adding a newline character after the message: +```r +???("Hello, world!") +``` -- x <- 5 -- x = 5 -- x < 5 -- x =< 5 +- `cat` +- `print` --- ## Footnotes From 4a1e58cbb2782bc1b64d43fec371d78019e685b6 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Fri, 6 Jan 2023 11:17:58 +0100 Subject: [PATCH 325/390] fix errors --- CHANGELOG.md | 5 +++++ r/r-core/README.md | 2 +- .../what-are-conditional-statements-r.md | 5 ----- ...data-type-conversion.md => data-type-conversion-r.md} | 0 ...{the-matrix-funtion-r.md => the-matrix-function-r.md} | 0 r/r-core/intro-to-r/why-learn-r.md | 5 ----- .../math-functions-for-vectorization-in-r.md | 9 --------- r/r-core/programs-in-r/README.md | 2 +- r/r-core/unordered-data-types-r/README.md | 4 ++-- ...d-data-types-in-r.md => unordered-data-types-in-r.md} | 0 .../creating-and-storing-variables-in-r.md | 2 +- 11 files changed, 10 insertions(+), 24 deletions(-) rename r/r-core/data-type-conversion-in-r/{data-type-conversion.md => data-type-conversion-r.md} (100%) rename r/r-core/functions-in-r-ii/{the-matrix-funtion-r.md => the-matrix-function-r.md} (100%) rename r/r-core/unordered-data-types-r/{unoredered-data-types-in-r.md => unordered-data-types-in-r.md} (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index a920843c93..1631ec0c27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## January 6th 2023 + +### Added +- [Intro to R - Topic - Add new topic](https://github.com/enkidevs/curriculum/pull/3150) + ## January 4th 2023 ### Added diff --git a/r/r-core/README.md b/r/r-core/README.md index 6cf3519ffd..f82eb5cc61 100644 --- a/r/r-core/README.md +++ b/r/r-core/README.md @@ -9,7 +9,7 @@ sections: - intro-to-r - variables-and-data-types - unordered-data-types-r - - data-type-conversions + - data-type-conversions-in-r - conditional-statements-in-r - functions-in-r - functions-in-r-ii diff --git a/r/r-core/conditional-statements-in-r/what-are-conditional-statements-r.md b/r/r-core/conditional-statements-in-r/what-are-conditional-statements-r.md index 7430e77d85..020ceec5ea 100644 --- a/r/r-core/conditional-statements-in-r/what-are-conditional-statements-r.md +++ b/r/r-core/conditional-statements-in-r/what-are-conditional-statements-r.md @@ -6,11 +6,6 @@ tags: - discussion type: normal category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone --- diff --git a/r/r-core/data-type-conversion-in-r/data-type-conversion.md b/r/r-core/data-type-conversion-in-r/data-type-conversion-r.md similarity index 100% rename from r/r-core/data-type-conversion-in-r/data-type-conversion.md rename to r/r-core/data-type-conversion-in-r/data-type-conversion-r.md diff --git a/r/r-core/functions-in-r-ii/the-matrix-funtion-r.md b/r/r-core/functions-in-r-ii/the-matrix-function-r.md similarity index 100% rename from r/r-core/functions-in-r-ii/the-matrix-funtion-r.md rename to r/r-core/functions-in-r-ii/the-matrix-function-r.md diff --git a/r/r-core/intro-to-r/why-learn-r.md b/r/r-core/intro-to-r/why-learn-r.md index 610d7da564..577447cebb 100644 --- a/r/r-core/intro-to-r/why-learn-r.md +++ b/r/r-core/intro-to-r/why-learn-r.md @@ -9,11 +9,6 @@ type: normal category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - context: standalone - --- # Why It's Good to Learn R diff --git a/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md b/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md index 9718fac177..b92a0c028d 100644 --- a/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md +++ b/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md @@ -102,12 +102,3 @@ vector <- vector * 2 + 1 - `1 3 5 7 9 11 13 15 17 19` - `2 4 6 8 10 12 14 16 18 20` - `1 2 3 4 5 6 7 8 9 10` - ---- -## Footnotes - -[1: Parallel Processing] -Parallel processing is the ability of a computer to perform multiple operations at the same time, using multiple processors or cores. Vectorization allows you to take advantage of parallel processing, because it allows the computer to perform the operations in parallel, rather than sequentially. This can significantly reduce the processing time, especially when working with large data sets. - -[2: Sequential Processing] -Sequential processing is the ability of a computer to perform one operation at a time, in a specified order. Looping through elements one at a time is an example of sequential processing, because the computer processes each element one at a time, in the order that they appear. Vectorization allows you to perform operations on arrays or vectors, rather than looping through the elements one at a time, which can be faster because it allows the computer to perform the operations in parallel. \ No newline at end of file diff --git a/r/r-core/programs-in-r/README.md b/r/r-core/programs-in-r/README.md index 3b65f8988b..0c3df7d678 100644 --- a/r/r-core/programs-in-r/README.md +++ b/r/r-core/programs-in-r/README.md @@ -6,7 +6,7 @@ insights: - area-of-a-rectangle-r - fizz-buzz-r - calculator-r - - fibonacci-sequence-in-r + - fibonacci-sequence-r - prime-number-checker-r - factorial-r - reverse-a-string-r diff --git a/r/r-core/unordered-data-types-r/README.md b/r/r-core/unordered-data-types-r/README.md index ed0ec0a88a..c2144381ce 100644 --- a/r/r-core/unordered-data-types-r/README.md +++ b/r/r-core/unordered-data-types-r/README.md @@ -3,8 +3,8 @@ name: Unordered Data Types description: Learn about different data types R has to offer. insights: - - unoredered-data-types-in-r - - unoredered-data-types-in-r-ii + - unordered-data-types-in-r + - unordered-data-types-in-r-ii - intro-to-dictionaries-r - dictionary-methods-in-r - dictionary-methods-in-r-ii diff --git a/r/r-core/unordered-data-types-r/unoredered-data-types-in-r.md b/r/r-core/unordered-data-types-r/unordered-data-types-in-r.md similarity index 100% rename from r/r-core/unordered-data-types-r/unoredered-data-types-in-r.md rename to r/r-core/unordered-data-types-r/unordered-data-types-in-r.md diff --git a/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md b/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md index 9020b35e20..96af5d4ada 100644 --- a/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md +++ b/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md @@ -68,7 +68,7 @@ Which of the following is **NOT** a way to create a variable in **R**? - `z = c(x, y)` --- -## Practice +## Revision Finish the code to create a new variable called `z` by summing the values of the `x` and `y` variables. Print the new variable. ```r From a9dd3d1ba466213caf46d1b4c5efb65db272244e Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Fri, 6 Jan 2023 11:19:18 +0100 Subject: [PATCH 326/390] rename folder --- .../README.md | 0 .../as-double-and-character-r.md | 0 .../as-logical-and-vector-r.md | 0 .../as-matrix-r.md | 0 .../as-numeric-and-integer-r.md | 0 .../data-type-conversion-r.md | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename r/r-core/{data-type-conversion-in-r => data-type-conversions-in-r}/README.md (100%) rename r/r-core/{data-type-conversion-in-r => data-type-conversions-in-r}/as-double-and-character-r.md (100%) rename r/r-core/{data-type-conversion-in-r => data-type-conversions-in-r}/as-logical-and-vector-r.md (100%) rename r/r-core/{data-type-conversion-in-r => data-type-conversions-in-r}/as-matrix-r.md (100%) rename r/r-core/{data-type-conversion-in-r => data-type-conversions-in-r}/as-numeric-and-integer-r.md (100%) rename r/r-core/{data-type-conversion-in-r => data-type-conversions-in-r}/data-type-conversion-r.md (100%) diff --git a/r/r-core/data-type-conversion-in-r/README.md b/r/r-core/data-type-conversions-in-r/README.md similarity index 100% rename from r/r-core/data-type-conversion-in-r/README.md rename to r/r-core/data-type-conversions-in-r/README.md diff --git a/r/r-core/data-type-conversion-in-r/as-double-and-character-r.md b/r/r-core/data-type-conversions-in-r/as-double-and-character-r.md similarity index 100% rename from r/r-core/data-type-conversion-in-r/as-double-and-character-r.md rename to r/r-core/data-type-conversions-in-r/as-double-and-character-r.md diff --git a/r/r-core/data-type-conversion-in-r/as-logical-and-vector-r.md b/r/r-core/data-type-conversions-in-r/as-logical-and-vector-r.md similarity index 100% rename from r/r-core/data-type-conversion-in-r/as-logical-and-vector-r.md rename to r/r-core/data-type-conversions-in-r/as-logical-and-vector-r.md diff --git a/r/r-core/data-type-conversion-in-r/as-matrix-r.md b/r/r-core/data-type-conversions-in-r/as-matrix-r.md similarity index 100% rename from r/r-core/data-type-conversion-in-r/as-matrix-r.md rename to r/r-core/data-type-conversions-in-r/as-matrix-r.md diff --git a/r/r-core/data-type-conversion-in-r/as-numeric-and-integer-r.md b/r/r-core/data-type-conversions-in-r/as-numeric-and-integer-r.md similarity index 100% rename from r/r-core/data-type-conversion-in-r/as-numeric-and-integer-r.md rename to r/r-core/data-type-conversions-in-r/as-numeric-and-integer-r.md diff --git a/r/r-core/data-type-conversion-in-r/data-type-conversion-r.md b/r/r-core/data-type-conversions-in-r/data-type-conversion-r.md similarity index 100% rename from r/r-core/data-type-conversion-in-r/data-type-conversion-r.md rename to r/r-core/data-type-conversions-in-r/data-type-conversion-r.md From 881b1edf4c40002eb0e5a22085f978657a3c1733 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 6 Jan 2023 13:39:56 +0100 Subject: [PATCH 327/390] Update README.md replace tech interviews photo with an nft one --- intro-to-nfts/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/intro-to-nfts/README.md b/intro-to-nfts/README.md index 2282bcb74a..24a5d426c6 100644 --- a/intro-to-nfts/README.md +++ b/intro-to-nfts/README.md @@ -1,6 +1,6 @@ name: Intro to NFTs -icon: 'https://img.enkipro.com/db79b7f9f0366f0c0e4183480a71fb91.png' +icon: 'https://img.enkipro.com/5978c30944938649dce922e2d89eb1a3.png' color: 'ffe0a6' @@ -10,4 +10,4 @@ language: python availableAspects: - introduction - - workout \ No newline at end of file + - workout From 0dc82ae61e7c0cc3f87a1ce02dc5ca65ad2e37b7 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 6 Jan 2023 13:40:43 +0100 Subject: [PATCH 328/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a920843c93..f7a3b147d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## January 6th 2023 + +### Changed +- [Intro To NFTs - Topic Icon - Replace icon](https://github.com/enkidevs/curriculum/pull/3151) + ## January 4th 2023 ### Added From 0514365e738907f49d045e376e2ad91353e88140 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 6 Jan 2023 15:23:48 +0100 Subject: [PATCH 329/390] Update README.md --- intro-to-nfts/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/intro-to-nfts/README.md b/intro-to-nfts/README.md index 24a5d426c6..311b918b36 100644 --- a/intro-to-nfts/README.md +++ b/intro-to-nfts/README.md @@ -1,6 +1,6 @@ name: Intro to NFTs -icon: 'https://img.enkipro.com/5978c30944938649dce922e2d89eb1a3.png' +icon: 'https://img.enkipro.com/dd95eab07fda8ae329bde32325d7e775.png' color: 'ffe0a6' From c7863fb999d9648b4f9e1c9fabc3232099a0a81a Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 10 Jan 2023 11:57:18 +0100 Subject: [PATCH 330/390] Update what-is-jitter.md --- comp-sci/networking/metrics/what-is-jitter.md | 1 - 1 file changed, 1 deletion(-) diff --git a/comp-sci/networking/metrics/what-is-jitter.md b/comp-sci/networking/metrics/what-is-jitter.md index 760f60e937..e310dcc7b1 100644 --- a/comp-sci/networking/metrics/what-is-jitter.md +++ b/comp-sci/networking/metrics/what-is-jitter.md @@ -8,7 +8,6 @@ links: revisionQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone --- From 184eec6a6ccfa2d4c33d80d0ac47dfca5fd52095 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 10 Jan 2023 11:58:02 +0100 Subject: [PATCH 331/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7a3b147d5..313dd5a2b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## January 10th 2023 + +### Changed +- [Comp sci - What is jitter - Remove type in the gap](https://github.com/enkidevs/curriculum/pull/3152) + ## January 6th 2023 ### Changed From 929cedb3bc1735df997046b3140fa6d6734cdf98 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 12 Jan 2023 15:23:23 +0100 Subject: [PATCH 332/390] Update lets-use-a-variable.md --- .../coding-intro-core/variables-and-data/lets-use-a-variable.md | 1 - 1 file changed, 1 deletion(-) diff --git a/coding-intro/coding-intro-core/variables-and-data/lets-use-a-variable.md b/coding-intro/coding-intro-core/variables-and-data/lets-use-a-variable.md index f784146f40..2e9a23909e 100644 --- a/coding-intro/coding-intro-core/variables-and-data/lets-use-a-variable.md +++ b/coding-intro/coding-intro-core/variables-and-data/lets-use-a-variable.md @@ -5,7 +5,6 @@ category: must-know practiceQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone revisionQuestion: formats: From a51c41c1ed8d8f24f26b9a326bb685310634e47c Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Thu, 12 Jan 2023 15:28:32 +0100 Subject: [PATCH 333/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 11ae115a38..44cf5a17f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## January 12th 2023 + +### Changed +- [Coding intro - Lets use a variable - Remove type in the gap](https://github.com/enkidevs/curriculum/pull/3153) + ## January 11th 2023 ### Fixed From 1834e12e4b2237540ef5276d52d99de6a172f96b Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 17 Jan 2023 14:24:06 +0100 Subject: [PATCH 334/390] Update comments.md Fix typo in code example and remove colon after question mark in pq --- web/html/html-structure/comments.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/web/html/html-structure/comments.md b/web/html/html-structure/comments.md index f52686530b..f35a519120 100755 --- a/web/html/html-structure/comments.md +++ b/web/html/html-structure/comments.md @@ -39,8 +39,8 @@ Example: <!-- Single line comment --> <!-- -<h1 Some header</h1> -<p>Random paragraph.</p> +<h1> Some header </h1> +<p> Random paragraph. </p> <a href="https://www.enki.com"> This is a link @@ -53,7 +53,7 @@ Example: ## Practice -In regards to HTML comments, which of the following is true?: +In regards to HTML comments, which of the following is true? ??? From c3b68c3d2dd0d4460bd907e66fedcb645b2c02d1 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 17 Jan 2023 14:48:39 +0100 Subject: [PATCH 335/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 44cf5a17f1..3bb39f4835 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +### January 17th 2023 + +### Fixed +-[Html - comments - fix typos](https://github.com/enkidevs/curriculum/pull/3154) + ## January 12th 2023 ### Changed From 6c339c58a089dde34c8d6706672f15f9728e35dd Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 17 Jan 2023 14:49:07 +0100 Subject: [PATCH 336/390] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bb39f4835..b4d1526bf3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,7 +48,7 @@ Types of change: ### Fixed -### January 17th 2023 +## January 17th 2023 ### Fixed -[Html - comments - fix typos](https://github.com/enkidevs/curriculum/pull/3154) From 6d3dcd71a4a53ddc8f232b1237e2af95f40c788f Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 23 Jan 2023 10:17:35 +0100 Subject: [PATCH 337/390] Update README.md --- tech-interviews/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/tech-interviews/README.md b/tech-interviews/README.md index 541f66d92c..056499b9da 100644 --- a/tech-interviews/README.md +++ b/tech-interviews/README.md @@ -10,3 +10,4 @@ language: python availableAspects: - introduction + - workout From b6f2cd94b307a3700838fa9afbd7a18e4fc27228 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 23 Jan 2023 10:19:48 +0100 Subject: [PATCH 338/390] Update CHANGELOG.md --- CHANGELOG.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b4d1526bf3..41c4053d28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,10 +48,15 @@ Types of change: ### Fixed +## January 23rd 2023 + +### Added +- [Tech Interviews - Topic - Add workout aspect](https://github.com/enkidevs/curriculum/pull/3155) + ## January 17th 2023 ### Fixed --[Html - comments - fix typos](https://github.com/enkidevs/curriculum/pull/3154) +- [Html - comments - fix typos](https://github.com/enkidevs/curriculum/pull/3154) ## January 12th 2023 From efd87dda70b703d422fd7d2da0d38d3f824b5c49 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Mon, 23 Jan 2023 17:43:46 +0100 Subject: [PATCH 339/390] change anders links to new domain --- .../building-the-ledger/bc-practice-distributed.md | 4 ++-- .../building-the-ledger/bc-practice-transaction.md | 4 ++-- .../the-blockchain/bc-practice-blockchain.md | 4 ++-- .../the-blockchain/bc-practice-blocks.md | 4 ++-- .../blockchain-fundamentals/the-blockchain/blocks-ii.md | 2 +- .../blockchain-fundamentals/wallets/bc-practice-identity.md | 4 ++-- .../blockchain-fundamentals/wallets/bc-practice-signing.md | 4 ++-- 7 files changed, 13 insertions(+), 13 deletions(-) diff --git a/blockchain/blockchain-fundamentals/building-the-ledger/bc-practice-distributed.md b/blockchain/blockchain-fundamentals/building-the-ledger/bc-practice-distributed.md index 9311cbde7d..bcc646671e 100644 --- a/blockchain/blockchain-fundamentals/building-the-ledger/bc-practice-distributed.md +++ b/blockchain/blockchain-fundamentals/building-the-ledger/bc-practice-distributed.md @@ -1,8 +1,8 @@ --- author: mihaiberq type: exercise -link: 'https://anders.com/blockchain/distributed.html' -linkType: anders +link: 'https://andersbrownworth.com/blockchain/distributed' +linkType: andersbrownworth answer: 00008e599d1733a484631fca41fd8fcd0a39d9c08f87f95bfdadf8101c6189f6 links: - '[Demo for the website](https://youtu.be/_160oMzblY8?t=559){video}' diff --git a/blockchain/blockchain-fundamentals/building-the-ledger/bc-practice-transaction.md b/blockchain/blockchain-fundamentals/building-the-ledger/bc-practice-transaction.md index 2615c520c3..a7b406bd28 100644 --- a/blockchain/blockchain-fundamentals/building-the-ledger/bc-practice-transaction.md +++ b/blockchain/blockchain-fundamentals/building-the-ledger/bc-practice-transaction.md @@ -1,8 +1,8 @@ --- author: mihaiberq type: exercise -link: 'https://anders.com/blockchain/tokens.html' -linkType: anders +link: 'https://andersbrownworth.com/blockchain/tokens' +linkType: andersbrownworth links: - '[Demo for the website](https://youtu.be/_160oMzblY8?t=711){video}' --- diff --git a/blockchain/blockchain-fundamentals/the-blockchain/bc-practice-blockchain.md b/blockchain/blockchain-fundamentals/the-blockchain/bc-practice-blockchain.md index 51fefc3d29..14c8d383de 100644 --- a/blockchain/blockchain-fundamentals/the-blockchain/bc-practice-blockchain.md +++ b/blockchain/blockchain-fundamentals/the-blockchain/bc-practice-blockchain.md @@ -1,8 +1,8 @@ --- author: mihaiberq type: exercise -link: 'https://anders.com/blockchain/blockchain.html' -linkType: anders +link: 'https://andersbrownworth.com/blockchain/blockchain' +linkType: andersbrownworth answer: '5161,22336,13883' links: - '[Demo for the website](https://www.youtube.com/watch?v=_160oMzblY8){video}' diff --git a/blockchain/blockchain-fundamentals/the-blockchain/bc-practice-blocks.md b/blockchain/blockchain-fundamentals/the-blockchain/bc-practice-blocks.md index 5f56a0a71f..e86265ab8e 100644 --- a/blockchain/blockchain-fundamentals/the-blockchain/bc-practice-blocks.md +++ b/blockchain/blockchain-fundamentals/the-blockchain/bc-practice-blocks.md @@ -1,8 +1,8 @@ --- author: mihaiberq type: exercise -link: 'https://anders.com/blockchain/block.html' -linkType: anders +link: 'https://andersbrownworth.com/blockchain/block' +linkType: andersbrownworth answer: 3996 links: - '[Demo for the website](https://www.youtube.com/watch?v=_160oMzblY8){video}' diff --git a/blockchain/blockchain-fundamentals/the-blockchain/blocks-ii.md b/blockchain/blockchain-fundamentals/the-blockchain/blocks-ii.md index 31e46f7f80..9e3c49f850 100644 --- a/blockchain/blockchain-fundamentals/the-blockchain/blocks-ii.md +++ b/blockchain/blockchain-fundamentals/the-blockchain/blocks-ii.md @@ -5,7 +5,7 @@ category: must-know links: - >- [Interactive tutorial of how blocks are - built](https://anders.com/blockchain/){website} + built](https://andersbrownworth.com/blockchain/){website} practiceQuestion: formats: - fill-in-the-gap diff --git a/blockchain/blockchain-fundamentals/wallets/bc-practice-identity.md b/blockchain/blockchain-fundamentals/wallets/bc-practice-identity.md index 6bb410a54f..09fb7c09f5 100644 --- a/blockchain/blockchain-fundamentals/wallets/bc-practice-identity.md +++ b/blockchain/blockchain-fundamentals/wallets/bc-practice-identity.md @@ -1,8 +1,8 @@ --- author: mihaiberq type: exercise -link: 'https://anders.com/blockchain/public-private-keys/keys.html' -linkType: anders +link: 'https://andersbrownworth.com/blockchain/public-private-keys/keys' +linkType: andersbrownworth answer: >- 42b698a0f0a4041b77e63488ad48c23e8e8838dd1fb7520408b121697b782ef222ee976351a7fe808101c7e79b040e5cb16afe6aa152b87e398d160c306a31bac links: diff --git a/blockchain/blockchain-fundamentals/wallets/bc-practice-signing.md b/blockchain/blockchain-fundamentals/wallets/bc-practice-signing.md index 2650ed2359..e8721e2236 100644 --- a/blockchain/blockchain-fundamentals/wallets/bc-practice-signing.md +++ b/blockchain/blockchain-fundamentals/wallets/bc-practice-signing.md @@ -1,8 +1,8 @@ --- author: mihaiberq type: exercise -link: 'https://anders.com/blockchain/public-private-keys/transaction.html' -linkType: anders +link: 'https://andersbrownworth.com/blockchain/public-private-keys/transaction' +linkType: andersbrownworth links: - '[Demo for the website](https://youtu.be/xIDL_akeras?t=153){video}' - >- From d92129bcd1a317fe6f9c77b83045bbd150220979 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Mon, 23 Jan 2023 17:45:26 +0100 Subject: [PATCH 340/390] add changelog --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41c4053d28..bd05abc1a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,8 +48,12 @@ Types of change: ### Fixed + ## January 23rd 2023 +### Fixed +- [Blockchain - Multiple Insights - Update domain for anders.com links ](https://github.com/enkidevs/curriculum/pull/3156) + ### Added - [Tech Interviews - Topic - Add workout aspect](https://github.com/enkidevs/curriculum/pull/3155) From c958beda9219b50bc884f445252223a54ced7611 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 23 Jan 2023 18:46:47 +0100 Subject: [PATCH 341/390] Update tsc-classes-and-interfaces-intro.md --- .../tsc-classes-and-interfaces-intro.md | 1 - 1 file changed, 1 deletion(-) diff --git a/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-classes-and-interfaces-intro.md b/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-classes-and-interfaces-intro.md index 62161bff44..364a41bd95 100644 --- a/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-classes-and-interfaces-intro.md +++ b/typescript/typescript-introduction/tsc-classes-and-interfaces/tsc-classes-and-interfaces-intro.md @@ -9,7 +9,6 @@ links: practiceQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone revisionQuestion: formats: From 2479502f4e0e5689ec5f6ad7a0d3fdf75fa158c5 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 23 Jan 2023 19:42:46 +0100 Subject: [PATCH 342/390] Update CHANGELOG.md --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41c4053d28..6c2a71393c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,9 @@ Types of change: ## January 23rd 2023 +### Changed +- [Typescript - Classes and Interfaces - remove type in teh gap](https://github.com/enkidevs/curriculum/pull/3157) + ### Added - [Tech Interviews - Topic - Add workout aspect](https://github.com/enkidevs/curriculum/pull/3155) From 0ae85ea5f9e2f0e55b36d4c90574f5496f1edabe Mon Sep 17 00:00:00 2001 From: Nemanja Stojanovic <n.stojanovic035@gmail.com> Date: Tue, 31 Jan 2023 22:00:19 +0100 Subject: [PATCH 343/390] Update accessing-dictionary-elements.md --- .../collections/accessing-dictionary-elements.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/coding-intro/coding-intro-core/collections/accessing-dictionary-elements.md b/coding-intro/coding-intro-core/collections/accessing-dictionary-elements.md index 5cd0ab7021..226ac418ac 100644 --- a/coding-intro/coding-intro-core/collections/accessing-dictionary-elements.md +++ b/coding-intro/coding-intro-core/collections/accessing-dictionary-elements.md @@ -62,14 +62,12 @@ my_dog = { color: "yellow" } -my_dog?????? +my_dog??? // "yellow" ``` -- . -- color -- , -- "yellow" +- .color +- ["yellow"] --- From 2e5905decd4d384479c82e046c44b86c97d7f2d5 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 1 Feb 2023 10:33:51 +0100 Subject: [PATCH 344/390] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e795bd0986..8b1591d38e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,8 @@ Types of change: ### Fixed +## February 1st 2023 +- [Coding Intro - Accessing Dictionary Elements - Update Question](https://github.com/enkidevs/curriculum/pull/3158) ## January 23rd 2023 From 714563f7924b0e1073209a54b4926c36ed7c191b Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 3 Feb 2023 12:13:30 +0100 Subject: [PATCH 345/390] Update CHANGELOG.md --- CHANGELOG.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db31a46798..022d1eb4ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,10 @@ Types of change: ### Changed - [Comp sci - What is jitter - Remove type in the gap](https://github.com/enkidevs/curriculum/pull/3152) +### Added +- [JavaScript - Tech Interview Exercises - add 25 exercises](https://github.com/enkidevs/curriculum/pull/3141) +- [Python - Tech Interview Exercises - add 25 exercises](https://github.com/enkidevs/curriculum/pull/3140) + ## February 1st 2023 - [Coding Intro - Accessing Dictionary Elements - Update Question](https://github.com/enkidevs/curriculum/pull/3158) @@ -106,8 +110,6 @@ Types of change: - [Tech Interviews - Tech Interview Exercises - Make exercises go after the preparation course](https://github.com/enkidevs/curriculum/pull/3142) ### Added -- [JavaScript - Tech Interview Exercises - add 25 exercises](https://github.com/enkidevs/curriculum/pull/3141) -- [Python - Tech Interview Exercises - add 25 exercises](https://github.com/enkidevs/curriculum/pull/3140) - [Tech Interviews - Tech Interview Exercises - Add 25 exercises](https://github.com/enkidevs/curriculum/pull/3139) ### Fixed From 97a36a28c2a4b5d64d0b87caf99d0967f30d547a Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Mon, 6 Feb 2023 19:11:03 +0100 Subject: [PATCH 346/390] update coding intro highlighter as well as fix two insights using multiple syntaxes in the same code --- .../chaining-conditions.md | 10 +++--- .../comparison-operators.md | 4 +-- .../conditions-intro.md | 6 ++-- .../logical-operators.md | 4 +-- .../coding-intro-functions/first-function.md | 6 ++-- .../robot-assemble-the-sandwich.md | 14 ++++---- .../coding-intro-functions/robot-food-time.md | 4 +-- .../robot-grill-me-a-sandwich.md | 2 +- .../coding-intro-functions/robot-im-hungry.md | 2 +- .../accessing-dictionary-elements.md | 30 ++++++++-------- .../collections/accessing-list-items.md | 6 ++-- .../collections/coding-intro-dictionaries.md | 34 +++++++++++++------ .../collections/coding-intro-lists.md | 2 +- .../collections-discussion-insight.md | 8 ++--- .../coding-intro-core/loops/ci-for-loops.md | 10 +++--- .../coding-intro-core/loops/do-while.md | 4 +-- .../coding-intro-core/loops/while-do.md | 4 +-- .../variables-and-data/lets-use-a-variable.md | 4 +-- .../variables-and-data/numbers.md | 6 ++-- .../variables-and-data/text.md | 4 +-- 20 files changed, 88 insertions(+), 76 deletions(-) diff --git a/coding-intro/coding-intro-core/coding-intro-conditions/chaining-conditions.md b/coding-intro/coding-intro-core/coding-intro-conditions/chaining-conditions.md index 09dcf23f83..37ad20bcac 100644 --- a/coding-intro/coding-intro-core/coding-intro-conditions/chaining-conditions.md +++ b/coding-intro/coding-intro-core/coding-intro-conditions/chaining-conditions.md @@ -21,7 +21,7 @@ revisionQuestion: Now, knowing that `0` means "do nothing", we'll want the robot to take an action if `input` has any other value: -```plain-text +```pseudo IF (input == 0) THEN INSTRUCT do_nothing() ELSE @@ -51,7 +51,7 @@ The next step is to create different *paths*: As a reminder, here is the instruction that led to making a grilled cheese sandwich: -```plain-text +```pseudo INSTRUCT make_a_grill_cheese_sandwich(cheese, grater, bowl, bread, butter, pan, plate) ``` @@ -59,7 +59,7 @@ To make the sandwich with a different type of bread, we'll create a variable nam To make the type change depending on the `input` value we would type: -```plain-text +```pseudo IF (input == 0) THEN INSTRUCT do_nothing() ELSE IF (input == 1) THEN @@ -91,7 +91,7 @@ You can chain multiple conditions using `ELSE IF`. If the `input` is `1` then th Complete the condition such that you only make a sandwich if you're hungry: -```plain-text +```pseudo hungry = ??? ??? (??? == true) THEN @@ -119,7 +119,7 @@ hungry = ??? Complete the following condition chain: -```plain-text +```pseudo ??? condition_1 THEN INSTRUCT do_something() ??? condition_2 THEN diff --git a/coding-intro/coding-intro-core/coding-intro-conditions/comparison-operators.md b/coding-intro/coding-intro-core/coding-intro-conditions/comparison-operators.md index 58606133f5..f19b94b115 100644 --- a/coding-intro/coding-intro-core/coding-intro-conditions/comparison-operators.md +++ b/coding-intro/coding-intro-core/coding-intro-conditions/comparison-operators.md @@ -21,7 +21,7 @@ revisionQuestion: The `input` variable will be used to help the robot decide which action to take. When the value is `0` it will do nothing. -```plain-text +```pseudo IF (input == 0) THEN INSTRUCT do_nothing() ``` @@ -58,7 +58,7 @@ You are not limited to the equality operator. Here is a table of the most common What do you think the robot will do here? -```plain-text +```pseudo hungry = false IF (hungry == true) THEN diff --git a/coding-intro/coding-intro-core/coding-intro-conditions/conditions-intro.md b/coding-intro/coding-intro-core/coding-intro-conditions/conditions-intro.md index 27cc969331..12461568a0 100644 --- a/coding-intro/coding-intro-core/coding-intro-conditions/conditions-intro.md +++ b/coding-intro/coding-intro-core/coding-intro-conditions/conditions-intro.md @@ -27,7 +27,7 @@ Remember that grilled-cheese-making-robot that we programmed? Let's repurpose it Let's create a variable named `input`, and based on its value the robot will make the sandwich with a different type of bread. -```plain-text +```pseudo input = 0 ``` @@ -40,7 +40,7 @@ In the following insights, we'll use `input` to help our robot make decisions. What type is the `input` variable? -```plain-text +```pseudo input = 0 ``` @@ -57,7 +57,7 @@ input = 0 What type is the `input` variable? -```plain-text +```pseudo input = "0" ``` diff --git a/coding-intro/coding-intro-core/coding-intro-conditions/logical-operators.md b/coding-intro/coding-intro-core/coding-intro-conditions/logical-operators.md index 70bfaf426d..0a76a4e15f 100644 --- a/coding-intro/coding-intro-core/coding-intro-conditions/logical-operators.md +++ b/coding-intro/coding-intro-core/coding-intro-conditions/logical-operators.md @@ -32,7 +32,7 @@ Since we're not using them at the moment, let's use groups of numbers for the *p To do this, we'll have to use the `AND` logical operator: -```plain-text +```pseudo IF (input == 0) THEN INSTRUCT do_nothing() ELSE IF ( @@ -83,7 +83,7 @@ Which of these is **not** a logical operator? Fill in the gaps: -```plain-text +```pseudo ??? - negates the condition ??? - all conditions must evaluate to true ??? - any condition must evaluate to true diff --git a/coding-intro/coding-intro-core/coding-intro-functions/first-function.md b/coding-intro/coding-intro-core/coding-intro-functions/first-function.md index d5b12bf650..387ee6c82a 100644 --- a/coding-intro/coding-intro-core/coding-intro-functions/first-function.md +++ b/coding-intro/coding-intro-core/coding-intro-functions/first-function.md @@ -35,7 +35,7 @@ We can think of a function as divided into three parts. Here's how you can write the `multiplyTwoNumbers` function using our own made-up[1] language: -```plain-text +```pseudo FUNCTION multiplyTwoNumbers INPUT num1, num2 INSTRUCT result = multiply(num1, num2) @@ -44,7 +44,7 @@ FUNCTION multiplyTwoNumbers To call this function we write its name, followed by a pair of `()`. -```plain-text +```pseudo INSTRUCT multiplyTwoNumbers(5, 3) ``` @@ -65,7 +65,7 @@ A function is made out of three parts: Match the definitions with their name: -```plain-text +```pseudo 1. ??? 2. ??? 3. ??? diff --git a/coding-intro/coding-intro-core/coding-intro-functions/robot-assemble-the-sandwich.md b/coding-intro/coding-intro-core/coding-intro-functions/robot-assemble-the-sandwich.md index 28d9f27688..06abbb9a83 100644 --- a/coding-intro/coding-intro-core/coding-intro-functions/robot-assemble-the-sandwich.md +++ b/coding-intro/coding-intro-core/coding-intro-functions/robot-assemble-the-sandwich.md @@ -21,7 +21,7 @@ revisionQuestion: Let's continue preparing the sandwich-making instructions for our robot by writing a function to perform the second step of our recipe[1] - building out the sandwich from the ingredients. -```plain-text +```pseudo FUNCTION build_sandwich INPUT cheese_bowl, sliced_bread, butter INSTRUCT buttered_slices = butter_the_bread(sliced_bread, butter) @@ -37,14 +37,14 @@ Computers are 100% literal[2] like that. We have to spell out everything **exact For example, in the code above, take a look at the last two lines of the function body: -```plain-text +```pseudo INSTRUCT sandwich = combine_slices(buttered_slices_with_cheese) OUTPUT sandwich ``` If you forgot to save the output of `combine_slices` into the variable `sandwich`: -```plain-text +```pseudo INSTRUCT combine_slices(buttered_slices_with_cheese) OUTPUT sandwich ``` @@ -60,7 +60,7 @@ Let's practice function creation! Write a function called `fill_glass` that takes in `glass` and `water`, calls `pour` function to pour the `water` into the `glass` and produces a `glass_of_water` as the result: -```plain-text +```pseudo ??? ??? ??? glass, water ??? glass_of_water = ???(glass, water) @@ -82,7 +82,7 @@ ENDFUNCTION Write a function called `fill_glass` that takes in `glass` and `water`, calls `pour` function to pour the `water` into the `glass` and produces a `glass_of_water` as the result: -```plain-text +```pseudo ??? ??? ??? glass, water ??? glass_of_water = ???(glass, water) @@ -137,7 +137,7 @@ In some languages, instructions usually end with a semicolon `;`. This means that the instruction: -```plain-text +```pseudo study_buddy = "enki" ``` @@ -145,6 +145,6 @@ will not work in those languages! We have to end it with a `;` like this: -```plain-text +```pseudo study_buddy = "enki"; ``` diff --git a/coding-intro/coding-intro-core/coding-intro-functions/robot-food-time.md b/coding-intro/coding-intro-core/coding-intro-functions/robot-food-time.md index f2a8a79eb5..cf30600752 100644 --- a/coding-intro/coding-intro-core/coding-intro-functions/robot-food-time.md +++ b/coding-intro/coding-intro-core/coding-intro-functions/robot-food-time.md @@ -18,7 +18,7 @@ Now it's time to run the functions we create as commands for the robot. The final part of the code we're giving the robot is: -```plain-text +```pseudo FUNCTION make_a_grill_cheese_sandwich INPUT cheese, grater, bowl, bread, butter, pan, plate INSTRUCT cheese_bowl, sliced_bread = prepare_ingredients(cheese, grater, bowl, bread) @@ -34,7 +34,7 @@ Now for the last part. Let's tell the robot to run the `make_a_grill_cheese_sandwich` function: -```plain_text +```pseudo INSTRUCT make_a_grill_cheese_sandwich(cheese, grater, bowl, bread, butter, pan, plate) ``` diff --git a/coding-intro/coding-intro-core/coding-intro-functions/robot-grill-me-a-sandwich.md b/coding-intro/coding-intro-core/coding-intro-functions/robot-grill-me-a-sandwich.md index 1c253d2086..e9d9fd7fb0 100644 --- a/coding-intro/coding-intro-core/coding-intro-functions/robot-grill-me-a-sandwich.md +++ b/coding-intro/coding-intro-core/coding-intro-functions/robot-grill-me-a-sandwich.md @@ -16,7 +16,7 @@ The robot instructions are almost done! We're getting hungry. Let's do the part 3 of our recipe[1] now, the grilling of the sandwich: -```plain-text +```pseudo FUNCTION grill_sandwich INPUT sandwich, pan, plate INSTRUCT heated_pan = preheat_the_pan(pan) diff --git a/coding-intro/coding-intro-core/coding-intro-functions/robot-im-hungry.md b/coding-intro/coding-intro-core/coding-intro-functions/robot-im-hungry.md index 634441c67e..b6bcd21325 100644 --- a/coding-intro/coding-intro-core/coding-intro-functions/robot-im-hungry.md +++ b/coding-intro/coding-intro-core/coding-intro-functions/robot-im-hungry.md @@ -27,7 +27,7 @@ Let's write some code to tell our robot how to make a sandwich! To get us started, start with the preparation of the ingredients first. -```plain-text +```pseudo FUNCTION prepare_ingredients INPUT cheese, grater, bowl, bread INSTRUCT cheese_bowl = grate_cheese_in_the_bowl(grater, cheese, bowl) diff --git a/coding-intro/coding-intro-core/collections/accessing-dictionary-elements.md b/coding-intro/coding-intro-core/collections/accessing-dictionary-elements.md index 226ac418ac..efaa429fdc 100644 --- a/coding-intro/coding-intro-core/collections/accessing-dictionary-elements.md +++ b/coding-intro/coding-intro-core/collections/accessing-dictionary-elements.md @@ -26,28 +26,28 @@ What matters is the key. To extract a value from a dictionary you need to refere Using the same example as previously, let's extract the `name`: -```plain-text +```python my_dog = { - name: "Artemis", - age: 4, - color: "yellow" + "name": "Artemis", + "age": 4, + "color": "yellow" } -my_dog.name -// "Artemis" +my_dog['name'] +# "Artemis" ``` -To extract the value, we first write the name of the dictionary (`my_dog`), followed by a dot (`.`) and then the **key** (`name`). This is commonly referred to as **dot notation**. +To extract the value, we first write the name of the dictionary (`my_dog`), followed by a key between square brackets. This is usually referred to as **bracket notation**. -Depending on the programming language, you can also extract a value using a key between square brackets: +Depending on the programming language, you can also extract a value using **dot notation**. -```plain-text -my_dog["age"] +You write the name of the dictionary, followed by a dot (`.`) and then the **key** (`name`). This would work in languages like JavaScript: + +```javascript +my_dog.age // 4 ``` -This is usually referred to as **bracket notation**. - --- @@ -55,7 +55,7 @@ This is usually referred to as **bracket notation**. Extract the value for the `color` key using **dot notation**: -```plain-text +```javascript my_dog = { name: "Artemis", age: 4, @@ -76,9 +76,9 @@ my_dog??? Extract the value for the `name` key using **bracket notation**: -```plain-text +```python person = { - name: "Andrei" + "name": "Andrei" } person????????? diff --git a/coding-intro/coding-intro-core/collections/accessing-list-items.md b/coding-intro/coding-intro-core/collections/accessing-list-items.md index 1bb6cc1cd1..6c6caee465 100644 --- a/coding-intro/coding-intro-core/collections/accessing-list-items.md +++ b/coding-intro/coding-intro-core/collections/accessing-list-items.md @@ -31,7 +31,7 @@ Accessing an item in an array is practically instant because there's no searchin Here's how you'd get the third element from the array `users`: -```plain-text +```python users = ["Andrei", "Catalin", "Mihai"] users[2] @@ -49,7 +49,7 @@ users[2] Given the following list, access the second element: -```plain-text +```python work_days = [ "Mon", "Tue", @@ -75,7 +75,7 @@ work_days = [ Complete the gap with the element found at that index: -```plain-text +```python spring = [ "March", "April", diff --git a/coding-intro/coding-intro-core/collections/coding-intro-dictionaries.md b/coding-intro/coding-intro-core/collections/coding-intro-dictionaries.md index cfb5be77a9..a313fc3524 100644 --- a/coding-intro/coding-intro-core/collections/coding-intro-dictionaries.md +++ b/coding-intro/coding-intro-core/collections/coding-intro-dictionaries.md @@ -25,28 +25,40 @@ The name is inspired by our everyday language dictionaries, which are collection One way to write a dictionary is using curly braces (`{ }`): -```plain-text +```python +# create a my_dog dictionary +# with 3 key/value pairs +my_dog = { + "name": "Artemis", + "age": 4, + "color": "yellow" +} +``` + +In this example, `name` is the **key**, and `"Artemis"` is the value. + +**Note** that different languages have different syntaxes. For instance, the above was written in Python, and requires keys to have quotations. + +The following dictionary is written in JavaScript and doesn't require quotations, but can have them: +```javascript // create a my_dog dictionary // with 3 key/value pairs my_dog = { name: "Artemis", age: 4, - color: "yellow" + "color": "yellow" } ``` -In this example, `name` is the **key**, and `"Artemis"` is the value. - - --- ## Practice Complete the gaps such that the dictionary has `age` as a **key** and `33` for the **value**: -```plain-text +```python person = { - ???: ??? + "???": ??? } ``` @@ -64,7 +76,7 @@ person = { Match the variable with its data type: -```plain-text +```python a = [ 1, 2, @@ -72,9 +84,9 @@ a = [ ] b = { - one: 1, - two: 2, - three: 3 + "one": 1, + "two": 2, + "three": 3 } // ??? is a dictionary diff --git a/coding-intro/coding-intro-core/collections/coding-intro-lists.md b/coding-intro/coding-intro-core/collections/coding-intro-lists.md index 154fcbb953..bd2a47a9d4 100644 --- a/coding-intro/coding-intro-core/collections/coding-intro-lists.md +++ b/coding-intro/coding-intro-core/collections/coding-intro-lists.md @@ -33,7 +33,7 @@ item1 <- -> item2 <- -> item3 Sometimes we can see lists written using square brackets `[ ]`, with the values separated by commas inside. -```plain-text +```python users = ["Andrei", "Catalin", "Mihai"] ``` diff --git a/coding-intro/coding-intro-core/collections/collections-discussion-insight.md b/coding-intro/coding-intro-core/collections/collections-discussion-insight.md index c10959203a..e403cc885d 100644 --- a/coding-intro/coding-intro-core/collections/collections-discussion-insight.md +++ b/coding-intro/coding-intro-core/collections/collections-discussion-insight.md @@ -56,13 +56,13 @@ To do this, you need to use the special `print()` function. Here is how you would print the test `"Enki"`: -```py +```python print("Enki") ``` And here is how you would print a collection's element: -```py +```python print(my_collection[0]) ``` @@ -70,7 +70,7 @@ print(my_collection[0]) There are many ways in which you can tackle this. For example, you could create a list that stores weekdays: -```plain-text +```python days = [ "Monday", "Tuesday", @@ -85,7 +85,7 @@ days = [ Here is a reminder of how you can access the items: -```plain-text +```python days[0] // "Monday" ``` diff --git a/coding-intro/coding-intro-core/loops/ci-for-loops.md b/coding-intro/coding-intro-core/loops/ci-for-loops.md index 7bc614980b..1dd4e574a0 100644 --- a/coding-intro/coding-intro-core/loops/ci-for-loops.md +++ b/coding-intro/coding-intro-core/loops/ci-for-loops.md @@ -25,7 +25,7 @@ The idea behind these loops is that you are repeating an instruction **for each* If, for example, you have this list of friends: -```plain-text +```pseudo friends = [ "John", "Dan", @@ -35,7 +35,7 @@ friends = [ You can repeat an instruction **for each** friend using the for loop. In this example we'll make a grilled cheese sandwich[1]: -```plain-text +```pseudo FOR EACH friend OF friends INSTRUCT make_a_grill_cheese_sandwich( cheese, @@ -51,7 +51,7 @@ ENDFOR As we have mentioned, you can also use a range: -```plain-text +```pseudo FOR seconds = 1 TO 20 INSTRUCT wash_hands() ENDFOR @@ -68,7 +68,7 @@ In this example, we repeat the `wash_hands()` instruction 20 times. Complete the loop so that it repeats **five times**: -```plain-text +```pseudo ??? counter = 1 ??? ??? INSTRUCT wash_hands() ??? @@ -86,7 +86,7 @@ Complete the loop so that it repeats **five times**: Complete the loop so that it rings the alarm every day: -```plain-text +```pseudo days = ["Monday", "Tuesday", ...] ??? EACH day ??? ??? diff --git a/coding-intro/coding-intro-core/loops/do-while.md b/coding-intro/coding-intro-core/loops/do-while.md index e8ea6798d0..da8a2c8fd5 100644 --- a/coding-intro/coding-intro-core/loops/do-while.md +++ b/coding-intro/coding-intro-core/loops/do-while.md @@ -26,7 +26,7 @@ In a `DO..WHILE` loop, you start by running the code for the first time, followe Going back to our sandwiches, let's say you want to make sure there is always one sandwich available. -```plain-text +```pseudo hungry = true sandwiches_made = 0 @@ -68,7 +68,7 @@ In a `DO..WHILE` loop, which happens first? What is the value of the variable `sandwiches_made` when the code stops running? -```plain-text +```pseudo sandwiches_made = 0 DO ( diff --git a/coding-intro/coding-intro-core/loops/while-do.md b/coding-intro/coding-intro-core/loops/while-do.md index 5bcbfcf51a..cd500c9709 100644 --- a/coding-intro/coding-intro-core/loops/while-do.md +++ b/coding-intro/coding-intro-core/loops/while-do.md @@ -28,7 +28,7 @@ The rule is that you **must** check the condition first, and only after that can Let's take a look at an example: -```plain-text +```pseudo hungry = true sandwiches_made = 0 @@ -58,7 +58,7 @@ We created a complex condition: if the `hungry` variable is equal to `true` **an Complete this loop such that it runs only if `number` is between `1` and `100` (inclusive): -```plain-text +```pseudo ??? ( number ??? 1 AND ??? <= 100 diff --git a/coding-intro/coding-intro-core/variables-and-data/lets-use-a-variable.md b/coding-intro/coding-intro-core/variables-and-data/lets-use-a-variable.md index 2e9a23909e..6767de021f 100644 --- a/coding-intro/coding-intro-core/variables-and-data/lets-use-a-variable.md +++ b/coding-intro/coding-intro-core/variables-and-data/lets-use-a-variable.md @@ -27,7 +27,7 @@ To get us started, let's say that we have the text `"Enki"` as our data, and we In programming, putting data into a variable is usually done with the `=` sign: -```plain-text +```python study_buddy = "Enki" ``` @@ -44,7 +44,7 @@ Putting data into a variable is called **an assignment**. Define a variable named `best_user` that stores `"You"`: -```plain-text +```python ??? ??? ??? ``` diff --git a/coding-intro/coding-intro-core/variables-and-data/numbers.md b/coding-intro/coding-intro-core/variables-and-data/numbers.md index 582ccb95d2..d78b9fc118 100644 --- a/coding-intro/coding-intro-core/variables-and-data/numbers.md +++ b/coding-intro/coding-intro-core/variables-and-data/numbers.md @@ -30,13 +30,13 @@ In order to make everything easier and faster to work with, programming language Let's define an integer! -```plain-text +```python my_age = 33 ``` > 💡 Depending on the programming language, you might have to type the data type before the variable name. -```plain-text +```javascript int my_age = 33 integer my_age = 33 @@ -70,7 +70,7 @@ c = "one" Create a variable named `age` which stores `33`: -```plain-text +```python ??? ??? ??? ``` diff --git a/coding-intro/coding-intro-core/variables-and-data/text.md b/coding-intro/coding-intro-core/variables-and-data/text.md index 4f2a480841..9c483b1cd3 100644 --- a/coding-intro/coding-intro-core/variables-and-data/text.md +++ b/coding-intro/coding-intro-core/variables-and-data/text.md @@ -28,7 +28,7 @@ We've already seen this type before when creating the `study_buddy` variable. Now, let's make another one: -```plain-text +```python best_user = "You" ``` @@ -53,7 +53,7 @@ Strings commonly have to be enclosed with ???. Complete the gaps to define a variable called `my_name` that stores the `"Andrei"` string: -```plain-text +```python my_name ??? ??? ``` From 077d8c6a5d5a43bf6e001abaa275eb0d87559930 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Mon, 6 Feb 2023 19:14:44 +0100 Subject: [PATCH 347/390] add changelog entry --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 022d1eb4ed..938aff7956 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 6th 2023 + +### Changed +- [Coding intro - Whole topic - Add new syntax highlighter and update two insights](https://github.com/enkidevs/curriculum/pull/3159) + ## February 3rd 2023 ### Changed From bd08590d4e67fc3653254c92dc94d7eac8f44b2c Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 10 Feb 2023 16:17:52 +0100 Subject: [PATCH 348/390] Update debugging-with-print.md --- .../debugging-with-print.md | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..9febc3ced4 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -70,25 +70,26 @@ The bug here is that the `while` condition will always evaluate `True` and the p ## Practice -Fill in the output of the `counter(3)` function: - +Given the following code: ```python -1 def counter(x): -2 print("Line 2:", x) -3 while x > 0: -4 print(x) -5 x -= 1 -6 print("Line 6:", x) +def counter(x): + print("Initial value:", x) + while x > 0: + print(x) + x -= 1 + print("Final value:", x) ``` +What would the output be if we plug in `3` into the `counter()` function? + ```py counter(3) -# Line 2: 3 +# Initial value: 3 # ??? # ??? # ??? -# Line 6: ??? +# Final value: ??? ``` - 3 From 5027c9fd779b92eef3182f546cc22e5d681a2dbc Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 10 Feb 2023 16:35:44 +0100 Subject: [PATCH 349/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 022d1eb4ed..d136007e88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 10th 2023 + +### Changed +- [Python - Debugging With Print - Update question](https://github.com/enkidevs/curriculum/pull/3160) + ## February 3rd 2023 ### Changed From 242dd2037463134aeb5075be436f8b29730cacf1 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Fri, 10 Feb 2023 16:48:39 +0100 Subject: [PATCH 350/390] replace broken links --- .../analyzing-ii/movie-count-per-release-year-visualized.md | 2 +- .../python-data-analysis-core/analyzing/modifying-pie-chart.md | 2 +- .../analyzing/visualize-movie-show-count.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/python-data-analysis/python-data-analysis-core/analyzing-ii/movie-count-per-release-year-visualized.md b/python-data-analysis/python-data-analysis-core/analyzing-ii/movie-count-per-release-year-visualized.md index 09c9679266..8b98f99641 100644 --- a/python-data-analysis/python-data-analysis-core/analyzing-ii/movie-count-per-release-year-visualized.md +++ b/python-data-analysis/python-data-analysis-core/analyzing-ii/movie-count-per-release-year-visualized.md @@ -7,7 +7,7 @@ category: how-to links: - >- - [Line Styles](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.plot.html){documentation} + [Line Styles](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html){documentation} practiceQuestion: formats: diff --git a/python-data-analysis/python-data-analysis-core/analyzing/modifying-pie-chart.md b/python-data-analysis/python-data-analysis-core/analyzing/modifying-pie-chart.md index 250874207a..59034b79c9 100644 --- a/python-data-analysis/python-data-analysis-core/analyzing/modifying-pie-chart.md +++ b/python-data-analysis/python-data-analysis-core/analyzing/modifying-pie-chart.md @@ -9,7 +9,7 @@ links: - >- [Matplotlib Modules](https://matplotlib.org/stable/py-modindex.html){documentation} - >- - [Pyplot Module](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot){documentation} + [Pyplot Module](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html){documentation} - >- [String Formatting](https://thepythonguru.com/python-string-formatting/){documentation} diff --git a/python-data-analysis/python-data-analysis-core/analyzing/visualize-movie-show-count.md b/python-data-analysis/python-data-analysis-core/analyzing/visualize-movie-show-count.md index aa7b440a36..2ba22af28c 100644 --- a/python-data-analysis/python-data-analysis-core/analyzing/visualize-movie-show-count.md +++ b/python-data-analysis/python-data-analysis-core/analyzing/visualize-movie-show-count.md @@ -9,7 +9,7 @@ links: - >- [Matplotlib Modules](https://matplotlib.org/stable/py-modindex.html){documentation} - >- - [Pyplot Module](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot){documentation} + [Pyplot Module](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html){documentation} practiceQuestion: formats: From dc53c65f3a056e5174cfc0d4e6f4fa3e886efc64 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Fri, 10 Feb 2023 16:50:07 +0100 Subject: [PATCH 351/390] changelog --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 022d1eb4ed..5fb86e2afc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 10th 2023 + +### Fixed +- [Python Data Analysis - Couple Insights - Fix broken links](https://github.com/enkidevs/curriculum/pull/3161) + ## February 3rd 2023 ### Changed From 871854239c38a9f7f7c5cb1ffac94ed0abc6cc7e Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 13 Feb 2023 14:28:14 +0100 Subject: [PATCH 352/390] Update intro-to-modules-discussion.md --- .../intro-to-modules/intro-to-modules-discussion.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python/python-core/intro-to-modules/intro-to-modules-discussion.md b/python/python-core/intro-to-modules/intro-to-modules-discussion.md index 54eaa3cbba..5e52640be1 100644 --- a/python/python-core/intro-to-modules/intro-to-modules-discussion.md +++ b/python/python-core/intro-to-modules/intro-to-modules-discussion.md @@ -32,12 +32,13 @@ To solve this, try using the following concepts: - importing modules (`import`, `from...import`...) - function creation (`def...`) -As for the file name, add it as a comment at the top of the code block where you've defined the function. +As for the file name and import statement, add them as a comment at the top of the code block where you've defined the function. For instance: ```py # my_first_module.py +# import ... # code here ``` From e3080949100a9914db0131f44fd667b8c29e64d0 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 13 Feb 2023 14:30:21 +0100 Subject: [PATCH 353/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 938aff7956..ae6a1caca1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 13th 2023 + +### Changed +- [Python - Intro To Modules Discussion - Add comment for import statement](https://github.com/enkidevs/curriculum/pull/3163) + ## February 6th 2023 ### Changed From b188c06d9b68d2da4f357f2e141244bdf86757aa Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 14 Feb 2023 11:25:10 +0100 Subject: [PATCH 354/390] Update cleaning-dataset.md --- .../cleaning-dataset.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/python-data-analysis/python-data-analysis-core/initializing-and-cleaning-datasets/cleaning-dataset.md b/python-data-analysis/python-data-analysis-core/initializing-and-cleaning-datasets/cleaning-dataset.md index 2f5d6d2939..e213eac005 100644 --- a/python-data-analysis/python-data-analysis-core/initializing-and-cleaning-datasets/cleaning-dataset.md +++ b/python-data-analysis/python-data-analysis-core/initializing-and-cleaning-datasets/cleaning-dataset.md @@ -46,7 +46,7 @@ To check the total number of rows and columns in your dataset, add `.shape` to y This dataset has 6234 rows and 12 columns. -Rows start from 0 instead of 1. This is why the last columns `show_id` is 6233 instead of 6234. +Rows start from 0 instead of 1. This is why the last rows index is 6233 instead of 6234. > We will remove the columns we don't need for our analysis and leave the ones we will use in this workout. @@ -66,10 +66,10 @@ This will give us a table with `True` / `False` values. `True` meaning empty. ??? is used to check if cells are empty or not? -- isnull() -- isnan() -- exists() -- isempty() +- `isnull()` +- `isnan()` +- `exists()` +- `isempty()` --- @@ -96,4 +96,4 @@ cars.???.??? import pandas as pd importedData = pd.read_csv('netflix_titles.csv') -``` \ No newline at end of file +``` From 82d9c643cd4d6ee41ac393e7edc8baaf7ac18e99 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 14 Feb 2023 11:26:29 +0100 Subject: [PATCH 355/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae6a1caca1..b71cf71489 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 14th 2023 + +### Fixed +- [Python Data Analysis - Initializing & Cleaning a Dataset - Fix wording for columns and rows](https://github.com/enkidevs/curriculum/pull/3164) + ## February 13th 2023 ### Changed From 9632f1f6947817e81a85374b4ac627dfaec999d6 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 14 Feb 2023 11:27:38 +0100 Subject: [PATCH 356/390] Update cleaning-dataset.md --- .../initializing-and-cleaning-datasets/cleaning-dataset.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python-data-analysis/python-data-analysis-core/initializing-and-cleaning-datasets/cleaning-dataset.md b/python-data-analysis/python-data-analysis-core/initializing-and-cleaning-datasets/cleaning-dataset.md index e213eac005..2fe3f29619 100644 --- a/python-data-analysis/python-data-analysis-core/initializing-and-cleaning-datasets/cleaning-dataset.md +++ b/python-data-analysis/python-data-analysis-core/initializing-and-cleaning-datasets/cleaning-dataset.md @@ -46,7 +46,7 @@ To check the total number of rows and columns in your dataset, add `.shape` to y This dataset has 6234 rows and 12 columns. -Rows start from 0 instead of 1. This is why the last rows index is 6233 instead of 6234. +Rows start from 0 instead of 1. That is why the last row's index is 6233 instead of 6234. > We will remove the columns we don't need for our analysis and leave the ones we will use in this workout. From f4b13784ad66fa1f7f7a98c6a870c7b2e9fc0064 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 14 Feb 2023 11:56:51 +0100 Subject: [PATCH 357/390] Update using-find-to-search-by-filename.md --- .../linux-file-management/using-find-to-search-by-filename.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/linux/user-and-file-management/linux-file-management/using-find-to-search-by-filename.md b/linux/user-and-file-management/linux-file-management/using-find-to-search-by-filename.md index 677ddcc3b8..77b11b5485 100644 --- a/linux/user-and-file-management/linux-file-management/using-find-to-search-by-filename.md +++ b/linux/user-and-file-management/linux-file-management/using-find-to-search-by-filename.md @@ -78,7 +78,7 @@ Search in the home directory for files that contain happy in their title: ``` - `find` -- `~` +- `/home` - `f` - `-name` - `"*happy*"` From 4dd46c29f33e23c06c14cabec16c899a569788f8 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 17 Feb 2023 12:47:08 +0100 Subject: [PATCH 358/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 90bfc5cfd7..3275ca6145 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 17th 2023 + +### Changed +- [Linux - Using Find to search by file name - Change tilde to home directory in question](https://github.com/enkidevs/curriculum/pull/3165) + ## February 14th 2023 ### Changed From afe0f37f3da436e77317260262df875cd8e01d1e Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 20 Feb 2023 16:17:42 +0100 Subject: [PATCH 359/390] Update while-loops.md --- python/python-core/looping/while-loops.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index 50fca2d674..2539ab2f0c 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -67,7 +67,7 @@ while x < ???: - print(x) - x = x + 1 - 10 -- x++ +- x++1 - x + 1 From cb1706b7cca2ba4808dc3ee783cf771831a3e297 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 20 Feb 2023 16:20:04 +0100 Subject: [PATCH 360/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 90bfc5cfd7..7619b383a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## February 20th 2023 + +### Changed +- [Python - While Loops - Update answer](https://github.com/enkidevs/curriculum/pull/3166) + ## February 14th 2023 ### Changed From 2b9652aa084138ffdab5b4682c7a6bb0e8ed00fe Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 22 Feb 2023 17:36:42 +0100 Subject: [PATCH 361/390] Update CHANGELOG.md --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3deeb54adb..7bea8bfe4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -131,7 +131,6 @@ Types of change: ### Fixed - [SQL - Check constraint - Fix typo](https://github.com/enkidevs/curriculum/pull/3148) - ## December 16th 2022 ### Changed From 3b8df1d66caeed89065ed4cde4da164908e310a7 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 22 Feb 2023 17:41:35 +0100 Subject: [PATCH 362/390] Update CHANGELOG.md --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e6f70e678..fd9f9b144b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -399,7 +399,6 @@ Types of change: ### Fixed - [SQL - The Roles That Joins Play - Replace wrong output table with the correct one](https://github.com/enkidevs/curriculum/pull/3044) - ## February 7th 2022 ### Fixed From 60c38864051e62a17c776f3070f25b6f27c4e46c Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 27 Feb 2023 10:22:26 +0100 Subject: [PATCH 363/390] replace link --- .../data-analysis-using-spreadsheets/intro-to-spreadsheets.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data-analysis/data-analysis-core/data-analysis-using-spreadsheets/intro-to-spreadsheets.md b/data-analysis/data-analysis-core/data-analysis-using-spreadsheets/intro-to-spreadsheets.md index e41e9fa29f..34730383c4 100644 --- a/data-analysis/data-analysis-core/data-analysis-using-spreadsheets/intro-to-spreadsheets.md +++ b/data-analysis/data-analysis-core/data-analysis-using-spreadsheets/intro-to-spreadsheets.md @@ -13,7 +13,7 @@ links: Sheets](https://tallyfy.com/microsoft-excel-vs-google-sheets/){website} - >- [Data Analysis - Functions](https://excelwithbusiness.com/blog/15-excel-data-analysis-functions-need/){website} + Functions](https://www.linkedin.com/pulse/15-excel-data-analysis-functions-you-need-know-akerele){website} practiceQuestion: formats: - fill-in-the-gap From efafbea947dba0a3a93925a9565423ec9fded29b Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 27 Feb 2023 10:23:29 +0100 Subject: [PATCH 364/390] Update CHANGELOG.md --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd9f9b144b..2645ff4b33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,12 @@ Types of change: ### Fixed + +## February 27th 2023 + +### Fixed +- [Data Analysis - Intro To Spreadsheets - Replace broken linke](https://github.com/enkidevs/curriculum/pull/3168) + ## February 22th 2023 ### Fixed From 2ebde40753f87f7972fdc57031953af98ef39891 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Mon, 27 Feb 2023 12:44:31 +0100 Subject: [PATCH 365/390] split some insights --- .../conditional-statements-in-r/README.md | 3 +- .../nesting-if-else-in-r-ii.md | 83 ++++++++++++ .../nesting-if-else-in-r.md | 75 +---------- r/r-core/data-type-conversions-in-r/README.md | 9 +- .../as-character-r.md | 80 ++++++++++++ ...uble-and-character-r.md => as-double-r.md} | 43 ++----- ...meric-and-integer-r.md => as-integer-r.md} | 42 ++----- ...ogical-and-vector-r.md => as-logical-r.md} | 62 +++------ .../data-type-conversions-in-r/as-matrix-r.md | 3 - .../as-numeric-r.md | 82 ++++++++++++ .../data-type-conversions-in-r/as-vector-r.md | 88 +++++++++++++ .../data-type-conversion-r.md | 2 +- r/r-core/environment-variables-in-r/README.md | 1 + .../global-environment-variables-in-r.md | 4 +- .../local-variable-methods-in-r.md | 90 +++++++++++++ .../local-variables-in-r.md | 61 +++------ .../local-vs-global-variables-in-r.md | 1 - .../functions-in-r/function-methods-in-r.md | 2 +- r/r-core/functions-in-r/functions-in-r.md | 2 +- r/r-core/looping-techniques-in-r/README.md | 3 +- ...ply-function.md => apply-function-in-r.md} | 34 +---- .../how-to-use-the-apply-function-in-r.md | 102 +++++++++++++++ r/r-core/loops-in-r/README.md | 3 +- ...ext-in-r.md => break-and-next-for-in-r.md} | 2 +- .../loops-in-r/break-and-next-while-in-r.md | 118 ++++++++++++++++++ r/r-core/loops-in-r/for-loops-in-r.md | 2 +- r/r-core/loops-in-r/intro-to-loops-in-r.md | 45 ------- r/r-core/loops-in-r/repeat-loops-in-r.md | 1 - r/r-core/loops-in-r/while-loops-in-r.md | 52 +------- 29 files changed, 721 insertions(+), 374 deletions(-) create mode 100644 r/r-core/conditional-statements-in-r/nesting-if-else-in-r-ii.md create mode 100644 r/r-core/data-type-conversions-in-r/as-character-r.md rename r/r-core/data-type-conversions-in-r/{as-double-and-character-r.md => as-double-r.md} (60%) rename r/r-core/data-type-conversions-in-r/{as-numeric-and-integer-r.md => as-integer-r.md} (61%) rename r/r-core/data-type-conversions-in-r/{as-logical-and-vector-r.md => as-logical-r.md} (64%) create mode 100644 r/r-core/data-type-conversions-in-r/as-numeric-r.md create mode 100644 r/r-core/data-type-conversions-in-r/as-vector-r.md create mode 100644 r/r-core/environment-variables-in-r/local-variable-methods-in-r.md rename r/r-core/looping-techniques-in-r/{apply-function.md => apply-function-in-r.md} (68%) create mode 100644 r/r-core/looping-techniques-in-r/how-to-use-the-apply-function-in-r.md rename r/r-core/loops-in-r/{break-and-next-in-r.md => break-and-next-for-in-r.md} (98%) create mode 100644 r/r-core/loops-in-r/break-and-next-while-in-r.md diff --git a/r/r-core/conditional-statements-in-r/README.md b/r/r-core/conditional-statements-in-r/README.md index e115365bb0..95d91c0f89 100644 --- a/r/r-core/conditional-statements-in-r/README.md +++ b/r/r-core/conditional-statements-in-r/README.md @@ -1,12 +1,13 @@ name: Control Flow -description: Learn about conditional statements in R. +description: Learn about conditional statements. insights: - what-are-conditional-statements-r - if-statements-in-r - if-else-in-r - nesting-if-else-in-r + - nesting-if-else-in-r-ii - switch-statements-in-r aspects: diff --git a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r-ii.md b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r-ii.md new file mode 100644 index 0000000000..a00e01b4ae --- /dev/null +++ b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r-ii.md @@ -0,0 +1,83 @@ +--- +author: Stefan-Stojanovic +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# Nesting ifelse Statements + +--- + +## Content + +To nest `ifelse` statements, you place one `ifelse` statement inside the `then` clause of another `ifelse` statement. Here is an example of how to do this: + +Here is an example of a nested `ifelse` statement: +```r +# Initialize variable x +x <- 3 + +# Nest ifelse statements +result <- ifelse(x > 0, ifelse(x > 2, "x is greater than 2", "x is 1 or 2"), "x is 0 or negative") + +# Print the result +print(result) +``` + +In this example, we use an `ifelse` statement to check if `x` is greater than `0`. +```r +ifelse(x > 0 +``` + +If it is, then we use another `ifelse` statement to check if `x` is greater than 2: +```r +ifelse(x > 0, ifelse(x > 2, +``` + +If it is, then we print "x is greater than 2". +```r +ifelse(x > 0, ifelse(x > 2, "x is greater than 2" +``` + +If it is not, then we print "x is 1 or 2": +```r +ifelse(x > 0, ifelse(x > 2, "x is greater than 2", "x is 1 or 2"), +``` + +Finally, If `x` is not greater than `0`, then we print "x is 0 or negative": +```r +ifelse(x > 0, ifelse(x > 2, "x is greater than 2", "x is 1 or 2"), "x is 0 or negative") +``` + +As a result of this code, the output will be "x is greater than 2". + +--- +## Practice + +What is the result of the following nested `ifelse`? + +```r +# Initialize variable x +x <- 5 + +# Nest ifelse statements +result <- ifelse(x > 0, ifelse(x > 10, "x is greater than 10", "x is between 1 and 10"), "x is 0 or negative") + +# Print the result +print(result) +# "???" +``` + +- `x is between 1 and 10` +- `x is greater than 10` +- `x is 0 or negative` +- `Error` \ No newline at end of file diff --git a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md index 3a4e44a1f8..26e2bf1795 100644 --- a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md +++ b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md @@ -1,16 +1,10 @@ --- author: Stefan-Stojanovic - tags: - introduction - discussion type: normal category: must-know -practiceQuestion: - formats: - - fill-in-the-gap - - type-in-the-gap - context: standalone --- @@ -22,53 +16,6 @@ practiceQuestion: Have you ever wanted to execute different actions in your R code based on multiple conditions? One way to do this is by using nested `ifelse` statements. -To nest `ifelse` statements, you place one `ifelse` statement inside the `then` clause of another `ifelse` statement. Here is an example of how to do this: - -Here is an example of a nested ifelse statement in R: -```r -# Initialize variable x -x <- 3 - -# Nest ifelse statements -result <- ifelse(x > 0, ifelse(x > 2, "x is greater than 2", "x is 1 or 2"), "x is 0 or negative") - -# Print the result -print(result) - -``` - -In this example, we use an `ifelse` statement to check if `x` is greater than `0`. -```r -ifelse(x > 0 -``` - -If it is, then we use another `ifelse` statement to check if `x` is greater than 2: -```r -ifelse(x > 0, ifelse(x > 2, -``` - - -If it is, then we print "x is greater than 2". -```r -ifelse(x > 0, ifelse(x > 2, "x is greater than 2" -``` - - -If it is not, then we print "x is 1 or 2": -```r -ifelse(x > 0, ifelse(x > 2, "x is greater than 2", "x is 1 or 2"), - -``` - - -Finally, If `x` is not greater than `0`, then we print "x is 0 or negative": -```r -ifelse(x > 0, ifelse(x > 2, "x is greater than 2", "x is 1 or 2"), "x is 0 or negative") -``` - -As a result of this code, the output will be "x is greater than 2". - - ### When to use nested ifelse statements --- @@ -76,24 +23,4 @@ Nested `ifelse` statements can be useful when you have multiple conditions to ch However, it is important to be careful when using nested `ifelse` statements, as they can quickly become difficult to read and maintain if you have too many levels of nesting. ---- -## Practice - -What is the result of the following nested `ifelse`? - -```r -# Initialize variable x -x <- 5 - -# Nest ifelse statements -result <- ifelse(x > 0, ifelse(x > 10, "x is greater than 10", "x is between 1 and 10"), "x is 0 or negative") - -# Print the result -print(result) -# "???" -``` - -- `x is between 1 and 10` -- `x is greater than 10` -- `x is 0 or negative` -- `Error` \ No newline at end of file +Let's create a nested `ifelse` in teh next insight. \ No newline at end of file diff --git a/r/r-core/data-type-conversions-in-r/README.md b/r/r-core/data-type-conversions-in-r/README.md index 52d95ce9b1..61978beb84 100644 --- a/r/r-core/data-type-conversions-in-r/README.md +++ b/r/r-core/data-type-conversions-in-r/README.md @@ -4,9 +4,12 @@ description: Learn how to convert data from one data type into another. insights: - data-type-conversion-r - - as-numeric-and-integer-r - - as-double-and-character-r - - as-logical-and-vector-r + - as-numeric-r + - as-integer-r + - as-double-r + - as-character-r + - as-logical-r + - as-vector-r - as-matrix-r aspects: diff --git a/r/r-core/data-type-conversions-in-r/as-character-r.md b/r/r-core/data-type-conversions-in-r/as-character-r.md new file mode 100644 index 0000000000..0d8e99799b --- /dev/null +++ b/r/r-core/data-type-conversions-in-r/as-character-r.md @@ -0,0 +1,80 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# as.character + +--- + +## Content + + +The `as.character` converts an object to character (string) type. + +```r +# Convert a number to a string +x <- 123 +x <- as.character(x) +print(x) +# "123" + +# Convert a vector of numbers to a vector of strings +v <- c(1, 2, 3) +v <- as.character(v) +print(v) +# "1" "2" "3" +``` + +--- +## Practice + +Convert the following logical vector to a character vector using the `as.character` function: + +```r +x <- c(TRUE, TRUE, FALSE, TRUE) + +x <- as.???(???) +print(x) +# "TRUE" "TRUE" "FALSE" "TRUE +``` + +- `character` +- `x` +- `y` +- `number` + +--- +## Revision + +Convert the following logical vector to a character vector using the `as.character` function: + +```r +y <- c(TRUE, FALSE, FALSE, TRUE) + +y <- ???.???(???) +print(y) +# "TRUE" "FALSE" "FALSE" "TRUE +``` + +- `as` +- `character` +- `y` +- `x` +- `number` \ No newline at end of file diff --git a/r/r-core/data-type-conversions-in-r/as-double-and-character-r.md b/r/r-core/data-type-conversions-in-r/as-double-r.md similarity index 60% rename from r/r-core/data-type-conversions-in-r/as-double-and-character-r.md rename to r/r-core/data-type-conversions-in-r/as-double-r.md index 0e77ba8c23..20957c5de6 100644 --- a/r/r-core/data-type-conversions-in-r/as-double-and-character-r.md +++ b/r/r-core/data-type-conversions-in-r/as-double-r.md @@ -19,16 +19,12 @@ revisionQuestion: --- -# as.character & as.double +# as.double --- ## Content - -### as.double ---- - The `as.double` converts an object to double (floating point) type. ```r # Convert a number to a double @@ -44,44 +40,23 @@ print(v) # 1.0 2.0 3.0 ``` - -### as.character ---- - -The `as.character` converts an object to character (string) type. - -```r -# Convert a number to a string -x <- 123 -x <- as.character(x) -print(x) -# "123" - -# Convert a vector of numbers to a vector of strings -v <- c(1, 2, 3) -v <- as.character(v) -print(v) -# "1" "2" "3" -``` - - --- ## Practice -Convert the following logical vector to a character vector using the `as.character` function: +Convert the following character vector to a double type using the `as.double` function: ```r -x <- c(TRUE, FALSE, TRUE, TRUE) +x <- c(5, 33, 315) -x <- as.???(???) +x <- ??? print(x) -# "TRUE" "FALSE" "TRUE" "TRUE +# 1.0 2.0 345.0 ``` -- `character` -- `x` -- `y` -- `number` +- `as.double(x)` +- `as a double` +- `x.as.double` + --- ## Revision diff --git a/r/r-core/data-type-conversions-in-r/as-numeric-and-integer-r.md b/r/r-core/data-type-conversions-in-r/as-integer-r.md similarity index 61% rename from r/r-core/data-type-conversions-in-r/as-numeric-and-integer-r.md rename to r/r-core/data-type-conversions-in-r/as-integer-r.md index a11269ef82..f67d4d9bf3 100644 --- a/r/r-core/data-type-conversions-in-r/as-numeric-and-integer-r.md +++ b/r/r-core/data-type-conversions-in-r/as-integer-r.md @@ -19,37 +19,12 @@ revisionQuestion: --- -# as.numeric & as.integer +# as.integer --- ## Content - -### as.numeric ---- - -The `as.numeric` function converts an object to numeric (integer or double) type. - -Here's an example -```r -# Convert a string to a number -x <- "123" -x <- as.numeric(x) -print(x) -# 123 - -# Convert a vector of strings to a vector of numbers -v <- c("1", "2", "3") -v <- as.numeric(v) -print(v) -# 1 2 3 -``` - - -### as.integer ---- - `as.integer`: Converts an object to integer type. ```r @@ -70,20 +45,21 @@ print(v) --- ## Practice -Convert the following character vector to a numeric vector using the `as.numeric` function: +Convert the following character vector to a integer type using the `as.integer` function: ```r -x <- c("1", "2", "3", "4", "5") +x <- ???("1", "2", "3", "4", "5") -x <- as.???(???) +x <- ??? print(x) # 1 2 3 4 5 ``` -- `numeric` -- `x` -- `y` -- `number` +- `c` +- `as.integer(x)` +- `as an integer` +- `x.asInteger` +- `char` --- ## Revision diff --git a/r/r-core/data-type-conversions-in-r/as-logical-and-vector-r.md b/r/r-core/data-type-conversions-in-r/as-logical-r.md similarity index 64% rename from r/r-core/data-type-conversions-in-r/as-logical-and-vector-r.md rename to r/r-core/data-type-conversions-in-r/as-logical-r.md index 6597f1007e..edc976a660 100644 --- a/r/r-core/data-type-conversions-in-r/as-logical-and-vector-r.md +++ b/r/r-core/data-type-conversions-in-r/as-logical-r.md @@ -18,15 +18,12 @@ revisionQuestion: context: standalone --- -# as.logical & as.vector +# as.logical --- ## Content - -### as.logical - The `as.logical` converts an object to logical (TRUE/FALSE) type. ```r @@ -49,26 +46,6 @@ print(m) # TRUE FALSE TRUE FALSE ``` - -### as.vector - -The `as.vector` converts an object to vector type. - -```r -# Convert a number to a vector -x <- 123 -x <- as.vector(x) -print(x) -# 123 - -# Convert a matrix to a vector -m <- matrix(1:4, nrow = 2) -v <- as.vector(m) -print(v) -# 1 3 2 4 -``` - - --- ## Practice @@ -88,35 +65,26 @@ v <- as.vector(c("True", "False", "True")) v <- as.logical(c("True", "False", "True")) ``` -??? +???) -- `D)` -- `A)` -- `B)` -- `C)` +- `D` +- `A` +- `B` +- `C` --- ## Revision -Which of the following will create a character vector from a logical vector? +Finish the code to create a logical vector from a character vector. ```r -# A) -v <- as.character(c(TRUE, FALSE, TRUE)) - -# B) -v <- as.vector(c("True", "False", "True")) - -# C) -v <- as.character(c(1, 0, 1)) - -# D) -v <- as.vector(c(1, 0, 1)) +v <- ???.???(c("True", "False", "True")) +print(v) +# TRUE FALSE TRUE ``` -??? - -- `A)` -- `D)` -- `B)` -- `C)` +- `as` +- `logical` +- `to` +- `character` +- `from` diff --git a/r/r-core/data-type-conversions-in-r/as-matrix-r.md b/r/r-core/data-type-conversions-in-r/as-matrix-r.md index 77b6303976..2ae558b9c9 100644 --- a/r/r-core/data-type-conversions-in-r/as-matrix-r.md +++ b/r/r-core/data-type-conversions-in-r/as-matrix-r.md @@ -25,9 +25,6 @@ revisionQuestion: ## Content - -### as.matrix - The `as.matrix` converts an object to matrix type. ```r diff --git a/r/r-core/data-type-conversions-in-r/as-numeric-r.md b/r/r-core/data-type-conversions-in-r/as-numeric-r.md new file mode 100644 index 0000000000..2f6c954049 --- /dev/null +++ b/r/r-core/data-type-conversions-in-r/as-numeric-r.md @@ -0,0 +1,82 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone + +--- + +# as.numeric + +--- + +## Content + +The `as.numeric` function converts an object to numeric (integer or double) type. + +Here's an example +```r +# Convert a string to a number +x <- "123" +x <- as.numeric(x) +print(x) +# 123 + +# Convert a vector of strings to a vector of numbers +v <- c("1", "2", "3") +v <- as.numeric(v) +print(v) +# 1 2 3 +``` + + +--- +## Practice + +Convert the following character vector to a numeric vector using the `as.numeric` function: + +```r +x <- c("1", "2", "3", "4", "5") + +x <- ???.???(???) +print(x) +# 1 2 3 4 5 +``` + +- `as` +- `numeric` +- `x` +- `y` +- `number` + +--- +## Revision + +Convert the following character vector to a numeric vector using the `as.numeric` function: + +```r +y <- c("11", "13", "16", "33", "51") + +y <- ???.???(???) +print(y) +# 11 116 3 33 51 +``` + +- `as` +- `numeric` +- `y` +- `x` +- `number` \ No newline at end of file diff --git a/r/r-core/data-type-conversions-in-r/as-vector-r.md b/r/r-core/data-type-conversions-in-r/as-vector-r.md new file mode 100644 index 0000000000..c16ee62207 --- /dev/null +++ b/r/r-core/data-type-conversions-in-r/as-vector-r.md @@ -0,0 +1,88 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone +--- + +# as.vector + +--- + +## Content + +The `as.vector` converts an object to vector type. + +```r +# Convert a number to a vector +x <- 123 +x <- as.vector(x) +print(x) +# 123 + +# Convert a matrix to a vector +m <- matrix(1:4, nrow = 2) +v <- as.vector(m) +print(v) +# 1 3 2 4 +``` + + +--- +## Practice + +Finish the code to convert a matrix into to a vector. Then print the vector + +```r +m <- ???(1:4, nrow = 2) +v <- ???.???(m) +print(???) +# 1 3 2 4 +``` + +??? + +- `matrix` +- `as` +- `vector` +- `v` +- `from` +- `to` + +--- +## Revision + +Which of the following will create a vector called `v` from numbers? +```r +# A) +v <- as.character(c(TRUE, FALSE, TRUE)) + +# B) +v <- as.vector(c("True", "False", "True")) + +# C) +v <- as.character(c(1, 0, 1)) + +# D) +v <- as.vector(c(1, 0, 1)) +``` + +???) + +- `D` +- `A` +- `B` +- `C` diff --git a/r/r-core/data-type-conversions-in-r/data-type-conversion-r.md b/r/r-core/data-type-conversions-in-r/data-type-conversion-r.md index 823fdfb6b7..4f3207fc90 100644 --- a/r/r-core/data-type-conversions-in-r/data-type-conversion-r.md +++ b/r/r-core/data-type-conversions-in-r/data-type-conversion-r.md @@ -25,7 +25,7 @@ In **R**, it is often necessary to convert data from one type to another. For ex - `as.vector`: Converts an object to vector type. - `as.matrix`: Converts an object to matrix type. -Note: Each of these methods has an `is.name` methods. For instance, `is.numeric`, `is.double` and so on. They are used to check if the value is the appropriate type. +Note: Each of these methods has an `is.name` method. For instance, `is.numeric`, `is.double` and so on. They are used to check if the value is the appropriate type. They return `TRUE` or `FALSE`. diff --git a/r/r-core/environment-variables-in-r/README.md b/r/r-core/environment-variables-in-r/README.md index 8b7bb8defb..0360d79d07 100644 --- a/r/r-core/environment-variables-in-r/README.md +++ b/r/r-core/environment-variables-in-r/README.md @@ -5,6 +5,7 @@ description: Learn about the local and global environment variables. insights: - global-environment-variables-in-r - local-variables-in-r + - local-variable-methods-in-r - local-vs-global-variables-in-r aspects: diff --git a/r/r-core/environment-variables-in-r/global-environment-variables-in-r.md b/r/r-core/environment-variables-in-r/global-environment-variables-in-r.md index 6a37ae98ac..1e78486fce 100644 --- a/r/r-core/environment-variables-in-r/global-environment-variables-in-r.md +++ b/r/r-core/environment-variables-in-r/global-environment-variables-in-r.md @@ -18,7 +18,7 @@ revisionQuestion: --- -# Global Environment Variables in R +# Global Environment Variables --- @@ -87,7 +87,7 @@ Which of the following is **NOT** a way to list all objects in the global enviro --- ## Revision -What function can be used to remove a global environment variable in R? +What function can be used to remove a global environment variable? ??? diff --git a/r/r-core/environment-variables-in-r/local-variable-methods-in-r.md b/r/r-core/environment-variables-in-r/local-variable-methods-in-r.md new file mode 100644 index 0000000000..f73c78fa01 --- /dev/null +++ b/r/r-core/environment-variables-in-r/local-variable-methods-in-r.md @@ -0,0 +1,90 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Local Variable Methods + +--- + +## Content + +To access the value of a local variable, you can type the name of the variable inside a `print`: + +```r +add <- function(x, y) { + z <- x + y + print(z) +} + +add(5, 10) +# 15 +``` + +You can also use the `get()` function to access the value of a local variable: +```r +add <- function(x, y) { + assign("z", x + y) + print(get("z")) +} + +add(5, 10) +# 15 +``` + +To remove a local variable, you can use the `rm()` function: +```r +add <- function(x, y) { + z <- x + y + rm(z) + print(z) +} + +add(5, 10) +# Error: object 'z' not found +``` + +--- +## Practice + +Which of the following is a way to remove the local variable called `z` in a function in **R**? + +??? + +- `rm(z)` +- `assign("z")` +- `get("z") ` + +--- +## Revision + +Using `get()` access and print the local variable `z`: +```r +add <- function(x, y) { + assign("z", x + y) + ???(???(???)) +} + +add(5, 10) +# 15 +``` + +- `print` +- `get` +- `"z"` +- `z` +- `"get"` \ No newline at end of file diff --git a/r/r-core/environment-variables-in-r/local-variables-in-r.md b/r/r-core/environment-variables-in-r/local-variables-in-r.md index a48e3a1129..58f428488e 100644 --- a/r/r-core/environment-variables-in-r/local-variables-in-r.md +++ b/r/r-core/environment-variables-in-r/local-variables-in-r.md @@ -17,7 +17,7 @@ revisionQuestion: --- -# Local Variables in R +# Local Variables --- @@ -49,41 +49,6 @@ add(5, 10) # 15 ``` -To access the value of a local variable, you can type the name of the variable: - -```r -add <- function(x, y) { - z <- x + y - print(z) -} - -add(5, 10) -# 15 -``` - -You can also use the `get()` function to access the value of a local variable: -```r -add <- function(x, y) { - assign("z", x + y) - print(get("z")) -} - -add(5, 10) -# 15 -``` - -To remove a local variable, you can use the `rm()` function: -```r -add <- function(x, y) { - z <- x + y - rm(z) - print(z) -} - -add(5, 10) -# Error: object 'z' not found -``` - --- ## Practice @@ -91,19 +56,27 @@ Which of the following is **NOT** a way to create a local variable in a function ??? +- `rm("z", x + y)` - `z <- x + y` - `assign("z", x + y)` -- `get("z") <- x + y` -- `rm("z", x + y)` --- ## Revision -What function can be used to remove a local variable in a function in **R**? +**Without** using `assign()`, create a local variable called `z` that sums up the two arguments. Also print the variable. -??? +```r +add <- function(x, y) { + z ??? ??? + print(???) +} + +add(5, 10) +``` -- `delete()` -- `remove()` -- `erase()` -- `rm()` \ No newline at end of file +- `<-` +- `x + y` +- `z` +- `"z"` +- `assign()` +- `x - y` \ No newline at end of file diff --git a/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md b/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md index ecec6695b8..2a437fc06c 100644 --- a/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md +++ b/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md @@ -23,7 +23,6 @@ revisionQuestion: ## Content - Global variables can be accessed from anywhere in your **R** session, while local variables can only be accessed within the function where they are defined. Here is an example that illustrates the difference between global and local variables: diff --git a/r/r-core/functions-in-r/function-methods-in-r.md b/r/r-core/functions-in-r/function-methods-in-r.md index e060752f07..24a29df65c 100644 --- a/r/r-core/functions-in-r/function-methods-in-r.md +++ b/r/r-core/functions-in-r/function-methods-in-r.md @@ -18,7 +18,7 @@ revisionQuestion: --- -# Function Methods in R +# Function Methods --- diff --git a/r/r-core/functions-in-r/functions-in-r.md b/r/r-core/functions-in-r/functions-in-r.md index c122b7dd98..b658e608bc 100644 --- a/r/r-core/functions-in-r/functions-in-r.md +++ b/r/r-core/functions-in-r/functions-in-r.md @@ -18,7 +18,7 @@ revisionQuestion: --- -# Functions in R +# Functions --- diff --git a/r/r-core/looping-techniques-in-r/README.md b/r/r-core/looping-techniques-in-r/README.md index e7ccd961bb..068ad00ca5 100644 --- a/r/r-core/looping-techniques-in-r/README.md +++ b/r/r-core/looping-techniques-in-r/README.md @@ -7,7 +7,8 @@ insights: - what-is-vectorization - statistical-functions-for-vectorization-in-r - math-functions-for-vectorization-in-r - - apply-function + - apply-function-in-r + - how-to-use-the-apply-function-in-r - the-lapply-and-sapply-functions-in-r aspects: diff --git a/r/r-core/looping-techniques-in-r/apply-function.md b/r/r-core/looping-techniques-in-r/apply-function-in-r.md similarity index 68% rename from r/r-core/looping-techniques-in-r/apply-function.md rename to r/r-core/looping-techniques-in-r/apply-function-in-r.md index 7f900c7200..3c46adb406 100644 --- a/r/r-core/looping-techniques-in-r/apply-function.md +++ b/r/r-core/looping-techniques-in-r/apply-function-in-r.md @@ -35,7 +35,7 @@ apply(X, MARGIN, FUN, ...) - `FUN` is the function that you want to apply to the matrix or array. - `...` are any additional arguments that you want to pass to the function. -Here is an example of how to use the `apply` function to apply a function to each row of a matrix: +Here is an example of how to use the `apply` function to apply a `sum` function to each row of a matrix: ```r matrix <- matrix(1:9, 3, 3) print(matrix) @@ -49,38 +49,6 @@ apply(matrix, 1, sum) # 12 15 18 ``` -Here is an example of how to use the `apply` function to apply a function to each column of a matrix: -```r -matrix <- matrix(1:9, 3, 3) -print(matrix) -# [,1] [,2] [,3] -# [1,] 1 4 7 -# [2,] 2 5 8 -# [3,] 3 6 9 - -apply(matrix, 2, sum) -# 6 15 24 -``` - -Here is an example of how to use the `apply` function to apply a function to all elements of a matrix: -```r -matrix <- matrix(1:9, 3, 3) -print(matrix) -# [,1] [,2] [,3] -# [1,] 1 4 7 -# [2,] 2 5 8 -# [3,] 3 6 9 - - -apply(matrix, c(1, 2), sum) -# 45 -``` - - -**Note**: you should be careful when using the `apply` function, because it can result in code that is less readable and more difficult to debug. - -You should consider using the `apply` function only when it is significantly faster than alternative approaches, such as looping through the elements one at a time. - --- ## Practice diff --git a/r/r-core/looping-techniques-in-r/how-to-use-the-apply-function-in-r.md b/r/r-core/looping-techniques-in-r/how-to-use-the-apply-function-in-r.md new file mode 100644 index 0000000000..4817fc0b5b --- /dev/null +++ b/r/r-core/looping-techniques-in-r/how-to-use-the-apply-function-in-r.md @@ -0,0 +1,102 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# Using the apply Function + +--- + +## Content + +Here is an example of how to use the `apply` function to apply a `sum` function to each column of a matrix: +```r +matrix <- matrix(1:9, 3, 3) +print(matrix) +# [,1] [,2] [,3] +# [1,] 1 4 7 +# [2,] 2 5 8 +# [3,] 3 6 9 + +apply(matrix, 2, sum) +# 6 15 24 +``` + +Here is an example of how to use the `apply` function to apply a `sum` function to all elements of a matrix: +```r +matrix <- matrix(1:9, 3, 3) +print(matrix) +# [,1] [,2] [,3] +# [1,] 1 4 7 +# [2,] 2 5 8 +# [3,] 3 6 9 + + +apply(matrix, c(1, 2), sum) +# 45 +``` + +**Note**: you should be careful when using the `apply` function, because it can result in code that is less readable and more difficult to debug. + +You should consider using the `apply` function only when it is significantly faster than alternative approaches, such as looping through the elements one at a time. + +--- +## Practice + +Apply the `sum` function to all elements of a matrix: + +```r +matrix <- matrix(1:9, 3, 3) +print(matrix) +# [,1] [,2] [,3] +# [1,] 1 4 7 +# [2,] 2 5 8 +# [3,] 3 6 9 + +???(???, ???, ???) +# 45 +``` + +- `apply` +- `matrix` +- `c(1, 2)` +- `sum` +- `1` +- `2` + +--- +## Revision + +Apply the `sum` function to each column of a matrix: + +```r +matrix <- matrix(1:9, 3, 3) +print(matrix) +# [,1] [,2] [,3] +# [1,] 1 4 7 +# [2,] 2 5 8 +# [3,] 3 6 9 + +???(???, ???, ???) +# 6 15 24 +``` + +- `apply` +- `matrix` +- `2` +- `sum` +- `c(1, 2)` \ No newline at end of file diff --git a/r/r-core/loops-in-r/README.md b/r/r-core/loops-in-r/README.md index 566eba55e9..597977e35b 100644 --- a/r/r-core/loops-in-r/README.md +++ b/r/r-core/loops-in-r/README.md @@ -5,8 +5,9 @@ description: Learn what loops are and how to use them. insights: - intro-to-loops-in-r - for-loops-in-r - - break-and-next-in-r + - break-and-next-for-in-r - while-loops-in-r + - break-and-next-while-in-r - repeat-loops-in-r - nesting-loops-in-r diff --git a/r/r-core/loops-in-r/break-and-next-in-r.md b/r/r-core/loops-in-r/break-and-next-for-in-r.md similarity index 98% rename from r/r-core/loops-in-r/break-and-next-in-r.md rename to r/r-core/loops-in-r/break-and-next-for-in-r.md index d9f9bcdcd7..91f6931f3c 100644 --- a/r/r-core/loops-in-r/break-and-next-in-r.md +++ b/r/r-core/loops-in-r/break-and-next-for-in-r.md @@ -17,7 +17,7 @@ revisionQuestion: --- -# For loops in R +# break & next in for Loops --- diff --git a/r/r-core/loops-in-r/break-and-next-while-in-r.md b/r/r-core/loops-in-r/break-and-next-while-in-r.md new file mode 100644 index 0000000000..02b415be09 --- /dev/null +++ b/r/r-core/loops-in-r/break-and-next-while-in-r.md @@ -0,0 +1,118 @@ +--- +author: Stefan-Stojanovic + +tags: + - introduction + - discussion +type: normal +category: must-know +practiceQuestion: + formats: + - fill-in-the-gap + - type-in-the-gap + context: standalone +revisionQuestion: + formats: + - fill-in-the-gap + context: standalone + +--- + +# break & next In while Loops + +--- + +## Content + +You can use the `break` and `next` statements to control the flow of a `while` loop. The `break` statement breaks out of the loop and terminates it, while the `next` statement skips the rest of the current iteration and goes to the next one. + +Here is an example of a `while` loop that uses the `break` statement to exit the loop when the value of `i` is 5: +```r +i <- 1 +while (TRUE) { + if (i == 5) { + break + } + print(i) + i <- i + 1 +} +``` + +Here is an example of a `while` loop that uses the `next` statement to skip the iteration when the value of `i` is even: +```r +i <- 1 +while (i <= 10) { + if (i %% 2 == 0) { + i <- i + 1 + next + } + print(i) + i <- i + 1 +} +``` + +You can use the `break` and `next` statements together to create more complex loops. For example, you can use a `break` statement to exit the loop when a certain condition is met, and use a `next` statement to skip certain iterations. +```r +i <- 1 +while (i <= 10) { + if (i == 5) { + break + } + if (i %% 2 == 0) { + i <- i + 1 + next + } + print(i) + i <- i + 1 +} +``` + +--- +## Practice + +Complete the following code snippet to stop when `i` reached 7: + +```r +i <- 1 +while (TRUE) { + if (??? == ???) { + ??? + } + print(i) + i <- i + 1 +} +``` + +- `i` +- `7` +- `break` +- `next` +- `j` +- `< 7` + +--- +## Revision + +What is the output of the following code? + +```r +i <- 1 +while (i <= 10) { + if (i == 5) { + break + } + if (i %% 2 == 0) { + i <- i + 1 + next + } + print(i) + i <- i + 1 +} + +# ??? +``` + +- `1 3` +- `1 2 3 4 5 6 7 8 9 10` +- `2 4 6 8 10` +- `1 2 4 6 8 10` \ No newline at end of file diff --git a/r/r-core/loops-in-r/for-loops-in-r.md b/r/r-core/loops-in-r/for-loops-in-r.md index 3735abf2fd..7d03395942 100644 --- a/r/r-core/loops-in-r/for-loops-in-r.md +++ b/r/r-core/loops-in-r/for-loops-in-r.md @@ -18,7 +18,7 @@ revisionQuestion: --- -# For loops in R +# For loops --- diff --git a/r/r-core/loops-in-r/intro-to-loops-in-r.md b/r/r-core/loops-in-r/intro-to-loops-in-r.md index a475ea333b..e6f33a313a 100644 --- a/r/r-core/loops-in-r/intro-to-loops-in-r.md +++ b/r/r-core/loops-in-r/intro-to-loops-in-r.md @@ -25,51 +25,6 @@ In **R**, you can use loops to perform tasks such as iterating over the elements There are three types of loops in **R**: `for` loops, `while` loops, and `repeat` loops. -### For - -A `for` loop allows you to iterate over a sequence of values or elements. You can use a for loop to execute a block of code for each value or element in the sequence. For example: -```r -# Print the numbers from 1 to 10 -for (i in 1:10) { - print(i) -} - -# Print the elements of a character vector -for (word in c("apple", "banana", "cherry")) { - print(word) -} -``` - -### While - -A `while` loop allows you to execute a block of code as long as a certain condition is TRUE. You can use a while loop to perform an action until a certain condition is met, or to perform an action indefinitely. For example: -```r -# Print the numbers from 1 to 10 -i <- 1 -while (i <= 10) { - print(i) - i <- i + 1 -} - -# Print "Hello, World!" indefinitely -while (TRUE) { - print("Hello, World!") -} -``` - -### Repeat - -A `repeat` loop is similar to a while loop, but the condition is checked at the end of the loop instead of at the beginning. You can use a `repeat` loop to perform an action indefinitely or until a certain condition is met. For example: -```r -# Print the numbers from 1 to 10 -i <- 1 -repeat { - print(i) - i <- i + 1 - if (i > 10) { - break - } -``` --- ## Practice diff --git a/r/r-core/loops-in-r/repeat-loops-in-r.md b/r/r-core/loops-in-r/repeat-loops-in-r.md index 05a2dcc27b..66790719bb 100644 --- a/r/r-core/loops-in-r/repeat-loops-in-r.md +++ b/r/r-core/loops-in-r/repeat-loops-in-r.md @@ -46,7 +46,6 @@ repeat { i <- i + 1 } ``` -You can use the `break` and `next` statements to control the flow of a repeat loop. The `break` statement breaks out of the loop and terminates it, while the `next` statement skips the rest of the current iteration and goes to the next one. Here is an example of a repeat loop that uses the `break` statement to exit the loop when the value of `i` is `5`: ```r diff --git a/r/r-core/loops-in-r/while-loops-in-r.md b/r/r-core/loops-in-r/while-loops-in-r.md index 2f1951d275..6d835651d1 100644 --- a/r/r-core/loops-in-r/while-loops-in-r.md +++ b/r/r-core/loops-in-r/while-loops-in-r.md @@ -18,67 +18,27 @@ revisionQuestion: --- -# Basic Data Types in R +# while Loops --- ## Content -A while loop allows you to execute a block of code as long as a certain condition is TRUE in R. You can use a while loop to perform an action until a certain condition is met, or to perform an action indefinitely. -Here is the syntax for a while loop in R: +A `while` loop allows you to execute a block of code as long as a certain condition is `TRUE`. You can use a `while` loop to perform an action until a certain condition is met, or to perform an action indefinitely. + +Here is the syntax for a `while` loop: ```r while (condition) { # code to be executed } ``` -The condition is an expression that is evaluated before each iteration of the loop. If the condition is TRUE, the code in the loop is executed. If the condition is FALSE, the loop is terminated. - -Here is an example of a while loop that prints the numbers from 1 to 10: -```r -i <- 1 -while (i <= 10) { - print(i) - i <- i + 1 -} -``` -You can use the break and next statements to control the flow of a while loop. The break statement breaks out of the loop and terminates it, while the next statement skips the rest of the current iteration and goes to the next one. - -Here is an example of a while loop that uses the break statement to exit the loop when the value of i is 5: -```r -i <- 1 -while (TRUE) { - if (i == 5) { - break - } - print(i) - i <- i + 1 -} -``` -Here is an example of a while loop that uses the next statement to skip the iteration when the value of i is even: -```r -i <- 1 -while (i <= 10) { - if (i %% 2 == 0) { - i <- i + 1 - next - } - print(i) - i <- i + 1 -} -``` +The condition is an expression that is evaluated before each iteration of the loop. If the condition is `TRUE`, the code in the loop is executed. If the condition is `FALSE`, the loop is terminated. -You can use the break and next statements together to create more complex loops. For example, you can use a break statement to exit the loop when a certain condition is met, and use a next statement to skip certain iterations. +Here is an example of a `while` loop that prints the numbers from 1 to 10: ```r i <- 1 while (i <= 10) { - if (i == 5) { - break - } - if (i %% 2 == 0) { - i <- i + 1 - next - } print(i) i <- i + 1 } From 49df82c2e98c544243394f8f2060e092bb4bb051 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Mon, 6 Mar 2023 10:42:02 +0100 Subject: [PATCH 366/390] replace the old domain with new one --- .../graph-algorithms/bellman-ford-algorithm.md | 2 +- .../mst-algorithms/kruskals-algorithm.md | 2 +- .../mst-algorithms/prims-algorithm.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/comp-sci/data-structures-and-algorithms/graph-algorithms/bellman-ford-algorithm.md b/comp-sci/data-structures-and-algorithms/graph-algorithms/bellman-ford-algorithm.md index 1a569045a4..8c3294a118 100644 --- a/comp-sci/data-structures-and-algorithms/graph-algorithms/bellman-ford-algorithm.md +++ b/comp-sci/data-structures-and-algorithms/graph-algorithms/bellman-ford-algorithm.md @@ -5,7 +5,7 @@ category: must-know links: - >- [Step-by-step, interactive Bellman-Ford algorithm - application](https://www-m9.ma.tum.de/graph-algorithms/spp-bellman-ford/index_en.html){website} + application](https://algorithms.discrete.ma.tum.de//graph-algorithms/spp-bellman-ford/index_en.html){website} revisionQuestion: formats: - fill-in-the-gap diff --git a/comp-sci/data-structures-and-algorithms/mst-algorithms/kruskals-algorithm.md b/comp-sci/data-structures-and-algorithms/mst-algorithms/kruskals-algorithm.md index 370d83f7d7..83549eeb23 100644 --- a/comp-sci/data-structures-and-algorithms/mst-algorithms/kruskals-algorithm.md +++ b/comp-sci/data-structures-and-algorithms/mst-algorithms/kruskals-algorithm.md @@ -5,7 +5,7 @@ category: must-know links: - >- [Step-by-step, interactive Kruskal`s algorithm - application](https://www-m9.ma.tum.de/graph-algorithms/mst-kruskal/index_en.html){website} + application](https://algorithms.discrete.ma.tum.de//graph-algorithms/mst-kruskal/index_en.html){website} revisionQuestion: formats: - fill-in-the-gap diff --git a/comp-sci/data-structures-and-algorithms/mst-algorithms/prims-algorithm.md b/comp-sci/data-structures-and-algorithms/mst-algorithms/prims-algorithm.md index aa7ae97377..08f66a2ed8 100644 --- a/comp-sci/data-structures-and-algorithms/mst-algorithms/prims-algorithm.md +++ b/comp-sci/data-structures-and-algorithms/mst-algorithms/prims-algorithm.md @@ -5,7 +5,7 @@ category: must-know links: - >- [Step-by-step, interactive Kruskal`s algorithm - application](https://www-m9.ma.tum.de/graph-algorithms/mst-prim/index_en.html){website} + application](https://algorithms.discrete.ma.tum.de//graph-algorithms/mst-prim/index_en.html){website} revisionQuestion: formats: - fill-in-the-gap From 6962d81e6ff73b77ab6fce9cdb7698c9ab49288a Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Mon, 6 Mar 2023 10:42:59 +0100 Subject: [PATCH 367/390] update changelog --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 90bfc5cfd7..28671244ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## March 6th 2023 + +### Fixed +- [Comp Sci - 3 insights - Replace old domain with new one for 3 links](https://github.com/enkidevs/curriculum/pull/3170) + ## February 14th 2023 ### Changed From 3daf760a20a5513af9a2ca58d4447da0fa3f0201 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 6 Mar 2023 11:07:48 +0100 Subject: [PATCH 368/390] Update writing-files.md --- python/python-core/basic-file-manipulation/writing-files.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 19da4a6441..29110bff8a 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -63,7 +63,7 @@ text.close() ## Practice -What will the output look like? +What will the file `name.txt` contain after we run this code? ```python file = open('name.txt', 'w+') @@ -78,8 +78,8 @@ file.close() ??? -- Nothing will be generated - JohnChris +- Will be empty - Chris - John From 6292f5f0c6763106b9bb4a59cd6d71740c9d8ecc Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 6 Mar 2023 11:08:50 +0100 Subject: [PATCH 369/390] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae78c54f6b..bdc89649ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,10 +48,12 @@ Types of change: ### Fixed + ## March 6th 2023 ### Fixed - [Comp Sci - 3 insights - Replace old domain with new one for 3 links](https://github.com/enkidevs/curriculum/pull/3170) +- [Python - Writing files - Fix PQ](https://github.com/enkidevs/curriculum/pull/3171) ## February 27th 2023 From a2d8f75cfd3e4a61c5bc04f6ecd86fb3d9301669 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 6 Mar 2023 11:54:07 +0100 Subject: [PATCH 370/390] Update types-string.md remove 2nd line in PQ as the code should be on a single line and add a comment for the output --- .../javascript-core/javascript-strings/types-string.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/javascript/javascript-core/javascript-strings/types-string.md b/javascript/javascript-core/javascript-strings/types-string.md index 07cd9d0624..54e656ae64 100644 --- a/javascript/javascript-core/javascript-strings/types-string.md +++ b/javascript/javascript-core/javascript-strings/types-string.md @@ -61,8 +61,11 @@ There are also special characters that can be used by preceding the character wi What special character is used to add a `new line` to strings denoted with quotes? ```javascript -let myString = 'this will ??? - be displayed on two lines'; +let myString = 'this will ??? be displayed on two lines'; + +// Output: +// this will +// be displayed on two lines ``` - `\n` From 9a29e0891552615d30288df1533d0b7125fcdbfa Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 6 Mar 2023 11:54:51 +0100 Subject: [PATCH 371/390] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae78c54f6b..c7a287aa36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,7 @@ Types of change: ### Fixed - [Comp Sci - 3 insights - Replace old domain with new one for 3 links](https://github.com/enkidevs/curriculum/pull/3170) +- [Javascript - Types Strings - Update PQ](https://github.com/enkidevs/curriculum/pull/3172) ## February 27th 2023 From a28f91de2810506d27f0413d12d5fb01f9007b6d Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 6 Mar 2023 11:55:52 +0100 Subject: [PATCH 372/390] Update types-string.md --- javascript/javascript-core/javascript-strings/types-string.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/javascript-core/javascript-strings/types-string.md b/javascript/javascript-core/javascript-strings/types-string.md index 54e656ae64..a72f41cfcf 100644 --- a/javascript/javascript-core/javascript-strings/types-string.md +++ b/javascript/javascript-core/javascript-strings/types-string.md @@ -63,7 +63,7 @@ What special character is used to add a `new line` to strings denoted with quote ```javascript let myString = 'this will ??? be displayed on two lines'; -// Output: +console.log(myString); // this will // be displayed on two lines ``` From 07bf0901c94dc11e2ccbe93ddcd4742eca259fc6 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Mon, 6 Mar 2023 13:41:55 +0100 Subject: [PATCH 373/390] Update README.md --- r/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/r/README.md b/r/README.md index 66f0acb1d0..e1d41cd62c 100644 --- a/r/README.md +++ b/r/README.md @@ -4,7 +4,7 @@ description: A programming language for statistical computing and graphics. color: D2FFA6 -icon: https://img.enkipro.com/1422996b1142be465484e6ee505547be.png +icon: https://img.enkipro.com/c3e32170cfa371e46883a17a8ccc057c.png language: r From dfa7fa337e489b802575ebb804b079d19b45e859 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Mon, 6 Mar 2023 22:28:44 +0100 Subject: [PATCH 374/390] split loops workout and minor improvement --- .../if-else-in-r.md | 4 --- .../if-statements-in-r.md | 4 --- .../nesting-if-else-in-r-ii.md | 4 +-- .../nesting-if-else-in-r.md | 4 +-- .../switch-statements-in-r.md | 4 --- .../what-are-conditional-statements-r.md | 4 --- .../as-character-r.md | 4 --- .../data-type-conversions-in-r/as-double-r.md | 4 --- .../as-integer-r.md | 4 --- .../as-logical-r.md | 4 --- .../data-type-conversions-in-r/as-matrix-r.md | 4 --- .../as-numeric-r.md | 4 --- .../data-type-conversions-in-r/as-vector-r.md | 4 --- .../data-type-conversion-r.md | 4 --- .../global-environment-variables-in-r.md | 4 --- .../local-variable-methods-in-r.md | 4 --- .../local-variables-in-r.md | 4 --- .../local-vs-global-variables-in-r.md | 4 --- .../the-matrix-function-r.md | 4 --- .../the-reduce-function-r.md | 4 --- .../functions-in-r-ii/the-sum-function-r.md | 4 --- .../function-methods-in-r-ii.md | 4 --- .../functions-in-r/function-methods-in-r.md | 4 --- r/r-core/functions-in-r/functions-in-r.md | 4 --- .../the-paste-function-in-r-ii.md | 4 --- .../functions-in-r/the-paste-function-in-r.md | 4 --- .../intro-to-r/first-program-hello-world-r.md | 4 --- r/r-core/intro-to-r/installing-r-locally.md | 4 --- r/r-core/intro-to-r/what-is-r.md | 6 ++-- r/r-core/intro-to-r/why-learn-r.md | 4 +-- .../apply-function-in-r.md | 4 --- .../how-to-use-the-apply-function-in-r.md | 4 --- .../looping-techniques-in-r.md | 4 --- .../math-functions-for-vectorization-in-r.md | 4 --- ...stical-functions-for-vectorization-in-r.md | 4 --- .../the-lapply-and-sapply-functions-in-r.md | 4 --- .../what-is-vectorization.md | 4 --- r/r-core/loops-in-r-ii/README.md | 12 +++++++ .../break-and-next-while-in-r.md | 4 --- .../repeat-loops-in-r.md | 6 +--- .../while-loops-in-r.md | 4 --- r/r-core/loops-in-r/README.md | 5 +-- .../loops-in-r/break-and-next-for-in-r.md | 4 --- r/r-core/loops-in-r/for-loops-in-r.md | 4 --- r/r-core/loops-in-r/intro-to-loops-in-r.md | 4 --- r/r-core/loops-in-r/nesting-loops-in-r.md | 4 --- .../programs-in-r/area-of-a-rectangle-r.md | 4 --- r/r-core/programs-in-r/calculator-r.md | 4 --- r/r-core/programs-in-r/factorial-r.md | 6 +--- .../programs-in-r/fibonacci-sequence-r.md | 6 +--- r/r-core/programs-in-r/fizz-buzz-r.md | 4 --- .../programs-in-r/prime-number-checker-r.md | 4 --- r/r-core/programs-in-r/reverse-a-string-r.md | 6 +--- .../as-numeric.md | 4 --- .../open-and-close-a-file.md | 4 --- .../readline-in-r.md | 4 --- .../the-file-function.md | 4 --- .../writelines-in-r.md | 4 --- ...another-way-to-create-dictionaries-in-r.md | 4 --- .../dictionary-methods-in-r-ii.md | 4 --- .../dictionary-methods-in-r.md | 4 --- .../intro-to-dictionaries-r.md | 4 --- .../unordered-data-types-in-r-ii.md | 4 --- .../unordered-data-types-in-r.md | 4 --- .../assignment-operators-r.md | 31 ++++++++----------- .../basic-data-types-r.md | 4 --- .../combining-variables-in-r.md | 4 --- .../creating-and-storing-variables-in-r.md | 4 --- .../printing-variables-in-r.md | 4 --- 69 files changed, 35 insertions(+), 287 deletions(-) create mode 100644 r/r-core/loops-in-r-ii/README.md rename r/r-core/{loops-in-r => loops-in-r-ii}/break-and-next-while-in-r.md (97%) rename r/r-core/{loops-in-r => loops-in-r-ii}/repeat-loops-in-r.md (96%) rename r/r-core/{loops-in-r => loops-in-r-ii}/while-loops-in-r.md (97%) diff --git a/r/r-core/conditional-statements-in-r/if-else-in-r.md b/r/r-core/conditional-statements-in-r/if-else-in-r.md index fc273d72cd..6dbdd9e616 100644 --- a/r/r-core/conditional-statements-in-r/if-else-in-r.md +++ b/r/r-core/conditional-statements-in-r/if-else-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/conditional-statements-in-r/if-statements-in-r.md b/r/r-core/conditional-statements-in-r/if-statements-in-r.md index cb50c6fabd..9f353ed81d 100644 --- a/r/r-core/conditional-statements-in-r/if-statements-in-r.md +++ b/r/r-core/conditional-statements-in-r/if-statements-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r-ii.md b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r-ii.md index a00e01b4ae..ca68732141 100644 --- a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r-ii.md +++ b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r-ii.md @@ -1,8 +1,6 @@ --- author: Stefan-Stojanovic -tags: - - introduction - - discussion + type: normal category: must-know practiceQuestion: diff --git a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md index 26e2bf1795..c29d61189f 100644 --- a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md +++ b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md @@ -1,8 +1,6 @@ --- author: Stefan-Stojanovic -tags: - - introduction - - discussion + type: normal category: must-know diff --git a/r/r-core/conditional-statements-in-r/switch-statements-in-r.md b/r/r-core/conditional-statements-in-r/switch-statements-in-r.md index dc289df4ad..b2f44ba3e6 100644 --- a/r/r-core/conditional-statements-in-r/switch-statements-in-r.md +++ b/r/r-core/conditional-statements-in-r/switch-statements-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/conditional-statements-in-r/what-are-conditional-statements-r.md b/r/r-core/conditional-statements-in-r/what-are-conditional-statements-r.md index 020ceec5ea..c9ea19dc57 100644 --- a/r/r-core/conditional-statements-in-r/what-are-conditional-statements-r.md +++ b/r/r-core/conditional-statements-in-r/what-are-conditional-statements-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know diff --git a/r/r-core/data-type-conversions-in-r/as-character-r.md b/r/r-core/data-type-conversions-in-r/as-character-r.md index 0d8e99799b..3f1fc26f9c 100644 --- a/r/r-core/data-type-conversions-in-r/as-character-r.md +++ b/r/r-core/data-type-conversions-in-r/as-character-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/data-type-conversions-in-r/as-double-r.md b/r/r-core/data-type-conversions-in-r/as-double-r.md index 20957c5de6..cadbc38c56 100644 --- a/r/r-core/data-type-conversions-in-r/as-double-r.md +++ b/r/r-core/data-type-conversions-in-r/as-double-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/data-type-conversions-in-r/as-integer-r.md b/r/r-core/data-type-conversions-in-r/as-integer-r.md index f67d4d9bf3..c0136cbc51 100644 --- a/r/r-core/data-type-conversions-in-r/as-integer-r.md +++ b/r/r-core/data-type-conversions-in-r/as-integer-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/data-type-conversions-in-r/as-logical-r.md b/r/r-core/data-type-conversions-in-r/as-logical-r.md index edc976a660..9586bf2ff2 100644 --- a/r/r-core/data-type-conversions-in-r/as-logical-r.md +++ b/r/r-core/data-type-conversions-in-r/as-logical-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/data-type-conversions-in-r/as-matrix-r.md b/r/r-core/data-type-conversions-in-r/as-matrix-r.md index 2ae558b9c9..f3becfaece 100644 --- a/r/r-core/data-type-conversions-in-r/as-matrix-r.md +++ b/r/r-core/data-type-conversions-in-r/as-matrix-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/data-type-conversions-in-r/as-numeric-r.md b/r/r-core/data-type-conversions-in-r/as-numeric-r.md index 2f6c954049..5c56835a4f 100644 --- a/r/r-core/data-type-conversions-in-r/as-numeric-r.md +++ b/r/r-core/data-type-conversions-in-r/as-numeric-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/data-type-conversions-in-r/as-vector-r.md b/r/r-core/data-type-conversions-in-r/as-vector-r.md index c16ee62207..63a36b9b9d 100644 --- a/r/r-core/data-type-conversions-in-r/as-vector-r.md +++ b/r/r-core/data-type-conversions-in-r/as-vector-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/data-type-conversions-in-r/data-type-conversion-r.md b/r/r-core/data-type-conversions-in-r/data-type-conversion-r.md index 4f3207fc90..7c65bcc516 100644 --- a/r/r-core/data-type-conversions-in-r/data-type-conversion-r.md +++ b/r/r-core/data-type-conversions-in-r/data-type-conversion-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know diff --git a/r/r-core/environment-variables-in-r/global-environment-variables-in-r.md b/r/r-core/environment-variables-in-r/global-environment-variables-in-r.md index 1e78486fce..894189a36f 100644 --- a/r/r-core/environment-variables-in-r/global-environment-variables-in-r.md +++ b/r/r-core/environment-variables-in-r/global-environment-variables-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/environment-variables-in-r/local-variable-methods-in-r.md b/r/r-core/environment-variables-in-r/local-variable-methods-in-r.md index f73c78fa01..d622439464 100644 --- a/r/r-core/environment-variables-in-r/local-variable-methods-in-r.md +++ b/r/r-core/environment-variables-in-r/local-variable-methods-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/environment-variables-in-r/local-variables-in-r.md b/r/r-core/environment-variables-in-r/local-variables-in-r.md index 58f428488e..5353b8e6aa 100644 --- a/r/r-core/environment-variables-in-r/local-variables-in-r.md +++ b/r/r-core/environment-variables-in-r/local-variables-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md b/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md index 2a437fc06c..5ad8c02f3f 100644 --- a/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md +++ b/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/functions-in-r-ii/the-matrix-function-r.md b/r/r-core/functions-in-r-ii/the-matrix-function-r.md index fc00b518ec..dc73b29e71 100644 --- a/r/r-core/functions-in-r-ii/the-matrix-function-r.md +++ b/r/r-core/functions-in-r-ii/the-matrix-function-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/functions-in-r-ii/the-reduce-function-r.md b/r/r-core/functions-in-r-ii/the-reduce-function-r.md index 89f4270ced..d4e4318ac0 100644 --- a/r/r-core/functions-in-r-ii/the-reduce-function-r.md +++ b/r/r-core/functions-in-r-ii/the-reduce-function-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/functions-in-r-ii/the-sum-function-r.md b/r/r-core/functions-in-r-ii/the-sum-function-r.md index 75e459e05e..31da0231ac 100644 --- a/r/r-core/functions-in-r-ii/the-sum-function-r.md +++ b/r/r-core/functions-in-r-ii/the-sum-function-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/functions-in-r/function-methods-in-r-ii.md b/r/r-core/functions-in-r/function-methods-in-r-ii.md index 2a92ede17c..c3a65018de 100644 --- a/r/r-core/functions-in-r/function-methods-in-r-ii.md +++ b/r/r-core/functions-in-r/function-methods-in-r-ii.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/functions-in-r/function-methods-in-r.md b/r/r-core/functions-in-r/function-methods-in-r.md index 24a29df65c..e01fca5972 100644 --- a/r/r-core/functions-in-r/function-methods-in-r.md +++ b/r/r-core/functions-in-r/function-methods-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/functions-in-r/functions-in-r.md b/r/r-core/functions-in-r/functions-in-r.md index b658e608bc..a96180b9f6 100644 --- a/r/r-core/functions-in-r/functions-in-r.md +++ b/r/r-core/functions-in-r/functions-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/functions-in-r/the-paste-function-in-r-ii.md b/r/r-core/functions-in-r/the-paste-function-in-r-ii.md index 76dce66aff..df5080c9bf 100644 --- a/r/r-core/functions-in-r/the-paste-function-in-r-ii.md +++ b/r/r-core/functions-in-r/the-paste-function-in-r-ii.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/functions-in-r/the-paste-function-in-r.md b/r/r-core/functions-in-r/the-paste-function-in-r.md index 1e4965573d..7dc0dcfd4b 100644 --- a/r/r-core/functions-in-r/the-paste-function-in-r.md +++ b/r/r-core/functions-in-r/the-paste-function-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/intro-to-r/first-program-hello-world-r.md b/r/r-core/intro-to-r/first-program-hello-world-r.md index c949a1376d..6e426b3b9b 100644 --- a/r/r-core/intro-to-r/first-program-hello-world-r.md +++ b/r/r-core/intro-to-r/first-program-hello-world-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/intro-to-r/installing-r-locally.md b/r/r-core/intro-to-r/installing-r-locally.md index 5c7912c5ae..df36215b03 100644 --- a/r/r-core/intro-to-r/installing-r-locally.md +++ b/r/r-core/intro-to-r/installing-r-locally.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know diff --git a/r/r-core/intro-to-r/what-is-r.md b/r/r-core/intro-to-r/what-is-r.md index b159378a19..c93a808e49 100644 --- a/r/r-core/intro-to-r/what-is-r.md +++ b/r/r-core/intro-to-r/what-is-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: @@ -29,6 +25,8 @@ y <- c(1, 4, 9, 16, 25) plot(x, y) ``` +![basic-plot](https://img.enkipro.com/3c8221e34bd83ad566107e6acd2e285a.png) + **R** also has a vast community of users and developers, which has led to the creation of a large number of packages that extend its functionality. This means that **R** is capable of handling a wide range of tasks, from data manipulation and visualization to machine learning and data analysis. > 💬 Why are you interested in **R**? diff --git a/r/r-core/intro-to-r/why-learn-r.md b/r/r-core/intro-to-r/why-learn-r.md index 577447cebb..cc3b4cdceb 100644 --- a/r/r-core/intro-to-r/why-learn-r.md +++ b/r/r-core/intro-to-r/why-learn-r.md @@ -1,9 +1,7 @@ --- author: Stefan-Stojanovic -tags: - - introduction - - discussion + type: normal diff --git a/r/r-core/looping-techniques-in-r/apply-function-in-r.md b/r/r-core/looping-techniques-in-r/apply-function-in-r.md index 3c46adb406..e310f34748 100644 --- a/r/r-core/looping-techniques-in-r/apply-function-in-r.md +++ b/r/r-core/looping-techniques-in-r/apply-function-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/looping-techniques-in-r/how-to-use-the-apply-function-in-r.md b/r/r-core/looping-techniques-in-r/how-to-use-the-apply-function-in-r.md index 4817fc0b5b..1623372809 100644 --- a/r/r-core/looping-techniques-in-r/how-to-use-the-apply-function-in-r.md +++ b/r/r-core/looping-techniques-in-r/how-to-use-the-apply-function-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/looping-techniques-in-r/looping-techniques-in-r.md b/r/r-core/looping-techniques-in-r/looping-techniques-in-r.md index 04c06feba6..4e39c98310 100644 --- a/r/r-core/looping-techniques-in-r/looping-techniques-in-r.md +++ b/r/r-core/looping-techniques-in-r/looping-techniques-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know diff --git a/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md b/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md index b92a0c028d..eadf6bfe79 100644 --- a/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md +++ b/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/looping-techniques-in-r/statistical-functions-for-vectorization-in-r.md b/r/r-core/looping-techniques-in-r/statistical-functions-for-vectorization-in-r.md index 2e8e6fe724..977acadd53 100644 --- a/r/r-core/looping-techniques-in-r/statistical-functions-for-vectorization-in-r.md +++ b/r/r-core/looping-techniques-in-r/statistical-functions-for-vectorization-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/looping-techniques-in-r/the-lapply-and-sapply-functions-in-r.md b/r/r-core/looping-techniques-in-r/the-lapply-and-sapply-functions-in-r.md index 050a2cb060..8936f7b39a 100644 --- a/r/r-core/looping-techniques-in-r/the-lapply-and-sapply-functions-in-r.md +++ b/r/r-core/looping-techniques-in-r/the-lapply-and-sapply-functions-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/looping-techniques-in-r/what-is-vectorization.md b/r/r-core/looping-techniques-in-r/what-is-vectorization.md index 7c8ee51324..91816180fb 100644 --- a/r/r-core/looping-techniques-in-r/what-is-vectorization.md +++ b/r/r-core/looping-techniques-in-r/what-is-vectorization.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/loops-in-r-ii/README.md b/r/r-core/loops-in-r-ii/README.md new file mode 100644 index 0000000000..828c825f88 --- /dev/null +++ b/r/r-core/loops-in-r-ii/README.md @@ -0,0 +1,12 @@ +name: while & repeat loops + +description: Next to for loops, R has while and repeat loops. + +insights: + - while-loops-in-r + - break-and-next-while-in-r + - repeat-loops-in-r + +aspects: + - workout + - deep \ No newline at end of file diff --git a/r/r-core/loops-in-r/break-and-next-while-in-r.md b/r/r-core/loops-in-r-ii/break-and-next-while-in-r.md similarity index 97% rename from r/r-core/loops-in-r/break-and-next-while-in-r.md rename to r/r-core/loops-in-r-ii/break-and-next-while-in-r.md index 02b415be09..b7b8c242c1 100644 --- a/r/r-core/loops-in-r/break-and-next-while-in-r.md +++ b/r/r-core/loops-in-r-ii/break-and-next-while-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/loops-in-r/repeat-loops-in-r.md b/r/r-core/loops-in-r-ii/repeat-loops-in-r.md similarity index 96% rename from r/r-core/loops-in-r/repeat-loops-in-r.md rename to r/r-core/loops-in-r-ii/repeat-loops-in-r.md index 66790719bb..b10646dc66 100644 --- a/r/r-core/loops-in-r/repeat-loops-in-r.md +++ b/r/r-core/loops-in-r-ii/repeat-loops-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: @@ -18,7 +14,7 @@ revisionQuestion: --- -# Basic Data Types in R +# repeat Loops --- diff --git a/r/r-core/loops-in-r/while-loops-in-r.md b/r/r-core/loops-in-r-ii/while-loops-in-r.md similarity index 97% rename from r/r-core/loops-in-r/while-loops-in-r.md rename to r/r-core/loops-in-r-ii/while-loops-in-r.md index 6d835651d1..2246d122d8 100644 --- a/r/r-core/loops-in-r/while-loops-in-r.md +++ b/r/r-core/loops-in-r-ii/while-loops-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/loops-in-r/README.md b/r/r-core/loops-in-r/README.md index 597977e35b..3aa793ad7f 100644 --- a/r/r-core/loops-in-r/README.md +++ b/r/r-core/loops-in-r/README.md @@ -1,4 +1,4 @@ -name: Loops +name: for Loops description: Learn what loops are and how to use them. @@ -6,9 +6,6 @@ insights: - intro-to-loops-in-r - for-loops-in-r - break-and-next-for-in-r - - while-loops-in-r - - break-and-next-while-in-r - - repeat-loops-in-r - nesting-loops-in-r aspects: diff --git a/r/r-core/loops-in-r/break-and-next-for-in-r.md b/r/r-core/loops-in-r/break-and-next-for-in-r.md index 91f6931f3c..5e833c65eb 100644 --- a/r/r-core/loops-in-r/break-and-next-for-in-r.md +++ b/r/r-core/loops-in-r/break-and-next-for-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/loops-in-r/for-loops-in-r.md b/r/r-core/loops-in-r/for-loops-in-r.md index 7d03395942..15ad2dbad0 100644 --- a/r/r-core/loops-in-r/for-loops-in-r.md +++ b/r/r-core/loops-in-r/for-loops-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/loops-in-r/intro-to-loops-in-r.md b/r/r-core/loops-in-r/intro-to-loops-in-r.md index e6f33a313a..6429c8e9c1 100644 --- a/r/r-core/loops-in-r/intro-to-loops-in-r.md +++ b/r/r-core/loops-in-r/intro-to-loops-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/loops-in-r/nesting-loops-in-r.md b/r/r-core/loops-in-r/nesting-loops-in-r.md index 8b80346447..4d8dbfde9a 100644 --- a/r/r-core/loops-in-r/nesting-loops-in-r.md +++ b/r/r-core/loops-in-r/nesting-loops-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/programs-in-r/area-of-a-rectangle-r.md b/r/r-core/programs-in-r/area-of-a-rectangle-r.md index 90adfec96a..570895d80b 100644 --- a/r/r-core/programs-in-r/area-of-a-rectangle-r.md +++ b/r/r-core/programs-in-r/area-of-a-rectangle-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know --- diff --git a/r/r-core/programs-in-r/calculator-r.md b/r/r-core/programs-in-r/calculator-r.md index e29c141a59..e6c3c356d0 100644 --- a/r/r-core/programs-in-r/calculator-r.md +++ b/r/r-core/programs-in-r/calculator-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know diff --git a/r/r-core/programs-in-r/factorial-r.md b/r/r-core/programs-in-r/factorial-r.md index 760d122c97..ec9b7e21e7 100644 --- a/r/r-core/programs-in-r/factorial-r.md +++ b/r/r-core/programs-in-r/factorial-r.md @@ -1,15 +1,11 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know --- -# Basic Data Types in R +# Factorial --- diff --git a/r/r-core/programs-in-r/fibonacci-sequence-r.md b/r/r-core/programs-in-r/fibonacci-sequence-r.md index fd8e780a0b..1710682ce1 100644 --- a/r/r-core/programs-in-r/fibonacci-sequence-r.md +++ b/r/r-core/programs-in-r/fibonacci-sequence-r.md @@ -1,15 +1,11 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know --- -# Basic Data Types in R +# Fibonacci Sequence --- diff --git a/r/r-core/programs-in-r/fizz-buzz-r.md b/r/r-core/programs-in-r/fizz-buzz-r.md index c7fe74126d..183ddd07e6 100644 --- a/r/r-core/programs-in-r/fizz-buzz-r.md +++ b/r/r-core/programs-in-r/fizz-buzz-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know diff --git a/r/r-core/programs-in-r/prime-number-checker-r.md b/r/r-core/programs-in-r/prime-number-checker-r.md index 657dd2edc8..7ee2377564 100644 --- a/r/r-core/programs-in-r/prime-number-checker-r.md +++ b/r/r-core/programs-in-r/prime-number-checker-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know diff --git a/r/r-core/programs-in-r/reverse-a-string-r.md b/r/r-core/programs-in-r/reverse-a-string-r.md index aacf58a058..41aa9a403f 100644 --- a/r/r-core/programs-in-r/reverse-a-string-r.md +++ b/r/r-core/programs-in-r/reverse-a-string-r.md @@ -1,15 +1,11 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know --- -# Basic Data Types in R +# Reverse A String --- diff --git a/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md b/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md index d256a1f244..012b076a2c 100644 --- a/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md +++ b/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/reading-and-writing-data-to-and-from-files/open-and-close-a-file.md b/r/r-core/reading-and-writing-data-to-and-from-files/open-and-close-a-file.md index ae7a949df5..9c44a697cc 100644 --- a/r/r-core/reading-and-writing-data-to-and-from-files/open-and-close-a-file.md +++ b/r/r-core/reading-and-writing-data-to-and-from-files/open-and-close-a-file.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/reading-and-writing-data-to-and-from-files/readline-in-r.md b/r/r-core/reading-and-writing-data-to-and-from-files/readline-in-r.md index 0efb1a05cc..ee80560cfa 100644 --- a/r/r-core/reading-and-writing-data-to-and-from-files/readline-in-r.md +++ b/r/r-core/reading-and-writing-data-to-and-from-files/readline-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/reading-and-writing-data-to-and-from-files/the-file-function.md b/r/r-core/reading-and-writing-data-to-and-from-files/the-file-function.md index 1ec8f748ba..22db7014e1 100644 --- a/r/r-core/reading-and-writing-data-to-and-from-files/the-file-function.md +++ b/r/r-core/reading-and-writing-data-to-and-from-files/the-file-function.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/reading-and-writing-data-to-and-from-files/writelines-in-r.md b/r/r-core/reading-and-writing-data-to-and-from-files/writelines-in-r.md index 00971017b9..d7e5354ab1 100644 --- a/r/r-core/reading-and-writing-data-to-and-from-files/writelines-in-r.md +++ b/r/r-core/reading-and-writing-data-to-and-from-files/writelines-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/unordered-data-types-r/another-way-to-create-dictionaries-in-r.md b/r/r-core/unordered-data-types-r/another-way-to-create-dictionaries-in-r.md index a746566651..a1b6ea5506 100644 --- a/r/r-core/unordered-data-types-r/another-way-to-create-dictionaries-in-r.md +++ b/r/r-core/unordered-data-types-r/another-way-to-create-dictionaries-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/unordered-data-types-r/dictionary-methods-in-r-ii.md b/r/r-core/unordered-data-types-r/dictionary-methods-in-r-ii.md index 229c387fdb..67d0e7aa72 100644 --- a/r/r-core/unordered-data-types-r/dictionary-methods-in-r-ii.md +++ b/r/r-core/unordered-data-types-r/dictionary-methods-in-r-ii.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md b/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md index 2d6e203344..f374e0b601 100644 --- a/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md +++ b/r/r-core/unordered-data-types-r/dictionary-methods-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md b/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md index a4c27788d3..5c7bfa5dab 100644 --- a/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md +++ b/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/unordered-data-types-r/unordered-data-types-in-r-ii.md b/r/r-core/unordered-data-types-r/unordered-data-types-in-r-ii.md index a708ec73e7..d78f6e9a95 100644 --- a/r/r-core/unordered-data-types-r/unordered-data-types-in-r-ii.md +++ b/r/r-core/unordered-data-types-r/unordered-data-types-in-r-ii.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/unordered-data-types-r/unordered-data-types-in-r.md b/r/r-core/unordered-data-types-r/unordered-data-types-in-r.md index 80e29767bf..1c8f504ef8 100644 --- a/r/r-core/unordered-data-types-r/unordered-data-types-in-r.md +++ b/r/r-core/unordered-data-types-r/unordered-data-types-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/variables-and-data-types/assignment-operators-r.md b/r/r-core/variables-and-data-types/assignment-operators-r.md index 76ca9e0e2d..5e9c860bb7 100644 --- a/r/r-core/variables-and-data-types/assignment-operators-r.md +++ b/r/r-core/variables-and-data-types/assignment-operators-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: @@ -53,25 +49,24 @@ print(y) --- ## Practice -Which of the following is a basic data type in R? - -??? +The most common assignment operator in R is ???. -- `numeric` -- `integer` -- `matrix` -- `function` -- `data frame` +- `<-` +- `->` +- `==` +- `is` --- ## Revision -What is the basic data type for a vector of categorical variables in R? +Which of these variables uses the recommended way of assigning values in **R**? + +```r +x <- 5 +y = 10 +``` ??? -- `factor` -- `character` -- `numeric` -- `logical` -- `NULL` \ No newline at end of file +- x +- y \ No newline at end of file diff --git a/r/r-core/variables-and-data-types/basic-data-types-r.md b/r/r-core/variables-and-data-types/basic-data-types-r.md index 85e813b7e9..d942a3a7b8 100644 --- a/r/r-core/variables-and-data-types/basic-data-types-r.md +++ b/r/r-core/variables-and-data-types/basic-data-types-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/variables-and-data-types/combining-variables-in-r.md b/r/r-core/variables-and-data-types/combining-variables-in-r.md index af53506118..aa701d9085 100644 --- a/r/r-core/variables-and-data-types/combining-variables-in-r.md +++ b/r/r-core/variables-and-data-types/combining-variables-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md b/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md index 96af5d4ada..915dc0d84d 100644 --- a/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md +++ b/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: diff --git a/r/r-core/variables-and-data-types/printing-variables-in-r.md b/r/r-core/variables-and-data-types/printing-variables-in-r.md index 0527bf95c1..698bf81988 100644 --- a/r/r-core/variables-and-data-types/printing-variables-in-r.md +++ b/r/r-core/variables-and-data-types/printing-variables-in-r.md @@ -1,9 +1,5 @@ --- author: Stefan-Stojanovic - -tags: - - introduction - - discussion type: normal category: must-know practiceQuestion: From 8075c195446e7d1e366d40cc569a46a1b637c8bb Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Tue, 7 Mar 2023 11:11:58 +0100 Subject: [PATCH 375/390] minor improvements --- r/README.md | 4 +- .../nesting-if-else-in-r.md | 6 +-- .../switch-statements-in-r.md | 10 ++--- .../as-character-r.md | 1 - .../data-type-conversions-in-r/as-double-r.md | 2 +- .../as-integer-r.md | 11 +++-- .../as-logical-r.md | 10 ++--- r/r-core/environment-variables-in-r/README.md | 2 +- r/r-core/functions-in-r-ii/README.md | 4 +- .../intro-to-r/first-program-hello-world-r.md | 12 ++++-- r/r-core/intro-to-r/what-is-r.md | 4 +- .../programs-in-r/area-of-a-rectangle-r.md | 2 +- r/r-core/programs-in-r/calculator-r.md | 40 ++++++++++++++----- .../as-numeric.md | 2 +- .../basic-data-types-r.md | 1 - 15 files changed, 63 insertions(+), 48 deletions(-) diff --git a/r/README.md b/r/README.md index e1d41cd62c..a524393139 100644 --- a/r/README.md +++ b/r/README.md @@ -2,9 +2,9 @@ name: R description: A programming language for statistical computing and graphics. -color: D2FFA6 +color: A9D0FF -icon: https://img.enkipro.com/c3e32170cfa371e46883a17a8ccc057c.png +icon: https://img.enkipro.com/ddf9da3da671b9073e995f1bb129d8f2.png language: r diff --git a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md index c29d61189f..8ef2d2c099 100644 --- a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md +++ b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r.md @@ -1,6 +1,5 @@ --- author: Stefan-Stojanovic - type: normal category: must-know @@ -14,11 +13,8 @@ category: must-know Have you ever wanted to execute different actions in your R code based on multiple conditions? One way to do this is by using nested `ifelse` statements. -### When to use nested ifelse statements ---- - Nested `ifelse` statements can be useful when you have multiple conditions to check and you want to execute different actions based on the results of those conditions. However, it is important to be careful when using nested `ifelse` statements, as they can quickly become difficult to read and maintain if you have too many levels of nesting. -Let's create a nested `ifelse` in teh next insight. \ No newline at end of file +Let's create a nested `ifelse` in the next insight. \ No newline at end of file diff --git a/r/r-core/conditional-statements-in-r/switch-statements-in-r.md b/r/r-core/conditional-statements-in-r/switch-statements-in-r.md index b2f44ba3e6..92904e96d7 100644 --- a/r/r-core/conditional-statements-in-r/switch-statements-in-r.md +++ b/r/r-core/conditional-statements-in-r/switch-statements-in-r.md @@ -48,12 +48,12 @@ c) Iterate over a sequence of values d) None of the above ``` -??? +???) -- `a)` -- `b)` -- `c)` -- `d)` +- `a` +- `b` +- `c` +- `d` --- ## Revision diff --git a/r/r-core/data-type-conversions-in-r/as-character-r.md b/r/r-core/data-type-conversions-in-r/as-character-r.md index 3f1fc26f9c..cfd3cb3ebc 100644 --- a/r/r-core/data-type-conversions-in-r/as-character-r.md +++ b/r/r-core/data-type-conversions-in-r/as-character-r.md @@ -21,7 +21,6 @@ revisionQuestion: ## Content - The `as.character` converts an object to character (string) type. ```r diff --git a/r/r-core/data-type-conversions-in-r/as-double-r.md b/r/r-core/data-type-conversions-in-r/as-double-r.md index cadbc38c56..475963e42d 100644 --- a/r/r-core/data-type-conversions-in-r/as-double-r.md +++ b/r/r-core/data-type-conversions-in-r/as-double-r.md @@ -46,7 +46,7 @@ x <- c(5, 33, 315) x <- ??? print(x) -# 1.0 2.0 345.0 +# 5.0 33.0 315.0 ``` - `as.double(x)` diff --git a/r/r-core/data-type-conversions-in-r/as-integer-r.md b/r/r-core/data-type-conversions-in-r/as-integer-r.md index c0136cbc51..d268b0ce96 100644 --- a/r/r-core/data-type-conversions-in-r/as-integer-r.md +++ b/r/r-core/data-type-conversions-in-r/as-integer-r.md @@ -41,7 +41,7 @@ print(v) --- ## Practice -Convert the following character vector to a integer type using the `as.integer` function: +Convert the following character vector to an integer type using the `as.integer` function: ```r x <- ???("1", "2", "3", "4", "5") @@ -60,14 +60,13 @@ print(x) --- ## Revision -Convert the following character vector to a integer type using the `as.integer` function: +Convert the following number to an integer type using the `as.integer` function: ```r -x <- c("1", "2", "3", "4", "5") - +x <- 13.57 x <- ??? -print(x) -# 1 2 3 4 5 +print(x) +# 13 ``` - `as.integer(x)` diff --git a/r/r-core/data-type-conversions-in-r/as-logical-r.md b/r/r-core/data-type-conversions-in-r/as-logical-r.md index 9586bf2ff2..c0bd5048dd 100644 --- a/r/r-core/data-type-conversions-in-r/as-logical-r.md +++ b/r/r-core/data-type-conversions-in-r/as-logical-r.md @@ -48,20 +48,20 @@ print(m) Which of the following will create a logical vector from a character vector? ```r -# A) +# A v <- as.vector(c(TRUE, FALSE, TRUE)) -# B) +# B v <- as.logical(c(TRUE, FALSE, TRUE)) -# C) +# C v <- as.vector(c("True", "False", "True")) -# D) +# D v <- as.logical(c("True", "False", "True")) ``` -???) +??? - `D` - `A` diff --git a/r/r-core/environment-variables-in-r/README.md b/r/r-core/environment-variables-in-r/README.md index 0360d79d07..0af82ca1d9 100644 --- a/r/r-core/environment-variables-in-r/README.md +++ b/r/r-core/environment-variables-in-r/README.md @@ -1,6 +1,6 @@ name: Environment Variables -description: Learn about the local and global environment variables. +description: Local versus global environment variables. insights: - global-environment-variables-in-r diff --git a/r/r-core/functions-in-r-ii/README.md b/r/r-core/functions-in-r-ii/README.md index 0b63e89fae..fe8a1531bb 100644 --- a/r/r-core/functions-in-r-ii/README.md +++ b/r/r-core/functions-in-r-ii/README.md @@ -1,6 +1,6 @@ -name: Intro to Functions +name: More on Functions -description: Function basics. +description: The matrix, reduce and sum functions. insights: - the-matrix-function-r diff --git a/r/r-core/intro-to-r/first-program-hello-world-r.md b/r/r-core/intro-to-r/first-program-hello-world-r.md index 6e426b3b9b..d69d0bc214 100644 --- a/r/r-core/intro-to-r/first-program-hello-world-r.md +++ b/r/r-core/intro-to-r/first-program-hello-world-r.md @@ -41,12 +41,16 @@ You should see the text "Hello, World!" printed to the screen. Which function is used to print text to the screen in R? +```r +???("Hello, World!") +``` + ??? -- `print()` -- `printout()` -- `echo()` -- `display()` +- `print` +- `printout` +- `echo` +- `display` --- ## Revision diff --git a/r/r-core/intro-to-r/what-is-r.md b/r/r-core/intro-to-r/what-is-r.md index c93a808e49..aed035296a 100644 --- a/r/r-core/intro-to-r/what-is-r.md +++ b/r/r-core/intro-to-r/what-is-r.md @@ -47,9 +47,7 @@ message <- "Hello, world!" ``` - print -- write -- output -- cat +- no i don't --- ## Footnotes diff --git a/r/r-core/programs-in-r/area-of-a-rectangle-r.md b/r/r-core/programs-in-r/area-of-a-rectangle-r.md index 570895d80b..2344a5ba75 100644 --- a/r/r-core/programs-in-r/area-of-a-rectangle-r.md +++ b/r/r-core/programs-in-r/area-of-a-rectangle-r.md @@ -10,7 +10,7 @@ category: must-know ## Content -In this tutorial, we will write a program in R that calculates the area of a rectangle. +In this insight, we will write a program in R that calculates the area of a rectangle. First, we will define a function `calculate_area()` that takes in two arguments: `length` and `width`. The function will return the area of the rectangle, which is calculated by multiplying the `length` and `width`. ```r diff --git a/r/r-core/programs-in-r/calculator-r.md b/r/r-core/programs-in-r/calculator-r.md index e6c3c356d0..3fa2afbe3d 100644 --- a/r/r-core/programs-in-r/calculator-r.md +++ b/r/r-core/programs-in-r/calculator-r.md @@ -11,18 +11,11 @@ category: must-know ## Content -In this workout, we will create a calculator program. - Creating a calculator program in R requires only a few lines of code. This tutorial will show you how to create a basic calculator program that can perform addition, subtraction, multiplication, and division. -To create a calculator program in R, we will do the following in a couple of insights: +To create the calculator, we will do the following: -1. Define a function that takes two numbers as arguments and returns the result of the desired calculation. For example, to create a function that performs addition, you could use the following code: -```r -add <- function(x, y) { - return(x + y) -} -``` +1. Define a function that takes two numbers as arguments and returns the result of the desired calculation. 2. Define similar functions for the other calculations that you want to support (e.g. subtraction, multiplication, division). @@ -59,6 +52,33 @@ tokens <- strsplit(input, " ")[[1]] # Extract the operation and the numbers operation <- tokens[1] x <- as.numeric(tokens[2]) -y <- as +y <- as.numeric(tokens[3]) + +# Perform the calculation and print the result +if (operation == "+") { + result <- add(x, y) +} else if (operation == "-") { + result <- subtract(x, y) +} else if (operation == "*") { + result <- multiply(x, y) +} else if (operation == "/") { + result <- divide(x, y) +} else { + print("Invalid operation") +} +if (!is.na(result)) { + print(paste(x, operation, y, "=", result)) +} +``` + +This code defines functions for addition, subtraction, multiplication, and division, reads user input from the command line, extracts the operation and numbers from the input, performs the appropriate calculation based on the operation, and prints the result to the command line. + +If our `input` was: +```r +input <- "+ 3 4" +``` +the output would look like this: +```plain-text +[1] "3 + 4 = 7" ``` \ No newline at end of file diff --git a/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md b/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md index 012b076a2c..f1cb7b337d 100644 --- a/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md +++ b/r/r-core/reading-and-writing-data-to-and-from-files/as-numeric.md @@ -20,7 +20,7 @@ revisionQuestion: ## Content -The `as.numeric` function is a useful function that converts an object to a numeric data type. +As mentioned in a previous insight, the `as.numeric` function converts an object to a numeric data type. You can use the `readline` function in combination with the `as.numeric` function to read a number from the console, or from a file. Here is an example of how to do this: ```r diff --git a/r/r-core/variables-and-data-types/basic-data-types-r.md b/r/r-core/variables-and-data-types/basic-data-types-r.md index d942a3a7b8..0c18a7d622 100644 --- a/r/r-core/variables-and-data-types/basic-data-types-r.md +++ b/r/r-core/variables-and-data-types/basic-data-types-r.md @@ -70,7 +70,6 @@ Which of the following is a basic data type in R? ??? - `numeric` -- `integer` - `matrix` - `function` - `data frame` From 6b563452dc33c73a543f3e2a14bce31ac9887dd4 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 7 Mar 2023 12:13:53 +0100 Subject: [PATCH 376/390] Update joins-role.md --- sql/dql/intro-joins/joins-role.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/sql/dql/intro-joins/joins-role.md b/sql/dql/intro-joins/joins-role.md index 4344e276ee..d835c50a48 100644 --- a/sql/dql/intro-joins/joins-role.md +++ b/sql/dql/intro-joins/joins-role.md @@ -29,13 +29,13 @@ Say we want to fetch a list of pokemon and their types in the `pokedex` database `pokemon` -| id | name | health | attack | -|----|------------|--------|--------| -| 1 | venusaur | 53 | 1 | -| 2 | charmeleon | 41 | 2 | -| 3 | pikachu | 50 | 3 | -| 4 | squirtle | 39 | 4 | -| 5 | magikarp | 25 | 5 | +| id | name | health | attack_id | +|----|------------|--------|-----------| +| 1 | venusaur | 53 | 1 | +| 2 | charmeleon | 41 | 2 | +| 3 | pikachu | 50 | 3 | +| 4 | squirtle | 39 | 4 | +| 5 | magikarp | 25 | 5 | `attack` @@ -55,7 +55,7 @@ SELECT attack.type1 FROM pokemon JOIN attack - ON pokemon.id = attack.id; + ON attack.id = pokemon.attack_id; ``` Notice that the query makes references to both tables and then also states the **joining condition**[1] (`pokemon.id = attack.id`). This query returns the following: From 7139b2a00247f4fd24f4527161eef01f3ce1edf3 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 7 Mar 2023 12:15:53 +0100 Subject: [PATCH 377/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index abf5a258d6..06254a52cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,11 @@ Types of change: ### Fixed +## March 7th 2023 + +### Fixed +- [SQL - Joins Role - Update Tables](https://github.com/enkidevs/curriculum/pull/3173) + ## March 6th 2023 ### Fixed From d6a0c2b6dc66b9cc630b39fd74ed724fe4d86a3b Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Tue, 7 Mar 2023 12:32:07 +0100 Subject: [PATCH 378/390] minor readme improvement --- r/r-core/conditional-statements-in-r/README.md | 2 +- r/r-core/functions-in-r/README.md | 4 ++-- r/r-core/loops-in-r/README.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/r/r-core/conditional-statements-in-r/README.md b/r/r-core/conditional-statements-in-r/README.md index 95d91c0f89..5ba1697adf 100644 --- a/r/r-core/conditional-statements-in-r/README.md +++ b/r/r-core/conditional-statements-in-r/README.md @@ -1,6 +1,6 @@ name: Control Flow -description: Learn about conditional statements. +description: Control Flow teaches you how to use conditional statements in programming. insights: - what-are-conditional-statements-r diff --git a/r/r-core/functions-in-r/README.md b/r/r-core/functions-in-r/README.md index a33895746f..f47e802615 100644 --- a/r/r-core/functions-in-r/README.md +++ b/r/r-core/functions-in-r/README.md @@ -1,6 +1,6 @@ -name: Intro to Functions +name: Functions Intro -description: Function basics. +description: Learn the basics of functions; how to define and call them, and more. insights: - functions-in-r diff --git a/r/r-core/loops-in-r/README.md b/r/r-core/loops-in-r/README.md index 3aa793ad7f..7c016ec717 100644 --- a/r/r-core/loops-in-r/README.md +++ b/r/r-core/loops-in-r/README.md @@ -1,6 +1,6 @@ name: for Loops -description: Learn what loops are and how to use them. +description: Learn what loops are and how to use the for loop. insights: - intro-to-loops-in-r From a77f92fdaa187830248eb445f244bd73924bdaa3 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 7 Mar 2023 13:03:29 +0100 Subject: [PATCH 379/390] remove duplicate question gap --- r/r-core/intro-to-r/first-program-hello-world-r.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/r/r-core/intro-to-r/first-program-hello-world-r.md b/r/r-core/intro-to-r/first-program-hello-world-r.md index d69d0bc214..21f592d002 100644 --- a/r/r-core/intro-to-r/first-program-hello-world-r.md +++ b/r/r-core/intro-to-r/first-program-hello-world-r.md @@ -45,8 +45,6 @@ Which function is used to print text to the screen in R? ???("Hello, World!") ``` -??? - - `print` - `printout` - `echo` @@ -62,4 +60,4 @@ Which function is used to run a script file in R? - `source()` - `run()` - `execute()` -- `eval()` \ No newline at end of file +- `eval()` From 2a155435bce3d00a2cca956893ded0a9220624ee Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Tue, 7 Mar 2023 15:13:37 +0100 Subject: [PATCH 380/390] fix missing questions gaps and other minor improvements --- .../if-else-in-r.md | 2 +- .../if-statements-in-r.md | 7 ++-- .../nesting-if-else-in-r-ii.md | 2 - .../switch-statements-in-r.md | 25 ++++++------ .../as-logical-r.md | 3 +- .../data-type-conversions-in-r/as-matrix-r.md | 40 +++++++++---------- .../data-type-conversions-in-r/as-vector-r.md | 12 +++--- .../local-vs-global-variables-in-r.md | 19 +++++++-- .../functions-in-r-ii/the-sum-function-r.md | 3 +- .../math-functions-for-vectorization-in-r.md | 38 ++++++++++++------ .../what-is-vectorization.md | 2 +- .../loops-in-r/break-and-next-for-in-r.md | 2 + r/r-core/loops-in-r/for-loops-in-r.md | 1 - .../intro-to-dictionaries-r.md | 2 + 14 files changed, 92 insertions(+), 66 deletions(-) diff --git a/r/r-core/conditional-statements-in-r/if-else-in-r.md b/r/r-core/conditional-statements-in-r/if-else-in-r.md index 6dbdd9e616..94fdec1159 100644 --- a/r/r-core/conditional-statements-in-r/if-else-in-r.md +++ b/r/r-core/conditional-statements-in-r/if-else-in-r.md @@ -72,9 +72,9 @@ print(result) ``` - `ifelse` +- `x` - `if` - `else` -- `x` --- ## Revision diff --git a/r/r-core/conditional-statements-in-r/if-statements-in-r.md b/r/r-core/conditional-statements-in-r/if-statements-in-r.md index 9f353ed81d..8d296113b2 100644 --- a/r/r-core/conditional-statements-in-r/if-statements-in-r.md +++ b/r/r-core/conditional-statements-in-r/if-statements-in-r.md @@ -49,15 +49,16 @@ Add the missing pieces of code for the `if` statement: ```r x <- 5 y <- 3 -if (???) { +if (??? ??? ???) { print('x is greater than y') } ``` -- `x > y` -- `x < y` - `x` +- `>` - `y` +- `x < y` +- `<` --- ## Revision diff --git a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r-ii.md b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r-ii.md index ca68732141..3adac3d090 100644 --- a/r/r-core/conditional-statements-in-r/nesting-if-else-in-r-ii.md +++ b/r/r-core/conditional-statements-in-r/nesting-if-else-in-r-ii.md @@ -6,9 +6,7 @@ category: must-know practiceQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone - --- # Nesting ifelse Statements diff --git a/r/r-core/conditional-statements-in-r/switch-statements-in-r.md b/r/r-core/conditional-statements-in-r/switch-statements-in-r.md index 92904e96d7..e15f303624 100644 --- a/r/r-core/conditional-statements-in-r/switch-statements-in-r.md +++ b/r/r-core/conditional-statements-in-r/switch-statements-in-r.md @@ -42,16 +42,17 @@ In this example, the code block associated with the value `"A"` is executed, and What does the `switch` statement do? ```plain-text -a) Select one of several code blocks to execute based on a value -b) Return a value based on a condition +a) Return a value based on a condition +b) Select one of several code blocks to execute based on a value c) Iterate over a sequence of values d) None of the above ``` -???) +??? + -- `a` - `b` +- `a` - `c` - `d` @@ -60,7 +61,7 @@ d) None of the above Which of the following is a valid way to use the switch statement in R? -A) +A ```r x <- "A" switch(x) { @@ -70,7 +71,7 @@ switch(x) { } ``` -B) +B ```r x <- "A" switch(x) @@ -79,7 +80,7 @@ switch(x) case "C": print("You selected C") ``` -C) +C ```r x <- "A" switch(x) { @@ -89,7 +90,7 @@ switch(x) { } ``` -D) +D ```r x <- "A" switch(x) @@ -100,7 +101,7 @@ switch(x) ??? -- `A)` -- `B)` -- `C)` -- `D)` \ No newline at end of file +- `A` +- `B` +- `C` +- `D` \ No newline at end of file diff --git a/r/r-core/data-type-conversions-in-r/as-logical-r.md b/r/r-core/data-type-conversions-in-r/as-logical-r.md index c0bd5048dd..f6d8bedf24 100644 --- a/r/r-core/data-type-conversions-in-r/as-logical-r.md +++ b/r/r-core/data-type-conversions-in-r/as-logical-r.md @@ -59,9 +59,10 @@ v <- as.vector(c("True", "False", "True")) # D v <- as.logical(c("True", "False", "True")) + +# ???) ``` -??? - `D` - `A` diff --git a/r/r-core/data-type-conversions-in-r/as-matrix-r.md b/r/r-core/data-type-conversions-in-r/as-matrix-r.md index f3becfaece..b1f0483b10 100644 --- a/r/r-core/data-type-conversions-in-r/as-matrix-r.md +++ b/r/r-core/data-type-conversions-in-r/as-matrix-r.md @@ -49,27 +49,26 @@ print(m) Which of the following will create a 3x3 matrix from a numeric vector? ```r -# A) +# A m <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3) -# B) +# B m <- as.matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3) -# C) +# C m <- as.matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 2, ncol = 4) -# D) +# D m <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 2, ncol = 4) -``` - -??? -- `B)` -- `A)` -- `C)` -- `D)` +# ???) +``` +- `B` +- `A` +- `C` +- `D` --- ## Revision @@ -77,22 +76,23 @@ m <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 2, ncol = 4) Which of the following will create a 2x4 matrix from a character vector? ```r -# A) +# A m <- matrix(c("a", "b", "c", "d", "e", "f", "g", "h"), nrow = 2, ncol = 4) -# B) +# B m <- as.matrix(c("a", "b", "c", "d", "e", "f", "g", "h"), nrow = 2, ncol = 4) -# C) +# C m <- matrix(c("a", "b", "c", "d", "e", "f", "g", "h"), nrow = 2, ncol = 4) -# D) +# D m <- matrix(c("a", "b", "c", "d", "e", "f", "g", "h"), nrow = 4, ncol = 2) + +# ???) ``` -??? -- `B)` -- `A)` -- `C)` -- `D)` +- `B` +- `A` +- `C` +- `D` diff --git a/r/r-core/data-type-conversions-in-r/as-vector-r.md b/r/r-core/data-type-conversions-in-r/as-vector-r.md index 63a36b9b9d..c4e05ebfb6 100644 --- a/r/r-core/data-type-conversions-in-r/as-vector-r.md +++ b/r/r-core/data-type-conversions-in-r/as-vector-r.md @@ -49,8 +49,6 @@ print(???) # 1 3 2 4 ``` -??? - - `matrix` - `as` - `vector` @@ -63,20 +61,20 @@ print(???) Which of the following will create a vector called `v` from numbers? ```r -# A) +# A v <- as.character(c(TRUE, FALSE, TRUE)) -# B) +# B v <- as.vector(c("True", "False", "True")) -# C) +# C v <- as.character(c(1, 0, 1)) -# D) +# D v <- as.vector(c(1, 0, 1)) ``` -???) +??? - `D` - `A` diff --git a/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md b/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md index 5ad8c02f3f..49764a73bd 100644 --- a/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md +++ b/r/r-core/environment-variables-in-r/local-vs-global-variables-in-r.md @@ -61,12 +61,23 @@ Note that the use of the `<<-` operator is generally discouraged as it can lead Which of the following is **NOT** true about global and local variables in **R**? +```plain-text +A) +Local variables can only be accessed within the function where they are defined. +B) +The `<<-` operator can be used to create a global variable within a function. +C) +The `<<-` operator is generally recommended for creating global variables. +D) +Global variables can be accessed from anywhere in your R session. +``` + ??? -- The `<<-` operator is generally recommended for creating global variables in **R**. -- The `<<-` operator can be used to create a global variable within a function. -- Local variables can only be accessed within the function where they are defined. -- Global variables can be accessed from anywhere in your **R** session. +- `C` +- `A` +- `B` +- `D` --- ## Revision diff --git a/r/r-core/functions-in-r-ii/the-sum-function-r.md b/r/r-core/functions-in-r-ii/the-sum-function-r.md index 31da0231ac..9fe6937886 100644 --- a/r/r-core/functions-in-r-ii/the-sum-function-r.md +++ b/r/r-core/functions-in-r-ii/the-sum-function-r.md @@ -59,6 +59,8 @@ Note: the `sum` function is not vectorized, which means that it cannot operate o Which of the following statements is true about the `sum` function in **R**? +??? + - All of the above. - The sum function returns the sum of all elements in an input vector. - The sum function only works on vectors of numeric data. @@ -77,7 +79,6 @@ print(sum(vec1, vec2, vec3)) # ??? ``` - - `45` - `21` - `15` diff --git a/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md b/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md index eadf6bfe79..393d2a5968 100644 --- a/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md +++ b/r/r-core/looping-techniques-in-r/math-functions-for-vectorization-in-r.md @@ -70,17 +70,24 @@ However, you should be careful when using vectorization, because it can result i --- ## Practice -Complete the following code snippet to double the elements of the `vector` variable: +Complete the following code snippet to take the square root of each element of the `vector` variable: ```r -vector <- 1:10 -vector <- ??? ??? 2 +vector <- 1:9 + +print(vector) +# 1 2 3 4 5 6 7 8 9 + +print(???(vector)) + +# 1.000000 1.414214 1.732051 2.000000 2.236068 2.449490 2.645751 2.828427 3.000000 + ``` -- `vector` -- `*` -- `matrix` -- `/` +- `sqrt` +- `square` +- `double` +- `root` --- ## Revision @@ -88,13 +95,18 @@ vector <- ??? ??? 2 What is the output of the following code? ```r -vector <- 1:10 -vector <- vector * 2 + 1 +numbers <- -6:-1 + +print(numbers) +# -6 -5 -4 -3 -2 -1 + +print(abs(numbers)) +# ??? ``` ??? -- `3 5 7 9 11 13 15 17 19 21` -- `1 3 5 7 9 11 13 15 17 19` -- `2 4 6 8 10 12 14 16 18 20` -- `1 2 3 4 5 6 7 8 9 10` +- `6 5 4 3 2 1` +- `1 2 3 4 5 6` +- `-6 -5 -4 -3 -2 -1` +- `-1 -2 -3 -4 -5 -6` diff --git a/r/r-core/looping-techniques-in-r/what-is-vectorization.md b/r/r-core/looping-techniques-in-r/what-is-vectorization.md index 91816180fb..9e892508b0 100644 --- a/r/r-core/looping-techniques-in-r/what-is-vectorization.md +++ b/r/r-core/looping-techniques-in-r/what-is-vectorization.md @@ -49,7 +49,7 @@ vector ^ 2 ``` -You can use vectorization to improve the performance of your R code, especially when working with large data sets. However, you should be careful when using vectorization, because it can result in code that is less readable and more difficult to debug. +You can use vectorization to improve the performance of your **R** code, especially when working with large data sets. However, you should be careful when using vectorization, because it can result in code that is less readable and more difficult to debug. --- diff --git a/r/r-core/loops-in-r/break-and-next-for-in-r.md b/r/r-core/loops-in-r/break-and-next-for-in-r.md index 5e833c65eb..78bb160ed9 100644 --- a/r/r-core/loops-in-r/break-and-next-for-in-r.md +++ b/r/r-core/loops-in-r/break-and-next-for-in-r.md @@ -71,6 +71,8 @@ for (i in 1:10) { } print(i) } + +# ??? ``` - `1 2 3 4 6 7 8 9 10` diff --git a/r/r-core/loops-in-r/for-loops-in-r.md b/r/r-core/loops-in-r/for-loops-in-r.md index 15ad2dbad0..de7c32e476 100644 --- a/r/r-core/loops-in-r/for-loops-in-r.md +++ b/r/r-core/loops-in-r/for-loops-in-r.md @@ -64,7 +64,6 @@ for (??? in ???) { What is the output of the following code? - ```r for (word in c("apple", "banana", "cherry")) { print(word) diff --git a/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md b/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md index 5c7bfa5dab..4689120d97 100644 --- a/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md +++ b/r/r-core/unordered-data-types-r/intro-to-dictionaries-r.md @@ -68,6 +68,8 @@ length(fruits) Which of the following is **NOT** a way to access an element in a list in **R**? +??? + - `list.key` - `list[[1]]` - `list[["pear"]]` From f5e92efa78a66b59c98a2409b1a471aa0717578e Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic <koka993@gmail.com> Date: Tue, 7 Mar 2023 15:24:44 +0100 Subject: [PATCH 381/390] remove type in the gap for 3 questions --- r/r-core/data-type-conversions-in-r/as-logical-r.md | 3 +-- r/r-core/data-type-conversions-in-r/as-matrix-r.md | 4 +--- r/r-core/data-type-conversions-in-r/as-vector-r.md | 4 ++-- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/r/r-core/data-type-conversions-in-r/as-logical-r.md b/r/r-core/data-type-conversions-in-r/as-logical-r.md index f6d8bedf24..d1c6260426 100644 --- a/r/r-core/data-type-conversions-in-r/as-logical-r.md +++ b/r/r-core/data-type-conversions-in-r/as-logical-r.md @@ -5,7 +5,6 @@ category: must-know practiceQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone revisionQuestion: formats: @@ -60,7 +59,7 @@ v <- as.vector(c("True", "False", "True")) # D v <- as.logical(c("True", "False", "True")) -# ???) +# ??? ``` diff --git a/r/r-core/data-type-conversions-in-r/as-matrix-r.md b/r/r-core/data-type-conversions-in-r/as-matrix-r.md index b1f0483b10..d61a68c4c7 100644 --- a/r/r-core/data-type-conversions-in-r/as-matrix-r.md +++ b/r/r-core/data-type-conversions-in-r/as-matrix-r.md @@ -10,7 +10,6 @@ practiceQuestion: revisionQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone --- @@ -88,10 +87,9 @@ m <- matrix(c("a", "b", "c", "d", "e", "f", "g", "h"), nrow = 2, ncol = 4) # D m <- matrix(c("a", "b", "c", "d", "e", "f", "g", "h"), nrow = 4, ncol = 2) -# ???) +# ??? ``` - - `B` - `A` - `C` diff --git a/r/r-core/data-type-conversions-in-r/as-vector-r.md b/r/r-core/data-type-conversions-in-r/as-vector-r.md index c4e05ebfb6..5663cd6b91 100644 --- a/r/r-core/data-type-conversions-in-r/as-vector-r.md +++ b/r/r-core/data-type-conversions-in-r/as-vector-r.md @@ -10,7 +10,6 @@ practiceQuestion: revisionQuestion: formats: - fill-in-the-gap - - type-in-the-gap context: standalone --- @@ -72,9 +71,10 @@ v <- as.character(c(1, 0, 1)) # D v <- as.vector(c(1, 0, 1)) + +# ??? ``` -??? - `D` - `A` From b192a89f8e29b96a1bac42f0ecdce33afd795a2a Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 7 Mar 2023 15:37:41 +0100 Subject: [PATCH 382/390] Update README.md --- r/r-core/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/r/r-core/README.md b/r/r-core/README.md index f82eb5cc61..57deea1df8 100644 --- a/r/r-core/README.md +++ b/r/r-core/README.md @@ -15,6 +15,7 @@ sections: - functions-in-r-ii - environment-variables-in-r - loops-in-r + - loops-in-r-ii - looping-techniques-in-r - reading-and-writing-data-to-and-from-files - programs-in-r From f7ebd8233e87b3c73aa117dd77d29894ecdd56e3 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Tue, 7 Mar 2023 15:39:26 +0100 Subject: [PATCH 383/390] Update CHANGELOG.md --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e116d52ea..4bbbd107a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,9 @@ Types of change: ### Added - [R - Topic - Add new topic](https://github.com/enkidevs/curriculum/pull/3150) +### Fixed +- [R - Topic - Refference missing workout in readme](https://github.com/enkidevs/curriculum/pull/3174) + ## March 6th 2023 ### Fixed From 540fb54102f2f3c5f26e245e23f032325a8e5bfe Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 8 Mar 2023 09:25:30 +0100 Subject: [PATCH 384/390] Update creating-and-storing-variables-in-r.md --- .../creating-and-storing-variables-in-r.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md b/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md index 915dc0d84d..20e356cf55 100644 --- a/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md +++ b/r/r-core/variables-and-data-types/creating-and-storing-variables-in-r.md @@ -39,9 +39,9 @@ print(y) You can also use the `assign()` function to create and store a variable: ```r -assign("z", c(x, y)) +assign("z", 6) print(z) -# 5 10 +# 6 ``` Or you can create variables using other variables: From b9c70392358af7e1271689175189ac6a0372a8be Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 8 Mar 2023 09:39:18 +0100 Subject: [PATCH 385/390] Update basic-data-types-r.md --- r/r-core/variables-and-data-types/basic-data-types-r.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/r/r-core/variables-and-data-types/basic-data-types-r.md b/r/r-core/variables-and-data-types/basic-data-types-r.md index 0c18a7d622..8110552cb7 100644 --- a/r/r-core/variables-and-data-types/basic-data-types-r.md +++ b/r/r-core/variables-and-data-types/basic-data-types-r.md @@ -55,6 +55,12 @@ print(cities) # Levels: Chicago New York San Francisco ``` +When creating `factor` variables, all unique values are stored as **Levels** and can be accessed using the `levels()` function: +```r +print(levels(cities)) +# "Chicago" "New York" "San Francisco" +``` + `NULL`: represents an empty object ```r empty <- NULL @@ -85,4 +91,4 @@ What is the basic data type for a vector of categorical variables in R? - `character` - `numeric` - `logical` -- `NULL` \ No newline at end of file +- `NULL` From f3c13c07cb07d89e3c61e0dc550af12e50d0b811 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 8 Mar 2023 09:45:24 +0100 Subject: [PATCH 386/390] Update assignment-operators-r.md --- .../assignment-operators-r.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/r/r-core/variables-and-data-types/assignment-operators-r.md b/r/r-core/variables-and-data-types/assignment-operators-r.md index 5e9c860bb7..cb36b79262 100644 --- a/r/r-core/variables-and-data-types/assignment-operators-r.md +++ b/r/r-core/variables-and-data-types/assignment-operators-r.md @@ -32,7 +32,7 @@ print(y) # 10 ``` -You can also use the `=` operator, but it is generally recommended to use `<-` as it is easier to read and less prone to errors. +You can also use the `=` operator: ```r x = 5 @@ -45,6 +45,18 @@ print(y) # 10 ``` +However, the `<-` operator is the recommended way to assign values to variables, while the `=` operator is generally used for argument passing in function calls. +```r +multiply <- function(a, b){ + a * b +} + +# pass 5 for a and 10 for b in the multiply function +result = multiply(a = 5, b = 10) + +print(result) +# Output: [1] 50 +``` --- ## Practice @@ -69,4 +81,4 @@ y = 10 ??? - x -- y \ No newline at end of file +- y From bf7d19c5068e2acd979e87363cc33892c2c3474f Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 8 Mar 2023 09:47:13 +0100 Subject: [PATCH 387/390] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bbbd107a4..b99d057028 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,11 @@ Types of change: ### Fixed +## March 8th 2023 + +### Fixed +- [R - Variables And Data Types - Add missing info, remove subjective info](https://github.com/enkidevs/curriculum/pull/3175) + ## March 7th 2023 ### Added From aa427316698855687dbad9b0cc4f9514a001e5b2 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 10 Mar 2023 11:21:08 +0100 Subject: [PATCH 388/390] Update javascript-compilation.md --- .../javascript-core/in-depth-ii/javascript-compilation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript/javascript-core/in-depth-ii/javascript-compilation.md b/javascript/javascript-core/in-depth-ii/javascript-compilation.md index 838a61aa2a..703e416866 100644 --- a/javascript/javascript-core/in-depth-ii/javascript-compilation.md +++ b/javascript/javascript-core/in-depth-ii/javascript-compilation.md @@ -59,7 +59,7 @@ Find the variable scopes in the following code: ```javascript var flag = true; -// flag is ??? +// flag is in ??? function test() { var x; From 37263ea453cd0dc57254a3fc585606177c7926d0 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Fri, 10 Mar 2023 12:33:54 +0100 Subject: [PATCH 389/390] Update CHANGELOG.md --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a82b4d7ece..4ce68702f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,12 @@ Types of change: ### Fixed + +## March 10th 2023 + +### Fixed +- [Javascript - Compilation - Add missing word in PQ](https://github.com/enkidevs/curriculum/pull/3176) + ## March 8th 2023 ### Fixed From eea76520890e1fb80f3516dfd4c8f2c67e917a3c Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic <Stefan-Stojanovic@users.noreply.github.com> Date: Wed, 15 Mar 2023 11:04:23 +0100 Subject: [PATCH 390/390] Update context-manager-types-with.md --- .../advanced-referencing/context-manager-types-with.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..c888d80fcb 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -86,7 +86,7 @@ class new_context_manager: # deal with unmanaged resources with new_context_manager as custom_name - # work with resources + # work with resources ``` - `__enter__`