#algos-and-data-structs

1 messages ยท Page 101 of 1

agile sundial
#

yeah, that's not ideal

old rover
#

but I think I'm actually getting better at it

#

slow improvement

inland iron
#

k, and what about the indentation error at "else:"? how would i fix that?

old rover
#
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?

agile sundial
#

parses a string in to an int? idk

old rover
#

i looked at the doc too

#

yeah i think you're right

inland iron
#

im new to python tbh

old rover
#

cast a string to an int?

agile sundial
#

depends on the language

old rover
#

you can't do it in java?

#

oh wait

agile sundial
#

that's not java

old rover
#

whatttttt

#

what is that????

jolly mortar
#

js

old rover
#

oh i forgot i learned that

#

just never used it again

jolly mortar
agile sundial
#

replace your indentation with spcaes

inland iron
#

thx...?

old rover
#
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

inland iron
old rover
#

so it goes inside the while loop

#

then 2 is divided by 2 and it becomes 1

#

confusion

agile sundial
#

yeah

#

the loop iterates one time

old rover
#

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?

agile sundial
#

it is log n, yeah

#

because the loop runs log n times

old rover
#

idk what that means

#

bc when you put in 2 it runs once

#

and 2 is the n

agile sundial
#

you're unsure what log n means?

old rover
#

i kinda forgot from high school math

#

guess i'll watch some videos

#

ok so i watched this and now i kinda remember them

#

hang on i'm watching O(log(n) videos rn

gusty grove
#

if you get -inf that means 1-sig was 0

buoyant garden
#

yes

gusty grove
#

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

buoyant garden
#
def sigmoid(z):
    result = 1 / (1 + np.exp(-z))
    return result
old rover
#

I have a question

#

why do we always use log base 2 in CS?

#

why is it implicit?

agile sundial
#

binary is base 2

old rover
#

oh ok

agile sundial
#

it's just easier for computers to work with than base10

old rover
#

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

buoyant garden
#

^^^

old rover
buoyant garden
#

?

old rover
buoyant garden
#

ah

old rover
#

yeah these people who just casually read 1k page long textbooks amaze me

spring jasper
#

I dont think anybody does that

buoyant garden
#

uh

old rover
#

uh

#

public static void main enters the chat

spring jasper
#

Doubt he would agree tbh

old rover
#

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

buoyant garden
#

^

spring jasper
#

Reading is fine but are you applying what youre reading

old rover
#

well i don't see how I would be explaining the math behind big O to an interviewer any time soon

buoyant garden
#

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"

old rover
#

they're more interested in seeing you say the time complexity of an algorithm by looking at it

buoyant garden
#

but thats just my convoluted brain

#

oop
'

old rover
#

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

old rover
#
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...

โ–ถ Play video
#

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?

spring jasper
#

What it does is divide the number by 2 every step

#

Its like binary search

#

Hence log(n)

old rover
#

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???

spring jasper
#

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

old rover
#

oh I don't really know binary search yet

spring jasper
#

Ah ok fair then

old rover
#

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?

mint jewel
#

yes

old rover
#

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??

mint jewel
#
  1. big O only really makes sense for large inputs
  2. 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

old rover
#

what about a thousand?

#

not big enough?

mint jewel
#

it is big enough I guess

#

but you are missing the point

old rover
#

I know it's not for how long something takes

spring jasper
#

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

mint jewel
#

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)

spring jasper
#

Its parseInt(3/2) which is equivalent to 3//2

mint jewel
#

but the actual output size will not be exactly linear to N

old rover
old rover
mint jewel
#

some number

#

fixed the sample code

old rover
#

oh I didn't realize thanks

#

does range start from zero?

mint jewel
#

yes

old rover
#

yes right?

#

ok

mint jewel
#

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

old rover
#

"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

agile sundial
#

it's about 7/8ths ok

old rover
#

the worst case scenario is right

spring jasper
#

He got the name right

old rover
#

big O does indeed mean upper bound on time

mint jewel
#

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

old rover
#

why is it

#

that every textbook I look at

#

has a different def of big O

mint jewel
#

it means that the algo will grow linearily for large enough inputs

old rover
#

can't y'all just standardize????

mint jewel
#

because it is used in casual conversation and people try to simplify the horrible math version to be more comprehensible

old rover
#

but then people who simplify it are completely wrong

mint jewel
#

and inevitably end up introducing wrong things

old rover
#

sigh

agile sundial
#

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

mint jewel
#

since mathematicians aren't horrible because they want to be seen as smart, but because it needs to be precise and well defined

old rover
#

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

mint jewel
#

yeah, that is fine. Its just an indication of how things grow on very large inputs

old rover
#

so what if my interviewer is like

#

oh yeah it's just how fast an algorithm runs

mint jewel
#

well, then they are wrong

#

don't tell them that though

old rover
#

also

#

if big O is used for the worst case scenario

#

what notation is used for the best case scenario?

mint jewel
#

little o

agile sundial
#

eh?

mint jewel
#

actually, that may be something else, never mind me

old rover
#

"An algorithm's Big O Notation is determined by how long the algorithm takes to return output in the worst case scenario."

spring jasper
#

Its omega

old rover
#

oh ok

#

so I need to learn that too ig

#

can I start algos and data structures w just big O?

spring jasper
#

ฮฉ(f(n))

mint jewel
#

yes

agile sundial
#

arguably big O is part of dsa

#

so you've already started

old rover
#

good stuff

spring jasper
#

Learning big o without any context of the data structures involved sounds boring tbh

old rover
#

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);
}
wise fiber
#

does anyone have the explanation for USACO Feb?

old rover
#

this is how this guide introduces fibonacci

wise fiber
old rover
#

it sounds Italian

spring jasper
#

It is

old rover
#

oh it is cool

#

I didn't wanna be racist or trigger anyone so I crossed out the text

wise fiber
#

crossing out italian is racist man

old rover
#

oof ya got me

wise fiber
#

๐Ÿค”

spring jasper
#

His name was Lenny from Pisa in italy somewhere

old rover
#

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?

spring jasper
#

Its easier i guess

#

Big O doesnt exist in a vacuum
Dang mathematicians

old rover
#

What does existing in a vacuum mean?

#

Not used?

#

irrelevant?

spring jasper
#

As in, they exist independent of other concepts or structures

old rover
#

I mean

#

Big O is important for algorithms

spring jasper
#

Its easier to understand something by doing, implementing the algorithm will help you more than just studying the theory

old rover
#

Yep

keen hearth
old rover
#

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

keen hearth
#

I can try my best to summarise it here with a sufficient level of rigour, if you like? ๐Ÿ˜„

old rover
#

just make sure to ping me bc i'm gonna take a shower

keen hearth
#

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).

brave oak
#

(in particular, Timsort - which Python uses, and which was made for Python, is baaasically mergesort but better with data that's already partially sorted)

old rover
#

i'm back

keen hearth
#

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.

old rover
#

noted

keen hearth
#

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 f is a member of the set O(g) (where g is also a function) if and only if there exist constants, n0 and k, such that, for all n > 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.

old rover
#

uhhh only math I did was calculus for CS before I switched my major

#

on a side note

keen hearth
#

If you imagine that f(t) and k * g(t) represent the positions of two cars along a race-track at time t.

old rover
#

can you recommend a book that's not a thousand pages long?

keen hearth
#

Erm, you might want to check out Khan Academy's algorithms course, not sure if I've already recommended it.

old rover
#

KHAN ACADEMY HAS AN ALGORITHMS COURSE?

#

WHAT?

keen hearth
#

Yes ๐Ÿ˜„

#

It's kind-of hidden on their website.

old rover
#

holy shit

#

do they have a data structures course too?

keen hearth
#

They're kind of the same subject tbh.

#

The course has input from one of the authors of the CLRS textbook I believe.

old rover
#

yeah Cormen

#

Cormen wrote CLRS w some other buddies

keen hearth
#

Btw, this kind of illustrates what I was saying:

#

From Wikipedia.

old rover
#

got it

#

uhhh

#

it's all of the algorithms?

#

or just a few

keen hearth
#

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.

old rover
#

i tried to read algorithms unlocked and CLRS

#

but they both made my head spin

#

and algorithms unlocked is just 200 something pages

agile sundial
#

khan academy's course is in js

keen hearth
#

That's true. The exercises are in JS, although they're optional.

agile sundial
#

if you wanna learn the exercises are not optional

old rover
#

but aren't algorithms language agnostic or something

#

so you should be able to learn them in anything

keen hearth
old rover
#

hey as long as it's not Siraj Rival I'm ok

keen hearth
#

They kind of frame the whole course around social networks. The course is a few years old now.

old rover
#

I mean does it matter? Have algorithms changed much in the last couple years?

keen hearth
#

Shouldn't matter, although it may use Python 2 ๐Ÿ˜„

old rover
#

UHHHHHHHHHH

#

yeah then I'll stick w Khan Academy

keen hearth
#

It's also pretty heavy on graph algorithms.

old rover
#

is that supposed to scare me or inform me

keen hearth
#

(Which are very useful to know!)

old rover
#

or both

#

lmao

#

ok good

agile sundial
#

graph theory is awesome

keen hearth
#

Inform ๐Ÿ˜„

old rover
#

ofc one of the guys wrote CLRS wrote algorithms unlocked

agile sundial
#

clrs was written by 4 guys lol

old rover
#

"one of the guys"

agile sundial
#

"(edited)"

#

the 4th edition of clrs is coming out soon, with color!

old rover
#

yay more thousand page long book that I won't read

#

yayyyyy

agile sundial
#

ok but imagine this

#

the red black trees, will be red and black

old rover
#

sure pretty illustrations are pretty

#

maybe I can use it as a picture book

keen hearth
#

Fancy

agile sundial
#

ikr

#

before it's just "the lightly shaded are red, and the darkly shaded are black"

keen hearth
#

Apparently they use MacDraw on an old macintosh to make the illustrations.

old rover
#

I don't even know how to read CLRS

agile sundial
#

i think it's in english

old rover
#

there's barely any bolded text

agile sundial
#

they use italics in some spots

keen hearth
#

I'm not sure why I know that ๐Ÿ˜„

old rover
#

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

agile sundial
#

well, i'm not denying that lol

keen hearth
#

The style is fairly mathematical. There are a lot of proofs.

#

You have to kind of get used to it.

old rover
#

I don't care about maths

agile sundial
#

computer science is all about that

old rover
#

I just don't like their writing style

agile sundial
#

it's very rigorous

keen hearth
#

But the explanations are very clear.

old rover
#

even in their "simpler, antipasta" book or whatnot it's still gigantic paragraphs

#

Algorithms Unlocked

agile sundial
#

it elucidates even the most minute details

old rover
#

how wonderful

agile sundial
#

quite

keen hearth
#

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 ๐Ÿ˜„

old rover
#

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

agile sundial
#

you mightt as well watch the lectures then

old rover
#

no

agile sundial
#

ok ยฏ_(ใƒ„)_/ยฏ

old rover
#

perhaps

#

so I have a question

#

there is no such thing as a "peak-finding algorithm" right?

keen hearth
#

That would probably be an "optimisation" algorithm.

old rover
#

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???

keen hearth
#

Nope sorry. Looks interesting though.

old rover
old rover
#

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?

keen hearth
#

It has nice illustrations ๐Ÿ˜„

keen hearth
old rover
#

what is n/2 --- 1?

#

damn you'd think MIT would actually teach this well

agile sundial
#

are you watching the lecture?

#

ah, you did

old rover
#

yeah

#

maybe MIT OCW is just not for me

agile sundial
#

n/2 - 1 is an index

old rover
#

I mean

#

my understanding of binary search

#

is you look at the middle

#

and then you compare it to the left and the right

agile sundial
#

usually you're looking for a specific key, but in this case you're just looking for a peak

old rover
#

oh

#

does --- mean ...?

agile sundial
#

that's probably just a typo

old rover
#

oh

#

ok

#

I will look at Grokking for a while and then come back

agile sundial
#

ok

keen hearth
# old rover and then you compare it to the left and the right

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.

old rover
#

slope???? valley????

keen hearth
#
                 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
#

oh ok

#

thanks

oblique panther
#

@old rover ๐Ÿ‘‹๐Ÿป

old rover
#

hey

oblique panther
#

what do you think the big-O of that algo is?

#

the fibb one?

oblique panther
#

why

old rover
#

I'm actually not sure I just read somewhere that recursive sequences tend to be O(2^n)

#

not a good answer I know

vocal gorge
#
// 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

old rover
#

it also doesn't help that I have seen recursion used like twice

#

that's my own fault tho

oblique panther
#
def fib(n):
    """You know I had to do it to them"""
    return n if n <= 1 else (fib(n - 2) + fib(n - 1))
old rover
#

ok so let's say we put in 5

oblique panther
#

do you know what T(n) means?

old rover
#

not really

#

probably should have said something

#

is it another notation?

oblique panther
#

it's a way of saying what the whole runtime is for a given algorithm

old rover
#

ohhhhh

#

ok

oblique panther
#

whereas O(g(n)) is a set of algorithms that scale according to g(n)

#

or something like that

vocal gorge
#

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.

old rover
#

so T(n) is actually what people are saying when they're like O(N) is the runtime of an algorithm

#

common misconception

oblique panther
#

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?

old rover
#

yes

oblique panther
#

explain

old rover
#

Idk what it looks like without recursion

oblique panther
#

it might be something like T(n) = 5 + n(n + 72) + sqrt(n)

#

do you know what the big-O of this would be?

old rover
#

O(1) constant time

oblique panther
#

no

old rover
#

F

oblique panther
#

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?

vocal gorge
#

not strictly speaking true - for example, T(n) = log(n)/n is O(1), so is T(n) = 10000 - e^(-n)

oblique panther
#

I can learn too lemon_hyperpleased

vocal gorge
#

it's O(1) if it's bounded by a constant - it doesn't have to be constant.

oblique panther
#

I knew the formal definition but I went out on a limb and figured there were no funny cases like this

vocal gorge
#

that might be true

icy crane
#

Oh, this is not ot oops

oblique panther
#

but also log(n) / n is (1/2)(n)(log(n)). so why isn't that O(n)?

#

wait

#

I am dumb sorry

old rover
#

idk Stelercus I think you're pretty cool

vocal gorge
#

log(n)/n is O(1) because it just goes to zero with increasing n, whereas 10000 - e^(-n) approaches 10000 from below.

keen hearth
old rover
#

oh

#

ok

#

nvm then

keen hearth
#

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)

old rover
#

brain goes brrrrr it's 9:30

#

brain has left the chat

#

I'll be back tomorrow

keen hearth
#

Alright, see ya ๐Ÿ˜„

cerulean river
#

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?

old rover
#

@cerulean river yeah sure as long as it has to do w algos/ds

cerulean river
#

thank you for clarifying this for me.

old rover
#

Any time

uneven jungle
#

how do you stop an iterative quicksort? I get it to sort everything, then it just continues and messes up.

austere sparrow
#

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

mint jewel
#

a priority queue from which every thread takes a state machine to advance

austere sparrow
#

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?

mint jewel
#

I think there is a priority queue implementation that allows modifying the element priority.

austere sparrow
#

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

mint jewel
#

I think heaps are good for this.

austere sparrow
#

yeah, asyncio.PriorityQueue is implemented with heapq

#

which also makes it a misnomer because it doesn't care about insertion order

inland iron
#

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?

shadow flower
#

you have to put x = x + 1 inside the while loop

#

i think

old rover
#

what's the time complexity of that algorithm

inland iron
#

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

inland iron
old rover
#

you know

#

the big O

inland iron
#

Im a relatively new python nerd, lul

old rover
#

oh

#

nvm

#

I am too don't worry

#

just trying to improve

inland iron
#

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

old rover
#

can I ask

#

why are you making substitutes for the min() and max() function?

#

are you trying to learn how they work?

inland iron
#

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

old rover
#

is it a high school or college assignment?

inland iron
#

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

spring jasper
#

It doesnt work because you hardcoded the index in the loop

shadow flower
spring jasper
#

Also you keep setting the biggest to the first element

shadow flower
#

because you are using the test numbers inside of the function

#

instead of the actual nums that are being taken in for the function

spring jasper
#

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

inland iron
#

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))

shadow flower
#

yeah

#

wait no

#

keep the indexes the same

#

like where you have Tnums[0]

spring jasper
#

That wont even run

shadow flower
#

change it to nums[0]

inland iron
#
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))
spring jasper
#

Bruh

shadow flower
#

not just a single index

hollow flame
#

hi

shadow flower
#

change everything to their respective indices

#

you are basically just switching out nums for Tnums

inland iron
#

wait i just realized i have duplicate code

hollow flame
#

any algo train or problem?

inland iron
#

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...?
shadow flower
#

i think this should work

inland iron
#

It doesnt

spring jasper
#

It wont

#

My guy

agile sundial
#

you're always accessing specific indices

hollow flame
#

yes

spring jasper
#

Youre hardcoding the indices

hollow flame
#

u r wrong

#

why x < len()

#

why did u do this

spring jasper
#

Thats not even the problem

agile sundial
inland iron
#

Its what i was suggested to do

shadow flower
#

oh i get what you guys are saying now

#

yeah you're hardcoding the indices

spring jasper
#

Suggested by who

shadow flower
#

it'll keep on looking at the second value

#

and repeating that 6 times

inland iron
#

i originally had is as x < 8 cause the list has a static 8 indexes

spring jasper
#

Thats not the problem....

inland iron
#

or 7 or something

hollow flame
spring jasper
#

The problem is biggest < nums[1]

agile sundial
#

the problem is not your bounds, the problem is that you're always comparing the same indices, because you've hardcoded them

hollow flame
#

no guys

#

listen

spring jasper
#

Bro stop

hollow flame
#

u should put counter in []

#

not 1

inland iron
#

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))

hollow flame
#

u should make a counter

#

then use it as index

inland iron
#

ohhhh so put the x = x + 1 in the []?

spring jasper
#

No, also i dont understand why youre not using a for loop

hollow flame
#

this code works now

agile sundial
#

please don't give out full solutions

hollow flame
hollow flame
#

i said

#

a counter

#

like for loops

spring jasper
#

X is the counter

hollow flame
#

that it goes into the index

inland iron
#

oh, the "for" thing?

hollow flame
#

u need x+=1

inland iron
#

kk

#

and that represents the index, right?

hollow flame
#

y

inland iron
#

im just asking so i can give the counter variable a clear name

#

like "index" or "counter"

#

not just "t"

spring jasper
#

x is the counter

#

Dont make another variable

hollow flame
inland iron
#

so i change x = x + 1 to x += 1?

spring jasper
#

That doesn't matter

#

The problem is that youre not using the counter when indexing

#

In the if statement

inland iron
#

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

hollow flame
#

just

#

put x in the index

#

not x+=1

inland iron
#
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)) ```
hollow flame
spring jasper
#

And the other one

hollow flame
inland iron
#

bro gimme a break, im a relatively new python user

hollow flame
inland iron
#

uhhhhh and it works now

hollow flame
#

go next

inland iron
#
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))
agile sundial
onyx umbra
#

hello

inland iron
hollow flame
inland iron
#

reccommended by my ICS teacher

spring jasper
#

Learn basic python first before you start implementing builtins

onyx umbra
#

no u definitely dont need to learn algo to code

#

just solve basic problems on some coding websites

hollow flame
agile sundial
spring jasper
#

This wasnt even an algorithms issue

onyx umbra
#

lol i know adavced algos and DSA, i m just saying u dont need to know them before hand

old rover
onyx umbra
#

well python is not very different from pseudo code

inland iron
old rover
#

most algo books teach w psuedocode

inland iron
#

cause it was reccomended by my ICS teacher

old rover
#

CLRS does

#

algorithms unlocked too

onyx umbra
inland iron
#

lol I started a deep disscussion, pog

onyx umbra
old rover
#

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

onyx umbra
#

if u know pseudo code then implementing is just copying it in good handwriting

#

logic is the main part

old rover
#

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

inland iron
spring jasper
#

Theres google too

inland iron
#

google is unhelpful for coding cause the problems are usually too specific

old rover
#

I like youtube indian guys who just solve the question no questions asked

onyx umbra
#

allow me to introduce "geekforgeeks", its all in one package for competitive programming

spring jasper
#

Google is incredibly helpful youre just not using it the right way

old rover
onyx umbra
#

lol figured

#

before starting to learn coding, i would suggest to learn google first๐Ÿ˜…

old rover
#

uhhhh

#

???

#

who are you talking to?

#

I do know how to google

onyx umbra
#

no one, murmuring to myself

old rover
#

ok

#

sounded like you were talking to me

inland iron
#

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?

spring jasper
#

What is number

#

And how does it change in the loop

inland iron
#

idk, i didnt know what to call the variable

spring jasper
#

What

#

Look at your code

inland iron
#

number is the iteration

spring jasper
#

You have a variable called number there

#

Is it?

inland iron
#

yeah, i copied the loop code from my minmax function project

#

and tried to change it

spring jasper
#

You define number outside the loop and then you dont change it

inland iron
#

x = x + 1?

spring jasper
#

Thats not number

inland iron
#

Uh okay

#

what do i do about it

spring jasper
#

You have to change it every iteration

inland iron
#

remind me how id do that again?

old rover
#

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

spring jasper
#

Its the last element

old rover
#

it is????

inland iron
#

uhhhhh i have no idea how to use binary

old rover
#

doesn't len(list) just return the length of a list?

spring jasper
#

Yes?

old rover
#

so it's the length of the list - 1

spring jasper
#

Yes

#

Its the last element

inland iron
#

yet again, the len(list) thing doesnt matter, it just works

old rover
#

but how is that a value

#

nvm

#

I am confusing myself

spring jasper
#

Its the index for the last element lmao

old rover
#

yeah i get that

#

hang on

#

lemme scroll and see how they use it

inland iron
#

IT JUST WORKS lmaoo

#

this is unhelpful

old rover
spring jasper
#

Bro this is literally what the channel is about

#

Calm down

inland iron
#

i need hep with the loop and the defining of the even and odd numbers

old rover
#

this is a channel where other people can ask questions

spring jasper
#

Nothing "just works" theres a reason they do

old rover
#

deal with it lmao

inland iron
#

not off topic, wrong word

old rover
#

I'm just trying to understand this stuff

#

oh mariosis

#

the next line makes sense

#

my bad dude

inland iron
#

anyways, how do i fix it

spring jasper
#

You fix it by first understanding how loops work and how indexing works

old rover
#

can he show us what happens with a sample input/output?

inland iron
#

input? the list is the input

#

the program literally outputs nothing

old rover
#

I have another question about this

#

what do they mean by "item"?

agile sundial
#

item, element, number

old rover
#

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

old rover
agile sundial
#

probably not

old rover
#

ok good

#

probably the wrong place since this doesn't have to do w algos/DS

cobalt cloak
#

oops

old rover
#

it's all good

#

you can open up a help channel tho

cobalt cloak
#

okay thank you i will do that now

old rover
#

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?

agile sundial
#

uhh

#

depends on the implementation

spring jasper
#

No

old rover
#

oh

#

but the overall code structure is the same

agile sundial
#

pretty much

old rover
#

so if I get this I can use it anywhere

#

cool

agile sundial
#

well yeah, that's thep oint

old rover
#

I feel the power of binary search racing through my veins

agile sundial
#

ok, but what's the big O

#

best, worst, and average case

old rover
#

O(log n) worst case

#

but idk about the best case and average case

spring jasper
#

Rhe best case is the element youre looking for is right in the middle of the list

old rover
#

so that would be O(N)

spring jasper
#

No since you start looking at the middle

old rover
#

O(1)?

agile sundial
old rover
#

๐Ÿ˜ฆ

spring jasper
#

You only have to do a couple operations and they dont depend on the size of the array

old rover
agile sundial
#

well, how do you arrive at O(log n)

old rover
#

I saw a while loop and guessed

#

don't do that

agile sundial
#

well, you're going to be a bit more rigorous

old rover
#

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

agile sundial
#

no

#

the implementation doesn't matter

old rover
#

so then why is it not O(log(n)?

agile sundial
#

lol wait

#

it's log n, my bad

old rover
#

wait I was actually right for once?

#

YAY

#

progress

agile sundial
#

well, since you guessed...

spring jasper
#

You guessed so no lol

old rover
#

ok but why is it actually O(log(n)

agile sundial
#

that's why just guessing is not the right way to go about it

#

why do you think it's log n

old rover
#

bc at each stage of the while loop you divide the list in half?

agile sundial
#

why does that make it log n

old rover
#

bc it's log base 2

agile sundial
#

what's log base 2

old rover
#

isn't base 2 normally used in CS

agile sundial
#

sure, but what's log base 2

old rover
#

it's the power to which 2 should be raised to get the value of n

agile sundial
#

that's not what i meant

#

what in binary search is log base 2, and why does that make it O(log n)

old rover
#

idk dude this is what the book tells me

agile sundial
#

ok, the book says it

#

that's like saying answering the question "why is this true", with "because it is"

old rover
#

ok

#

I don't know why

agile sundial
#

draw a picture of an array

#

and do binary search on it

inland iron
#

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

old rover
#

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

#
agile sundial
#

the amount of times you cut the list in half is the exponent

old rover
#

so then what does he mean by "guesses"?

agile sundial
#

tries, checks

old rover
#

are guesses iterations?

agile sundial
#

not necessarily, but since you guess once per iteration, they are equal

old rover
#

ok but 2^32 is not 4 million

#

it's around there

#

but not really

agile sundial
#

it's about 4 billion

old rover
#

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

agile sundial
#

what

spring jasper
#

log2(100) isnt 7 either

old rover
#

it's 128

#

so it's slightly off

agile sundial
#

yes, that's why he said "at most"

#

not "it will take x"

spring jasper
#

You cant have .664 of a step

#

You round up

#

Actually you dont round up, you ceil

old rover
#

can't endure CLRS but complains that Grokking is imprecise

#

ok well

#

I finally figured it out

#

good shit

agile sundial
#

it's not imprecise, it's reasonably accurate

old rover
#

whatever

agile sundial
#

anyway, since it takes log(n) checks...

#

(continue the reasoning)

old rover
#

that means it has a time complexity of O(log(n)?

#

n0

agile sundial
#

yeah, but you're missing a step in between

old rover
#

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

agile sundial
#

right, mathematically, you could describe that as

#

#checks = log(n)

old rover
#

by checks you mean iterations right

agile sundial
#

yeah

old rover
#

what goes in the N?

#

a large input

#

sorry i'm just very burnt out rn

agile sundial
#

maybe you should take a break

old rover
#

yeah perhaps

#

oh boy here we go again

agile sundial
#

if you want a rigorous definition, pick a rigorous resource ยฏ_(ใƒ„)_/ยฏ

#

otherwise, you're going to have to deal with simplified explanations

old rover
#

simplified is good for beginners

#

it was just a joke

wise dust
#

Ok

violet bramble
#

Hi anyone know about arc consistency algorithms in constraint satisfaction problems

keen hearth
#

What's your question?

violet bramble
# keen hearth 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?

keen hearth
#

What do you mean by two programs sorry?

violet bramble
#

One program where the algorithm is implemented and another for the sudoku i.e sudoku.py and ac3.py

keen hearth
#

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.

violet bramble
#

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

keen hearth
#

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.

violet bramble
#

Just a solver that is specific to sudokus

#

the main issue is coding the constraints and the neighbours and cross checking between them

keen hearth
#

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

austere sparrow
#

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.

violet bramble
#

Alright thanks ill have a look at those

old rover
#

so do linked lists have no index?

#

is that what Grokking algorithms is trying to say?

spring jasper
#

Well yes

#

To get to a particular node you need to traverse all nodes before it

old rover
#

yeah I'm not gonna get this until I see it in code

spring jasper
#

Arrays are different to linkedlists

old rover
#

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

spring jasper
#

In memory he means

#

Linkedlists arent contiguous

old rover
#

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)?

spring jasper
#

The max num of steps is ceil log2(128)

#

So 7 yes

old rover
#

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

spring jasper
#

Pretty much yes

old rover
#

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??

spring jasper
#

Depends, inserting in the middle of the list is O(n) i think

#

Appending is constant if you have a pointer to the tail

old rover
#

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

onyx root
#

@old rover do you understand how a linked list works?

old rover
spring jasper
#

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

onyx root
spring jasper
#

Well then now's the time haha

old rover
#

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

spring jasper
#

A deep understanding of pointers isnt really needed

#

Theyre things that point to other things

old rover
#

so is a pointer just a value that "points" to the next value in memory?

spring jasper
#

It points to another address in memory, not necessarily the next one in line

old rover
#

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

spring jasper
#

Im not a C buff, someone else might be better at explaining pointers

austere sparrow
#

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

old rover
#

so they call the things in linked lists nodes

#

the first thing is called a root node

austere sparrow
halcyon plankBOT
#

@austere sparrow :white_check_mark: Your eval job has completed with return code 0.

001 | 1
002 | 2
003 | 3
spring jasper
#

Or the head node

#

Head and tail are more common terms

old rover
#

they did this in Scala back at UB

#

but I was gone by then lmao

#

irrelevant

austere sparrow
#

are you familiar with queues?

old rover
#

uhh no

spring jasper
#

Queues come later in traditional ds textbooks i believe

#

They always start with the linked list

mint jewel
#

car cdr are very common terms as well

austere sparrow
#

@old rover are you familiar with trees?

spring jasper
#

Lisper begone

mint jewel
#

I have seen at least 2 not lisp examples with car cdr

spring jasper
#

What do they even mean

#

fst and snd atleast have intuitive names

mint jewel
#

address register, decrement register

#

they never actually never mapped to those registers

#

it was just a neat name

austere sparrow
# old rover no ...

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