Big O notation is what I learned today in my coding assignments and I wanted to share it with you since teaching helps it stick.
Effectively what we are accomplishing with this notation is a description of the amount of resource consumption that a program will consume over time. Ideally we end up with O(1) but that won't be the case for everything so we need a way to describe growing demands in resources across time or iteration.
The notation goes as follows for what I understand in Python:
Constant O(1)
Logarithmic O(log n)
Linear O(n)
Squared O(n^2)
Exponential O(2^n)
Factorial O(n!)
What each of these notations is describing is the amount of operations a process will increase by, worst case, if scaled with 'n' inputs.
What's an example?
for i in range(6):
counter += 1
If we were to imagine that range allows any input of an integer we could see how this function only iterates once per input value giving it a LINEAR growth.
If we look at a number line this makes sense.
0-1-2-3-4-5-6
Our process starts at 0 and iterates once to get to 1 etc. until it eventually reaches 6. This is O(n).
If we added another layered loop:
for i in range (6): <- Loops what's below it 6 times.
for d in range(6): <- Loops what's below it 6 times.
counter += 1
We have now increased the processing demand QUADRATICALLY. Why? Because if we assume 6 to be the variable integer that we could influence we can see that by doing it twice we have to count to 6 uh.... 6 times.
0-6-12-18-24-30-36 <-
That's O(n^2). Now we have dramatically increased the amount of processes something requires with a SINGLE line of code.
Why is this important?
Well computers run things so fast that this 'lag' you could call it might build up over time. Memory leaks, mandatory resets, etc. are some results of this. The frequency at which this maintenance needs to be performed to keep the code functioning is directly connected to the 'Big O' notation used to determine how elegant the solution is.
Turns out different algorithms have varying Big O values which is how one might determine the best option for their given task.
It's also just a neat way to look at data but I'll wax poetic in logarithms once I have a more full understanding of them.
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
✓ Live Streaming✓ Interactive Chat✓ Private Shows✓ HD Quality
Anya is LIVE right now
FREE
Free to watch • No registration required • HD streaming
So these days I have started to stream my code study.
So today morning I learnt:
How to take absolute value. Found some anomaly in the system lol. Basically it was not taking abs() but fabs() however my python was the latest version
I studied how to sort three numbers in python, although I have done this in other language since the syntax of python is still foreign to me I had difficulty sorting them in ascending order and also descending order using the built in function sorted() and also making my own implementation
I understood what is range function and how to use it with for loops, had a bit of hit and miss while understanding how it really worked but google's bard helped, I also learnt about reverse sorting
I learnt what is interning while trying to understand the difference between identity operators and equality operators. Found some anomaly in my system again, that my computer's range of interning is much larger than what is documented ?
I learnt what is keyword argument when with using reverse built in sort, yeah so I was amazed that the order of arguments didn't mattered for keyword argument.
I was also confusing syntax of python with javascript since that is what is what recently code in.
Learnt about what does len() function does, like properly rather than just guessing about what it does.
understood about control statements such as if, else and elif
learnt about break and continue in loops in python which is same as java script.
learnt about how to check the divisibility of a number. I didn't knew that it was separate topic in my syllabus I just thought it was something people would knew.
Learnt the basics about on how to make a READ , EVAL PRINT LOOP, REPL
Learnt about stupid pattern program in python, I don't know why the heck they still teach these things and put it in syllabus. There is no real world use of it as far as I can see. I still have to post the notes about it in my blogs and store it my cloud drive.
Learnt how to do a summation of series, using and not using numpy.
figured out how to do a factorial of a number
was trying to make an short algorithm on how to do the fibonacci series but well, I was so sleepy that my mind didn't worked as it should, I took the hint from bard then felt bad that I was directly looking at the solution when rather I should sleep and approach the problem from afresh in next study stream. So stopped my study stream.
Tagged by @sineala so taking a work break to think about something other than how irritated I am at my main client right now.
Name(s): Gwyneth Rhys, just gwyneth (both on AO3, because I’m a dumbass and signed up with gwyneth before realizing all my fic had been posted by my full name) or gwyn (on Dreamwidth, for instance). Here and on Instagram I am teatotally.
Fandom(s): Currently, I’m mostly Captain America/MCU, still. I’ve written some in Schitt’s Creek, most recently, as well as numerous other fandoms, from the Professionals through Buffy through the Fast and the Furious and too many small fandoms to name. I wish I wasn’t still stuck on Stucky, but here we are.
Where you post: At AO3 almost exclusively. I’ve done some commentfic at my dreamwidth account and other dreamwidth accounts, but by and large everything ends up there anyway.
Most Popular One Shot (by kudos): That’d be I can’t remember how this started (but I can tell you exactly how it ends), the time loop/Groundhog Day story. It’s the closest I’ve ever come to having a popular story (well, by my low history, anyway).
Most Popular Multi-Chapter (by kudos): That’s an interesting one because going by hits it’s Dark Approach, the first fic I wrote for Steve and Bucky, and it’s only I think by virtue of the fact that it’s been up the longest and was written when we were all in the throes of Cap madness. But if I go by the defined kudos, then it’s Don’t Wait Up for Me, even though that’s got fewer hits. The former never got many kudos, while the latter got more of those but not of other things. I’ve never figured any of this out and I definitely use the term “popular” loosely.
Favorite story you’ve written so far: Man, I have no idea, because I like a lot of them. In Cap fandom, I’m especially fond of some of those mentioned above, but I’d probably pick lucida, obscura at this point because it’s got so many lines I was so proud of per square inch, comparatively. Outside of the fandom, I’d go with The Sun Was the First Star We Knew, which is a reverse-the-apocalypse fic for the movie Sunshine (starring Chris Evans and Cillian Murphy eye fucking each other through the solar system) I wrote for Yuletide last year. I think it’s maybe one of the best things I’ve ever written.
Fic you were nervous to post: I wrote a story in the War Dogs universe, where Bucky and Steve rescue a dog from the Hydra factory during their escape and she becomes a Howling Commandog, that was mirroring my sad mood, called Changing of the Guard. It’s about first Bucky’s “death” and then Steve’s, and how it affected the dog. I knew all the people who’d fallen in love with Gretel the doggo in the other War Dogs stories would be upset because it made her sad, and I avoided doing it for a few years. I mean, there’s a reason it’s one of the least-read stories I have.
How do you choose your titles?: I have multiple methods. I’m not one of those people who only use song lyrics or poems, though I’ve used those many times. I often hear things and make note of a line or phrase, or use common phrases, or sometimes a line from the story itself. One time I completely misheard a lyric in a song I’d heard on the radio, but never could verify what the song was, and what I thought I’d heard, which was hilarious to me.
Do you outline?: God no. I cannot write like that; it made me miserable in fiction writing workshops when the instructors insisted I had to turn in an outline at the beginning of the program. Once I’ve written an outline, I feel like I’ve already written the story, so why bother. It takes all the mystery out of life, to quote Monty Python. I see stories in my mind like movies, so I just make a brain-movie.
In-Progress: I’m trying to get back to writing the Steve/Bucky WIP I was working on before I had to break for Yuletide, Reverie, but I’m having a hard time convincing myself it’s worth the effort.
Coming soon/not yet started: I have a few ideas floating around but nothing concrete. There was this prompt someone gave me a long time ago that I thought could be super fun, but it was too long to tackle as commentfic, where the Avenger is a local indie newspaper and all our heroes have various jobs there. I’d have to do some thinking and planning, because even though I trained as a journalist and have edited magazines and papers, newspapers are a very different thing nowadays, so it’d probably involve going retro and maybe making it a screwball comedy like His Girl Friday or something. I’d also like to write another time loop story for something, but I have many fandoms I could do that for and can’t decide which. Time loops for all, maybe!
Prompts?: I mean, I’m always open to the idea, but usually it’s just people asking “sēquèle?” and that is never my thing.
Upcoming work you’re most excited about: Finishing Reverie. I have some cool stuff written in dribs and drabs in my notes program, but it kind of feels like I’m writing into a black hole, so I haven’t psyched myself up yet.
I’m terrible at tagging because I am always doing these last, but if they haven’t done it themselves already, I’ll go with @what-alchemy , @cacchieressa , and @sdwolfpup
Closures are really common in JavaScript, but their definition can seem to be a little dark. Let's take a look at them!
Introduction
MDN web docs defines closures like so:
"A closure is the combination of a function and the lexical environment within which that function was declared."
What does that really mean? We can view closures as objects that contain a function and a reference to the environment in which the function was created. They allow to implement such things as callbacks or event handlers. They give us access to an outer function's scope from an inner function.
Basically, we can use a closure by defining a function inside another function. We then have to expose it by returning it or passing it to another function.
In JavaScript, closures are used to enable data privacy because the enclosed variables are only in scope within the parent function.
A few definitions
First, let's take a look at some definitions.
Scope
In JavaScript, a scope refers to the "place" where variables and functions are accessible and in what context it is being executed. When something is accessible from anywhere in our code, it is in the global scope. Local scope refers to something that is only accessible in a certain part of our code.
When we create a function, it has access to variables created inside and outside the function. Variables created inside a function are locally defined and can only be accessed inside this function.
First-Class Functions
Basically, functions are considered as First-Class Citizens when they are "being able to do what everyone else can do". So, they can be assigned to a variable, passed as an argument or returned from a function.
Inner Functions
Also called Nested Functions, they are defined inside of another function (outer function). Every time this outer function is called, an instance of the inner function is created.
Basic example
Knowing what we know, let's make a simple example using a closure.
function say() { let x = 'Hello World!'; function hello() { console.log(x); } return hello; } let sayHello = say(); sayHello();
Here, our function say() returns the inner function hello() from the outer function before being executed. The hello() function is only available within the body of the say() function and has no local variables. Nevertheless, because inner functions have access to the variables of outer functions, hello() can access the variable x declared in the parent function.
Once say() has finished executing, we might expect that the x variable would no longer be accessible, but it is not the case. sayHello() is a reference to the instance of the function hello() that is created when say() function is run and so a reference is kept to the lexical environment of hello() where the variable x exists. This is why this last variable remains available when sayHello() is invoked.
A factory of functions
Let's imagine the following code:
function sentenceFactory(x) { return function(y) { return String(x) + String(y); }; } let sentence1 = sentenceFactory('Hello '); let sentence2 = sentenceFactory('Hey '); console.log(sentence1('John')); console.log(sentence2('Paul'));
Here, we create some kind of factory, sentenceFactory(x), that takes a single argument and returns a new function that also takes one argument. Our functions sentence1 and sentence2 are closures and they share the same function body definition, but they store different lexical environments.
Controlling side effects
Closures can be helpful to control side effects, such as Ajax request or timeout.
The previous code would print out our message immediately after one second. Maybe we don't want that and print our message later. We can do that with a closure:
JavaScript does not support private data and does not provide a native way of doing this. However, we can emulate private methods using closures. Private methods are useful for restricting access to code and provide a way of managing our global namespace.
function Person(name) { let _name = name; function takeInstrument() { return 'guitar'; } return { sayHello: function() { console.log('Hello ' + _name); }, getName: function() { console.log(_name); }, play: function() { console.log(_name + ' is playing the ' + takeInstrument()); } } } const person1 = Person('George'); person1.sayHello(); person1.getName(); person1.play();
In this example, name and takeInstrument() are private because they cannot be accessed directly from outside the Person(name) function. They are accessed by three public functions that are returned.
Loop problem
It can be very tempting to create closures in a loop. Let's first imagine the following example:
function generateLinks() { var info = [ {'name': 'John', 'instrument': 'Guitar'}, {'name': 'Paul', 'instrument': 'Bass'}, {'name': 'George', 'instrument': 'Guitar'}, {'name': 'Ringo', 'instrument': 'Drum'} ]; for (var i = 0, link; i < info.length; i++) { var item = info[i]; var link = document.createElement("a"); link.innerHTML = item.name; link.onclick = function() { alert(item.instrument); }; document.body.appendChild(link); } } window.onload = generateLinks;
This code doesn't work as expected: our alert always shows the same message. But why? Four closures have been created by the loop, but each one shares the same single lexical environment. The item.instrument value is determined when the onclick callbacks are fired. It means that the loop continues until the end and so the item variable is left pointing to the last entry when generateLinks() exits.
We could fix it like so:
function createAlert(info) { return function() { alert(info); }; } function generateLinks() { var info = [ {'name': 'John', 'instrument': 'Guitar'}, {'name': 'Paul', 'instrument': 'Bass'}, {'name': 'George', 'instrument': 'Guitar'}, {'name': 'Ringo', 'instrument': 'Drum'} ]; for (var i = 0, link; i < info.length; i++) { var item = info[i]; var link = document.createElement("a"); link.innerHTML = item.name; link.onclick = createAlert(item.instrument); document.body.appendChild(link); } } window.onload = generateLinks;
We could also fix our code by using let instead of var.
In other programming languages
Closures are not available just in JavaScript. We can use them in other programming languages.
def adder(nombre): return lambda v: v + n adder10 = adder(10) adder10(1)
With Swift:
func adder(_ n: Int) -> (Int) -> Int { return { n + $0 } } let adder10 = adder(10) print(adder10(5))
And so on!
Conclusion
Through this article, we took a look at closures in JavaScript and saw how they work. We saw that a closure is formed when an outer function exposes an inner function and it contains a function and a reference to the environment in which it was created. Closures can be used to deal with callback functions and to emulate private data.
One last word
If you like this article, you can consider supporting and helping me on Patreon! It would be awesome! Otherwise, you can find my other posts on Medium and Tumblr. You will also know more about myself on my personal website. Until next time, happy headache!