r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

Show parent comments

292

u/procrastinatingcoder Apr 05 '22

It generally refers to keeping a table of previous results, and re-using those for your next calculations. It's nothing special, and I find the term "dynamic" in dynamic programming to be the most misleading thing ever personally.

157

u/[deleted] Apr 05 '22

It was deliberately misleadingly named so the researcher could continue funding or something like that.

It’s a shame as the basics are simple to grasp.

14

u/tv_head__ Apr 05 '22

Got any source ? (if you don't mind my asking)

115

u/TheAtro Apr 05 '22

I spent the Fall quarter (of 1950) at RAND. My first task was to find a name for multistage decision processes. An interesting question is, "Where did the name, dynamic programming, come from?" The 1950s were not good years for mathematical research. We had a very interesting gentleman in Washington named Wilson. He was Secretary of Defense, and he actually had a pathological fear and hatred of the word "research". I’m not using the term lightly; I’m using it precisely. His face would suffuse, he would turn red, and he would get violent if people used the term research in his presence. You can imagine how he felt, then, about the term mathematical. The RAND Corporation was employed by the Air Force, and the Air Force had Wilson as its boss, essentially. Hence, I felt I had to do something to shield Wilson and the Air Force from the fact that I was really doing mathematics inside the RAND Corporation. What title, what name, could I choose? In the first place I was interested in planning, in decision making, in thinking. But planning, is not a good word for various reasons. I decided therefore to use the word "programming". I wanted to get across the idea that this was dynamic, this was multistage, this was time-varying. I thought, let's kill two birds with one stone. Let's take a word that has an absolutely precise meaning, namely dynamic, in the classical physical sense. It also has a very interesting property as an adjective, and that is it's impossible to use the word dynamic in a pejorative sense. Try thinking of some combination that will possibly give it a pejorative meaning. It's impossible. Thus, I thought dynamic programming was a good name. It was something not even a Congressman could object to. So I used it as an umbrella for my activities.

— Richard Bellman, Eye of the Hurricane: An Autobiography (1984, page 159)

https://en.wikipedia.org/wiki/Dynamic_programming

16

u/sageknight Apr 06 '22 edited Apr 06 '22

Wanna get funding from Air Force? Name something that rhymes with dynamite.

1

u/happyneandertal Apr 06 '22

“We call it, the Dynamo Hellcat Mach 2” waves hands in dynamic flurish

6

u/KuntaStillSingle Apr 06 '22

You can hardly object to someone for getting angry at the type of research RAND was up to in that time lol.

9

u/[deleted] Apr 05 '22

https://youtu.be/OQ5jsbhAv_M in the first couple of minutes.

5

u/tv_head__ Apr 05 '22

Lol nice I also love how they still use big ass chalkboards.

14

u/ICantPCGood Apr 05 '22

Oh, that actually sounds similar to how I would describe it. I guess I’ve just been over complicating it in my head. Thanks!

9

u/Select-Sir9364 Apr 05 '22

Is this table of previous results similar to memoization?

11

u/Drifts Apr 06 '22

my limited understanding is that it is exactly memoization

5

u/Unsounded Apr 06 '22

They’re actually two different concepts, dynamic programming is a bit more nuanced, and is defined as a problem being able to be solved by breaking down a larger problem set into a smaller one and the micro decisions being optimal in the sense that you can solve the sub problem and it doesn’t require context from outside the sub problem.

Memoization can help, and is used for some dynamic programming problems but it isn’t the same.

1

u/og-at Apr 06 '22

so . . . memoizing?

1

u/Sexual_tomato Apr 06 '22

Oh, so every time I use python's functools.cache decorator I'm doing "dynamic programming". Neat.

I'm self-taught and employed as a developer, but mapping industry terms to what I already know can be frustrating.

I once had an Interviewer ask me what a closure is. I said I had no idea. They explained that it was a function that defines some variable, then returns a function that uses that variable. That's it. After them telling me that, I told them about instances where I've used the concept and typed up a quick example.

Example:

So, in Python, if you ever see a decorator function that takes parameters, it's actually a function that returns a function of one argument but uses those arguments in the returned function body.

def log_this(log_level):
    def do_log(function):
        def wrapper(*args, **kwargs):
            log = logging.getLogger(function.__name__)
            log.log(log_level, f"Calling {function.__name__}")
            result = function(*args, **kwargs)
            log.log(log_level, f"Called {function.__name__}").   
            return result
    return wrapper
return do_log

1

u/procrastinatingcoder Apr 06 '22

That's not exactly it... you should be wary of thinking "i recognize this X, therefore it must be this Y that I knew but didn't know the name for".

Especially beware "using Python's X". You don't know what Python does, don't try to put names to it unless you explicitly define it or the doc says so. Python does a whole lot of magic behind the scenes, either take what's provided as information (doc says X), or build your own X; but don't try to reinterpret something as X because they look similar, it's a very common problem that most people aren't aware of.

A whole lot of stuff gets done for you in Python, and a whole lot of mechanism are in place, so using something is never as simple as it seems. Python does string interning for instance, but only up to a certain length and depending on the sub-version. In layman's words, it means there's only a single copy of every string in the system, even if completely different part of the code use it, so long as it's identical and below a certain threshold (it used to be very small, now it's 4096 I believe, I'd have to double-check)

so, for example:

s1 = "X"*10
s2 = "X"*10

s1 is s2 --> True


ss1 = "X"*4097
ss2 = "X"*4097

s1 is s2 --> False

It also does the same thing with numbers below a certain value (-something to 256, depends, test on your own system). And it goes more complex than that for many things.

A more relevant example would be the one you gave, read up the first line of the documentation:

@ functools.cache(user_function)
Simple lightweight unbounded function cache. Sometimes called “memoize”.

It's memoization, not dynamic programming. Assuming things and making links where there is a tenuous one at best is one of the biggest tells of a modern self-learned (though many people fall into that self-learned or not).

Also, you shouldn't call things decorator unless that's what they are, and this refers to the "Decorator design pattern".

Same with closure, while it's roughly what you said, you also need to know the implication to the scope, because closure is specifically something that deals with scope at its core. The wikipedia page can give you more information on the subject.

If you want to map "industry" terms to what you know, you should look it up online from mostly reputable sources (there's good blogs out there, or wikipedia articles, etc.) and don't just assume you know or that what someone said in a tutorial (which are usually simplified and where they only tell you half the information that will be relevant to you) was complete.

My little rant about imprecise information and partial knowledge is done, but I do hope you learned a few things.

2

u/Sexual_tomato Apr 06 '22

From my understanding, dynamic programming is the act of caching results of a function call or operation for simple subsets of a problem that overlaps finding an optimal solution to a harder overarching problem, like finding the shortest path between two nodes in a weighted graph. My personal interaction with it comes from the class I took in control theory when I got my engineering degree, but I just called it "don't waste time computing stuff I've already computed otherwise the Matlab code takes all night to run."

That being said, thank you for your really detailed explanation, and I appreciate your willingness to outline all the inaccuracies I glossed over.

I'm aware of all the points you made, and I realize that it painted my understanding in a bit of a dubious light. But, given that I typed all that out on my phone, it was time to get off the toilet, and this is a thread regarding the total lack of basic understanding, I figured the extra nuance would be too much noise. Imo, you adding the extra context in a separate comment is a better way to read it anyway :)

1

u/procrastinatingcoder Apr 06 '22

There's a distinction between memoization and dynamic programming. As a "short but obvious" comparison. I really "glossed over" that distinction in my post, which was meant to just be as simple as can be, and someone else already explained it somewhat. But here goes another simple non-detailed explanation with an example.

Memoization:

  • Caching a function's result.

Here's an "example" undirected weighted graph.

A--5--B--7--C
|           |
3           |
|           |
D-----------5

The shortest path from A->C has value 12, therefore if you see the method: graph.findShortestPath(A, C), you know the answer is 12 and you don't actually need to run that function.

HOWEVER

You can't do something like:

shortest_path = graph.findShortestPath(A, C) + graph.findShortestPath(C, D)

In other words, you can't re-use the result from A to C to compute A to D.

As an extra note: You could use memoization to compute the shortest path from A to D passing through C.

Dynamic Programming:

  • Caching the result of sub-problems in order to solve the bigger problem

With the classic example of fibonacci (adding the two previous number of the sequence together makes the next number. the sequence starts with 0, 1, so it follows like this:

fibonacci = 0, 1, 1, (1+1), (1+(1+1), ((1+1) + (1+(1+1))), ...

fibonacci = 0, 1, 1, 2, 3, 5, 8, 13, 21, ...

If you have the Nth and the (N-1)th values, you don't need to recompute everything that came before to get the (N+1)th value. So Dynamic programming can be applied. Dynamic programming is particularly useful in pattern matching, and is a very common way to apply some distances like the Levenshtein one. An example of the fibonacci function would be:

class Foo:
    def __init__(self):
        self.values = [0, 1]

def fibonacci(int: i):
    if len(self.values) >= i:
        return self.values[i]
    ...calculate fibonnaci up to i here, and store the results...

It basically requires the bigger problem's solution to be built from the smaller problem's solution.

Long story short, dynamic programming is usually terrible for most graph-related things, it's in fact one of the reasons why things like graph coloring, etc. Are such a pain. You can't know for sure that the solution to a smaller version of the graph will be part of the solution of a bigger graph that includes that one.

What you're using to doing is thus memoization, and not dynamic programming.

As an added note, you could say that memoization is part of dynamic programming, but not all memoization tends to work with dynamic programming.

I already gave up to write anything longer than a text message on my phone, all good though!