#algos-and-data-structs
1 messages ยท Page 101 of 1
k, and what about the indentation error at "else:"? how would i fix that?
function twoDivides(x){
var count = 0;
while (parseInt(x) > 1) {
x = x / 2;
count = count + 1;
}
return count;
}
how do you do this in python?
what is parseInt?
parses a string in to an int? idk
im new to python tbh
can't you do that w casting?
cast a string to an int?
depends on the language
that's not java
js
I'm not entirely sure why you're getting that error
replace your indentation with spcaes
function twoDivides(x){
var count = 0;
while (parseInt(x) > 1) {
x = x / 2;
count = count + 1;
}
return count;
}
so how does putting in 2 return 1 here?
while 2 >1
also, thx. i tried the smallest = biggest = input() and it worked
oh
am dumb
sorry
seems like i may have burnt out
so is it O(log(n) bc it's getting the input gets halved?
you're unsure what log n means?
i kinda forgot from high school math
guess i'll watch some videos
What are Logarithms or logs? How are they related to Exponents? Watch this video to know the answers.
To learn more about Logarithms, enrol in our full course now: https://bit.ly/logarithms_DM
In this video, we will learn:
0:00 Exponents
0:26 What are Logs?
1:13 Logarithms (Example)
To watch more videos related to Logarithm, click here: htt...
ok so i watched this and now i kinda remember them
hang on i'm watching O(log(n) videos rn
if you get -inf that means 1-sig was 0
yes
sig has to be smaller than 1 and larger than 0
it can be 0 though
but it can never be 1
whats your sigmoid function
def sigmoid(z):
result = 1 / (1 + np.exp(-z))
return result
binary is base 2
oh ok
it's just easier for computers to work with than base10
ok that makes sense
you know
I may be ready for data structures and algos now
but using someone's github notes bc they already exist and are nice and short
^^^
I can't believe I didn't think of that sooner
?
looking at someone's notes on github
ah
yeah these people who just casually read 1k page long textbooks amaze me
I dont think anybody does that
uh
Doubt he would agree tbh
i was kidding
some people learn differently
like I saw this 200 page long book called algorithms unlocked
and even that was just too much
i don't like fluff in books
^
Reading is fine but are you applying what youre reading
well i don't see how I would be explaining the math behind big O to an interviewer any time soon
personally, i understand the math alot more when its in code, like equations confuse the hell out of me, but seeing like the python implementation im like "ooooooooooooooooooo"
they're more interested in seeing you say the time complexity of an algorithm by looking at it
guys I actually got another interview
but now i have to do two leetcode questions in the span of 45 minutes
F in the chat for me ig
@gusty grove this good
function twoDivides(x){
var count = 0;
while (parseInt(x) > 1) {
x = x / 2;
count = count + 1;
}
return count;
}
I know I've sent this code before
but can someone please explain why this is O(log(n)?
I watched videos on log and I watched videos on O(log(n)
Free 5-Day Mini-Course: https://backtobackswe.com
Try Our Full Platform: https://backtobackswe.com/pricing
๐น Intuitive Video Explanations
๐ Run Code As You Learn
๐พ Save Progress
โNew Unseen Questions
๐ Get All Solutions
Subscribe To Live Tech Offers: https://offerfeed.io
Join Our Coaching Service: https://backtobackswe.com/coaching
Lo...
this one specifically
but I still don't get it
well if you put in 2
it returns 1
yeah part of it is dividing
while 2 is bigger than 1 so you enter the while loop
then you do 2/2 = 1
and count is 1
uhhhhhhh
no?
count is 0 which is an integer
and then it becomes 1
what does parseInt even do?
turn a string into an integer?
i looked at the doc
ok
so then how would you be returning a string here
my plan????
this isn't "my function"
this is from this github repo trying to teach big O
I didn't ask that
I asked why is it O(log(n)
not for you to "fix" the function
idk why you're getting a headache
but why is it O(log(n) other than just saying it's bc there's a while loop?
this is #algos-and-data-structs
What it does is divide the number by 2 every step
Its like binary search
Hence log(n)
when he says "so _____ total" is he referring to operations?
and when you input 8 it returns 3
8 divided by 2 isn't 3
maybe it's bc 2^3 is. 8
ohhhhhh
maybe that's why
and 2^4 is 16
and so on and so forth
just think of the number 2 when you're doing your input v output
bc it's log base 2
pattern recognition
is that what you guys were trying to say???
I was just thinking that the number of steps depends on the division operation and that binary search is literally just like that
So it should have the same O
oh I don't really know binary search yet
Ah ok fair then
I was focusing on learning big O first
but I think I may have actually figured it out
oh look
a for loop inside a for loop that isn't O(n^2)
how interesting
I don't actually know how to put this into python
i get why there's an O(n) there
but why is O(log(n)?
is it bc it's getting halved?
yes
understood
this may be stupid but
nlogn(3)
[3, 1, 3, 1, 3, 1]
how does nlogn(3) return that? I see it's "pushed" to a list
but if 3/2 how is it still 3??
- big O only really makes sense for large inputs
- 3 * โlog_2(3) is indeed 6
don't use big O to predict how long something will take
it doesn't do that
at all
I know it's not for how long something takes
nlogn(3)
Starts the inner loop with j = 3
It appends that
Then j = 3//2 which is 1 and then appends that too
And then the loop terminates and starts over again
but it's not j = 3//2 it's j =3/2
consider an algo like
def weird(N):
arr = []
for k in range(N):
arr.append(k)
n = 0
while n * n < N:
arr.append(n)
n += 1
this is O(n)
Its parseInt(3/2) which is equivalent to 3//2
but the actual output size will not be exactly linear to N
oh my bad i'm not familiar w JS stuff
what is N supposed to be here?
yes
big O tells you the growth, so I can guess that running weird with 1000 will about twice as fast as running it with 2000
but it just a guess
"Big O is short for Big O Notiation.
Big O is how programmers talk about scalability of algorithms.
An algorithm's Big O Notation is determined by how long the algorithm takes to return output in the worst case scenario.
The math term for the worst case scenario is "upper bound"."
this is this github repo's definition of big O
it's wrong btw
but the sad thing is that this is the understanding of most people in the tech field
it's about 7/8ths ok
the worst case scenario is right
He got the name right
big O does indeed mean upper bound on time
not necessarily on time, but yeah
and honestly, I wouldn't really agree with that
that algo above will always take longer than just a linear function would predict
it means that the algo will grow linearily for large enough inputs
can't y'all just standardize????
because it is used in casual conversation and people try to simplify the horrible math version to be more comprehensible
but then people who simplify it are completely wrong
and inevitably end up introducing wrong things
sigh
i'm sure most textbooks will have close to the exact same definition when they are being rigorous.
the issue is when you try to simplify it
since mathematicians aren't horrible because they want to be seen as smart, but because it needs to be precise and well defined
well unfortunately my reading comprehension skills are not good enough to understand them being well defined and precise
it takes some balls to admit that at least
i'll work on it dw
yeah, that is fine. Its just an indication of how things grow on very large inputs
also
if big O is used for the worst case scenario
what notation is used for the best case scenario?
little o
eh?
actually, that may be something else, never mind me
"An algorithm's Big O Notation is determined by how long the algorithm takes to return output in the worst case scenario."
Its omega
oh ok
so I need to learn that too ig
can I start algos and data structures w just big O?
ฮฉ(f(n))
yes
good stuff
Learning big o without any context of the data structures involved sounds boring tbh
better start learning data structures then
at least I'm making progress
what is fibonacci
// assume number is an integer
function fib(number) {
if (number <= 1) return number;
return fib(number - 2) + fib(number - 1);
}
does anyone have the explanation for USACO Feb?
this is how this guide introduces fibonacci
Fib numbers? here u go
https://cp-algorithms.com/algebra/fibonacci-numbers.html
it sounds Italian
It is
crossing out italian is racist man
oof ya got me
๐ค
His name was Lenny from Pisa in italy somewhere
leonardo of pisa
didn't they write a whole book on this shit or something
anyways I digress
why does it matter that I'm not learning data structures in conjunction w big O
is it just customary?
As in, they exist independent of other concepts or structures
Its easier to understand something by doing, implementing the algorithm will help you more than just studying the theory
Yep
Actually, big-oh could be used for best-case, average-case, or worst-case performance.
oh boy
then what the hell is this github repo saying
guess that's why you don't just randomly read github repos and trust them
but I don't like reading gigantic textbooks too
what do I do w my life
I can try my best to summarise it here with a sufficient level of rigour, if you like? ๐
sure go ahead
just make sure to ping me bc i'm gonna take a shower
Alright, I'll write it out here then ping you ๐
So, we want to characterise the performance of an algorithm. We could just time how long it takes to run for a specific problem, but there are a couple of problems with this:
- An algorithm is designed to solve a set of problems not a single problem. (We don't just want an algorithm that sorts one particular list of numbers, we want it to be able to sort any list of numbers.)
- The actual time it takes to complete will depend on the properties of the computer that it runs on.
So instead we characterise the performance by looking at the relationship between the size of the input and the run-time.
Imagine we have a mathematical function T(n) that tells us how many CPU instructions it takes to sort a list of n numbers (with our sorting algorithm).
But actually, to define T we need to decide if we are dealing with the worst-case, best-case, or average-case list of length n.
[1, 1, 1], [1, 2, 3], and [3, 2, 1] are all length-3 lists of numbers, but they are different and may take a different number of CPU instructions to sort. Some sorting algorithms are faster if the list is already sorted (bubble-sort), and some are slower in that case (quicksort).
(in particular, Timsort - which Python uses, and which was made for Python, is baaasically mergesort but better with data that's already partially sorted)
i'm back
So if T(n) is worst-case run-time, it's telling us what is the maximum number of CPU instructions it would take to sort a list of length n.
Note I haven't mentioned big-oh yet.
noted
But actually exactly figuring out a mathematical formula for T is kind-of difficult.
The actual number of instructions is going to depend on things like which programming language and CPU architecture the algorithm is implemented in.
Also, T might be complicated for small values of n.
So we simplify it by:
- removing any constant factor in the formula, and
- only looking at very large values of
n.
That's where big-oh comes in.
A rigorous definition of big-oh would be something like this:
The function
fis a member of the setO(g)(wheregis also a function) if and only if there exist constants,n0andk, such that, for alln > n0,f(x) < k g(x)
That's probably a little abstract unless you've done some mathematics before at university.
In everyday language it means that you can multiply the function g by a constant such that it eventually overtakes the function f, and f never catches up.
If you imagine that f(t) and k * g(t) represent the positions of two cars along a race-track at time t.
can you recommend a book that's not a thousand pages long?
Erm, you might want to check out Khan Academy's algorithms course, not sure if I've already recommended it.
Yes ๐
It's kind-of hidden on their website.
They're kind of the same subject tbh.
The course has input from one of the authors of the CLRS textbook I believe.
It's just core concepts.
The algorithms are just to use as examples.
In practice, it's not all that useful to know 10 different sorting algorithms, but they provide nice examples for teaching the ideas.
i tried to read algorithms unlocked and CLRS
but they both made my head spin
and algorithms unlocked is just 200 something pages
khan academy's course is in js
That's true. The exercises are in JS, although they're optional.
if you wanna learn the exercises are not optional
but aren't algorithms language agnostic or something
so you should be able to learn them in anything
You might also want to check out this course by Udacity. The instructor is a cool guy ๐ https://www.udacity.com/course/intro-to-algorithms--cs215
This class will give you an introduction to the design and analysis of algorithms, enabling you to analyze networks and discover how individuals are connected.
hey as long as it's not Siraj Rival I'm ok
They kind of frame the whole course around social networks. The course is a few years old now.
I mean does it matter? Have algorithms changed much in the last couple years?
Shouldn't matter, although it may use Python 2 ๐
It's also pretty heavy on graph algorithms.
is that supposed to scare me or inform me
(Which are very useful to know!)
graph theory is awesome
Inform ๐
ofc one of the guys wrote CLRS wrote algorithms unlocked
clrs was written by 4 guys lol
"one of the guys"
ikr
before it's just "the lightly shaded are red, and the darkly shaded are black"
Apparently they use MacDraw on an old macintosh to make the illustrations.
I don't even know how to read CLRS
i think it's in english
there's barely any bolded text
they use italics in some spots
I'm not sure why I know that ๐
I'm not reading page long paragphs
I mean look it up
there's reddit posts saying CLRS is hard to read
I'm not the only one
well, i'm not denying that lol
The style is fairly mathematical. There are a lot of proofs.
You have to kind of get used to it.
I don't care about maths
computer science is all about that
I just don't like their writing style
it's very rigorous
But the explanations are very clear.
even in their "simpler, antipasta" book or whatnot it's still gigantic paragraphs
Algorithms Unlocked
it elucidates even the most minute details
how wonderful
quite
I looked a bit closer at that Udacity course. It shouldn't really make much difference that it uses python 2, aside from the occasional print x.
And the coding is all done online, so you don't need to install python 2 on your machine ๐
I'm actually trying something different
I'm going through the MIT OCW notes bc they're short and concise and then doing problems associated w the algorithms they're talking about
let's see if that works
you mightt as well watch the lectures then
no
ok ยฏ_(ใ)_/ยฏ
perhaps
so I have a question
there is no such thing as a "peak-finding algorithm" right?
That would probably be an "optimisation" algorithm.
why are they saying to look at the left half?
they said the straightforward algorithm is to look left to right
I actually watched the entire lecture and it lost me here too
y'all ever heard of Grokking algorithms???
Nope sorry. Looks interesting though.
Nope sorry in response to why they're asking to look at the left half or Grokking algorithms?
Sorry, Grokking algorithms.
oh ok
yeah I've never seen a book w algorithms focus on visual stuff as much as this one
have I mentioned how it's only 200 pages?
It has nice illustrations ๐
So it looks like the idea of that "peak-finding" algorithm is to keep splitting the list in half, each time taking the half that appears to be uphill from the midpoint.
damn couldn't they just say that
what is n/2 --- 1?
damn you'd think MIT would actually teach this well
n/2 - 1 is an index
I mean
my understanding of binary search
is you look at the middle
and then you compare it to the left and the right
usually you're looking for a specific key, but in this case you're just looking for a peak
that's probably just a typo
ok
Yeah, basically you want to determine whether the index you are currently at (the midpoint) is a valley, peak, or slope. If it's a peak, you've found a peak. If it's a slope, you know there must be a peak somewhere in the uphill direction. If it's a valley, the same thing, but both directions are uphill so you can choose one arbitrarily. At each step you narrow down the range of indices to search in by cutting it in half.
slope???? valley????
v
peak: ..., 1, 2, 1, ...
valley: ..., 2, 1, 2, ...
slope: ..., 0, 1, 2, ...
^
These aren't technical terms, just the best words I could think of to describe the three possibilities.
@old rover ๐๐ป
hey
O(2^n)
why
I'm actually not sure I just read somewhere that recursive sequences tend to be O(2^n)
not a good answer I know
// assume number is an integer
function fib(number) {
if (number <= 1) return number;
return fib(number - 2) + fib(number - 1);
}
the recurrent equation for T(n) here is T(n) = T(n-1) + T(n-2), and that happens to be precisely the recurrent equation for fibonacci numbers themselves. So you get the famous fact that the complexity of recursively calculating fib(n) is... fib(n) ๐
And fib(n) for big n is approximately exponential - it's something like phi^n where phi is the golden ratio.
so 2^n isn't that incorrect of an answer
it also doesn't help that I have seen recursion used like twice
that's my own fault tho
def fib(n):
"""You know I had to do it to them"""
return n if n <= 1 else (fib(n - 2) + fib(n - 1))
ok so let's say we put in 5
do you know what T(n) means?
it's a way of saying what the whole runtime is for a given algorithm
whereas O(g(n)) is a set of algorithms that scale according to g(n)
or something like that
Basically, you know how the O-notation is by itself about functions? Well, when we say the algorithm is O(something), that means the algorithm's T(n) is O(something).
so it's the precise-ish number of operations or something like that.
so T(n) is actually what people are saying when they're like O(N) is the runtime of an algorithm
common misconception
So when you have a recursive function, T(n) appears in T(n) = ...
If you have a T(n) = ... equation where there's no recursion, you can determine the big-O just by looking at it
do you know how to do that?
yes
explain
Idk what it looks like without recursion
it might be something like T(n) = 5 + n(n + 72) + sqrt(n)
do you know what the big-O of this would be?
O(1) constant time
no
F
T(n) can only belong to O(1) if n isn't actually used in the calculation of the runtime.
I see two fellow staffers furiously typing
what have I done wrong?
not strictly speaking true - for example, T(n) = log(n)/n is O(1), so is T(n) = 10000 - e^(-n)
I can learn too 
it's O(1) if it's bounded by a constant - it doesn't have to be constant.
I knew the formal definition but I went out on a limb and figured there were no funny cases like this
that might be true
Wat I thought you knew everything
Oh, this is not ot oops
but also log(n) / n is (1/2)(n)(log(n)). so why isn't that O(n)?
wait
I am dumb sorry
idk Stelercus I think you're pretty cool
log(n)/n is O(1) because it just goes to zero with increasing n, whereas 10000 - e^(-n) approaches 10000 from below.
T(n) is like the maximum number of CPU instructions it would take for the algorithm to complete for an input of size n
You could also say the time in seconds of the algorithm, or the number of python bytecode instructions.
The reason we use big-oh notation is to avoid these details.
If T(n) was n or 2n or n + 100000 or even 1000000 n + 100000, it would still be O(n)
Alright, see ya ๐
Hey guys, are we allowed to ask Hackerrank/Leetcode questions here? By that I mean if I am confused as to how to why my code is not working (usually not compiling and I cannot seem to understand why) are we allowed to discuss that here?
@cerulean river yeah sure as long as it has to do w algos/ds
thank you for clarifying this for me.
Any time
how do you stop an iterative quicksort? I get it to sort everything, then it just continues and messes up.
I have to advance several state machines concurrently, and sometimes an event can make a state machine go into 'high priority' state, and in that case it should be advanced instead of a low-priority state machine. State machines can also be added and removed. What would be an asymptotically good way of achieving this?
by 'concurrently' I mean arranging their updates in a round-robin fashion
a priority queue from which every thread takes a state machine to advance
ah, hmm
but
I should be able to add and remove them
and how do you suppose this will work @mint jewel ? how will a state machine change its position in the priority queue when it's triggered to become high-priority?
I think there is a priority queue implementation that allows modifying the element priority.
I found a 15-page C++ paper http://ceur-ws.org/Vol-1525/paper-13.pdf wish me luck...
although in my case I can probably get away with a dict or something like that
but I will have on the order of 1000 state machines
I think heaps are good for this.
yeah, asyncio.PriorityQueue is implemented with heapq
which also makes it a misnomer because it doesn't care about insertion order
Im trying to make algorithms that act as substitutes for the min() and max() function, but this time they are defined functions. Yet again though, I can't get my loop to work and it only iterates through the next number (6) once and stops. This is the (albeit unfinished) max function btw.```py
Tnums = [1,6,200,-12,123,2,65]
def findMax(nums):
biggest = Tnums[0]
x = 0
while x < len(nums):
biggest = Tnums[0]
if biggest < Tnums[1]:
(placeholder)
x = x + 1
return biggest
Tnums = [1,6,200,-12,123,2,65]
print("The largest number is:", findMax(Tnums))
How do I fix the iteration loop here?
what's the time complexity of that algorithm
is that what it should look like?
Tnums = [1,6,200,-12,123,2,65]
def findMax(nums):
biggest = Tnums[0]
x = 0
while x < len(nums):
biggest = Tnums[0]
if biggest < Tnums[1]:
biggest = Tnums[1]
x = x + 1
return biggest
Tnums = [1,6,200,-12,123,2,65]
print("The largest number is:", findMax(Tnums))
Okay, i tried it and it didnt work
wym time complexity?
Im a relatively new python nerd, lul
yeah, i mean im coming to this channel cause i went to a help channel and i wasted 2 hours and got nowhere
lmao
anyways, what is wrong with my algorithm now? it still doesnt work
no errors, just doesnt work as intended
can I ask
why are you making substitutes for the min() and max() function?
are you trying to learn how they work?
its for an assignment, but i only really need help with the loop. I just dont understand why the loop isnt working. I can mostly figure everything else out on my own
is it a high school or college assignment?
Well yeah, why
i dont want the answer to the whole project
I just wanna know what the problem with my loop is, cause i cant think of why it isnt working
It doesnt work because you hardcoded the index in the loop
i think switching out Tnums for nums inside of the function would fix it
Also you keep setting the biggest to the first element
because you are using the test numbers inside of the function
instead of the actual nums that are being taken in for the function
Also that yea, just noticed
Theres a simple way to find a max in a list, you just need a for loop, an if and a variable
So, like this? ```py
Tnums = [1,6,200,-12,123,2,65]
def findMax(nums):
biggest = nums
x = 0
biggest = nums
while x < len(nums):
if biggest < nums:
biggest = nums
x = x + 1
return biggest
Tnums = [1,6,200,-12,123,2,65]
print("The largest number is:", findMax(Tnums))
That wont even run
change it to nums[0]
Tnums = [1,6,200,-12,123,2,65]
def findMax(nums):
biggest = nums
x = 0
biggest = nums[0]
while x < len(nums):
if biggest < nums:
biggest = nums
x = x + 1
return biggest
Tnums = [1,6,200,-12,123,2,65]
print("The largest number is:", findMax(Tnums))
Bruh
not just a single index
hi
change everything to their respective indices
you are basically just switching out nums for Tnums
wait i just realized i have duplicate code
any algo train or problem?
one sec
Tnums = [1,6,200,-12,123,2,65]
def findMax(nums):
x = 0
biggest = nums[0]
while x < len(nums):
if biggest < nums[1]:
biggest = nums[1]
x = x + 1
return biggest
Tnums = [1,6,200,-12,123,2,65]
print("The largest number is:", findMax(Tnums))
``` fixed the duplicate code...?
i think this should work
It doesnt
you're always accessing specific indices
yes
Youre hardcoding the indices
Thats not even the problem
it's a non-issue right now
Its what i was suggested to do
Suggested by who
i originally had is as x < 8 cause the list has a static 8 indexes
Thats not the problem....
or 7 or something
why?
The problem is biggest < nums[1]
the problem is not your bounds, the problem is that you're always comparing the same indices, because you've hardcoded them
Bro stop
he's correct yeah
u should put counter in []
not 1
Like this? ```py
Tnums = [1,6,200,-12,123,2,65]
def findMax(nums):
x = 0
biggest = nums[0]
while x < len(nums):
if biggest < nums[]:
biggest = nums[1]
x = x + 1
return biggest
Tnums = [1,6,200,-12,123,2,65]
print("The largest number is:", findMax(Tnums))
i don't think so
u should make a counter
then use it as index
ohhhh so put the x = x + 1 in the []?
No, also i dont understand why youre not using a for loop
this code works now
please don't give out full solutions
ok
why x+1
i said
a counter
like for loops
X is the counter
that it goes into the index
oh, the "for" thing?
u need x+=1
y
im just asking so i can give the counter variable a clear name
like "index" or "counter"
not just "t"
yes
so i change x = x + 1 to x += 1?
That doesn't matter
The problem is that youre not using the counter when indexing
In the if statement
so, like py Tnums = [1,6,200,-12,123,2,65] def findMax(nums): x = 0 biggest = nums[0] while x < len(nums): if biggest < nums[x+=1]: biggest = nums[1] x = x + 1 return biggest Tnums = [1,6,200,-12,123,2,65] print("The largest number is:", findMax(Tnums))
Cause if so, it gives a syntax error at the counter
no
just
put x in the index
not x+=1
Tnums = [1,6,200,-12,123,2,65]
def findMax(nums):
x = 0
biggest = nums[0]
while x < len(nums):
if biggest < nums[x]:
biggest = nums[1]
x = x + 1
return biggest
Tnums = [1,6,200,-12,123,2,65]
print("The largest number is:", findMax(Tnums)) ```
why did u put 1 in the index
And the other one

bro gimme a break, im a relatively new python user
that's why we say learn algo first
uhhhhh and it works now
Tnums = [1,6,200,-12,123,2,65]
def findMax(nums):
x = 0
biggest = nums[0]
while x < len(nums):
if biggest < nums[x]:
biggest = nums[x]
x = x + 1
return biggest
Tnums = [1,6,200,-12,123,2,65]
print("The largest number is:", findMax(Tnums))
i don't think anyone says that. algorithms are not a beginner topic
hello
i mean, i use sololearn
before coding u have to know
reccommended by my ICS teacher
Learn basic python first before you start implementing builtins
no u definitely dont need to learn algo to code
just solve basic problems on some coding websites
so how do u solve problems?
uh, how would that even be possible. algorithms are coding
This wasnt even an algorithms issue
lol i know adavced algos and DSA, i m just saying u dont need to know them before hand
what????? do you even know what you're talking about?
well python is not very different from pseudo code
I did that on a website thats like a sort of duolingo for coding, called SoloLearn
most algo books teach w psuedocode
cause it was reccomended by my ICS teacher
yes
lol I started a deep disscussion, pog
try hackerrank, its good for beginners
I wouldn't recommend random coding problems
I would recommend projects
that's why you do it in psuedocode
that's what TAs did when they taught me how to code
if u know pseudo code then implementing is just copying it in good handwriting
logic is the main part
learn itertools for your DS/algos problems on leetcode
not that I know it I just heard about it a lot
also please don't stare at a problem for more than 30 minutes if no thoughts come to mind
Unfortunately thats what I usually do and only afterwards do I realize I have easy access to Discord and the lovely helpful people there as well as an ICS teacher with 30+ years of coding experience
oh I only have this server
Theres google too
google is unhelpful for coding cause the problems are usually too specific
I like youtube indian guys who just solve the question no questions asked
allow me to introduce "geekforgeeks", its all in one package for competitive programming
Google is incredibly helpful youre just not using it the right way
u indian?
yep
lol figured
before starting to learn coding, i would suggest to learn google first๐
no one, murmuring to myself
Okay, now Im making a slightly less useless function that iterates through a list and determines if they are even or odd numbers, and outputs them as such. (if the list is [1, 2, 3, 4, 5, 6] the program will output [Odd, even, odd, even, odd, even] ```py
Tnums = [1, 22, 31, 48, 57, 66]
outputlist = []
evenNum = False
oddNum = False
def evenOrOdd(nums):
x = 0
number = nums[0]
while x < len(nums):
y = number % 2
if y == 1:
evenNum = True
#print("helloo")
elif y == 0:
oddNum = True
#print('helo')
x = x + 1
return number
if oddNum:
#print("odd")
elif evenNum:
#print("even")
And it obviously doesnt work
the comments are test placeholders
what am i doing wrong?
idk, i didnt know what to call the variable
number is the iteration
You define number outside the loop and then you dont change it
x = x + 1?
Thats not number
You have to change it every iteration
remind me how id do that again?
so when they say high = len(list) - 1
that's just the length of the list - 1 tho
that's not an actual value in the list?
or is it?
I know if you're using binary search it has to be a sorted array
Its the last element
it is????
uhhhhh i have no idea how to use binary
doesn't len(list) just return the length of a list?
Yes?
so it's the length of the list - 1
yet again, the len(list) thing doesnt matter, it just works
Its the index for the last element lmao
dude
i need hep with the loop and the defining of the even and odd numbers
this is a channel where other people can ask questions
Nothing "just works" theres a reason they do
deal with it lmao
not off topic, wrong word
I'm just trying to understand this stuff
oh mariosis
the next line makes sense
my bad dude
anyways, how do i fix it
You fix it by first understanding how loops work and how indexing works
can he show us what happens with a sample input/output?
item, element, number
yeah I though it was a number based off the code
oooooooh it has exercises
I already like this book
I should probably write the code out
does it really matter that the book is in python 2.7?
probably not
oops
okay thank you i will do that now
yep np
binary search explained in literally one page
what a god
I have another question
Does binary search always have two paramaters?
yes right?
No
pretty much
well yeah, that's thep oint
I feel the power of binary search racing through my veins
Rhe best case is the element youre looking for is right in the middle of the list
so that would be O(N)
No since you start looking at the middle
O(1)?
nah, it's not log n
๐ฆ
You only have to do a couple operations and they dont depend on the size of the array
then what is it?
well, how do you arrive at O(log n)
well, you're going to be a bit more rigorous
Ok so after I guessed I googled the time complexity
does it say O(log(n) bc it's a different implementation of binary search?
probably
so then why is it not O(log(n)?
well, since you guessed...
You guessed so no lol
ok but why is it actually O(log(n)
that's why just guessing is not the right way to go about it
why do you think it's log n
bc at each stage of the while loop you divide the list in half?
why does that make it log n
bc it's log base 2
what's log base 2
isn't base 2 normally used in CS
sure, but what's log base 2
it's the power to which 2 should be raised to get the value of n
that's not what i meant
what in binary search is log base 2, and why does that make it O(log n)
ok, the book says it
that's like saying answering the question "why is this true", with "because it is"
lmAO my next assignment is a PALINDROME CHECKER
i have a to code a program that can check if a word is the same when its letters are reversed
the amount of times you cut the list in half
is the exponent
that's why it's O(log(N)?
no that's wrong
this is why I shouldn't just watch random youtube videos from people who don't know shit
๐ด Subscribe for more algorithm videos - https://www.youtube.com/channel/UCpTo8a_5OeZkR9tEcwSBbAA?sub_confirmation=1
๐ด Support me on Patreon - https://www.patreon.com/persistentprogrammer
โ Connect with me...
the amount of times you cut the list in half is the exponent
tries, checks
are guesses iterations?
not necessarily, but since you guess once per iteration, they are equal
it's about 4 billion
oh is that billion
sorry my eyes are dying
yeah that is billion
my bad
why couldn't he use the actual precise number?
I would've spotted the entire relationship like half an hour ago
grrrrr
what
log2(100) isnt 7 either
can't endure CLRS but complains that Grokking is imprecise
ok well
I finally figured it out
good shit
it's not imprecise, it's reasonably accurate
whatever
yeah, but you're missing a step in between
idk what the step is here
I said that the amount of iterations in the while loop it takes to break the list into smaller pieces is the exponent you put over the 2
by checks you mean iterations right
yeah
maybe you should take a break
if you want a rigorous definition, pick a rigorous resource ยฏ_(ใ)_/ยฏ
otherwise, you're going to have to deal with simplified explanations
Ok
Hi anyone know about arc consistency algorithms in constraint satisfaction problems
Yes, hello ๐
What's your question?
Im looking to implement the arc consistency 3 algorithm in sudoku to reduce the domain of each variable and potentially solve the sudoku. Is the best way to start by having two python programs one for the ac3 algorithm and one for the sudoku?
What do you mean by two programs sorry?
Oh right. You could do, although I'm not sure how you would structure the code in that case. I would first focus on how you are going to represent a partially-solved sudoku puzzle.
You need to keep track of the domains of each of the boxes in the sudoku (which digits you haven't ruled out yet for each box).
If the domain of a box is ever empty, that means it is unsolvable.
Oh okay i guess the first thing would probably be to create rows, columns as the variables and populate the variables with domain 1-9 if it is not already filled
Yep I think so.
Oh actually, I think I get what you meant now. You mean should you write an implementation for constraint satisfaction that works for any CSP, then use it to solve sudoku?
Vs writing a constraint satisfaction solver that is specific to sudoku puzzles.
Just a solver that is specific to sudokus
the main issue is coding the constraints and the neighbours and cross checking between them
You could encode the constraints in a general way that could be used by the AC3 algorithm. Or you could write constraint propagation functions that are specific to Sudoku. The latter approach is taken here: https://norvig.com/sudoku.html
Speaking of sudoku, sgtpuzzles (Simon Tatham's Puzzle Collection) seems to be an absolute gem for solving algorithms. It's written in C, but its files have plain English comments on how each solving algorithm works.
Alright thanks ill have a look at those
Arrays are different to linkedlists
yep ik
he says that the elements in a linked list aren't next to each other
like if you wanted the fifth element
you'd have to from the 1st to the 5th
but if you were using an array you could just pull out the 5th one
yeah he mentions it's about memory
Suppose you have a sorted list of 128 names, and youโre searching through it using binary search. Whatโs the maximum number of steps it would take?
is this bc 2^7=128?
bc binary search has a time complexity of O(log(n)?
ok cool
You have a name, and you want to find the personโs phone number in the phone book.
this is also binary search
Pretty much yes
so O(log(n)
good shit
when they say linked lists have slow reads and fast inserts
they mean getting to each element is slow
but putting in new elements is fast
right?
also I watched a video and someone called the "elements" in the array pointers??
Depends, inserting in the middle of the list is O(n) i think
Appending is constant if you have a pointer to the tail
should I take a break and learn pointers rn or can I just continue w DS/algos
bc Grokking hasn't even mentioned pointers yet in the book so far
@old rover do you understand how a linked list works?
working on that rn just asking clarifying questions
Inserting in the middle means you start from the head, traverse the list until you find the index you want to insert at and then change a couple references
I ask because linked lists are made with pointers, so you might already understand pointers
I've never heard of pointers
Well then now's the time haha
yep
why doesn't Grokking even mention them
I guess in trying to be simple and readable he has to let go of some things
which is fine tbh that's why I have Google
A deep understanding of pointers isnt really needed
Theyre things that point to other things
Linked Lists explained (fast) with animated example, and how to write a Linked List program in Python 3, with add, remove, find and size functions example code implementation.
PYTHON LINKED LISTS
โบ Linked Lists Intro https://youtu.be/Bd1L64clh34
โบ Fast Linked Lists Intro https://youtu.be/Ast5sKQXxEU
โบ Doubly Linked Lists https://youtu.be/sDP_p...
so is a pointer just a value that "points" to the next value in memory?
It points to another address in memory, not necessarily the next one in line
yeah the book says it can go all over the place
it doesn't have to be sequential
maybe just do a re read of it
Im not a C buff, someone else might be better at explaining pointers
A linked list is basically
None # empty list
(1, None) # [1]
(1, (2, None)) # [1, 2]
(1, (2, (3, None))) # [1, 2]
the advantage of it is that you can prepend an item in O(1), or take a tail without copying and without mutation
!e
you traverse it like
def iter_list(list_):
while list_ is not None:
item, list_ = list_
yield item
list_ = (1, (2, (3, None)))
for item in iter_list(list_):
print(item)
@austere sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
are you familiar with queues?
uhh no
Queues come later in traditional ds textbooks i believe
They always start with the linked list
car cdr are very common terms as well
@old rover are you familiar with trees?
no ...
Lisper begone
I have seen at least 2 not lisp examples with car cdr
address register, decrement register
they never actually never mapped to those registers
it was just a neat name
So a tree is a data structure where you can have nodes and branches:
a
/ \
b c
/|\
d e f
/| |
g h i
you can imagine a table of contents, or an HTML page (if you know HTML), or a family tree, or a phylogenetic tree of species, or an inheritance tree.
And a linked list is just a special case of a tree:
a
\
b
\
c
\
d
\
e