#algos-and-data-structs

1 messages ยท Page 19 of 1

fiery cosmos
#

i am not

#

im just wondering about the asymptotics of if i were

haughty mountain
#

for a list no

#

if you delete in the middle of a list you need to shift all the element right of it one step left

fiery cosmos
#

ahh ok

#

ooh i just thought of some great analysis to write about

haughty mountain
#

linked list -> O(n) indexing, O(1) removal if you're "at" the index
list -> O(1) indexing, O(n) removal

fiery cosmos
#

oh they're reversed

#

interesting

#

ditto for inserting, O(1) for linked, O(n) for normal list, because of the shifting ducky_australia

#

alright but i really must go now, tysm!!!

haughty mountain
#

as I mentioned, O(1) insertion is only true for linked list if you insert at a node you already have O(1) access to

#

and I suspect deque doesn't even have O(1) insertion in the middle anyway, even if it was a supported operation like in usual linked lists

#

deque is a linked list of blocks, and I expect it will "re-align" the blocks on insertion/deletion

#

I haven't checked the source though

#

but in short just use deque for deque operations, most other operations are terrible

opal oriole
#

Unrolled doubly linked list I think.

haughty mountain
#

it's a kinda worse version of C++'s deque

#

which has O(1) indexing

opal oriole
#

More memory, but if you want that O(1), worth.

#

(Can use the technique in general on linked lists / unrolled linked lists)

gleaming pivot
#
class Solution(object):
    def plusOne(self, digits):
        lis = []
        for i in digits:
            if i == 9:
                return [1,0]
            elif i != 9:
                lis.append[i]
                return lis[::-1] + 1

#

is it possible to solve this problem

#

this method?

amber harbor
#

Hey so I'm learning about shell sort and we have to find the worst case for it. We're using the original sequence and after running the algorithm with reversed and random input, we found the random input takes more time to run. Anyone have any ideas on this? Thanks

hollow needle
#

Hello
How can you calculate epochs of Adaline algorithm with a certain epsilons and learning rate for patterns like OR ?!

haughty mountain
#

iirc a power of two array size is a bad case there

amber harbor
#

yup.

floral wasp
#

Hi guys, i need help i don't know how to use str on my poo look

hybrid epoch
# gleaming pivot this method?

No. The .append method is not subscriptable. Your code returns an early, incorrect output for the input [9,9]. Also, you're trying to concatenate an int with a list

floral wasp
amber harbor
#

you mean like 1 2 4 8 16 32...

haughty mountain
#

Shellsort, also known as Shell sort or Shell's method, is an in-place comparison sort. It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compar...

amber harbor
#

oh, I mean what data order would result in its worst case

haughty mountain
#

it mentions a worst case under the table in this section

amber harbor
#

like its best case is when the array is already sorted right?

haughty mountain
#

probably

#

power of two is the worst case for the N, because consecutive zeroes

#

and then that even/odd config

#

so something like

n = 2**12
A = [None]*n
A[::2] = range(0, n//2)
A[1::2] = range(n//2, n)

shell_sort(A)
#

not a huge case, but you can raise that power

#

a few more powers up things should get pretty slow if it behaves quadratically

amber harbor
#

What is N in the example above? the number of elements in array a?

#

I still don't understand it very well... could you perhaps give me an example?

haughty mountain
halcyon plankBOT
#

@haughty mountain :white_check_mark: Your 3.11 eval job has completed with return code 0.

[0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]
haughty mountain
#

so small/large elements on even/odd positions respectively

amber harbor
#

like that?

haughty mountain
#

you can see the example I gave

#

positions 0, 2, 4, ... have elements 0, ..., n-1

#

positions 1, 3, 5, ... have elements n, ..., 2n-1

amber harbor
#

oh... I see. thank you

lucid wyvern
#

Hey is this where I can ask help to optimise a program ?

agile sundial
#

probably

lucid wyvern
#

TLDR a group of friend and I are trying to get the number than appear more than 3 times in the inner triangle of a pascal triangle as fast as possible.
We've set up the limit row to 250

#

And so far I'm here :

#
def search_pascal_multiples_fast(row_limit):
    triangle = [[1]]
    for i in range(row_limit):
        triangle.append([1] + [triangle[i][j-1] + triangle[i][j] for j in range(1, len(triangle[i]))] + [1])
    return sorted([number for number, count in Counter([number for row in [row[1:-2] for row in triangle] for number in row]).items() if count > 3])
#

And I clueless on how to make it better. Any ideas ?

vocal gorge
#

huh, interesting. what comes to my mind is what it means mathematically: e.g. 120 occurs in 5 places because binomial(10,3)=binomial(10,7)=binomial(16,2)=binomial(16,14)=binomial(120,1). That last one is always going to be there and the first four are two pairs. So what's special about 120 is just that it happens that

10!/(3! 7!) = 120 = 16!/(2! 14!)

which... doesn't give me any fancy ideas on how to predict it, hmm.
Of course, OEIS has an entry for it, https://oeis.org/A003015, and it's 20 years old and has tons of references. But it seems like it really is just a search task.

lucid wyvern
#

Yeah but most of maths concept they mention here fly right over my head.
The only one I have a grasp on is the nCr and it's slower than my approach

#

But I did try singmaster's conjecture

fiery cosmos
#

hey all, i need help implementing a randomized list for my algo. i don't want it to be truly random, so i'll need random seed i think. what i would like to do is, if the range i say (0-10), put the numbers in the same random order each time i run the program. i cannot pre-determine the random stack because it'll vary in size.

lucid wyvern
fiery cosmos
#

ok i will try this, thank you

#

do i need like a i for i in random.seed...

lucid wyvern
#

Random.seed() takes an integer so what I wrote previously should work I think

fiery cosmos
#

no you have to set the seed somehow, will google

#

ty

lucid wyvern
fiery cosmos
#

then you would be randomizing the seed to one of those

#

the seed confers a non-randomness to the random function, or at least, the same "randomness" each time

#
import random

random.seed(1)

list = [i for i in (random.randint(0,10))]

print(list)
#

this gives error:

#

Exception has occurred: TypeError 'int' object is not iterable

#

so i'll need a range somewhere as well

#

ah, randrange

midnight sorrel
#

Hi, I have a binary matrix of size o*p. I'm given K queries where each consists of given sub-matrix, with upper left coord (x1,y1) and lower right coord (x2,y2).
My task is to count one's in each submatrix. It should be done in O(o*p + k) time complexity. How do I do that?

fiery cosmos
#

hey all, i need to update some logic for my hashtable

#

lmk if you can assist

fiery cosmos
#

i was trying to randomize a list in the same way each time, but i've abandoned that. now i am trying to fix up my logic for when i pick a new bucket to place a key into. its a hashtable algo

fiery cosmos
#

i'm struggling with my logic bc i essentially have like a while trying and failing thing is true: do x but i'm not able to see how to meet the original condition to break the while look

#

loop

#

i'm ending up just inserting the same key over and over again

vocal gorge
haughty mountain
fiery cosmos
#

its a bit more nuanced, i need them to be unique. but i'm more focused rn on trying to implement the logic you mentioned y'day, eg, while failing a try_insert, pick new bucket location, try again. i am going to read over the old messages now

#

lol i just end up inserting the same key for every location in the table

#

ok i think i got it

#

wait, nvm

fiery cosmos
#

i got it inserting and not overwriting anything but now i am unable to insert all of my keys and i'm not sure why

#

i have plenty of space in the table

fiery cosmos
#

this is exactly what i wanted thanks. this works:
self.stack = random.sample(range(0,primary_hash_int),primary_hash_int)

#

something about my chaining logic is still broken

fiery cosmos
#

yep

#

awesome

opal oriole
#

(random.seed(0) or whatever)

fiery cosmos
#

yep. i got it. tested and everything

#

pretty neat

#

reproducible randomness

opal oriole
fiery cosmos
#

dude, Knuth is everywhere in this field

#

thanks for ref

opal oriole
#

Knuth might as well be the field.

fiery cosmos
#

i swear everywhere i look i see his name. wild the influence he has had

opal oriole
#

Knuth also just wrote a lot of notes on various things that are useful and many use them as reference.

fiery cosmos
#

i like how in the fisher-yates wiki they have a pencil and paper method

#

nice way to learn an algo

opal oriole
#

Random shuffles were done on paper long before (modern) computers.

fiery cosmos
#

oh i'm sure

#

i wonder how these graphs are generated not that but what dataset they're basing this on

#

obviously its not search engine stuff

opal oriole
#

Book/paper references to the word.

fiery cosmos
#

right

opal oriole
#

Of all books we have.

#

Google scanned in a lot of books and papers that were physical.

#

But other organizations did too.

fiery cosmos
#

and sent them to Alphabet/GOOG?

opal oriole
#

Made a specific machine for it.

#

But that graph looks like it's only for recent.

fiery cosmos
#

only really post 1950, or the y axis doesn't allow one to see few mentions on the scope of millions

#

or whatever the upper bound is

opal oriole
#

Looks like it's per year, not cumulative, but there was a lot of "algorithm" prior 1950.

fiery cosmos
#

right im thinking we just cannot see the 1-1000 refs / year or whatever it was due to the scale of y

opal oriole
#

More than 1000.

flat hornet
#

Guys, what is the best place to learn and to train algorithms and data structurs?

fiery cosmos
#

see pins and also abdul bari on youtube

fiery cosmos
#

and here

flat hornet
#

learn data structurs is know how things work like in the array for example?

fiery cosmos
opal oriole
fiery cosmos
#

also, depth first and breadth first searches

opal oriole
#

Yeah, Knuth is something else.

flat hornet
#

know the performance of components, what is better for use?

fiery cosmos
#

heaps

flat hornet
fiery cosmos
#

those are some common ones, they you have the ways you want to represent your graphs, you have the graph traversal algorithms, there are heaps, etc

haughty mountain
fiery cosmos
#

kind of mixing in DS and different algos here, but each algorithm is underpinned by one or more datastructure

fiery cosmos
#

the stack and queue mentioned there can be implemented as a pythonic array or deque

#

fiery i hate to ask but are you able to assist with fixing my chaining logic

#

i have it running but i am failing to insert all of my keys

haughty mountain
#

why is there an else there?

#

up top

#

ok, why is your else doing all that?

#

why are there try_inserts in the else?

#

the else is only there to deal with linking a new bucket

flat hornet
#

do you need make functions

fiery cosmos
haughty mountain
#

y'know, you might benefit from adding a comment to each block to remember what it's supposed to do, which might deter you from making it do something it shouldn't do

fiery cosmos
#

you aren't wrong, i need to do that anyway before submission

haughty mountain
#

you still need the while loop if you're going with the "potential free list" route

fiery cosmos
#

how about this:

#

no i need my try except block

#

i keep getting pop from empty list errors

#

or maybe just a break

haughty mountain
#

yep, I would move the keys[0] is not None into a method in the Bucket though

#

e.g. is_empty

fiery cosmos
#

ok ok

#

wait

#

i don't need that bucket argument

#

this is a bucket

haughty mountain
#
while self.stack and ...:
  ...
if not self.stack:
  raise ...exception about no free buckets...
#

return self.keys[0] is None

fiery cosmos
#

so i should not have any try_inserts in my else block at all?

haughty mountain
fiery cosmos
#

in the event that the insert is successful, i want to update the pointers

#

err

#

the is_empty method will guarantee successful insertion

haughty mountain
#

if you want to add a comment to that block it would be like

# Add a new bucket to chain
#

as the comment suggests, no insertion is going on

haughty mountain
#

so find a free bucket, link it, and go to that bucket

#

yeah, you also need one of the pops before

#

well

#

you could also do a different style loop I guess

fiery cosmos
#

no matter the logic i continuously find i am unable to add all keys

fiery cosmos
haughty mountain
#

this is iffy but should work

while True:
  if not self.stack:
    raise ...
  new_p = self.stack.pop()
  if ...[new_p].is_empty():
    break
haughty mountain
fiery cosmos
haughty mountain
#

just do it afterwards?

#

the loop is to find a free bucket

#

when you have that you know what to do

fiery cosmos
#

ah ok

haughty mountain
#

again, a reasonable place to add a comment

#

for the loop

#

that it finds a free bucket

fiery cosmos
#

hmm im struggling with the whole passing along new_p vs the original p thing

#

like i can't just name it p or it'll overwrite where i want to put the pointer

#

i guess this is where i need that logic i pasted above

haughty mountain
#

the bottom two lines

fiery cosmos
#

yeah i got it

haughty mountain
#

update the link, then follow the link

fiery cosmos
#

ugh it's just adding the same keys over and over

haughty mountain
#

huh?

#

code?

agile sundial
#

raising the string is wild

haughty mountain
#

yeah, raise your custom exception

fiery cosmos
#

no i know i can fix that later

#

we did a lot of error handling yesterday

haughty mountain
#

what's the rest of the loop?

#

lol

#

yeah, no wonder

fiery cosmos
#

๐Ÿ˜ข

haughty mountain
#

let's think, how can multiple of the same key even be inserted?

fiery cosmos
#

why do i feel like the culprit is my second try_insert call in elif

fiery cosmos
haughty mountain
#

wait, why do you have an try_insert there?

#

it's an error

#

but not the error I saw

fiery cosmos
#

how else might i try to insert after following the pointer?

haughty mountain
#

the last step doesn't need insert anything

#

it just adds a bucket and moves to it

#

the second step (in the elif) should similarly not insert

#

it does a way simpler task

#
elif there is a link:
  ???
fiery cosmos
#

ok let me ask you this, how can we spend multiple iterations of i to insert a single element

#

we'd run out of loop iterations to insert them all, or could potentially

haughty mountain
fiery cosmos
#

if we spend several loops to find the proper p value, we've used multiple of our finite number of loops to insert one key

haughty mountain
#

so?

#

the reason we have n iterations is that it's for sure enough iterations

#

it's effectively a while loop

fiery cosmos
#

i don't believe it is. it's only enough if we are guaranteed to insert the key during a single iteration. consider when keys = tablesize

haughty mountain
#

err

#

this loop is for inserting 1 key

fiery cosmos
#

correct

haughty mountain
#

ok, what's the issue?

fiery cosmos
#

if we fail our first insert, and never attempt another one, we're using at least 2 of the tablesize number of iterations to insert a single key

haughty mountain
fiery cosmos
#

hmm this might explain why i had it working before but i was failing to insert all the keys

haughty mountain
#

this loop is to insert a single key

fiery cosmos
#

right, but its not guaranteed to. what if we use 5 of our tablesize iterations to insert 1 key, and each key takes > 1 iteration to insert on average? we would run out of iterations

haughty mountain
#

wdym?

#

how would we run out of iterations?

fiery cosmos
#

if we are not inserting during any given iteration, only finding a new p, we could run out of iterations to insert every key, especially as the number of keys to insert gets closer to the tablesize

#

shit i really wish i could go back to what i had before and test with a larger bound on the loop..

haughty mountain
#

err, let's fix the loop first and then come back to this

#

did you fix the elif?

fiery cosmos
#

fair enough. but i hope you can tell what i'm on about. i removed the try_insert from there

haughty mountain
fiery cosmos
haughty mountain
#

i.e. follow the link

#

ok, there is a very simple reason why your code inserts the same key over and over

flat hornet
#

where is apply data structurs in python, in what functions?

haughty mountain
#

look at your if block

fiery cosmos
#

need a break?

haughty mountain
#

I'll take a break

fiery cosmos
#

lol

haughty mountain
#

yes, you successfully inserted

fiery cosmos
#

ok so that's much better, now im only failing to insert 3 keys

haughty mountain
#

you're done, so break or even return

#

could you post the full loop?

#

just to check it looks alright now

#

yeah, that looks fine

fiery cosmos
#

btw i randomized the stack with a seed for better performance ๐Ÿ™‚

#

ok yeah it is somewhat surprising i am failing to insert every key

haughty mountain
#

so what's the issue you're seeing?

fiery cosmos
#

yeah no nvm. i was thinking this whole loop was to insert every key. nevermind

#

i was incorrect

haughty mountain
fiery cosmos
#

i know i know

#

it just clicked

haughty mountain
#

and why is n steps enough?

fiery cosmos
#

uh

#

i suppose in the condition that every single other table slot is full?

haughty mountain
#

how many unique links can you even follow in a row?

fiery cosmos
#

in the unlikely condition that every try_insert fails

haughty mountain
#

how many links are there?

fiery cosmos
#

oh idk

haughty mountain
#

there are only n links

fiery cosmos
#

n-1

haughty mountain
#

right

#

you'll never be able to follow n links

fiery cosmos
#

ok sweet. any idea why i'm failing to insert some? i should try a larger input too.

#

rn keys = 84

#

when tablesize is 120, and input keys = 115, i successfully add 106 keys and fail to insert 9

#

seems to be some constant fraction of the keys

#

interesting

haughty mountain
#

I'm assuming you meant to call is_empty

fiery cosmos
#

where

haughty mountain
#

in the code I replied to

#

it's only used once

fiery cosmos
#

uhh, you want it in elif? eg, elif table p has a pointer, follow it and check if that slot is empty?

haughty mountain
#

you're not calling the is_empty function in your code

fiery cosmos
#

its in the else clause, do i need it more than that?

haughty mountain
#

...call it

fiery cosmos
#

oooooooooo

haughty mountain
#

thanks lancebot

fiery cosmos
#

ty

#

yep, that fixed it up

#

ty ty

#

ok, i think i am finally done tinkering and ready to complete the analysis. the rough part is, i need to redo every single test call and generate new numbers. i should really get busy on that bc the first time around it took me foreverrr

haughty mountain
#

a statically typed language would have screamed at you, sadly this is python ๐Ÿ˜›

fiery cosmos
#

i have missed those () before, yeah

haughty mountain
fiery cosmos
#

you just read my mind, i had already typed out a message saying if i had more time i would write a method to run all the tests for me

#

i have 11 schemes at least, before i get into looking at the same scheme with changing input size

haughty mountain
#

the automation shouldn't be too hard

#

you would probably save time

fiery cosmos
#

eh, i'm sure its pretty tough given i have so many varying command line calls and different input files

haughty mountain
#

or at least save annoyance

#

even bash would do fine

#

just a bunch of nested loops

fiery cosmos
#

i should have made it do that automatically..

#

right now i am manually keying in each combination each time along with the arguments ๐Ÿคฆโ€โ™‚๏ธ

#

๐Ÿคฆโ€โ™‚๏ธ ๐Ÿคฆโ€โ™‚๏ธ ๐Ÿคฆโ€โ™‚๏ธ

haughty mountain
#

even if you don't want the loops and that complexity

#

why not just write all the commands to run to a file?

#

and then run that

fiery cosmos
#

wdym

haughty mountain
#

you know the commands you type out over and over? write them one per line in a file

#

and then you can just run that file as a script

fiery cosmos
#

how so

#

so thankfully i already have all the names, cause i have them as outputfile names

haughty mountain
#
u0_a258: ~
> cat a.sh
echo do a
echo do b
echo do c
u0_a258: ~
> bash a.sh
do a
do b
do c
#

I'm saying write the commands to run to a file, then you can just run all in one batch

#

some manual work and copy pasting, then you can re-run stuff as needed easily

#

without typing stuff

#

(and you can avoid a ton of the initial typing using loops, but even without that this is a better way than writing everything every time)

fiery cosmos
#

im with you. i do need to learn bash soon

haughty mountain
#

as said, you can literally just write out the commands one per line to a file

#

that's a valid script

#

then you can run it and have everything generated by executing one script

#

suddenly the annoying part isn't annoying anymore and you don't need to fear having to redo it

fiery cosmos
#

oh

haughty mountain
#

since redoing it is just running the script

fiery cosmos
#

like everything in one line in a python script

#

then run that

flat hornet
#

Guys in general, in big aplications do you develop a data structurs or use structurs of python, like lists, arrays?

haughty mountain
opal oriole
#

It just does what you write in the terminal.

haughty mountain
#

@fiery cosmos what platform are you on again?

fiery cosmos
#

i mean like, everything in one line in a text editor?

haughty mountain
#

one command per line

opal oriole
#

One line per program execution / command.

fiery cosmos
#

i'm on windows, i use powershell for unix/command line or w/e. my IDE is VScode

opal oriole
#

On windows you make a batch file.

haughty mountain
#

yeah, for this trivial usage they should behave the same

#

just write one command per line to a .bat file

#

run that

fiery cosmos
#

so:
open notepad
write one command per line
save as .bat
run the .bat with.. command line?

haughty mountain
#
python myfile.py --my --flags
python myfile.py --different --flags
...
opal oriole
#

Command line or double click it, but it will close the terminal window immediately after finishing if you double click it to run.

#

You can add a "pause" as the last line.

#

Will wait for a key press to exit then.

#

(Then just double click the bat file to run)

fiery cosmos
#

ok i think i've got it. just did a test with a single command

#

this is awesome

flat hornet
#

Squiggle do you can explain for me about use of data struturs in system?

#

Or do you need understand how work only

#

because already are created in functions?

opal oriole
haughty mountain
fiery cosmos
#

no this is so amazing that this works i've spent like 5 hrs before doing this manually

#

automatically naming output according to the inputs would have been cool too. next time

#

the other better thing about this is i can see every command all at once, and ensure i'm not rerunning things or overlooking things

opal oriole
#

Naming output?

fiery cosmos
#

right now i am manually passing an output name each time for a given input, eg, whatever text file name you write in

#

and actually, it'd probably error pretty bad if you named a non txt file

opal oriole
#

You can have it write to stdout (the terminal, same as printing normally), and batch / bash lets you redirect such output to a file.

#

But i'm guessing they want you to write to a file.

flat hornet
#

in a system?

opal oriole
flat hornet
#

or in code?

fiery cosmos
#

alright let's try this bad boy

opal oriole
#

(and many other ways)

fiery cosmos
#

i think running that and having every input get run almost immediately is the most satisfying thing ive ever done in coding

#

watching out the outputs spring into existence with a single enter

#

i might be hooked y'all

flat hornet
#

:

fiery cosmos
#

hmm

#

my comparisons are a bit different, i guess that's ok

#

i'll update my graphs

opal oriole
fiery cosmos
#

how will this batch file treat blanklines

opal oriole
fiery cosmos
#

itll skip and continue though

opal oriole
#

Imagine it auto types that file into the terminal for you.

#

Line by line.

#

It runs a "batch" of programs.

fiery cosmos
#

i got you

bitter viper
#

I have a file with records of how a user navigated through a website.
It is encoded as follows:
A;B;C;<;G;<;<;M
Where letters represent the current page and < represents the user clicking on the back button. Every action is separated by a semicolon. In the above example, the user started at A, navigated to B, then C, then back to B, then to G, then back to B, back to A, and from A to M

My objective is to track all the "movements" of the user in order to measure the popularity of each link. I decoded the path to a doubly-linked-list in order to navigate from the start point to the end point, counting each "jump" taken.

This requires a lot of resources since I have 100k paths to analyze and I was looking for an idea to optimize the process. Any suggestions?

agile sundial
#

why a doubly linked list? and how do you measure popularity?

bitter viper
#

Popularity is measured by frequency that a link is used.

Doubly linked because I decode the "path" and then traverse it to increase a variable storing the frequency each link was used.

I'm trying to find a way to decode and count at the same time, but can't put my finger on it

flat hornet
agile sundial
bitter viper
#

< means that the user went back to the parent page, and that the next link will be from (parent) to (other) page

agile sundial
#

right, but how are you counting that in the frequency calculation

bitter viper
#

< are not counted, only the next action will be

#

Therefore, A;B;<;D should give: one click on link to B from A, one click on link to D from A

agile sundial
#

oh you need to track the links?

bitter viper
#

Yes, the end objective is listing all the links out of page A and identifying the frequency that each one is used by the user

#

But I have thousands of "paths" from a user jumping around the website

agile sundial
#

seems fairly trivial then. use a stack, when you see a letter, add to a Counter the link (the previous letter, the new letter). then pop if you see a <

bitter viper
#

Mmh, makes a lot of sense.

#

No need for a full fledged linked list, a stack will do

agile sundial
#

you could either split the string on ; or just iterate using indexes

#

well a stack could be implemented with a linked list. though python's list will be just fine (and probably better)

bitter viper
#

Coming from C++ to Python has it's challenges

#

Thanks a lot -- will give it a try

agile sundial
#

python's list is basically a std::vector

bitter viper
#

Also for context, the project is based on this dataset https://snap.stanford.edu/data/wikispeedia.html
Where each page is an article with all outgoing links to other articles.
The goal is to analyze the popularity of outgoing links in articles based on their position, length of the word, etc.

undone sluice
#

A(?=B) and A(?!B) both of them in regex is equivalent positive and negation in logic?

feral frigate
#

How do I get good at solving Problem Solving questions?

unique topaz
grim bough
#

Is it true

#

?

fierce sluice
#

I got a question
is there an equivalent to cpp's

set<pair<float, int>> my_set;
my_set.insert(pair<float, int>(1.2, 1));
my_set.insert(pair<float, int>(2.4, 2));
pair<float, int> min_number = *(my_set.begin());
my_set.erase(my_set.begin());
#

It gives the minimum in O(log(n))

#

So in other words, is there any way to get minimum in python O(log(n))?

austere sparrow
#

Constructing the set is obviously O(n) already

#

There's a binary heap:

#

!d heapq

halcyon plankBOT
#

Source code: Lib/heapq.py

This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.

Heaps are binary trees for which every parent node has a value less than or equal to any of its children. This implementation uses arrays for which heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2] for all k, counting elements from zero. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that its smallest element is always the root, heap[0].

fierce sluice
fiery cosmos
#

is a print statement considered a return

haughty mountain
fiery cosmos
#

this batch file is saving my life rn

#

hmm

#

feel like i might be counting my chaining comparisons wrong

#

either that or it really is just wildly more efficient

#

yeah i added a comparison counter to my while loop

fiery cosmos
#

if inserting n keys into a hashtable and each key takes time of O(n), it'd take n^2 time to insert them all?

haughty mountain
#

but insertion really shouldn't be O(n)

#

worst case yes, typical case no

fiery cosmos
#

thanks i just wanted to ensure i had the logic correct

haughty mountain
#

one thing that could be interesting is a scatter plot of the cost per inserted key, as you add keys

fiery cosmos
#

i agree

#

i can say that it would look somewhere between exponential and linear for linear and quad probing, mostly linear in the case of chaining

#

chaining with a randomized stack is remarkably efficient, as measured by very low number of comparisons

haughty mountain
#

what's the range for your random keys?

fiery cosmos
#

for their input or my supplemental input

haughty mountain
#

I guess both are interesting

fiery cosmos
#

1s

haughty mountain
#

what I'm curious about is really "do you expect any collisions?"

#

but knowing the range answers that

fiery cosmos
#

theirs are 0-99,999

haughty mountain
#

that seems fine

fiery cosmos
#

mine are 0-90k

haughty mountain
#

then you should get some random collisions

fiery cosmos
#

oh i get quite a few

#

let me share a graph

#

sry, this is comparisons

#

but the primary and secondary collisions end up adding up to this value

#

or somewhere similar

#

as expected, chaining is much more efficient

#

the amortization analysis of cost to insert keys could be interesting as a function of load factor

haughty mountain
fiery cosmos
#

of course

#

if they are all the same, lots of collisions

haughty mountain
#

say you insert numbers 1-120 in a table of size 120, with mod 120

#

no collisions

fiery cosmos
#

should be near to zero

#

right

#

yeah i should really test input with many of the same key, and measure the comparisons required to enter all

#

but alas i am burnt out

haughty mountain
#

I just wanted to make sure that you don't sample numbers between [0, tablesize) or something

fiery cosmos
#

thanks for that

#

i'm a little bit brighter than that

#

slightly

#

๐Ÿ˜‚

#

very pleased that you and squiggle got me going with the batch file

#

thats, a game changer

#

and as i have said before, i seriously hope i get to continue learning software dev because i really enjoy learning and troubleshooting

haughty mountain
#

I tell you, laziness is great

#

automate the annoying things

fiery cosmos
#

i see it as being more competent and automating things others simply don't know how to, but i appreciate the humbleness of describing it as lazy

haughty mountain
#

even stuff like text editing can be automated with a powerful enough text editor ๐Ÿ˜›

vocal gorge
#

oh, I thought you were going to say "github copilot" :p

haughty mountain
vocal gorge
#

so good at automation you automated yourself away

haughty mountain
#

(the secret is automating your work and not telling anyone, so people think you're working hard)

fiery cosmos
#

my batch file open in a text editor was being really weird, instead of moving stuff when i tried to insert into the middle of a string line it started overwriting all the proceeding characters pithink

fiery cosmos
haughty mountain
#

insert mode

#

try pressing the insert key on your keyboard to toggle it

fiery cosmos
#

oooooh, that's what that key does????

#

wow

#

TIL

#

must be a legacy thing

#

also, oddly enough the only way to open a batch file on windows (that i could find), was dragging it into an open text editor. if you double-click it'll just run itself and disappear

#

i should get on linux, i have always hated windows and having to be logged into certain softwares

haughty mountain
#

my friend discovered that the insert key enters insert mode in vim, which I found bizarre

fiery cosmos
#

something something surveillance

#

vim?

#

virtual machine?

haughty mountain
fiery cosmos
#

lms

haughty mountain
fiery cosmos
#

oh ok

haughty mountain
#

quite old school text editor

#

but very powerful

#

(and very different from your usual text editors)

fiery cosmos
#

oh i see why i didn't find it, in windows 11 they hide all that useful stuff from you, including copy

#

you have to go right click -> show more options -> edit

haughty mountain
#

that's terrible

vocal gorge
#

something something boiling frogs

fiery cosmos
#

truly awful, agree

vocal gorge
#

in windows12 you'll have to enable these options in the settings first ๐Ÿ˜‰

fiery cosmos
#

lmao

#

confused with the jokes today

haughty mountain
#

I'm living in a cozy terminal on linux since like a decade

fiery cosmos
#

i've had every intention of going there, i've even partitioned my SSDs to make a linux enviro, never got around to it

#

how does it affect gaming

haughty mountain
#

I don't use guis much unless it makes a lot of sense for them being guis, like web browser, image editing, and some other stuff pithink

haughty mountain
fiery cosmos
#

have you heard of puter

haughty mountain
#

a lot of stuff works fine, mutiplayer games that use anti-cheat are likely not going to work

#

even if the game itself would work

fiery cosmos
#

oof that's a big ask. i guess one could always have one PC for gaming and one for everything else

#

Puter is a cloud operating system. Store, open, and edit your files from anywhere at any time in the cloud.

#

its an OS within a web browser

#

pretty cool

haughty mountain
#

but most games I want to play kinda just work

#

because of big efforts from valve

fiery cosmos
#

do you use steam

haughty mountain
#

yeah

#

valve has proton which is a compatibility layer that allows running windows games on linux

#

(based on wine)

fiery cosmos
#

never heard of proton or wine. sidebar my email carrier is protonmail

agile sundial
#

just use WSL

fiery cosmos
#

i really need to learn R but i prefer learning python and DS

#

what's wsl

vocal gorge
#

why do you need to learn R?

agile sundial
fiery cosmos
fiery cosmos
fiery cosmos
#

what is linear regression all about

haughty mountain
fiery cosmos
#

what is the purpose of it

#

what is multiple linear regression

gleaming pivot
fiery cosmos
#

i don't think my explanation of insertion asymptotics is making sense

haughty mountain
fiery cosmos
#

lol bruh

agile sundial
#

the number of people that buy ice cream if it costs 20 dollars is 50. the number of people that buy ice cream if it costs 10 dollars is 100. i wonder how many people will buy ice cream if it costs 5 dollars

fiery cosmos
#

seems simple enough

azure osprey
agile sundial
#

wait, why would it be exponential

azure osprey
#

Well word spreads quick

#

Once things are cheap ๐Ÿ˜‰

agile sundial
#

that's not how it works

azure osprey
#

Yea i was jk

#

But seriously irl it should be exponential

agile sundial
#

idk about that

haughty mountain
#

and if you sell it 200, half of a person will buy it

#

idk if this model makes total sense ๐Ÿ˜›

agile sundial
#

just floor it for the half a person case

#

and it does make sense for the free case if you change it from "how many people will buy it" to "how many people that are able and willing to buy it would buy it"

#

but anyways, it does work as an example

haughty mountain
#

this feels related ๐Ÿ˜›

fiery cosmos
#

"sublinear"

haughty mountain
#

but yeah, basically you can use linear regressions to try to fit functions to data

#

(it's fairly basic linear algebra to do it)

fiery cosmos
#

just for modelling? or like, what's the primary purpose. is it the same as linear regression analysis? what is multiple linear regression? why is there an entire branch of algebra dedicated to lines (actually, your previous post gives me some idea)

haughty mountain
haughty mountain
fiery cosmos
haughty mountain
#

the linear algebra part is how the constants are picked

#

linear algebra is really about linear combinations of stuff, not just about lines

fiery cosmos
#

are those not the same things

agile sundial
#

no, see his example, he has 4 things that might vary, which gives a 4 dimensional thing, not a line

fiery cosmos
#

so a line must then be just a single equation

#

of multiple terms

#

which can each vary?

agile sundial
#

his example is a single equation. a line is an equation with 1 varying thing, essentially

fiery cosmos
#

in what way is that not the same

agile sundial
#

well a line is something like ax = b, right. a plane could be something like ax + by = c a 3 dimensional surface could be something like ax + by + cz = d

lean lake
#

hello all! im learning DS and im kinda stuck.

so i made a random walk function that uses an adjacency list (from a dictionary) .. where would i start if i had to modify my code so that it can use a weighted adjacency matrix instead?

def random_walk(graph, nodeid, steps):
    da_walk = [nodeid]
    while len(da_walk) < steps:
        nodeid = random.choice(list(graph[nodeid]))
        da_walk.append(nodeid)
        turns = steps - 1
        random_walk(graph, nodeid, turns)
    return da_walk
glossy breach
#

Basically the same thing but use a list of tuples (id, weight) in your adjacency list instead of just id

fiery cosmos
#

which books are good to learn ALGO and DS using python

haughty mountain
#

none of them are super easy

fiery cosmos
#

which several are the least difficult

haughty mountain
#

multithreaded algos is kind of a no-go in python

#

polynomials and fft is a fun topic

fiery cosmos
#

ok, that's super helpful to know bc i was leaning that way

fiery cosmos
haughty mountain
#

most of these are pretty mathy

#

it's fun because the naive way of multiplying polynomials is O(nยฒ) where n is the degree

#

with fft you can do it in O(n log n)

#

string matching might not be hard, but it very much depends on what's covered

#

there is a ton of stuff in that bucket

fiery cosmos
#

i mean this'll all be straight out of CLRS, so whatever they cover in there

haughty mountain
#

yes, and idk what that is without having to look it up

fiery cosmos
#

lms

haughty mountain
#

computational geometry is so very fiddly

#

linear programming is a pretty huge topic with a lot of theory around it

#

idk what they cover in number theoretic algorithms

fiery cosmos
#

i've x'd that out bc there is a ton of subject matter

#

like more than double the concepts of other chapters

#

if you're curious i can put it here

agile sundial
#

fft for polynomials sounds really cool

fiery cosmos
#

that's definitely on the list

#

need to pick several

#

sounds like polys and fft, string matching, and one more

haughty mountain
#

the number theory topics looks fun though

agile sundial
#

yeah those look useful

#

I'm learning those right now in school lol

fiery cosmos
#

those stars mean grad school topics tho

#

meaning more difficult

agile sundial
#

no it just means hard

fiery cosmos
#

right

agile sundial
#

any section will have those, though

fiery cosmos
#

chpt 30 has only 3 subjects and none are starred

haughty mountain
#

fwiw chapter 30 will involve some complex math

fiery cosmos
#

i don't think anyone in my group has a math background

haughty mountain
#

(as in complex numbers, not necessarily so complicated)

fiery cosmos
#

we're a ragtag bunch of like virus people and fresh from undergrad ppl

agile sundial
#

and fft, which is somewhat complicated

fiery cosmos
#

i don't think the majority of math is necessarily that complex, i just think its a matter of not knowing it

#

is an issue

#

bc then you have to pause everything and try to go learn it

#

i mean obviously there is some very difficult math yes

haughty mountain
#

it's just a bunch of even-odd splits

fiery cosmos
#

are B-trees still used? i think someone said for databases they are often used?

#

there are no spinning discs in my PC ๐Ÿคทโ€โ™‚๏ธ

agile sundial
#

ram is still much faster than SSDs, so they're still useful

fiery cosmos
#

the book starts with showing a spinning HDD as soon as B-trees come up

haughty mountain
#

aren't B-trees better BBSTs anyway?

#

in terms of memory usage and cache locality

agile sundial
#

that's what I thought

agile sundial
fiery cosmos
#

one node can have a thousand children???

#

dog

haughty mountain
#

so if you want something like an always sorted set, B trees are great

#

slightly better ๐Ÿ˜›

#

you lose some guarantees of BBSTs, but nothing overly useful

#

like, if I have a pointer to an element in the set and I delete some element, is that pointer still valid?

fiery cosmos
#

is there a formal definition of a pointer? for me its sort of like a murky concept

haughty mountain
fiery cosmos
#

like when we just made bucket.pointer = some other bucket

agile sundial
#

it's similar to an int with a value that's a memory address

haughty mountain
#

but indices

fiery cosmos
#

yes, it was just pointing at an index in the table

#

ill do some reading

#

rn i need to figure out this B-tree problem

#

how do memory addresses on the RAM work? is there like a mapping to individual bytes / bits ?

#

is that done by the RAM manufacturer or the OS

haughty mountain
#

bytes, OS

fiery cosmos
#

i'm not understanding the third property of B-trees:
3. the keys x.key_i separate the ranges of keys stored in each subtree: if k_i is any key stored in the subtree with root x.c_i, then
k_1 <= x.key_1 <= k_2 <= x.key_2 <= ... <= x.key_x.n <= k_x.n+1

#

and a byte is 8 bits (the part of the semiconductor that can be either 0 or 1)

#

trivia (without looking): what is the name for a string of four bits

fiery cosmos
#

inserting into B-trees is rather involved

#

splitting nodes and adding the median key to its parent

median trout
#

Hey guy's a beginning programmer here with a question; I plugged the following formula into a variable and I get the following TypeErrors:

#

But if I split the problem up into seperate expressions it will run fine. can anyone tell me why?

median trout
#

do int() on the whole mathematical expression? there is no built in function called num()

gusty geode
#

oh shoot I was thinking about a module that I'm used to using

fiery cosmos
#

i don't understand the predecessor subgraph of BFS

#

what is it

#

it notated as G_pi

gusty geode
median trout
#

that's what I thought but obviously I am wrong.

gusty geode
#

or are you not trying to multiply it by 1000?

median trout
#

you can see I changed them all to floats it made no difference

gusty geode
#

nope I just tested it and it worked

#

you forgot to add the * between (1000*(...

median trout
#

oh, ok duh. I feel stupid now. Thank you

fiery cosmos
#

yooo good job

#

did you really know that off the top of your head??

haughty mountain
#

technically a byte could be different from 8 bits, but not on modern and non-exotic platforma

#

if you want to be super pedantic 8 bits is an octet

fiery cosmos
#

8 bits = octet = 1 byte

haughty mountain
fiery cosmos
#

bruh

haughty mountain
#

The byte is a unit of digital information that most commonly consists of eight bits. Historically, the byte was the number of bits used to encode a single character of text in a computer

#

so there have been different byte sizes historically

#

I think 7 was kinda common for a bit

fiery cosmos
#

so there is an interesting implication of self vs. non-self in many things, one of them being the immune system, i wonder if it is the same in computers

#

and how the concept of sameness manifests

#

eg, how does a computer know an if check is same or non-same. i guess everything just has its own machine-code representation

#

but like, how does it know

if pi == pi```
#

or similar

#

not important

#

good old predecessor subgraphs, you gotta love em

opal oriole
haughty mountain
#

yeah, 1 hex digit is a nibble

haughty mountain
haughty mountain
fiery cosmos
#

so it'd be like
is 10110110 = 10110110?

fiery cosmos
# fiery cosmos

i can read it from this into english in my head but haven't yet made sense of it

haughty mountain
#

!e

import math, struct
print(struct.pack('d', math.pi).hex())
halcyon plankBOT
#

@haughty mountain :white_check_mark: Your 3.11 eval job has completed with return code 0.

182d4454fb210940
haughty mountain
#

that's pi

#

8 bytes of data

fiery cosmos
#

looks like a lot more than 8, if each letter is 1 byte = 8 bits

haughty mountain
fiery cosmos
#

i thought 1 bit was a single either 0 or 1

haughty mountain
#

yes

#

!e

import struct, math
print(struct.pack('d', math.pi).hex('|', 1))
halcyon plankBOT
#

@haughty mountain :white_check_mark: Your 3.11 eval job has completed with return code 0.

18|2d|44|54|fb|21|09|40
haughty mountain
#

easier to count now

haughty mountain
#

it's kinda neat

haughty mountain
#

so it's a base 16 digit

#

2 of those gets us a byte

#

I could convert that hex into an int and get the parts of the double pithink

fiery cosmos
#

i'll need to look up some sort of graphic. i'm not seeing where you got from 0's and 1's to

fiery cosmos
#

definition of predecessor subgraph is on pg. 600, pretty much the same as shown above

#

i'm noting that V_pi has a U {s} and E_pi has a - {s}

haughty mountain
halcyon plankBOT
#

@haughty mountain :white_check_mark: Your 3.11 eval job has completed with return code 0.

+ 3.141592653589793
fiery cosmos
#

Gฯ€ = (Vฯ€, Eฯ€) where: Vฯ€ = {v โˆˆ V : v.ฯ€ =/= NIL} U {s} and Eฯ€ = {(v.ฯ€, v) : v โˆˆ Vฯ€ - {s}}

haughty mountain
#

Vฯ€ is all the vertices with a predecessor + the source (root)

#

Eฯ€ are the edges that goes from vertices v in Vฯ€ to their predecessor ฯ€[v]

#

err, ignoring the source in the second one

fiery cosmos
#

"the predecessor subgraph G is a graph comprised of sets V predecessor and E predecessor where the set of predecessor nodes V is equal to the set of vertex v in the set of vertices V such that v's predecessor is not equal to None, union source node s, and. the set of predecessor edges are equal to (a vertex v's predecessor, v) edge such that vertex v is in the set of predecessor vertices V minus the set containing the source vertex s."

haughty mountain
#

I read ฯ€ as "parent" in my head here ๐Ÿ˜›

haughty mountain
fiery cosmos
#

they use ancestor and descendent in this bit

#

i was going to say, there is someone else more mathematically inclined which will have a proper appreciation for the mathematical gymnastics you are doing up there, as for myself, it was one big whoosh

haughty mountain
#

then I extract all the parts of the floating point number (sign, exponent, mantissa)

#

and rebuild the number

fiery cosmos
#

what are these symbols: >> <<, what is mantissa???

haughty mountain
brisk saddle
#

aawhat the FUCK

haughty mountain
fiery cosmos
#

i'm over here trying to understand graphs and dude is reconstructing pi using bits for fun

brisk saddle
#

that you stop coding forever

haughty mountain
#

floating point numbers are basically scientific notation but in binary

stray fractal
brisk saddle
#

your a floating point

haughty mountain
#

1.(mantissa bits) * 2**(exponent bits - 1024)

#

and then the sign bit

fiery cosmos
haughty mountain
#

shifting and masking

fiery cosmos
#

thinking in bit operations

nope

haughty mountain
brisk saddle
#

do i look like someone who would dothis

haughty mountain
#

kinda

#

you've done weirder things

#

I know more magic tricks

fiery cosmos
#

is there a magic trick for making me understand all the crap in all these chapters all at once

#

like the matrix for CLRS

haughty mountain
#

!e rounding

print(123.45 + 2**52 - 2**52)
print(123.54 + 2**52 - 2**52)
halcyon plankBOT
#

@haughty mountain :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 123.0
002 | 124.0
haughty mountain
#

@brisk saddle I probably showed this one before

brisk saddle
haughty mountain
#

if you ignore nan inf and subnormals they are very well behaved

#

the + - trick is kinda dumb

fiery cosmos
#

!e
x = 5318008
x.reverse()
print(x)

halcyon plankBOT
#

@fiery cosmos :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | AttributeError: 'int' object has no attribute 'reverse'
fiery cosmos
#

bruh

haughty mountain
#

I add 1000

#

1123.4

#

you round to keep 4 digits: 1123

haughty mountain
#

!e this?

x = str(5318008)
x = x[::-1]
print(x)
halcyon plankBOT
#

@haughty mountain :white_check_mark: Your 3.11 eval job has completed with return code 0.

8008135
haughty mountain
#

and very mature ๐Ÿ˜›

fiery cosmos
#

lol i knew there was a reverse slicing method to go through it. and yeah, that's the only numbers related thing from my childhood i could dream up

lean lake
#

#help-cookie i need some pointers to get me unstuck in my DS class. im kind of struggling atm. thanks

lean lake
#

@haughty mountain took me some time, but it's working now! thanks for pushing me in the right direction!

G2 = np.array([
    [0,    0.5,  0,    0.5],
    [0.5,  0,    0,    0.5],
    [0.25, 0.25, 0.25, 0.25],
    [0.5,  0.5,  0,    0],
])

GG2 = nx.from_numpy_matrix(G2, create_using=nx.DiGraph)


def random_walk2(graph, nodeid, steps, da_walk=None):
    if da_walk is None:
        da_walk = []
    da_walk.append(nodeid)

    if steps == 1:
        return da_walk

    nodeid = random.choices(list(GG2[nodeid]), weights=[k["weight"] for k in list(GG2[nodeid].values())])[0]

    return random_walk2(graph, nodeid, steps-1, da_walk)


print(random_walk2(GG2, 0, 4))
fiery cosmos
#

my friend made similar looking diagrams when making a regex parser

static veldt
#

'hello'

#

`helo1

#
    base=input('what is the base of the triangle:')
    def basecalculator(base):
        try:
            newbase=int(base)
            return newbase
        except:
            inp=input('enter an integer')
            basecalculator(inp)
    height=input('what is the height of the triangle:')
    def heightcalculator(height):
        try:
            newheight=int(height)
            return newheight
        except:
            inp=input('enter an integer')
            heightcalculator(inp)
    beforearea=basecalculator(base)*heightcalculator(height)
    finalarea=beforearea/2
    return finalarea
print('your area is',trianglecalculator())```
static veldt
#

and i dont know what else to do

#

is anyone free to help

hot latch
#

Hey I've been trying t do this leetcode problem for a while and am still having some issues

#

do you guys have any ideas on hwo to do it?

#

so we need to choose m-1 rows that maximizes the minimum of the maximum of each column

#

I guess the brute force is simple but I don't nkow how to optimize the problem

agile geyser
#

what would be the time complexity of

#

would it look something like O(log(nCr)) ?

signal ocean
#
#Create a code generator. This can that take text as input, replaces 
#each letter with another letter, and outputs the โ€œencodedโ€ message.

string = input("What message would you like to be encoded? ")
key = input("Key: ")
#/.string = "abcdefg" # Used for testing
#/.key = 2
enc = ""

for i in range(len(string)):
    enc += chr(ord(string[i])+key)

print("The encrypted message is: ", enc)

Anyone able to figure out why my code doesn't work? At the moment I know it has something to do with how I'm shifting the characters. This line:
enc += chr(ord(string[i])+key)

plush wraith
#

Dynamic programming algorithms improve time efficiency by efficient sorting algorithms.
is it true?

fiery cosmos
#

no

#

dynamic programming algos improve efficiency by maintaining a table and looking up answers rather than re-computing subproblems

wise verge
signal ocean
#

Yes

#

The error tells me there's a problem with me using the utf-8

#

Nvm, I found something similar to the way I want to do it and I'll be looking at it before I ask more questions

haughty mountain
#

am I dumb or isn't that solution super greedy?

#

you want to maximize the minimum

#

to increase this you need to remove some existing minimum

#

so you can just remove some row that contains the minimum

#

why is picking any such row ok? because if there are many rows with a minimum you're screwed anyway

#

so remove one row containing a minimum, compute the result, done

#

yeah, I think that should work

fiery cosmos
#

i've been drawing pictures on trees for hrs, i feel like there is something wrong w a problem statement in the book

haughty mountain
#

give the statement then

fiery cosmos
#

so i made a B-tree

#

and i've been drawing what each of the sets looks like

#

not seeing how a path can split the S' set given that by definition is it every key smaller than key k

#

they're saying the S' set is the set of trees with keys smaller than k

#

so how could the path split that further when it is sort of already upper bounding it

#

let me give an example B-tree

#

i drew another tree with more keys, since nodes with 3 keys will have 4 pointers

#

and give the range that is specified by each key of a tree

haughty mountain
#

where is the problem in the book?

hybrid epoch
#

What book?

#

If you don't mind sharing

fiery cosmos
#

the only conclusion i could draw is that you follow different pointers leaving the node on the path to the children while each key k is less than the search k (terrible way of explaining it)

fiery cosmos
#

do b-trees require latches?

fiery cosmos
#

also stuck on another one if n e 1 is bored

wraith solar
#

r

fiery cosmos
#

I want to learn DSA in one month

#

is it possible?

dreamy valley
#

Enough to pass an interview or final exam? Probably

vocal gorge
#

well, in universities DSA is usually a semester or two (source: googled syllabus dsa course), so a month seems doable if you can go through it at several times the rate.

eager scroll
#

hi

#

i have a list removable
removable = [3,1,0]
I have to remove those indexes characters from a string to create a new string
upto certain range
how to do it

       c=removable[i]
       temp=temp[:c]+temp[c+1:]
summer fossil
#

Hii, You yeah You
Can u fix my code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

def height(root):
    if root==None:
        return 0
    return max((1+height(root.left)), (1+height(root.right)))

class Solution:
    
    def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        h = height(root)
        lis = []

        def fun(root, level, q):
            if root == None:
                return 0
            
            if level == 1:
                lis.append(root.val)

            elif level != 1 and q == True:
                fun(root.left, level-1, True)
                fun(root.right, level-1, True)

            elif level != 1 and q == False:
                fun(root.right, level-1, False)
                fun(root.left, level-1, False)

        for i in range(1, h+1):
            if i%2==0:
                fun(root, i, False)
            else:
                fun(root, i, True)

        return lis
Output:= [[3],[20,9],[15,7]]
myoutput = TypeError: [3, 20, 9, 15, 7] is not valid value for the expected return type list<list<integer>>

Thanks!

#
question:=https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/```
dreamy valley
summer fossil
haughty mountain
#

[] * height is a fun way to spell []

hybrid epoch
pearl ridge
#

if a method uses a method that is O(n) then is that method also of the same time complexity?

vocal gorge
#

well, of at least that time complexity

#

if it calls it O(n) times, that's O(n^2) complexity already

fiery cosmos
#

oof i'm finally at NP-completeness, may god have mercy on my soul

fiery cosmos
#

so all this mess about encoding problem instances as languages / in binary certificates is just to formalize the P and NP classes yes?

#

does one ever actually have to pass binary certificates as arguments to their algo or this this just how to build a formal problem instance into a language?

#

from the book:
a verification algorithm a two-argument algorithm A where one input is an ordinary string x and the other is a binary string y called a certificate. a two argument algorithm A verifies an input string x if there exists a certificate y such that A(x, y) = 1

#

the language verified by a verification algorithm A is
L = {x โˆˆ {0, 1}* : there exists y โˆˆ {0, 1}* such that A(x, y) = 1}

fiery cosmos
#

you use a hardware random number generator to get a randomized input seed to pre-program https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator

A cryptographically secure pseudorandom number generator (CSPRNG) or cryptographic pseudorandom number generator (CPRNG) is a pseudorandom number generator (PRNG) with properties that make it suitable for use in cryptography. It is also loosely known as a cryptographic random number generator (CRNG) (see Random number generation ยง "True" vs. pse...

timber fox
#

Can anyone here help me how to start with data structures in python??

#

Like any books? To learn DSA in python

fiery cosmos
#

the main book of the field is language-agnostic. it contains pseudocode

timber fox
#

Sorry could you please simplify it?? I didn't get you

fiery cosmos
#

the main book that is used to teach algorithms does not use a specific language, and there is good reason for that

timber fox
#

Oh ok

fiery cosmos
#

if you want online courses that are python-specific, use EdX

#

maybe

#

although the python courses i took on there were about dictionaries and the like, nothing about real DS or algos

#

this is the primary book for DS/algo

timber fox
#

Thanka a lot sir

fiery cosmos
#

also pins in this channel

#

is the MIT opencourseware version of that book

fiery cosmos
#

oof

#

this 3CNF stuff is pretty brutal

haughty mountain
#

the study of NP hard problems boils down to being able to show things like problem A is easier than problem B

#

this is true if I can translate a problem of type A into type B

#

because if I can solve B I can by extension solve A

#

that's the basic idea, but there are loads of details to make it formal

#

viable as in will eventually get the right answer, sure

#

that eventually might be an eternity away though

fiery cosmos
#

Is my idea for a non deterministic algo accurate or is that not a typical paradigm one might use

haughty mountain
#

it's as bad as the deterministic one

#

or worse

fiery cosmos
#

I thought non deterministic was just not returning the exact same answer every time is runs. Iโ€™m not talking about approximation algos, unless they are synonymous

#

Is non a non deterministic algorithm synonymous with an approximation algorithm?

#

Wikipedia didnโ€™t seem to indicate that

haughty mountain
#

it's not synonymous

fiery cosmos
#

they're surely related somehow, i would presume

haughty mountain
#

but your scheme of keeping the minimum makes it some kind of approximation scheme

fiery cosmos
#

what might a typical non-deterministic paradigm look like? i'm happy if you just provide a link to a known algo

haughty mountain
#

there is an interesting one, I just need to remember which one it is...

fiery cosmos
#

ok ok. my mind just went the approximation route apparently after reading the chapter. book didn't discuss deterministic vs non-deterministic, unless i missed it. i'll check the index

haughty mountain
#

I think it's this, but the wiki is probably to hard to read

#

this is an algorithm that gets the correct answer with a not too low probability

#

so if you repeat it enough times you can be increasingly certain about the correctness of your answer

smoky dew
#

say I have a class A whose objects each hold unique identifiers x y and z, what would be the right data structure to be able to get the objects from either one of these identifiers? a dict would work if they only had a single identifier but not with multiple, and a list would just be inefficient. is there something else?

haughty mountain
#

I'm assuming you mean you should be able to get A from one of x, y, z?

#

you could use a dict and map all three to A

#

it won't be too wasteful since you're not storing copies, just references

lethal ore
#

With Reinforced Supervised Learning Using Machine Learning On A Closed System With Say Python, Is It Possible To Link My Library From Google Books And Choose Specific Books By Sequence For The AI To Read And Store It In Memory To Go Alongside Training Data For Such A System Later.

split vector
#

hey guys, is sorting an array then doing the rest of the algorithm is still a brute force or brute force doesn't include sorting ?

haughty mountain
#

brute force is a very generic term

#

you could use it to describe a lot of things

#

when I hear brute force I think "try basically all relevant possibilities"

split vector
#

is this a brute force ?

haughty mountain
#

the last part looks greedy, but it also looks weird

split vector
#

how can I make it a brute force then

agile sundial
#

what's the problem statement?

haughty mountain
#

wouldn't budget += i.revenue - i.spend be the sensible thing?

agile sundial
#

spend could be negative ig

haughty mountain
#

I don't think it can be negative

agile sundial
#

oh it's just greedy then right. establish as many as you can

split vector
haughty mountain
agile sundial
#

sorting works because then you don't have to care about what project you go to next

haughty mountain
#

why would you want to make something brute force?

agile sundial
#

ah yeah, it's not guaranteed to be profitable (smh being realistic?)

split vector
split vector
agile sundial
#

I guess brute force would just be trying each permutation of the investments to do in order

haughty mountain
#

oh wait

#

you get the initial investment back on top of revenue?

haughty mountain
#

if so you just take all you can, starting from the smallest

agile sundial
#

oh so you can't lose money

split vector
#

no

haughty mountain
#

yeah, it makes the problem pretty boring

agile sundial
#

that would just be an if statement though right? if it's negative profit, don't do it

haughty mountain
#

yes

split vector
#

But I need to check back if I got a project revenue

haughty mountain
agile sundial
#

isn't it n+1 cause you need to loop lol

haughty mountain
#

ฮฉ(n!) then

split vector
#

btw is this O(n^2) ?

agile sundial
#

yeah, because the bubble sort

haughty mountain
#

the rest of the code is O(n)

#

idk why you would want to do bubble sort though

split vector
#

is it possible to do it with out sorting ?

haughty mountain
split vector
#

that I can do

#

But my problem is

#

I have to write 2 algorithms

#

one is brute force

#

and the other one is any other algorithm with less O( )

#

and when I got this algorithm I dont know if it is a brute force or not ๐Ÿ˜…

#

this one

haughty mountain
#

I don't think you can solve efficiently without sorting, I can construct cases where you need to do things in sorted order to be optimal

#

no, what you have (if we ignore the sorting being written in a slow way) is a very good solution

split vector
haughty mountain
#

as said, I don't think you can do it without considering the sorted order somehow, and your second part is O(n) and cheaper than sorting

split vector
#

and it is greedy algorithm right ?

haughty mountain
#

the very dumb solution that @agile sundial mentioned of considering all permutations of all subsets will eventually consider the sorted version of the thing you need

just insanely inefficiently

haughty mountain
dreamy valley
# split vector this one

are you sure you're solving the right problem there?
because there's no obvious "brute force" version of this one, but if I tweak the parameters a bit it looks like an O(2^n) problem that might have an efficient dynamic programming solution

haughty mountain
#

brute factorial

haughty mountain
split vector
#

so for the 2 algorithm the brute force one is the one @agile sundial mentioned, and mine is a greedy algorithm yea ?

haughty mountain
#

well, asking for a brute force one here is just weird

dreamy valley
#

that's why I'm wondering if the problem is specified wrong

haughty mountain
#

there is no obvious brute force algo here

split vector
#

I guess our tutor hates us then

haughty mountain
#

I think any brute force algo will use basically the second loop you have

#

because you need to check if the investment is valid

dreamy valley
#

I was thinking of the case where you have n investments that you have to make simultaneously and you have to optimize your return in one investment cycle. The fact that you can get the return from investment A before you have to invest in B is what makes sorting+greedy work here

#

but that does seem to be what the poorly written explanation is saying so ๐Ÿคทโ€โ™‚๏ธ

haughty mountain
dreamy valley
#

yeah I was just having a hard time reading it

#

still weird to ask for a brute force algorithm

haughty mountain
#

it is

split vector
#

what I can adjust to it to make it a brute force i didn't get

#

how the code will be

haughty mountain
#

in a bunch of cases there is some obvious but inefficient brute force, this is not one of these cases