Personally I think it's really cool to learn other languages. Python's limited language may limit you on types of data structure you can learn (eg pointers). For Leetcode, you'd likely spend the most of your time just practicing with algorithms anyways: learning algos is one thing, implementing them on a random problem is much more difficult.
#algos-and-data-structs
1 messages · Page 4 of 1
"ultimate goal of getting a job at one of the companies that do leetcode style questions?"
what data structures are impossible with python's references?
I'm sure there's diversity in companies, but I'm pretty sure technical interviews with these qs are only part of the process in most companies, and a good resume/past exp or projects is needed
e.g. pointers
basically doesnt exist in python
a pointer isn't a data structure
but is useful in the implementation of DS
what data structure is impossible without pointers?
may limit you on types of data structure you can learn
never said its impossible
just ud have to implement it slightly diff from what u might find in a diff lang
sure, you just implied it
imo, you shouldn't learn DSA just to pass a tech interview; all devs should have some understanding of them
Python's references are pointers to objects. Python doesn't have null pointers, but it does have references to None which can be used instead of a null pointer in nearly every case I can think of
you can easily build, for instance, a binary tree where the left and right attributes of a Node are references to either another Node or to None
or a doubly linked list where the next and prev attributes of a Node are either references to another Node or to None
the only data structure that I can think of off the top of my head that you really can't meaningfully implement in Python is a dynamic array, because it requires manual memory allocation to implement
why am i being pinged 😭
and i meant u cant actually use pointers urself; ull just get the object it refers to
but that is using pointers yourself
the only thing you can't do is make a reference point to no object at all - every reference needs to point to something
oh ok
you can't easily do fun pointer arithmetic in python 0/10 won't use again
Hello, can anyone please pinpoint of this NFA to DFA transition is wrong? It's practice in class. The other NFA to DFA questions are correct however this one is not when I look at the correct answer
This is the NFA
This is the DFA I drew
State 2 is incorrect. It should be 2, 4, 3 according to the solution and sending transition a to state 4,3
"these three" 
those questions are a bit more involved than I feel like getting myself on the hook for helping with right now.
isn't the tigers one just "what's the minimum discomfort if I place the x oldest tigers in the y closest cages?"
size and capacity is what defines the discomfort
I think what I suggested is the solution
dp[x][y] =
min(
dp[x][y-1],
dp[x-1][y-1] + (discomfort adding xth tiger to yth cage)
)
yes, the order is forced
and the "use x items in the first y spots" is a very common dp thing
more just a way to formulate the dp
you need to find a formulation that can be expressed in terms of smaller instances of itself, then you can optimize by not computing cases multiple times
7.1. seems similar
so you want to maximize the number of delegates
now the question is what kind of dp formulation would make that happen, it will also need to incorporate the "cooldown" of 2 days
wdym?
you don't have control over the order of things
you can choose to take all d_i or just z_i at every step, if you pick d_i then you have a cooldown
I think this is easier than your typical knapsack problem, but I guess it's similar
the overall question is if the maximum number of delegates you can get is >=floor(D/2) + 1
so you'll want to compute that maximum value
for each i you have z_i which is the number of delegates you would get by doing nothing, you can also decide to take all d_i delegates (at the cost of the cooldown)
d/2+1 isn't really important for what you want to do, you just want to maximize
computing the maximum you can achieve solves the problem, yeah
now, how can you formulate the maximization as a dp?
it's not that knapsack-like, it's simpler than that
if there was no cooldown you would just take d_i all the time
can you give some dp formulation?
like the one I gave for the other problem 
I guess important question, what are the states?
why? why not just start at 0 and compute the maximum?
wdym?
what if picking d[i+1] is optimal?
the thing you have there might pick d[i] when it's not optimal
e.g.
d = [4, 10, 1]
z = [1, 1, 1]
what things would be part of your dp space?
as a hint the solution I imagine has 2 state variables
like, picking the right variables is key to be able to formulate a dp
e.g. in the other problem, first x tigers, first y cages
no, they are just two independent numbers, in the last problem I had the subproblem of dp[x][y] = "minimum if I allow using first x tigers and y first cages"
the key is that in this formulation you can express dp[x][y] in terms of smaller subproblems
sounds pretty vague
I mean the whole thing you described sounds pretty vague to me
it's probably not surprising that one part of the relevant dp state is "if I consider the first x contests"
elaborate?
can you formulate what you mean in the form of a dp?
like, a recursive relation for it
why would this be optimal?
huh?
I don't really know what you mean here, maybe show an example?
max?
do you mean sum?
and d_i is?
so you pick the 4
which is not optimal
what about
d = [4, 10, 1, 100]
z = [1, 1, 1, 1]
picking 10 here is not optimal
I don't think so
you seem to be trying to do something greedy
when you actually need to consider a bunch of options
if you had the answer for dp[x], can you use dp[i] for i < x to compute dp[x]
x is the same as before, "if you consider the x first contests"
expressing stuff in smaller problems is what it's all about?
though I'm asking if just having this x as a variable works or not
e.g. do you know if the value dp[x-1] is ok to use?
say I picked the d option in contest x-1
can I pick d in contest x?
no
because of the 2 day cooldown
so I have no clue if I can use dp[x-1] and pick the d option in contest x
kinda, but there is a neater way of modeling it
what if we add the cooldown as part of the state
you would have two variables in the state, let's call them x and c
considering the first x contests, and I have to wait c turns to make a d choice again
(actually maybe this could boil down to just looking two back, but this was an easier thing to imagine in my head)
like, I know the dp formulation I would do
can dp[x][...] be expressed in dp[x-1][...]?
so, c will have possible values 0, 1, 2
I'm asking if dp[x][2] can be expressed in dp[x-1][0], dp[x-1][1] and dp[x-1][2]
same question for dp[x][1] and dp[x][0]
dp[x][2] means you picked d[x], which you can only do for dp[x-1][0]
dp[x][1] means you were at dp[x-1][2] and had to pick z[x] because of the cooldown
what about dp[x][0]?
well yeah, but what action can arrive there, and from which prior states?
and from which states?
not only that one
right
and you want to pick the better option of those
ok, can we write down this as a nice dp formulation?
(so an expression for each of dp[x][0], dp[x][1] and dp[x][2])
the first one is indeed the expression for dp[x][0]
but the other ones aren't correct
actually
first one isn't quite right either
dp[x][0] = max(dp[x-1][0], dp[x-1][1]) + z[x]
dp[x][1] = dp[x-1][2] + z[x]
dp[x][2] = dp[x-1][0] + d[x]
for 0 we had two options, as discussed, both involve picking z[x]
for 1 we can only arrive from 2, picking z[x]
for 2 we can only arrive from 0, picking d[x]
(it's getting early, rather)
others here can probably help as well
in any case this is the formulation you can implement
they say that you either picked z[i] from the previous dp value
or you picked d from two steps back followed by z z
the approaches are pretty similar in the end I think
it's their dp values, and they kinda go the other direction it seems
my dp[x] was expressed in terms of smaller x
their x(i) is expressed in terms of larger i
I think both formulations are fine, slightly different ways to think about the problem
it's a thing in general, depending on how you view the problem you can find slightly different formulations that all work
(and sometimes finding any view of the problem that works as a dp is hard)
(but you spot patterns in solutions as you practice)
what is ]
(BS, y, BL) = split(B, x)
(NS, z, NL) = split(N, y)
doing
nvm
didnt see the split func
for loops are just abstracted summations right
for example i have this string
"!Hello!"
is there a way for me to check if there is a "!" and then another "!" after it ignoring the text between the exclamation points ?
another example would be smth like ```py
"0Python1"
i wanna check if in the string , there is sequence of a 0 and then a 1
kind of like an opening and closing bracket , the 0 acts like an opening bracket and the 1 acts like a closing bracket, i wanna check if there is that pattern of a 0 and 1 after it, meanwhile ignoring the text between both of them
!e
sum(bool(print(i)) for i in range(10))
@haughty mountain :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
now...a summation calling a function with side effects sounds like fun math
.latex $$f(x) = {i := i + 1, x^2}_2$$
where i is a global integer
does math even have visibility rules? access modifiers?
everything is global and public, clearly
What's the difference between the last 3 choices
the last one isn't valid syntax
2 and 3 are indeed equal though, they just want you to pick the one with the same summation variable and order I guess
when sorting this arrray [1, 2, 3, 5, 4] using bubble sort, is the total number of passes 4 or 5?
2
assuming it is not optimized bubble sort
4
why 4 though?
wouldn't it be something like this:
pass 1: 1, 2, 3, 4, 5
pass 2: 1, 2, 3, 4, 5
pass 3: 1, 2, 3, 4, 5
pass 4: 1, 2, 3, 4, 5
pass 5: 1, 2, 3, 4, 5
hey all, i am trying to show:
Hello
inductive assumption:
T(n) < cn^2
I want to ask about fcc project 1
Arithmetic formatter
One of the rule said:
Number of each side of the operator has a max of 4 digits width
Otherwhise it should return error.
I already split the string by spaces so i got 3 part
Num1 = first number
Num2 = 2nd number
Op = the operand
I write
Elif len(num1) > 4:
Return 'error'
Elif len(num2) > 4:
Return 'error'
But when it wont pass the test when num2 get assign with
'24 + 85215'
Num 1 should be 24
Num 2 should be 85215
And it should have return an 'error'
well, -2cn + c = c(1-2n), so for all n>=1 that's below 0. Hence, < cn^2.
thank you!!
Other way around. If it comes from math, it's probably the more abstract version.
I think 3 is zero
fwiw you dropped an n
.latex
$$\begin{align}
T(n) &< c(n-1)^2 + n \\
&= cn^2 - 2cn + c + n \\
\{\mathrm{if\;} c \geq 1, n \geq 1\} &\leq cn^2
\end{align}$$
though this particular one is quite obvious,
T(n) = 1 + 2 + ... + n
its really not clicking for me what exactly this means
-2cn + c + n <= 0, if c>=1 and n>=1
i mean, i know what in means in english, that the recurrence can be upper bounded by some function f(n) = cn^2
how do you mean
so i was mowing the lawn and realized that i'm getting substitution proofs, proofs by induction, and substitutions to solve recurrences all mixed up in my head
evaluate something like T(5) by hand
T(5) = T(4) + 5 = T(3) + 4 + 5 = ...
it's a very clear pattern
ok so how does that help me to see the answer
T(n) = 1 + 2 + ... + (n-1) + n
```isn't helpful?
why are you bringing summations into it
because that's what this recurrence expands to
you have that
T(n) = n (n+1)/2
(assuming T(0) = 0)
which is clearly O(n²)
literally no idea what you're talking about
.latex it's the case that $\sum_{i=1}^n i$ is exactly equal to $\frac{n(n+1)}{2}$
def foo(n):
if n == 0:
return
bar()
foo(n - 1)
``` How many times does `bar` execute if n = 2 (`foo(2)`)?
2
do you agree that T(5) = 1 + 2 + 3 + 4 + 5?
for which formula
the one you brought up, T(n) = T(n-1) + n
don't you need a base case
CLRS 4.3-1:
show that the solution of T(n) = T(n-1) + n is O(n^2)
i don't see how it could evaluate to this
T(2) = 3
T(3) = 6
you need to assume some base case where T(small value) evaluates to a constant, let's assume T(0) = 0 maybe better T(1) = 1
T(3) = T(2) + 3 = T(1) + 2 + 3 = 1 + 2 + 3 = 6
in general
T(n)
= T(n-1) + n
= T(n-2) + (n-1) + n
= T(n-3) + (n-2) + (n-1) + n
= T(n-4) + (n-3) + (n-2) + (n-1) + n
= ...
= 1 + 2 + ... + (n-3) + (n-2) + (n-1) + n
15 = 1+2+3+4+5
so why is this clearly O(n^2)
it's a quadratic...
(n^2 + n)/2
e.g. it's for sure <= n²
How about ```py
def foo(n):
if n == 0:
return
bar()
bar()
foo(n - 1)
but in general all degree k polynomials are O(n^k)
4
So basically 2n right?
yea
How about ```py
def foo(n):
if n == 0:
return
for i in range(3):
bar()
foo(n - 1)
Yeah, and in terms of n?
depends on if you put n in the num or the denom
if its in the denominator, then its bar() / n == 6/2 = 3
bar() / n = 3, bar() = 3n
Same as before, except 3n instead of 2n.
Because each time we do 3 bars, instead of 2.
bars/n yea
We are counting how many times bar is executed. Which is 6 in the case of n = 2, and 3n in the case of any n.
honestly i'm no closer to being able to solve any of the homeworks and i think i'd be a fool to borrow 6k to try to pass this course
Not bars per n. Just bars total.
the homeworks are like CLRS 2-1
just all words and variables and i immediately get confused even trying to comprehend what they're asking
So how about ```py
def foo(n):
if n == 0:
return
for i in range(m):
bar()
foo(n - 1)
(m could be anything)
i really appreciate you hand tailoring this lesson for me but i'm afraid my mind simply does not work in these terms, which is, disappointing
You were able to answer the previous ones, if you can't get this one I can give you the answer and it may become more obvious.
but in the previous ones it didn't make sense to put n on the bottom as we weren't dividing anything
thats why i had to think of it as bar() per n, otherwise i'd never know to put n on the bottom
In the first one, it executes n times right?
The second one, bar executes 2n times, because all we did was call bar once more each time.
why are we dividing by n?
how many bars / for each n
It's not bars per n, it's bars executed total in terms of n.
don't we just want the total?
it has to be otherwise it'd be n/bars = isn't correct
Look at the first one again.
bars / n makes sense mathematically, bc we can multiply both sides by n to get bars total
How many times does bar execute for n = 2, n = 3, n = 4, n = n?
you would have to know bars per n to work in terms of unknown n
you don't
for which expression
def foo(n):
if n == 0:
return
bar()
foo(n - 1)
2n, 3n, 4n, n^2
For n = 2, bar executes 2 times.
right
For n = 3, n = 4?
Correct.
So the TOTAL number of times bar executes in foo is n times.
In general.
Not bars per n, just bars.
If n = 3, we get 3 bars, if n = n, we get n bars.
right
So now what if we change it to: ```py
def foo(n):
if n == 0:
return
bar()
bar()
foo(n - 1)
For many bars for n = 2, 3, 4, n?
n=2 = 4 bars, n=3 = 6 bars, n=4 = 8 bars, n=n = 2n bars
Correct.
So now what if: ```py
def foo(n):
if n == 0:
return
bar()
bar()
bar()
foo(n - 1)
n=2 = 6 bars, n=3 = 9 bars, n=4 = 12 bars, n=n = 3n bars
Correct.
Now what if: ```py
def foo(n):
if n == 0:
return
for i in range(3):
bar()
foo(n - 1)
n=2 = 6 bars, n=3 = 9 bars, n=4 = 12 bars, n=n = 3n bars
Correct. It's the same thing just written with a loop which makes it easier to change the number.
Notice the pattern. n is the number of times the function foo gets called, and the coefficient is the number of times bar gets called per foo call.
totally
For example with 3n, n is the number of times foo is called, and 3 is the number of bars per each call.
So now what if: ```py
def foo(n):
if n == 0:
return
for i in range(m):
bar()
foo(n - 1)
and 3* is the number of bars per each call.
Yes.
Amount of work per call.
And when you repeat some work n times, that is what multiplication is.
(Repeated addition / repeat work)
bar calls are = m*n
m^2 / n^2 whichever var youre choosing
(The initial n given to foo)
Correct.
So now lets go back to ```py
def foo(n):
if n == 0:
return
bar()
foo(n - 1)
The time T taken of the function is the number of bars.
T(n) = ?
n
looks like foo(n) and foo(n-1)
the bar work i suppose at each lvl
Yes.
So we have T(n) = n, a nice non-recursive form, and a recursive form T(n) = T(n - 1) + 1.
so reading this im seeing like the amount of work done by this recursive algo is equal to the amount of work done at this lvl + the amt of work done at the previous lvl
Exactly.
Counting the amount of work at each level, plus the previous level.
And that previous level itself is also recursive.
thats where i get thrown i think. when i see T(0) or T(1) and its not defined in the problem
In this case it comes from the if n == 0: return
not in the LHS but on the right like something = T(1) + n and theres no T(1) to be found
We make sure we stop when doing the T(n - 1) until we reach T(0)
T(0) is just 0, no bars.
Because it returns before then.
T(1) = T(0) + 1
Basically foo(1) just runs 1 bar, and then calls foo(0) which does nothing, because it returns before it reaches the bar.
right ok
So T(0) = 0 is the base.
Base cases in code often show up as those if statements at the start that return early.
Without that if statement, it would run forever. n = -1, -2, etc.
of course
Which would make T(n) = inf
well this has been very helpful so far, i hope it translates to understanding the material better
So trying ```py
def foo(n):
if n == 0:
return
bar()
bar()
foo(n - 1)
What is the non-recursive and recursive?
T(n) = ?
(You already did the non-recursive before for this one)
T(n) = 2n and T(n) = T(n-1)+2
Correct.
How about ```py
def foo(n):
if n == 0:
return
for i in range(m):
bar()
foo(n - 1)
Correct.
Now notice that m is the same at each level in the recursion. So each level does the same amount of work. Which what lets us get the nice mn form, because we do m bars, n times (n levels).
If you look at the recursive version, you can see how you would get the non-recursive from it:
yeah the whole T(n) = (work at last lvl) + work at this lvl thing makes a lot of sense
at least, for recursive functions that is
T(n) = T(n - 1) + m
So for example n = 4:
T(4) = T(3) + m
= (T(2) + m) + m
= ((T(1) + m) + m) + m
= (((T(0) + m) + m) + m) + m
= (((0 + m) + m) + m) + m
= ((m + m) + m) + m
= (m + m + m) + m
= m + m + m + m
or 4m because multiplication is repeated addition
It expands out and combines, and in this case we can see that it always combines to nm for some n.
Each level adds m work / time.
Now m itself comes from doing bar m times, and bar counts as 1 work / time.
m is a counting of the number of bars we do per level.
So it looks like m = 1+1+1+1... (m of them (there are m bars, each worth 1)).
That is what the for loop is basically doing.
If m = 2, then the number of bars per level is 1+1 = 2.
If m = 3, then the number of bars per level is 1+1+1 = 3.
Each iteration of the for loop runs 1 bar.
what if you were given something like T(n) = T(n+1) + n
Yeah I was building to that.
ok
So right now m is the same per each level.
Each level does the same amount of work, but what if each level does different amounts of work?
What if for n = 2, the top level did 3 bars, and the second did 5?
Then the total is 3 + 5.
If we had 3 level with 9, 4, 3 bars each. Then the total is 9 + 4 + 3.
What if each level did some number of bars equal to the level it's currently on?
So level 2 (n = 2) did 2 bars, level 1 did 1 bar, level 0 did 0.
It would look like this: ```py
def foo(n):
if n == 0:
return
for i in range(n):
bar()
foo(n - 1)
The number of bars each level does depends on which level it is.
(depends on the current n at that level)
What would be the recursive T(n) for this?
T(n) = T(n) + 1?
That would run forever.
And also if you subtract T(n) from both sides you get 0 = 1 which can't be right.
T(n) = T(i)+1?
Well, i is not defined.
You have to work in terms of what you are given (n).
For n = 2, 3, 4, n?
How many bars?
lms
For n = 2, how much work does that level do (how many bars)? Not including the next level n = 1 and n = 0?
3 bars
oh right duh
For the n = 1 level how many bars?
For the n = n level?
n
And remember what m was? The work per level.
So in the recursive version, what is the work per level?
mn
Work per level in this.
Remember T(n) looks something like T(n) = T(n - 1) + work per level.
The T(n - 1) is coming from the foo(n - 1).
And the work per level from the loop.
If level 2 does 2 work, and level 1 does 1 work. Then it makes sense that the nth level does?
n work
So T(n) = ?
T(n) = T(n-1)+n
Correct.
Now you have the recursive T(n) for foo.
How much work foo does for any given n.
But what about the non-recursive form?
Is there a nice one?
If level 1 does 1 work, level 2 does 2 work, level 3 does 3 work, ... level n does n work. And we want the total work. We add up the work done at each level.
Which looks something like 1 + 2 + 3 + ... + n.
If 1 + 2 + 3 + ... + n is the total work. Then T(n) = 1 + 2 + 3 + ... + n, and you may note that this is just an expansion similar to the one done before, where you just substitute over and over until you reach T(0).
be back in 2 mins. have to give cat his medicine
T(n) = T(n - 1) + n
For n = 3:
T(3) = T(2) + 3
= (T(1) + 2) + 3
= ((T(0) + 1) + 2) + 3
= ((0 + 1) + 2) + 3
= (1 + 2) + 3
= 1 + 2 + 3
So in general:
T(n) = 1 + 2 + 3 + ... + n
It follows that pattern.
🐱
ok so in essence if we have a recursively defined function which does n work at each level it follows the same mathematical summation as 1 + 2 + 3 + ... + n
right
Or the total number of bars.
Or the "time" T.
Or number of steps.
Whatever you prefer.
But we know that pattern right? 1 + 2 + 3 + ... + n.
or know how to quickly derive it
So multiply out the numerator.
2T(n) = n*(n+1) ?
I meant go from n(n+1) to n^2 + n on the top.
S = 1 + 2 + ... + (n-1) + n
2S = 1 + 2 + ... + (n-1) + n +
n + (n-1) + ... + 2 + 1
2S = (n+1) n
S = (n+1) n / 2
We have ```
T(n) = 1 + 2 + 3 + ... + n = (n(n+1)) / 2 = (n^2 + n) / 2
Now I will split it up: ```
= n^2 / 2 + n / 2
And from this it should be pretty obvious what the big O of foo is.
right its O(n^2) bc some function c*n^2 can upper bound T(n)
Yes.
So now you know how to take something like foo, get its T(n), and from that its big O.
well this has been a real treatise in summations 🙂
And notice the route: code -> recursive T(n) -> non-recursive T(n) -> bounded big O.
If the code has no recursion then the recursive T(n) step does not apply. Although you can if you want to.
Like if you have just ```py
for i in range(n):
bar()
Which is obviously O(n).
did you see my earlier message regarding substitution proofs / induction / substitution to solve recursions
Which?
ill link
other example function
def foo(n):
if n <= 1:
return
foo(n/2)
foo(n/2)
for i in range(n):
bar()
should be familiar as the same structure as ||merge sort||
this 1
Recurrences are relating a function to itself but with modified arguments, like T(n) = T(n - 1) + 1.
right
So one level to another (or multiple).
you combine substitution and induction, right?
Induction is this neat thing where if you have a recurrence you can prove a non-recursive form by showing that you can get from one level to another by using the induction hypothesis (plus a base case).
idk do we
guess the answer, substitute it in to make the thing non-recursive, and then you can do an inductive proof
ooohhh
that's why you substitute
to make it non recursive!
Substitution is a method to show that you can get from one level to another. It's how you can get from one equation to another.
yes, because recursion is often annoying to deal with in analysis
Substitution is a "legal step" in math when trying to show something.
Yeah or in general to show that they are the same thing, the recursive and non-recursive forms.
i'm pretty good with induction to show like a base case and then set to n (or n-1) and then solve for n+1 (or n)
Like for example: ```
x = 10
y = x
I want to prove / show that y is 10. To do this I can use substitution:
Replace x with 10:
y = (10)
In the recurrence stuff you are trying to show that the recursive one is the same as the non-recursive one (and the other way around, it goes both ways).
eeoowwhh
And we want the non-recursive one because we know how to upper bound it for big O.
Math is a lot of just seeing the same thing from a different POV and the POV shift here is recursive to none-recursive.
And showing that POV shift to the reader (which includes yourself, there is a feedback loop of you writing it and reading it) step by step.
yeah its a lot of "if its true that x, then it must be true that y due to z axiom / rule / property" type thing
in a recursive solution the order you solve subproblems gets handled for you, when writing it iteratively you need to follow an order such that if dp[a] depends on dp[b], then dp[b] gets computed first, usually the ordering you need is pretty obvious
Draw out the call tree, see what depends on what and in what order.
n was replaced by n+1
looks like they plugged in n+1 in some places and (n+1)^2 in others
but that has the perfect form as if you just plug in (n+1) in for n
no squaring necessary
Not sure.
you see this too right
like, you can get to the RHS of the implication by simply plugging in n+1 for all n
then that squared term is anomolous
Might be an error.
didn't we do this a while back and I pointed out those notes had a bunch of errors?
yeah i was getting that feeling, i just revisited it bc prof just told me to
we also did T(n) = 2T((n/2) + 17) + n is O(nlgn) IIRC

ok you're right you pointed it out here
at least i'm able to see the same thing now, that's progress i guess
🎊
can you remind me how we did this one or just point out the msg
thanks i owe y'all so much, if it weren't for y'all i wouldn't have a chance in hell at this (i might not still but its infinitely better than i'd do in a vacuum)
and there was some additional stuff earlier than that
you can search for posts from me containing 17
Ok thanks
it looks like you are allowing terms in here to be described by the O(n) term.. is that it?
I'm being a bit lazy. The O(n log n) term will dominate the O(n) terms anyway
i just wonder if i'm interpreting your steps correctly. sorry if it is late where you are? what time is it?
so I use the O(n) to contain terms that are at most linear so I don't have to keep writing stuff that ultimately don't matter
right
My first PyPI package — re-doing a readability algorithm from the original publication. I learned a few things along the way. Like, sometimes an algorithm's output is best modeled as an enum, not a number. https://github.com/public-law/new-dale-chall-readability
why is i&-i == rightmost bit? and what does i~&(i-1) do?
for i&-i
-i is ~(i - 1) which might be more helpful
i - 1 will take the rightmost sequence ...100...000 and make it ...0111...111, everything else unchanged
Now all one bits in i correspond to a one bit in i-1 except the lowest one. So i&~(i-1) gives the lowest set bit
see how high 1 bits in i still align with 1 bits in i-1
i: 0b1010100
i-1: 0b1010011
thanks a lot I got it
How is it that my code passes the time limit of one second?
size, m = list(map(int, input().split()))
pairs = [list(map(int, input().split())) for i in range(m)]
lof = [[] for i in range(size+1)]
for i in pairs:
x, y = i
lof[x].append(y)
lof[y].append(x)
def func(n, lst):
if n==0:
return 1
sm = func(n-1, lst[:])
for j in lof[n]:
if lst[j]==1:
return sm
lst[n] = 1
return sm+func(n-1, lst[:])
print(func(size, [0]*(size+1)))```
this task
If I copy the list every time the function is executed shouldn't it be 2**20 x 20 which over 20 million exections
and also loop through the pairs of n-1 which is at most 20
so the max should be 2**20 x 20 x 20 which way to many exections under one second for python
first off isn't it just 20 * 2**20 you don't do any 20*20 work afaict?
there is also some early exiting going on, so maybe the worst case isn't so bad
It's looks so close but feels so far.
looks like by definition polynomials must have the form ax^3 + bx^2 + cx + d, but could also be degree zero polynomials, eg f(x) = x^0
degree 1 polynomial has the form f(x) = a_0 + a_1x
your d term there could be written dx^0
good point
public static i just saw where your name comes from, don't know what it means but its in the math text i'm reading
in a math text?? interesting lol, it's the main method in java
A Programmer's Introduction to Mathematics
ah, that makes more sense
having trouble picturing what is meant in the formula
this is a great resource for people trying to convert from code to the math:
wow, this would sure look nicer in a less procedural language
yea 😦
like, this can be sum(math.prod(foo(i,j) for j in range(1,n+1) if j!=i) for i in range(1,n+1)) in Python
You can drag around P1 and P2.
The "current" x.
x1-x2 gives the x-distance between the two points.
And x2-x1 the same but negated.
So when x = x1, you have x1 - x2 in the numerator and denominator, so = 1.
Which is multiplied by y1.
The other term has x1 - x1 in the numerator, so it's 0, which is multiplied by y2.
So the end result is y1 + 0 or just y1.
So when x = x1, the y output of f is y1.
And when x = x2, the y output of f is y2.
yeah i get it so x1 causes y1 as output and x2 causes y2 as output
And the in between values follow the line.
by making the other terms eval to zero
Yeah.
So when it's half way.
It's 0.5 y1 and 0.5 y2.
did you try CLRS
idk how helpful it'd be but there is at least one chapter in there on dynamic programming if not more
how would i factor this? i asked in the maths server and got ghosted
some ppl really don't like helping with algebra haha
its supposed to wind up like this:
.latex there are nicer ways to think about that last expression, it can be rewritten as
$$
y1 \frac{x - x2}{x1 - x2} + y2 \left(1 - \frac{x - x2}{x1 - x2}\right)
$$
idt this is the right place to ask but try multiplying the top/bottom of the second fraction by -1
I should have had subscripts, but whatever
whats the first step i should do
i did a first step to get it in that form which im pretty sure is right
how should i proceed
in particular, it's a case of doing a linear interpolation, e.g. t b + (1-t) a is a linear interpolation between a and b as t goes from 0 to 1
oh i see what you did, simply factored out y1 from first term and y2 from second
just trying to comprehend the algebra for now
wait where did the 1 - come from in the second term
separate the terms of the denominator so you get 4 fractions total, combine the ones that contain x and combine those that don't into fractions again
deadly trick, add 0x - x1 = x - x1 + (x1 - x2) - (x1 - x2) = x - x2 - (x1 - x2)and then you can separate out the x1 - x2 from the fraction
i don't know how to separate out the terms
for brevity, lets define d = x1 - x2
y1 (x - x2)/(x1 - x2) + y2 (x - x1)/(x2 - x1)
= y1 (x - x2)/d - y2 (x - x1)/d
= y1 x/d - y1 x2/d - y2 x/d + y2 x1/d
= y2 x1/d - y1 x2/d + y1 x/d - y2 x/d
= (y2 x1 - y1 x2)/d + x (y1 - y2)/d
line 2->3 is separating (a-b)/c = a/c - b/c
line 3->4 is just reordering terms to have the ones with x at the end
line 4->5 factors out common factors
the second term has x2 - x1 in the denom
hence the - in line 2
a/(b - c) = -a/(c - b)
- -1/-1 is another fancy form of 1.
(-1 / -1) * a / (b - c) = (-1 * a) / (-1 * (b - c)) = -a / (-b + c) = -a / (c - b)
looks like you simultaneously distributed the coefficients while pulling apart the fractions
i still don't see where the 1 came from but we got to where we needed to go without it so far as i can tell
it's really just a(b+c) = ab+ac in disguise
which 1?
(a-b)/c = (1/c) * (a-b)
here
.latex $\frac{a-b}{c} = \frac{1}{c}(a-b)$
.latex $= \frac{a}{c} - \frac{b}{c}$
ah, yeah that's me rewriting into a different form, let me write some steps out
again d = x1 - x2
y1 (x - x2)/d - y2 (x - x1)/d
= y1 (x - x2)/d - y2 (x - x1 + d - d)/d
= y1 (x - x2)/d - y2 (x - x2 - d)/d
= y1 (x - x2)/d - y2 ((x - x2)/d - 1)
= y1 (x - x2)/d + y2 (1 - (x - x2)/d)
no i'm great with what we did i don't want to confuse myself 😂
it's not a complicated rewrite, add 0
a/b = (a + b - b)/b = (a + b)/b - 1
coming up with the right variables and finding the formulation is hard
it's basically just practice and recognizing common patterns and tricks
I didn't learn dp doing classes or whatnot
In this video, we go over five steps that you can use as a framework to solve dynamic programming problems. You will see how these steps are applied to two specific dynamic programming problems: the longest increasing subsequence problem and optimal box stacking. The five steps in order are as follows:
- Visualize examples
- Find an appropria...
I did competitive programming for a few years, so I've solved a lot of problems, a fair share dp problems
though I wouldn't say I'm amazing at it
do functions map between set set domain to the set codomain? or range perhaps?
In mathematics, the range of a function may refer to either of two closely related concepts:
The codomain of the function
The image of the functionGiven two sets X and Y, a binary relation f between X and Y is a (total) function (from X to Y) if for every x in X there is exactly one y in Y such that f relates x to y. The sets X and Y are called...
functions dont need to map something to every element of the codomain, the range is the subset of the codomain containing just the elements which are actual outputs of the function
Range is ambiguous (either codomain or image).
range seems more concrete (just outputs) then what is codomain?
codomain or set of destination of a function is the set into which all of the output of the function is constrained to fall.
sooo
If you plug in some values and get some out, you have some subset of the domain A that you plugged in, and you got out some subset of the codomain B. B is the image of A under f.
And range can refer to either the codomain or the image.
In the image I gave, red is the domain, blue is the codomain, yellow is the image (when you plug in some values from the domain into f).
If someone says range they probably actually mean image.
As the term "range" can have different meanings, it is considered a good practice to define it the first time it is used in a textbook or article. Older books, when they use the word "range", tend to use it to mean what is now called the codomain.[1][2] More modern books, if they use the word "range" at all, generally use it to mean what is now called the image.[3] To avoid any confusion, a number of modern books don't use the word "range" at all
The confusion is caused by old books meaning codomain, and new ones meaning image. So new books don't use "range" at all now.
ahh this is typifying what this guy is saying in his book is that part of the difficulty in math is that the pedagogy is a bit scattered and not contained in a centralized place
what exactly is this theorem telling us:
Yeah and across languages too. Like how in English they use "identity element" and everyone else uses "neutral element".
For any n+1 points, there is a unique polynomial degree (at most) n that goes through all of them.
eg. If you have 3 points theres always a quadratic of the form ax^2+bx+c that passes through all of them
there are 10 points at which a 9th degree polynomial crosses all of them?
Wikipedia Search Results
Lagrange polynomial
Shamir's secret sharing scheme in cryptography. For equispaced nodes, Lagrange interpolation is susceptible to Runge's phenomenon of large oscillation. Given
Chinese remainder theorem
numbers, which makes it less efficient and less used. Nevertheless, Lagrange interpolation is a special case of this construction, applied to polynomials instead
Page 1/5
·
just one
oh wow
so if i pick 3 points in the euclidian plane, there is only a single 2nd degree polynomial which will pass through all of them, eg a single correct answer
ye
thats sort of remarkable
2 degree or less to be precise, if the three points are collinear then you only need a linear polynomial
and it doesn't violate the theorem bc there is only one polynomial of that degree which passes through all
the theorem says "of degree at most n"
how then is it not violated if you select 3 colinear points and connect them with a degree 2 polynomial and a linear polynomial
i guess the answer is no such two polynomials connect any 3 linear points
yes the straight line is the only one, theres no other degree 2 polynomial which would pass through the 3 points
If you want to mess around with Lagrange polynomials: https://www.desmos.com/calculator/nkerwfajsh
@fiery cosmos
thats neat but i need to learn as much algebra as fast as i can 😭
last night the prof really took the wind out of my sails and made me feel like its not going to work. i'm going to take the course anyway and withdraw if my grades get bad enough. i don't understand bc its not an algebra course, surely i can learn enough to do the proofs / asymptotics / whatever else
just bc i haven't made a lot of progress on my own doesn't mean i can't learn during the semester. she also revealed that the uni has private tutors that are paid and only part of the engineering school? so i don't think i could get one even if i had money to throw around
More points for fun: https://www.desmos.com/calculator/qdb3pr3jh3
I think normally algebra and some calculus are prerequisites for algo courses because of algo analysis, but I think what's needed isn't that advanced
though being used to do algebra and rewriting expressions is pretty important
Algebra is needed yes
Calculus, I don't think so
Never really had to do any calculus in my Data Structures and Algos course, especially for Complexity analysis
what you do have to do a lot is solving recurrence relations
i've been practicing that quite a lot hoping it will click. algmyr and squiggle have been helping me a ton. i got some good algebra practice today with algmyr, and squiggle walked me through how summations describe perfectly the work done by functions with recursive calls
we have been running a lot of these recurrence relations by substitution
yea there's like a few ways to solve them, the popular one being substitution
There's also master's theorem if you want to learn later
i am aware of that yes and hope to get more practice in it
but I would put that on hold for now if you are just starting with the basics
i've been going through all these basics for around a month including practicing algebra, learning discrete math, and implementing pseudocode
The special case of master's theorem is easy enough to understand, but the general thing is a beast
I have forgotten it already, it's been like 3-4 months since I had learned it
Would have to revise it again
Referring to any kind of loop in the graph
There's no special name for an edge with same source and destination AFAIK
In graph theory, a loop (also called a self-loop or a buckle) is an edge that connects a vertex to itself. A simple graph contains no loops.
Depending on the context, a graph or a multigraph may be defined so as to either allow or disallow the presence of loops (often in concert with allowing or disallowing multiple edges between the same vertic...
I guess it is called loop
Graph Theory has a name for everything. Some are pretty funny.
Who cares as long as the message is conveyed.
you should see some of the bio terms 😂
In molecular biology, an exonic splicing enhancer (ESE) is a DNA sequence motif consisting of 6 bases within an exon that directs, or enhances, accurate splicing of heterogeneous nuclear RNA (hnRNA) or pre-mRNA into messenger RNA (mRNA).
doesn't that just sound, made up?
self-loop is a common term
Mitogen Activated Protein (MAP) kinase kinase kinase, MAPKKK (or MAP3K) is a serine/threonine-specific protein kinase which acts upon MAP kinase kinase. Subsequently, MAP kinase kinase activates MAP kinase. Several types of MAPKKK can exist but are mainly characterized by the MAP kinases they activate. MAPKKKs are stimulated by a large range of ...
last one i promise
they're just so funny
what do you call the array that a hashing function maps data to
IIRC its hash table / hash map
Buckets / slots.
depends what you mean, if you have chained hashing the thing containing the collisions is typically called a bucket
though there are hash tables that work differently
right
e.g. python's hash table is a flat hash table, where you essentially just have an array
collisions are dealt with differently
oohh i am thinking about chaining using linked lists to avoid collision
i always forget about inbuilt libraries 🤦♂️
Made https://github.com/Agent-Hellboy/Visualise to visualise backtracking/recursion problem
!voice-verify
is there any function that returns all possible combinations of elements within input lists
ex: combinations([1,2,3], [4,5,6])
[[1,4], [1,5] ... [3,6]
itertools.product
thanks
file = open("log.txt","a")
from pynput.keyboard import Key,Listener
log = "sadsads"
def on_press(key):
print("{0}pressed.")
file.write(key)
def on_release(key):
if Key.esc:
print(1)
exit(1)
with Listener(on_press=on_press,on_release=on_release) as listener:
listener.join()
```if i do that it gives an error so i gotta make it
```import pynput
file = open("log.txt","a")
from pynput.keyboard import Key,Listener
log = "sadsads"
def on_press(key):
print("{0}basıldı.")
file.write(key)
def on_release(key):
if Key.esc:
print(1)
exit(1)
with Listener(on_press=on_press,on_release=on_release) as listener:
listener.join()
``` but when i change my code like that my file just dissappers
is this sufficient to prove T(n) = T(n-1)+n is O(n^2)?
T(n) <= cn^2 plus constants and lower order terms
basically yeah, you could pick c = 1 and you have
= cn² - (n + 1) <= cn²
(any c >= 1/2 would work, actually)
well given that my expression finished as:
cn² - (2n + 1)c + n
choose c = 1
= n² - (n + 1) <= n²
I picked a particular value for c
1*(2n + 1) =/= (n + 1)?
-(2n + 1) + n = -(n + 1)
ok ok
I pick a c large enough so that I can get rid of the +n
so I'm left with n² - (something positive)
which is clearly <= n²
right and this is where i need to keep in mind that it cannot be a negative number as asymptotics only deal with positive functions
and furthermore one cannot have negatively sized input
i've been going through my algebra book and woof.. i was really bad
with c=1/2
= n²/2 - (n + 1/2) + n = n²/2 - 1/2 <= n²/2
n²/2 is pretty darn close to the actual answer
so looks like you used "dividing by number is multiplying by its reciprocal" to go in reverse from ((1/2)n^2) -> (n^2)/2
one small tip, I would put <= when I do a step that actually makes something bigger, but = when I just rearrange/simplify
it makes it a lot simpler to read since you know what to expect
right right ok
I guess I'm used enough to it that I just consider those to be obviously the same 
yeah i mean i should too, its obvious multiplying something by 0.5 is the same as dividing in half. i'm just in a weird place math wise
also i noticed i started the same types of substitution problems like 50 times looking through my notebooks so either i'm being impacted by stress or got covid brain or literally getting dementia of some kind. never in a million years would i have known i tried it so much
asymptotics can totally be applied to negative functions, but as you say input size is >=0 and also we are counting operations so it's clearly >=0
i think in CLRS they make a big stink about nonnegative functions
like eg they're assuming all the functions they work with to be non negative
i need to practice problems that have like fractions / logs / exponents / functions alltogether
it's a sensible thing to assume
I guess asymptotics get a bit weird if you allow both negative and positive things
for stuff like time complexity everything is >=0 for sure though
hm ok i got some feedback apparently i need to work it until its in the exact form
how would i get from here to the exact form? Just pick a c?
can we use c=1/2 and then go from n²/2 - 1/2 <= n²/2 = ((2*(n²/2)) - 2(1/2) = n²/2) = n²-1 <= n²??
wdym exact form?
what's the actual task asking for?
Idk that’s the only feedback I got. Most of these are from CLRS and they simply say “show that T(n) = expression is O(n^2)”
The question I posed was “is this enough to prove it’s O(n^2)” and the answer was no because it’s not in the exact form
you're done here if you want to show that c=1/2 works
n²/2 - 1/2 <= n²/2
what is the exact phrasing of the question?
do you have a page I can look at?
Let me see
pg. 87
exercise 4.3-1
"show that the solution of T(n) = T(n-1)+n is O(n^2)"
i think we got there by taking c=1/2 and multiplying both sides by two to get (c(n^2)) - 1 <= (c(n^2))
if you pick a specific c you shouldn't have c left in your expression
to satisfy the definition of big O you would technically need to find a c and a n0
what c to pick doesn't really matter as long as it's big enough
same for n0
Right we got it in the proper format with c=1/2 and then multiplying both sides by 2 makes the RHS in the proper form, exactly n^2 right?
T(n)
= T(n-1) + n
<= c(n-1)² + n
= ...
= cn² - (2n+1)c + n
```let's pick c=1, n0=0
= n² - (n + 1)
<= n²
Ok tysm
it shows the same constants work for T(n-1) and T(n), so in the end this shows the big O bound we want
Looking for help to understand below code:
class TreeNode:
def init(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
queue = collections.deque([root])
How will deque convert 'root' element to queue?
it doesn't
it's makes a deque from the list that contains root
The code has deque([root]). Will [root] converts the tree to a list?
([]) -> What does this denotes?
Does [..] makes any variable to a list?
as said, it's not a conversion, e.g. [1, 2, 3] doesn't convert the integers, it just creates a list containing the integers 1, 2 and 3
a list is just a sequence of things
course they could be variables (or any expressions) py x = 1 y = 2 lst = [x, y, 3]
Are there any types forbidden from lists? Like you can make a list of dictionaries right
no, yes
why does this think that 4 is prime?
prime_list = []
def is_prime(num):
prime = True
for i in range(int(num/2)):
if i > 1:
if num % i == 0:
prime = False
return prime
for i in range(1,99):
if is_prime(i):
prime_list.append(i)
print(prime_list)
- you don’t have to go to 1/2 of the input number; you only have to check up to the square root of the input number.
- range() with one argument creates an iterable (0 inclusive, arg exclusive). So, for the number 4, your function would have checked for divisibility by 0 and 1, except you also added the condition
i>1, so it actually doesn’t check for any divisors. - By the way, you can return a value from the function as soon as a non-trivial divisor is detected. Instead of having a variable
primeto keep track of the state, simply replaceprime = Falsewithreturn Falseandreturn primewithreturn True.
Algorithmic prime generation is actually pretty interesting. Your approach works, but there are also methods like the Sieve of Eratosthenes, etc. Do further research if you are interested 😉
gonna go look into that right now. thanks!
thats pretty neat-o its like backwards from what I was doing.
trying my hand at algorythmizing the sieve now
such a different thought process to wrap my mind around. I come up with an idea that I think works, then it doesn't work at all 🙂
then i keep playing with it and eventually it works and i have no idea why
i am pretty sure this works up to a point then the index goes out of range
nums = [i for i in range(1,101)]
numbs = [i for i in range(1,101)]
numbz = [i for i in range(1,101)]
for x in nums:
for y in numbs:
if x % y == 0:
numbz[y] = "X"
whoops
Hey everybody! I'm new to python and have an idea that I'm trying to implement. I've broken several calculations into different modules to run various situations. The problem I'm facing is that I don't quite know how to save those values to a data collector module which will be used to store the majority of re useable data. Importing every file and running instances of the classes in other modules seems... messy.
Eventually I'd like to export the data handler data to an interface and keeping it one spot seemed like the best way.
Secondly - I have a large amount of tables that I need to sort through based on a few conditions. In excel I could do index matches/vlookups and a whole bunch of stuff. How do I do that in python without programming hundreds of if else functions (which may or may not be how a couple tables work now)
Sorry this isn't necessarily the normal type of post here, it just seems that the calculator I'm building will end up having a lot more to deal with here than anywhere else.
holy smokes
@brazen eagle sounds like a very ambitious project!
@brazen eagle what I would do in your situation, is try to break the problems up into small pieces. Instead of working on a module to store data, just keep it in the same file and keep it as an abbreviated list of just a part of your data set. you can surgically manipulate it from there. That way, you avoid all that pesky OOP classes and modules and blah blah blah until you know you are able to complete the computations you need to. Don't try to rush it, take your time and solve one problem at a time.
also, @brazen eagle i like your name.
Instead of importing every module in a single file, let each module accept a DataCollector class as a parameter
You could look into pandas when working with spreadsheets in Python.
idk where should i ask this
will this code be slower or is there any good way than this?
any(list(map(lambda x: x if re.search("Ganyu", x) else None, banner)))
Basically what i wanna do is if the user input is exist on banner list
to start with, there should never be a reason to do any(list(...)) instead of just any(...)
and also, why not any(re.search("Ganyu", x) for x in banner)?
idk if i can do that
aight cool
tqtq
You need Pandas 🐼… I started with a strong background in excel. Basically, a Pandas dataframe is like a spreadsheet, and instead of index matches and vlookups, you can do joins and merging on multiple tables or dataframes.
import abc
from dataclasses import dataclass
class Player(abc.ABC):
@abc.abstractproperty
def name(self) -> str:
""" """
@dataclass(frozen=True)
class Human(Player):
name: str
Human("me")
Creating the class instance fails. Is there a simple fix?
!e
import abc
from dataclasses import dataclass
class Player(abc.ABC):
@abc.abstractproperty
def name(self) -> str:
""" """
@dataclass(frozen=True)
class Human(Player):
name: str
Human("me")
@jolly mortar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 13, in <module>
003 | TypeError: Can't instantiate abstract class Human with abstract method name
!e Probably what you want instead of an ABC is a Protocol, but if you really want to use an abstract property on your frozen dataclass, you'll have to get creative:
import abc
from dataclasses import dataclass
class Player(abc.ABC):
@abc.abstractproperty
def name(self) -> str:
""" """
@dataclass(frozen=True)
class Human(Player):
name: str
def __init__(self, name):
object.__setattr__(self, "_name", name)
@property
def name(self):
return self._name
print(Human("me"))
@stable pecan :white_check_mark: Your 3.11 eval job has completed with return code 0.
Human(name='me')
@fervent canyon Thank you for responding! It is a just a wee bit ambitious. So the calculator is a structural calculator, which will when done will encompass everything from a bit of web scraping for initial data, to analysis based on input for anything I’d need in a couple different materials, and report printing! Luckily, structural code as it is, is very module friendly, so each section is its own thing with a couple return values that are used in other parts. The couple modules I have put together run and get me good numbers! One problem at a time is great advice, this will be a long time in the making.
alg i'm not understanding what happens to these final terms. if i pick c=1 and n0 = 0, then n=1 (given by for all n greater than n0 definition), and we get n² - 2, and claim that since we end with n²-2 then T(n) <= O(n²). the same thing happens here: (queued to proper time): https://youtu.be/LC96q_6r3BQ?t=546 where he finishes with the proper notation except a single -(c-1)n term
i guess thats the "exact form" they want? it certainly makes sense that n²-2<=n²
I'm not entirely convinced about the exact form part since the question asks about O(n²), it could be to find c and n0 that makes things work
There is an actual exact form
T(n) = n (n+1)/2
but that's not really what the question asks about
right. i'm really frustrated w my professors rn. they teach online school and do f***all, while we pay huge money
no wonder people turn to youtube
the answers i get via email are like "no, that's not correct"
super helpful 🙄
we started with T(n-1) <= c (n-1)² and then we derive that T(n) <= c n² based on that
what's the exact thing they said?
so based on what i shared before (my handwritten expression), i sent and said is this sufficient to prove that the recursive function shown is O(n^2). their response: "no because it is not the exact form"
i also got:
"start by choosing a c and getting rid of lower order term"
which isn't helpful again, bc they're not specifying begin by choosing a c or select a c from the very beginning...
don't do online school
emailed my advisor 2 days ago, no response
how do you practice "the squeaky wheel gets the grease" not in person
that's what I did
picking a large enough c made it so we can get rid of the lower order term
If you want you can use induction to show that it works for c >= c0.
You kind of have to guess what the grader wants here which is pretty annoying. How formal?
this is enough I think
T(n)
= T(n-1) + n
<= c(n-1)² + n
= ...
= cn² - (2n+1)c + n
```let's pick c=1, n0=0
= n² - (n + 1)
<= n²
I would think that is enough too.
in short I mean to say every n >= 0 works fine
though you can pick a higher n0 and it doesn't really matter, the existence of such an n0 is the important part
c >= 1, n >= 0, but they seem to want a specific c, so just choose 1.
is there a final step here where you add (n+1) to the LHS* and claim T(n) + (n+1) <= n²? and if not how to i read those final two lines
no, we have shown that if T(n-1) <= c (n-1)² then T(n) <= c n², for some appropriate c (and n0, though that turned out to be very boring in this case)
alternatively
T(n)
= T(n-1) + n
<= c(n-1)² + n {use assumed form of T(n-1)}
= ...
= cn² - (2n+1)c + n
<= cn² {if c >= 1/2 and n >= 0}
though finding the exact bounds for c and n seems overkill, finding some valid values is enough
its the final two steps i don't get
is it simply that n² - (some 2n constant) + n < n²?
i don't see how the final two lines there justify what we are trying to show
.latex For $c = \frac{1}{2}$, $$cn^{2}-(2n+1)c+n = \frac{1}{2}n^{2}-1$$
oh i think i see. i plugged in c=1/2 and n=1, and solved to get 0<=1
.latex $$<=\frac{1}{2}n^{2}<=n^{2}$$. For n >= 0.
\geq strikes again
i get (1/2)n² - 5/2 <= (1/2)n²)
@ruby quail
How would a data collector class work so i wouldn’t have to write individual pass ins for every variable?
-1/2 yeah.
huh? and where did that - 1 come from in your RHS
Error.
ok
is this correct?
or do you see how i got that
.latex For $c = \frac{1}{2}$, $$cn^{2}-(2n+1)c+n = \frac{1}{2}n^{2}-\frac{1}{2}$$
why are you subtracting something on the far right
you have two c's there
where is cn^2 - c from
.latex For $c = \frac{1}{2}$, $$cn^{2}-(2n+1)c+n = \frac{1}{2}-\frac{1}{2}*2n+\frac{1}{2}+n = \frac{1}{2}n^{2}-\frac{1}{2}$$
1/2 n, not 1/2
.latex For $c = \frac{1}{2}$, $$cn^{2}-(2n+1)c+n = \frac{1}{2}n-\frac{1}{2}\cdot2n+\frac{1}{2}+n = \frac{1}{2}n^{2}-\frac{1}{2}$$
btw you can just do \frac12 instead of \frac{1}{2}
Yeah I prefer {}, Also n^2 not n. Take 3:
.latex For $c = \frac{1}{2}$, $$cn^{2}-(2n+1)c+n = \frac{1}{2}n^{2}-\frac{1}{2}\cdot2n+\frac{1}{2}+n = \frac{1}{2}n^{2}-\frac{1}{2}$$
ok ok im with you idk how i got 5/2
.latex For $c = \frac{1}{2}$, $$cn^{2}-(2n+1)c+n = \frac{1}{2}n^{2}-\frac{1}{2}\cdot2n-\frac{1}{2}+n = \frac{1}{2}n^{2}-\frac{1}{2}$$
so it basically comes down to expression - constant k <= expression
expression - foo <= expression
right
As long as foo >= 0
ok well i'm glad we got there following the long route 🙂
this is what i need to comprehend
i'm also reading my discrete math book
set theory seems pretty straightforward
makes me want to know latex so i can write all the cool s*** i'm learning
Hard to say without knowing the data
it's honestly not that hard, just takes like 15 mins to get the basics down
.latex ${A}}$
.latex ${x \mid x \text{ is positive and even}}$
.latex $${2x | x \in \mathbb N }$$
latex is pretty easy, at least the math part of it. The other typesetting for documents is still black magic for me
yeah the main problem is understanding what to write heh
.latex ${A \cap B \cap C^{c}}$
A intersect B intersect C's complement
I recommend an interactive editor that lets you see the latex in real-time. So you can fix mistakes and all that. Much faster to try things out.
(Which I should have been using before rather than typing it in discord)
ok
right i need to graduate from MS word equations
what's this?
Apostrophe (formerly known as UberWriter) is an open-source, minimalist markdown text editor, that Wolf Vollprecht develops. Apostrophe supports formatting with Markdown. It was originally created for the Ubuntu App Showdown, and has since received recognition as one of the Top 10 Ubuntu Apps of 2012.
neat, i've just been using overleaf
Too laggy for me.
yeah, since it's for entire documents
For shared documents I sometimes use overleaf. But for my own stuff I prefer markdown for everything except latex for math.
we don't want to show <= n² if we pick c = 1/2
we want to show <= n²/2
@opal oriole
if we show n² when picking c=1/2 you have an extra factor 2 which will create an exponential
Yeah. @fiery cosmos
The goal is cn^2, and we picked 1/2, so (n^2)/2 is the end.
haven't gotten any work done today and trying to understand set theory
@ruby quail would you mind if I DM’d you? Might be easier to show that way. I have a few single value returns, and now one in a tuple! Eventually it will have strings that compare to a list for auto sizing of various components.
I'm not really sure what else they could mean by wanting the "exact form".
<= n^2 breaks things as @haughty mountain wrote.
we are doing induction, we're assuming T(k) <= c k², we then show that if T(n-1) <= c(n-1)² then it follows that T(n) <= cn²
It's important that the c is the same
if I pick c=1/2 and show that if T(n-1) <= (n-1)²/2 then it follows that T(n) <= n², then I haven't proven the thing we needed to prove
hang on
when you say T(n-1), do you mean the expression on the LHS and plugging in n-1 for n? or do you mean the T(n-1) on the RHS, eg, the form of the expression we are evaluating
which is T(n-1) + n
LHS
our assumed formula gives us an expression for T(n-1)
we want to verify that we get a matching expression for T(n)
i think doing this via text is adding more confusion
it's the point of the induction, "is this still true when we take a step up"
ok, let's step through the logic, we have this recurrence we want to show is O(n²)
(I'll use k instead of n here for a small bit to not have multiple n)
we assume T(k) = c k²
huh? here k is a variable
but we don't know if this is true yet, we want to verify that it's consistent with the recurrence
what I mean by "consistent" here is that if the inequality is true at some step, after taking another step it's still true
i.e. if T(n-1) <= c(n-1)² holds, then we can prove that T(n) <= cn² also holds
ok pause 1 sec
i think the RHS being equal to T(n-1) + other stuff is confusing me. bc right off the bat i can't see if you've decremented the LHS from n to n-1 and even if you did, if the RHS is just in the given form or its been generalized to ck^2 and then n-1 was plugged in
can you see why its confusing
bc you're manipulating it to be (n-1), but thats already the given form
in other words, if you change the LHS to be T(n-1) instead of T(n), then wouldn't the RHS necessarily become T(n-2)?
it would, but it's not relevant here
T(n-1) = T(n-2) + n-1
but we only care about T(n-1) in the context of T(n) = T(n-1) + n
and we only care about replacing that recursive T(n-1) with a nicer expression, our assumed formula
so we are or are not going to change the T(n) to T(n-1) on the LHS
set equal to. bc i thought your whole thing was assume its true for the n-1 form, then show its true for n form, meaning we'd be analyzing T(n-1) = kn^2??
and i don
don't mean the T(n-1) on the RHS here
we are analyzing T(n), but to do that analysis we want to make use of the bound T(n-1) <= c (n-1)²
ok so you are only talking about the expression following the equals sign
not the T(n)
do you see how it being in that form leads to so much confusion
when we're typically working with some n - 1 form
I mean, they are the same thing, they are equal 