#algos-and-data-structs

1 messages · Page 113 of 1

old rover
#

saying random numbers could potentially work

#

but since it was sorted a more efficient strategy would be to pick the middle value

#

if that middle value is higher than what I had in mind you could go further down

#

and if that middle value is lower than what I had in mind you could go further up

#

that is basically the binary search algorithm

umbral plaza
#

ohh data structure and algorithm is the way of solving a problem in aoptimized way

old rover
#

yes

umbral plaza
#

i see i will try it then

old rover
#

oh before you do that

#

you should learn what big O is

#

this is the easiest explanation of big O there is

#

I know people will disagree with me and say the math + theory is very important to know and what not

#

but this guy dumbs it down to very simple pieces so anyone can learn big O

#

Grokking Algorithms also does a great job too (imo)

umbral plaza
#

ohh

#

here is a thing i am really confused what to do next i am learning python but its really hard what to choose and do

old rover
#

do you know the basics

#

bc if you don't know the basics this will be very difficult

umbral plaza
#

i know the basics i learned web scrapping little ml and now i am looking at fast api

#

and i am filled with confusion what to do next cause i know only basic of those things how they actually works

austere salmon
#

I don't get why binary search is O(log n). I would expect it to be O(n/2^n), but does anyone know why it is O(log n)?

spring jasper
#

Because with every step you halve the space youre searching in
eg for an array of 128 items you would need up to 7 comparisons to find your item

half lotus
#

Because it halves the search space each iteration. If you take a look at the graph of the log function you'll see it matches the halving behaviour

spring jasper
#

With 1000 items it would take you 9.98 so 10 steps, this relationship is logarithmic with base 2

old rover
#

it's approximated

#

but it gives you a nice idea

#

2 to the 7 is somewhat close to 100

spring jasper
#

Its not an approximation, its ceil(log2(n))

old rover
#

what's ceil

#

the ceiling value

#

it just drops everything and keeps it at 0?

half lotus
#

It rounds up the decimal to the closest integer

old rover
#

oh

half lotus
#

Always rounds up, never down

#

Floor would be the opposite - rounding down

old rover
#

so if you had 2.9

#

it would round up to 3

spring jasper
#

Python equivalent is like int(n+1)

old rover
#

oh

#

ok

half lotus
#

That example is true if you assume n is not an integer

old rover
#

log 2 base 128 is 7

#

is the n in ceil(log2(n)) supposed to be 100?

#

oh ok

#

now I see

#

log 2 base 100 is like 6.6

#

so ceil would round it up to 7

fervent saddle
#

It lets you assign a variable to a value in an expression, and the value also gets used in the expression

#
ch = "a"
slices_from_ch = [
    s[ch_index:]
    if (ch_index := s.find(ch)) != -1
    else something_else
    for s in list_of_strings
]```
#

Without walrus here, you would have to call s.find twice. Once to check if the character was there, and again to find and use its index in the slice

#

Or I guess you could also define your own function and use that, but that also wouldn’t be as good

half lotus
low sun
#

alright, thank you

onyx root
#

I'm disappointed that in the video above, Nick White says the first reason we care about Big-O is because it comes up in interviews 😦

spring jasper
#

He's not wrong though

mint jewel
#

Most people will never write code at a scale where big O is meaningful, and of they do it's using a database which automatically optimizes anyway

feral solar
#

If you want to work at the top tier companies you absolutely need to understand computational complexity.

#

It's not just for interviews and the database can't always save you from yourself.

meager jetty
#

On the other side I saw people trying to optimize things and getting wrong results or losing so much time on unnecessary optimizations.... first thing to learn your program should gives the right results and after be really careful to what you want to optimize, use profiler and your brain ... (ex10gig of ram and faster cpu are nothing compare to losing data lol)

mint jewel
#

you can call the 3 arg form of the property constructor

feral solar
mint jewel
#

And make a function that builds it for a specific name

#

I am on phone and can't show code samples unfortunately, but yeah, you pass a getter, setter and deleter

low sun
#

would you find more ease using the __setattr__/__set_attribute__ and __getattr__/__get_attribute__ dunder methods?

#

not sure exactly what you'll be doing so I'm not sure if that would be of interest

mint jewel
#

Ye

fervent saddle
#

I’ve heard game developers have to worry about time complexity a lot. But maybe that’s untrue

mint jewel
#

@fervent saddle depends on the game. If you have a lot of things, yes

mint jewel
#

No, the getter is a function that takes self and returns an attribute

#

the getter builder needs to create such a function

#

Also, if you put an attribute with the same name as a property on the instance, it will stop the property from working

#

Generally you use ._attr

#

Oh, it didn't render

#

I see, that's right

#

Anyway, it should along the lines of lambda attr: lambda self: getattr(self, f'_{attr}')

mint jewel
old rover
#

@onyx root yeah I agree he could work on his phrasing a bit

#

it’s a pretty nice topic to know

onyx root
old rover
#

@onyx root yeah that whole algo expert io garbage

mint jewel
#

As far as I can tell, your getter takes the name of an attribute

#

Which is not what a getter should be doing. A getter takes self

old rover
#

Ned’s blog is also a pretty good source to learn big O too

#

he has one blog post about it

#

pretty well written

mint jewel
#

Yes

slim kestrel
#

hey im pre new and i got a question regarding tkinter

#

where can i get some help

lean dome
heavy cloak
#

confused

#

why is it invalid

#

nvm

heavy cloak
#

pluralize = lambda x: {i+"s" for i in x if x.count(i) > 1}

#

this doesnt work the way i want it to

#

is there any way

#

bruh

#

one sec wrong thing

#

pluralize = lambda x: {i+"s" for i in x if x.count(i) > 1 or i}

#

is there any way i can use or

#

to return i instead of i + s if the condition aint true?

#

??

#

i just need a yes or no

grizzled schooner
#

yes

#

if you want if/else in list comps you basically use a ternary

#

so thing if condition else other_thing

oblique panther
#

!warn 734499019962712154 Don't post random videos in our server.

halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied warning to @fiery cosmos.

unkempt umbra
#

does it basically guarantee linear complexity?

#

for string contain operation

#

or idk the work

#

in operator

eager hamlet
clever glen
#

Hey im a daytrader looking to start doing research on creations on trading algorithms i know a good amount of java but i cant find good resources to help me get to that level in python
any ideas

spring jasper
#

What level is that

#

!resources you can try your hand here and then pick up fluent python

halcyon plankBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

old rover
#

Is good amount of java supposed to imply that he knows ds/algorithms?

spring jasper
#

Apparently its for intermediate python users, not really sure what that means tho

clever glen
#

thanks

#

yeah like intermediate

#

I basicly know all variables

#

i dont know if thats still beginner though lmao

agile sundial
#

knowing variables is barely knowing a language

clever glen
#

It was more than that

#

But if i could give a percentage

#

Maybe like 25%?

unkempt umbra
#

i feel like trading algorithms should be closer to data science than computer science

radiant torrent
#

Quick question about the " += " operator:

Reversing a string:


 reversed = ""
    for char in st:
        reversed = char + reversed  # this works
        # reversed += char          # but why doesn't this work?
    return reversed
unkempt umbra
#

it should work

#

what error does it give

radiant torrent
#

Sure, just a sec

unkempt umbra
#

also i'd rename reversed since its the name of a builtin func but thats for another day

#

and also you can just do st[::-1] to get the reversed string but if this is just for learning purposes then ye its all good

#

(and also if this is for learning purposes, then this is quadratic time which ain't good)

radiant torrent
#

Thank you for the feedback. The code doesn't give an error, rather it doesn't carry out its function - it doesn't reverse the string when I use the " += " operator.

lean dome
#

a += b means a = a + b, not a = b + a

radiant torrent
#

Ahh, I see.

#

So the " += " operator wouldn't be appropriate in this case.

old rover
#

no I wouldn't consider variables 25% of a language

lean dome
#

It's pretty impossible to rate your own knowledge of anything objectively. Unknown unknowns.

clever glen
#

Obv i dont know alot

spring jasper
#

Do you know looping mechanisms, conditionals, recursion, classes, etc

clever glen
#

Yes

#

Im prob capped out there though

#

Thats like max

spring jasper
#

I'd say thats the basics of python tbh

clever glen
#

Yeah thats what i was thinking im like right after the basics

#

I mean that course was expensive i better have learned something 😂

spring jasper
#

The way you learn after all that is by making things and interacting with the internet and other people's code (packages)

#

For trading you wanna learn how to do http requests and how to manipulate dataframes

clever glen
#

Yeah ive been messing around with those concepts

#

I never learned it in java but i was able to call api’s

sharp vault
#

Anyone here who knows how to sort a list of dicts by the length of a key?
You can sort a list of strings by length first, then alphabetically second by doing this

directories.sort()
directories.sort(key=len)

and you can sort a list of dictionaries alphabetically by doing this

files = sorted(files, key=itemgetter('name'))

but I'm not sure how to sort a list of dictionaries by length of key first, then alphabetically second.
I'd appreciate any help 🙂

clever glen
#

Manipulate the dataframe i got from that

#

Pretty intresting stuff

#

Im sorry if i sound noobish anything that has to do with calling things from the internet is new territory for me

trim fiber
jolly mortar
#

if you don't have a pre-existing function which does that you could always make your own lambda with whatever logic you want

spring jasper
#

What does "sort a list of dicts alphabetically" mean

sharp vault
# trim fiber Can you write example input and expected output?
input = [
    {
        'name': '110000-119999.7z',
        'size': 500000000
    },
    {
        'name': '0-9999.7z',
        'size': 500000000
    },
    {
        'name': '20000-29999.7z',
        'size': 500000000
    },
    {
        'name': '100000-109999.7z',
        'size': 500000000
    },
    {
        'name': '50000-59999.7z',
        'size': 500000000
    }
]

output = [
    {
        'name': '0-9999.7z',
        'size': 500000000
    },
    {
        'name': '20000-29999.7z',
        'size': 500000000
    },
    {
        'name': '50000-59999.7z',
        'size': 500000000
    },
    {
        'name': '100000-109999.7z',
        'size': 500000000
    },
    {
        'name': '110000-119999.7z',
        'size': 500000000
    }
]
spring jasper
#

sorted(input, key=lambda d: d["name"])?

#

If you wanna sort by multiple keys afaik your lambda just needs to return a tuple

sharp vault
#

If I just use normal sort by key, 100000-109999.7z comes before 20000-29999.7z.

trim fiber
#
>>> input.sort(key=lambda entry: entry["name"])
>>> input
[{'name': '0-9999.7z', 'size': 500000000}, {'name': '100000-109999.7z', 'size': 500000000}, {'name': '110000-119999.7z', 'size': 500000000}, {'name': '20000-29999.7z', 'size': 500000000}, {'name': '50000-59999.7z', 'size': 500000000}]
>>> input.sort(key=lambda entry: len(entry["name"]))
>>> input
[{'name': '0-9999.7z', 'size': 500000000}, {'name': '20000-29999.7z', 'size': 500000000}, {'name': '50000-59999.7z', 'size': 500000000}, {'name': '100000-109999.7z', 'size': 500000000}, {'name': '110000-119999.7z', 'size': 500000000}]
spring jasper
#
sorted(input, key=lambda d: (len(d["name"]), d["name"]))```
Sorts by length of the value first, then lexicographically
dusk anchor
#

reversed += char does also work with the output h
he
hel
hell
hello

prisma jacinth
#

my anaconda gives an error:

#

are there any solutions for this

trim fiber
merry salmon
#

I have a function as a variable. How can I call that function with variables?

agile sundial
dusk anchor
trim fiber
pliant heath
#

Anyone knows of a data structure where i can efficiently find synonyms of words?
for example: [big, large, huge, giant]

i want to confirm that two sentences are equivalent

  1. this is a huge dog
  2. this is a giant dog
grizzled schooner
#

maybe a set

pliant heath
#

how do i index it?
Im trying to pass "huge" and get synonyms big, large, giant etc

grizzled schooner
#

you can’t index sets

#

sorry I’m not sure that I understand exactly what you’re trying to do

pliant heath
#

i want to confirm that two sentences are equivalent

  1. this is a huge dog
  2. this is a giant dog
grizzled schooner
#

ok

#

so if you have a set with synonyms for large/huge/etc

#

you can look up if something is in that set in constant time, so it’s faster than a list in this case

pliant heath
#

sure, but what if i need to store synonyms of every word in english ?

suppose i have 2 sets, one for synonyms of phone and one for large
how do i know what set to look into if i have to check the term "mobile" ?

#

i dont want to iterate through the entire collection of sets while checking the hashes

grizzled schooner
#

ah

#

I guess you could use a dictionary, like
big = {“huge”, “large”, etc}
d = {“large”: big}

nimble wasp
#

could anyone please how come this is valid? how does it work?

pliant heath
pliant heath
grizzled schooner
#

I’m pretty sure you need to either map every word to a set/category or iterate through every set and check for membership, so I’m not sure if there’s a better way

pliant heath
nimble wasp
#

@pliant heath got it. thanks a lot.

icy spruce
#

From Cracking the Coding Interview

Can somebody please explain why index - 1 at line 4 and not index + 1 at line 7. Also why return left; at line 27 and not return right;. Thank you.

Sorry if this is not Python related but I don't know a good discord channel to ask general computer science questions. Any good suggestions?

eager hamlet
main flower
#

So

#

Edge 3-5 is because in DFS you can see that you enter node 3 and then later you enter node 5 so there Has to be an edge 3-5

#

The same goes with edge 5-2

#

And the same thing with 5-6

eager hamlet
#

it goes 1 3 4 5

#

4 has no neighbors

#

so it goes back to 3

#

but if 35 didn't exist

#

it would go back to 1

#

which would go to 5

#

same thing

near wren
#

not sure how much numpy discussion happens here, but i'm looking into writing a branch cut algorithm (in terms of complex analysis) using probably something like A*

#

and I'm wondering if it could be generally useful (for now just working in f : R^2 -> C, so can be visualized in 3 dimensions)

#

context: i'm representing winding with sqrt(-1) on a riemann surface, which in this case represents winding around a periodic boundary (of a globe for this use case)

#

the branch cut will be useful in computing invariants on Gaussian Mixtures

#

so realistically this may go in scikit-learn

sly verge
#

I have a fun challenge. I need to generate all possible 9-number sets with numbers from 0-35 (e.g. [0,1,2,3,4,5,6,7,8], [27,28,29,30,31,32,33,34,35], and everything in between such as [0,15,19,20,24,25,,28,30,34]). These sets need to be stored in an array like this: [ [0,1,2,3,4,5,6,7,8] , [27,28,29,30,31,32,33,34,35] , [0,15,19,20,24,25,,28,30,34] , [many many more arrays] , [27,28,29,30,31,32,33,34,35] ].

#

Here comes the fun part

#

The arrays need to be generated (or later sorted) in such a way that if I slice the array from 0 to N, all 0-35 numbers appear relatively with the same frequency

mint jewel
#

sets as in no duplicates and unordered?

sly verge
#

yes

mint jewel
#

this is somewhat approaching the point where python is inconveniently slow, but if you are patient, it should be fine

#

(and have quite a bit of RAM, 94MM*9 ints is quite a bit of space in python)

#

other than that, I would expect ```py
import itertools
from random import shuffle
combs = list(itertools.combinations(range(36), 9))
shuffle(combs)

sly verge
#

That would take care of part Am right?

mint jewel
#

the shuffle should handle the frequencies too

sly verge
#

should I try this or my computer is gonna freeze?

mint jewel
#

didn't test it yet, since it takes quite some time on my slow CPU

#

it doesn't freeze as long as you don't only have a single core

#

but it will memoryerror unless you have 64bit python

sly verge
#

I should be fine then

#

NameError: name 'itertools' is not defined

mint jewel
#

ah, forgot the import

sly verge
#

it's running now

#

let's see how long it takes

mint jewel
#

I feel like I understimated how slow shuffling is, this may not finish within reasonable time

sly verge
#

it just finished

mint jewel
#

wow, still going for me

sly verge
#
94143280```
mint jewel
#

you can use ```py
import itertools
from collections import Counter
Counter(x for y in itertools.islice(combs, 10000) for x in y)

sly verge
#

thank you

#

it worked perfectly

#

but now that I see the results, I think this isn't what I actually needed lol

#

I mean is what I wanted but not what I needed

mint jewel
#

it happens

sly verge
#

actually, I think I figured out what I need. It is similar

#

I need 9-element lists with numbers 0-11 where numbers are not repeated and order matters. And I need to make sure that both numbers are sampled evenly, and that they are ordered evenly. This means that if I had as little as 30 of these lists, all numbers would appear a similar number of times, and they would also appear in the different indices of the arrays a similar number of times

mint jewel
#

both numbers?

sly verge
#

what do you mean?

mint jewel
#

make sure that both numbers are sampled
which numbers?

sly verge
#

I mean I need to make sure that both: a) numbers are sampled evenly (they show up with the same frequency across all lists); and b) they land uniformly across the different array indices

#

I was referring to making sure both conditions are satisfied

mint jewel
#

ah, I see

#

if you need it for small subsequences, shuffle won't work

#

most permutation algos I know of do gradual changes

#

there may be some specific reordering you could apply to the permutations from itertools.permutations that would make this work, but I don't know an actually good solution

sly verge
#

I will explore that. Thank you

eager hamlet
old rover
#

my question is pretty stupid

#

but is it also the same thing if that teal/blue color was the first color

#

and then the color to the left is the second color

#

it's basically the same thing

oblique panther
old rover
#

@oblique panther yeah it’s been a long day

oblique panther
#

see if you can code it lemonsaurus

old rover
#

Maybe tomorrow

#

classes are getting annoying

oblique panther
old rover
#

@oblique panther it really just looks like setting the head to null and going from there

#

head to none I mean

#

since none is null in python

oblique panther
lean dome
#

if you set the head to None, how can you go from there? You've lost your reference to the first node.

oblique panther
#

also if this is a singly linked list, that changes it a lot

old rover
#

🥴

#

Guess I don’t know then

#

I’ll find out tomorrow

agile sundial
#

how do you reverse a doubly linked list

#

just swap the head and tail pointers?

dapper sapphire
#

Actually, I never tried it. But what swapping makes sense.

half lotus
#

It's a doubly linked list so why wouldn't you have access to the tail?

#

Never mind... I confused the tail with the prev pointer

#

Yeah, I guess you could not have a tail but I always add one cause it's convenient

#

You could just go through the list to find the tail and then do the reverse

#

Wait do you even need the tail? I feel like I am being mislead by that msg

lean dome
half lotus
#

I think they meant swapping the prev/next pointers

agile sundial
#

ahh, no I'm wrong

#

you still have to change next and prev

lean dome
#

there's no need to have a tail pointer - you can reverse a linked list in one pass in O(N), which is basically as fast as you can ever do anything with a linked list

dapper sapphire
#
None <- head(0) <-> 1 <-> 2 <-> tail(3) -> None
eager hamlet
lean dome
#

The first one under "Constraints and notes"? Or under "Statement clarification"?

#

Nevermind, that's the same graph 😄

#

The edge 52 is needed because if it weren't there, the DFS would end in 562 instead of 526. I don't see why 53 and 56 are required, though.

#

Could be that there's multiple solutions for a given graph - seems like the BFS and DFS order would both be the same with or without 53 and 56. In both cases, it seems like there's no way to know whether we get to it by bubbling up the stack or not.

minor chasm
#

has anyone read graph algorithm book from neo4j?

sly verge
#

I am asking this again since the previous responses didn't help me solve my problem (in no small part because I didn't know what my problem was).

#

I need to create multiple arrays with 9 elements each. The arrays should be populated with a random selection from numbers 0 through 11, such that all numbers occur with the same frequency when taking all arrays together. Furthermore, for each number, its location across multiple arrays has to be uniform. For instance, number 4 should be roughly the same number of times on index 0, index 1, index 2 ... index 8. And the same for all numbers

#

What matters the most is that these arrays are all in a bigger array such that if I were to take the 40 first elements of the array (that is, 40 arrays with 9 random numbers 0-11 each) the two conditions above hold true, the same as if I selected the first 100 elements of the array

#

so basically, these arrays need to be created and appended to the bigger array already doing this from the start.

sly verge
#

I posted this question in a more clear way on stackoverflow in case someone wants to check it out

fiery cosmos
#

hey is anyone there

#
        """
        Swaps subtree A with subtree B

        :param subtree_a : Root of the subtree A.
        :param subtree_b : Root of the subtree B.

        Example:

            A
           / \
           B  C
         /   / \
        D   J   K

        SWAP(B, C)
            A
           / \
          C  B
         / |  \
        J  K   D

        SWAP(D, C)

            A
           / \
          D  B
              \
               C
              / \
             J   K
        """

#

couls someone help me with swapping of subtrees

trim fiber
fiery cosmos
#

i dont known how to start

#

I have build the basic tree and node

#
    def __init__(self, root: Node) -> None:
        """
        Initialises the tree with a root of type `Node` from `node.py`

        :param root: The root node of our tree.
        """

        self.root = root
#
    def __init__(self, colour: Colour) -> None:
        """
        Initialises the node with the required elements.

        :param colour: The colour of the node.
        """
        self.colour = colour
        self.parent = None
        self.children = []
        self.propagated_colour = colour
#

@trim fiber

trim fiber
fiery cosmos
#

Yeah as you can see in th constructor of node it contains a list of children

trim fiber
#

So do you have method which adds a child?

fiery cosmos
#
    def put(self, parent: Node, child: Node) -> None:
        """
        Inserts a node into the tree.
        Adds `child` to `parent`.

        :param parent: The parent node currently in the tree.
        :param child: The child to add to the tree.
        """
        # TODO implement me please.
        parent.add_child(child)
trim fiber
fiery cosmos
#
    def add_child(self, child_node: 'Node') -> None:
        """
        Adds a child node to the list of children of this node.
        (HINT) this should also perform some _things_.
        :param child_node: The pointer to the child node to add to children.
        """
        self.children.append(child_node)
#

@trim fiber I will change it

#

could you help me with swapping of the subtrees

trim fiber
#

Okay, so when you want to swap values you just can put

x = "x"
y = "y"
print(f"x = {x}, y = {y}")
x, y = y, x
print(f"x = {x}, y = {y}")
#

!e

x = "x"
y = "y"
print(f"x = {x}, y = {y}")
x, y = y, x
print(f"x = {x}, y = {y}")
halcyon plankBOT
#

@trim fiber :white_check_mark: Your eval job has completed with return code 0.

001 | x = x, y = y
002 | x = y, y = x
trim fiber
#

As you can see we can easily swap values in one line

#

Right?

#

@fiery cosmos

fiery cosmos
#

but would it swap the subtree as well

trim fiber
#

Oh, just image that you have subtree x and y, then

x.children, y.children = y.children, x.children
trim fiber
fiery cosmos
#

subtree_a.children,subtree_b.children=subtree_b.children,subtree_a.children

#

I tried this didnt work

#

@trim fiber

fiery cosmos
#

it didnt pass the test case

trim fiber
#

Because we need to update position in parents

#

Can you do it on your own?

fiery cosmos
#

what parents how do i go from child to parent

#

@trim fiber are u there

trim fiber
#

Each node has .parent property, right?

fiery cosmos
#

yeah got it now

#
  x=subtree_a.parent
  y=subtree_b.parent
  subtree_a,subtree_b=subtree_b,subtree_a
  x.children=subtree_a
  y.children=subtree_b
#

is this correct @trim fiber

trim fiber
fiery cosmos
#

how

#

my code is not working

#

subtree_a.parent.children,subtree_b.parent.children=subtree_b.parent.children,subtree_a.parent.children

#

this is not working either

trim fiber
#

!e

x = ['a', 'b', 'c', 'd']
print("before", x)
b = x.index('b')
d = x.index('d')
del x[b]
x.insert(b, 'd')
del x[d]
x.insert(d, 'b')
print("after swap", x)
halcyon plankBOT
#

@trim fiber :white_check_mark: Your eval job has completed with return code 0.

001 | before ['a', 'b', 'c', 'd']
002 | after swap ['a', 'd', 'c', 'b']
trim fiber
#

Just a quick demo

fiery cosmos
#

but here we are swapping between two different list sometimes as well

#

SWAP(D, C)

        A
       / \
      D  B
          \
           C
          / \
         J   K
trim fiber
#

When you use node.parent.children you can swap objects between different lists

fiery cosmos
#

I just did that it didnt work

trim fiber
fiery cosmos
#
subtree_a.parent.children,subtree_b.parent.children=subtree_b.parent.children,subtree_a.parent.children
trim fiber
fiery cosmos
#

why do I have to use .insert

trim fiber
#

Because you need to update position of one child, not every

fiery cosmos
#

could you please show me the code i am confused

#

the list of children is an unorderd list anyway

trim fiber
fiery cosmos
#

okay

spring jasper
#

whats the height of this tree, i think im losing my mind

agile sundial
#

3

#

or 4

#

probably 3

spring jasper
#

is this not the proper algorithm for the height of a tree

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

this gives 4

#

hackerrank having me pull out my hair

lean dome
#

It should be 3, not 4. The height is defined to be the maximum number of edges you must traverse to get from a leaf node up to the root

#

7-6, 6-5, 5-3 is 3 total edges, for a height of 3

spring jasper
#

that doesnt make sense, why does a tree of 1 node have height 0

#

thats like a list of 1 element having length 0

lean dome
#

Math, man.

spring jasper
#

smh not like this

#

tree stubs get no love

lean dome
#

One could argue that a tree with no edges is zero dimensional, like a point, and therefore has no height

austere sparrow
#

@spring jasper log2(1) = 0 🙂

fiery cosmos
#
  def swap(self, subtree_a: Node, subtree_b: Node) -> None:
        """
        Swaps subtree A with subtree B

        :param subtree_a : Root of the subtree A.
        :param subtree_b : Root of the subtree B.

        Example:

            A
           / \
           B  C
         /   / \
        D   J   K

        SWAP(B, C)
            A
           / \
          C  B
         / |  \
        J  K   D

        SWAP(D, C)

            A
           / \
          D  B
              \
               C
              / \
             J   K
        """
#

could someonehelp me with this

trim fiber
fiery cosmos
#

seems ez to me. find given nodes, swap children.

#

wow they literally given subtree as well.

#

just replace children

trim fiber
slow sorrel
#

Can I ask for questions on here? or is this taken

trim fiber
fiery cosmos
#

Yeah

#

I tried this

#

if the subtree_a.parent==subtree_b.parent

#

then I would use the index one you gave me

#

otherwise

#

@trim fiber are u there

#

hello is anyone there

trim fiber
#

Could you explain what have you tried? How it works?

nocturne summit
#

new here so i dont know if im asking in the right place, but does anyone know how to determine the complexity (big o notation) for a comb sort algorithm? both time and space

#

i know what they are, but not how to prove

vocal gorge
# nocturne summit new here so i dont know if im asking in the right place, but does anyone know ho...

The basic answer for that is always "examine the source code to figure out how many operations and how much extra memory it uses depending on the input".
For comb sort specifically, the inner loop is O(n), and it is run at worst something like O(n) times much like in bubble sort, so O(n^2). The in-place implementation of bubble sort doesn't make any lists or something, so it just uses O(1) extra memory.

#

(the most complicated part of a formal proof would be proving the outer loop runs O(n) times in the worst case)

nocturne summit
#

but how do i determine that the loops run O(n) times ?

vocal gorge
#

the inner loop runs length - gap times, which is length (1 - 1/shrink_rate), which is O(length)

nocturne summit
#

and the outer loop?

glossy mulch
#

i'm having a bit of trouble with python <classes>.
inherited methods keep using inherited variables even if the variables were redefined in child classes, and i don't want to just redefine the method for every child class when they all use identical structures.

vocal gorge
glossy mulch
#

i thought so

#

actually: reviewing the code i notice in the one and only child class i was testing, i had forgotten to redefine the variable.

#

why was it literally just that one class i forgot

calm spade
#

So i am making this rpg thing and i want to implement a fighting system. I want it to be based on the player's health, armor, strength, and his opponents health & strength. How do i do that?

vocal gorge
calm spade
#

My problem is with how do i calculate it

#

Like how do i calculate if the player hit or didnt or how much health he lost n stuff

vocal gorge
#

That's still part of game development - you're deciding what mechanics to use.

calm spade
#

Makes sense

#

Alr ty

fiery cosmos
#

hey could anyone help me with this problem

heavy cloak
#

confused why this is invalid

trim fiber
vocal gorge
#

the syntax is definitely invalid. For one, you have for i in x twice.

trim fiber
vocal gorge
#

so what this does is:

  1. if the string is fully uppercase, it lowercases it.
  2. Otherwise, returns unchanged, even if it's lIkEtHaT
trim fiber
vocal gorge
#

of course, it might not be what was intended, but switching it to just lower would change the behaviour.

trim fiber
#

Right, I assumed that i is always a character

vocal gorge
#

ah, good point, then yeah

trim fiber
#

Then it can be "".join(map(str.lower, x))

agile sundial
#

or just x.lower() ?

trim fiber
#

I am always overcomplicate everything

astral current
#

yo guys,

#

can someone help me?

#

i am using pycharm for python and trying turtle but when i execute the code it runs but it doesnt open the turtle screen

astral current
#
import turtle

turtle.forward(5)```
trim fiber
astral current
#

i have to do this line at the end of my code and everything runs fine

#

right!?

#

why does it just work on the Python IDE

#

but not in pycharm

#

:T

#

anyway thanks

#

?close

fallow ginkgoBOT
#

This is not a Modmail thread.

astral current
#

how to close?

trim fiber
#

No need to close

astral current
#

oo

#

ok

trim fiber
#

It's topical chat

astral current
#

ty

#

:))

trim fiber
#

When you acquire help channel then you should close 😉

astral current
#

can you also modify the short cuts?

#

in pycharm

#

like to run the file press f5

#

instead of shift f10

trim fiber
astral current
#

ok thanks

#

🙂

trim fiber
#

Visit this chat and ask them about it 😉

old rover
#

I have made the executive decision to watch Schafer talk about OOP before continuing further w leetcode

#

at least I'll have a stronger foundation of OOP to tackle all these ds/algos questions

golden moat
#

is there a functional-style group-by in python?

trim fiber
#

!docs functools.reduce

halcyon plankBOT
#
functools.reduce(function, iterable[, initializer])```
Apply *function* of two arguments cumulatively to the items of *iterable*, from left to right, so as to reduce the iterable to a single value. For example, `reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])` calculates `((((1+2)+3)+4)+5)`. The left argument, *x*, is the accumulated value and the right argument, *y*, is the update value from the *iterable*. If the optional *initializer* is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If *initializer* is not given and *iterable* contains only one item, the first item is returned.

Roughly equivalent to:... [read more](https://docs.python.org/3/library/functools.html#functools.reduce)
trim fiber
#

Something like that?

golden moat
#

yeah.. I wanted to build it with foldl initially

#

I just can't get my mind behind the concept

#

my input is something 'simple' like [3, 100, "and", 8, 1000] and I want to return [[3, 100], [8, 1000]]

trim fiber
#

!e

def reducer(aggregated, element):
  if element == "and":
    aggregated.append([])
  else:
    if len(aggregated) == 0:
      aggregated.append([])
    aggregated[-1].append(element)

import functools
print(functools.reduce(reducer, [3, 100, "and", 8, 1000], []))
#

Hmm

trim fiber
halcyon plankBOT
#

@trim fiber :white_check_mark: Your eval job has completed with return code 0.

[[3, 100], [8, 1000]]
trim fiber
#

However this function looks awful

golden moat
#

[*map(lambda x: ([*map(int, x)]) , list(map(str.split, ' '.join(map(str, [3, 100, "and", 8, 1000])).split("and"))) )] as does my approach

trim fiber
#

Do you want to find one-line solution?

golden moat
#

somewhat

#

I wanted something subjectively more beautiful

#

I mean your function is at least readable

#

which is good

old rover
#

whoms't

#

why is Schafer covering getters and setters in Python

#

🥴

#

I thought that was unpythonic

agile sundial
#

explicit getValue and setValue are unpythonic

#

there is a pythonic way to do it, property

#

he might just be going over that to say "don't do this"

old rover
#

what's the difference between an instance variable

#

and an attribute

#
class Employee:
  pass

emp1 = Employee()
emp2 = Employee()
print(emp1)
print(emp2)

emp1.first = "Corey"
emp1.last = "Schafer"
emp1.email = "Corey.Schafer@company.com"
emp1.pay = "50000"

#

would first, last, email, and pay be instance variables?

#

ELI5: Self is like the temporary name they give you at the hospital before your parents give you a name. For example, they'd call you "Baby Boy Smith" until your parents are ready to give you a name, and then everything associated with "Baby Boy Smith" is now you. All babies have this temporary name when they're first created, but then they're given different names to differentiate them.

#

I like this explanation

agile sundial
#

is that talking about the self parameter?

old rover
#

yes

#

in the def init function

spring jasper
#

You can use itertools.groupby for that so why not

agile sundial
#

mmmm, sure, but self is used in other places too. i don't think that explanation is adequate.

spring jasper
#
from itertools import groupby

l = [8, 300, "and", 5, 1000]

print([list(k) for g,  k in groupby(l, key=lambda x: isinstance(x, int)) if g])
# [[8, 300],[5, 1000]]
spring jasper
#

You can probably fix that lambda up too

old rover
#

Schafer doesn't really go over what self is much either

#
class Employee:
  def __init__(self,first,last,pay):
    self.first = first
    self.last = last
    self.pay = pay
    self.email = first + "." + last + "@company.com"

emp1 = Employee()
emp1.first = "Corey"
emp1.last = "Schafer"
emp1.email = "Corey.Schafer@company.com"
emp1.pay = "50000"

#

he said you can do this whole .first, .last, .email, and .pay after

#

but you would have to do it for every instance of the class

#

it's better practice to use the init so you write less code

agile sundial
#

yeah

#

it's just like using a function, you get to reuse code

old rover
#

that's good then

#

I kind of knew that already

#

but this is helping me clear up my doubts

old rover
#

I only wish corey did data structures/algos

#

seems like he avoids it like the plague

spring jasper
#

Because theyre not that important

fiery cosmos
#

I wanna propagate colour in a subtree

#

like for example

#
   Y
  / \
 C   G
  \   \
  R    Y
#
Will produce the propagations:

   R
  / \
 R   G
  \   \
  R    Y
#

The tree contains a colour propagation, based on the hierarchy:

RED (R)

GREEN (G)

BLUE (B)

CYAN (C)

YELLOW (Y)

#

how do I do that

vernal otter
#

how do i make a unmute command

willow meteor
#

what data structure would you use for a dict except it has multiple keys for a value?

#

what i'm thinking of is either a tuple as the key - but it would be a pita to loop through everything to check

spring jasper
#

Dicts can already take tuples as keys

trim fiber
#

Yep

#

Everything which has __hash__ method

#

As far as I know

willow meteor
#

or i could have an index dictionary, so let's say I have this data: {(1,2,3):"small numbers",(4,5,6):"bigger numbers"}, i could do {0:"small numbers",1:"bigger numbers"} and a {1:0,2:0,3:0,4:1,5:1,6:1}

willow meteor
#

is there a better alternative to either of the above solutions?

spring jasper
#

Why would you loop through it to check if a key exists

trim fiber
willow meteor
#

so i want to be able to use 1 to get "small numbers"

#

(1,2,3) is a tuple, but i won't be able to use in in the key unless i loop it all

spring jasper
#

Why not

{
   "small": [1,2,3],
   "big": [4,5,6]
}
willow meteor
#

how would i access "small" if i have 2?

spring jasper
#

Oh, my b misunderstood

#

You could just have each number be a key

#

You dont have to put them in a tuple

willow meteor
#

thanks either way :))

spring jasper
#

Why is it more worth

willow meteor
#

file size and also i want to be able to modify the value easier

spring jasper
#

That means you gotta loop over the keys and then loop over the items in the tuple

#

It sounds like O(keys * key_size)

willow meteor
#

with the index approach, i only need to change 1 value; if stored seperately, i would need to make a code whenever i need to change it

#

to loop over everything and change them

spring jasper
#

What are you trying to do exactly

willow meteor
#

a "translator" between user input shorthand to longhand. there are many ways the user can enter something which aren't logically connected

golden moat
#

@spring jasper thanks for posting the itertools solution, I'm not too familiar with itertools, but expected that groupby could do exactly what I wanted

fiery cosmos
#

how do i remove a child from its parent and entire

#

tree

#
    def __init__(self, root: Node) -> None:
        """
        Initialises the tree with a root of type `Node` from `node.py`

        :param root: The root node of our tree.
        """

        self.root = root
#
    def __init__(self, colour: Colour) -> None:
        """
        Initialises the node with the required elements.

        :param colour: The colour of the node.
        """
        self.colour = colour
        self.parent = None
        self.children = []
        self.propagated_colour = colour
#
    def remove_child(self, child_node: 'Node') -> None:
        """
        Removes the child from the list of children.
        NOTE: You don't have to worry about adding the subtree of this node to
        the children, we are removing this child_node and all its subtree from
        existence.
        :param child_node: The pointer to the child node to remove.
        """
        self.children.remove(child_node)
#
    def rm(self, child: Node) -> None:
        """
        Removes child from parent.

        :param child: The child node to remove.
        """
        # TODO implement me please.
        self.remove_child(child)
trim fiber
fiery cosmos
#

why would I use reciderion I already have the node I wanna remove

#

t.rm(b)
File "/home/tree.py", line 101, in rm
self.remove_child(child)
AttributeError: 'Tree' object has no attribute 'remove_child'

trim fiber
#
from dataclasses import dataclass, field
from typing import List
@dataclass
class X:
  children: List = field(default_factory=list)

  def add_child(self, child):
    if child not in self.children:
      self.children.append(child)

  def remove_child(self, child):
    if child in self.children:
      self.children.remove(child)
    else:
      for _child in self.children:
        _child.remove_child(child)
fiery cosmos
#

No take a look at the whole code there are two class Node and Tree

#

@trim fiber

halcyon plankBOT
#

Hey @fiery cosmos!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

trim fiber
#

Or just write that this method is for this class

fiery cosmos
#

this one is the tree class

#

this one is node class

trim fiber
#

You are trying to call .remove_child method on Tree object

fiery cosmos
#

yeah

trim fiber
#

Tree object doesn't have .remove_child method, right?

fiery cosmos
#

I tries parent as well

trim fiber
#

However root property has

fiery cosmos
#

why does it have self in the method then

trim fiber
#

To use self.root?

fiery cosmos
#

okay

trim fiber
#

You need to take tree's root and remove its child

fiery cosmos
#

Traceback (most recent call last):
File "/home/tests/test_sample_tree.py", line 124, in test_can_rm
t.rm(b)
File "/home/tree.py", line 102, in rm
my_parent.remove_child(child)
AttributeError: 'NoneType' object has no attribute 'remove_child'

#
    def rm(self, child: Node) -> None:
        """
        Removes child from parent.

        :param child: The child node to remove.
        """
        # TODO implement me please.
        my_parent=child.parent
        my_parent.remove_child(child)
trim fiber
#

It seems that your child has no parent

fiery cosmos
#

Yeah why is that

trim fiber
#

Idk, someone tries to test how your code works with bad data

#

Bad = invalid

#

So maybe add some checks against that

#

Like if my_parent is not None:

fiery cosmos
#
 def test_can_rm(self):
        """
        Can we remove a child?
        """

        root = Node(Colours.CYAN)

        t = Tree(root)

        a = Node(Colours.GREEN)
        b = Node(Colours.RED)

        t.put(root, a)
        t.put(root, b)

        assert len(root.children) == 2

        t.rm(b)

        assert len(root.children) == 1, \
            "[tree.rm] did not remove the node."

        assert b not in root.children, \
            "[tree.rm] did not remove the correct child."

#

This is what I am testing it

#

with

trim fiber
#

Okay, however I don't see any update of parent property in Node.add_child method

#

You should add there something like child_node.parent = ...

fiery cosmos
#

= what

trim fiber
#

What is the parent for this child?

#

I am trying to give you my support, not the solution pithink

fiery cosmos
#
 def put(self, parent: Node, child: Node) -> None:
        """
        Inserts a node into the tree.
        Adds `child` to `parent`.

        :param parent: The parent node currently in the tree.
        :param child: The child to add to the tree.
        """
        # TODO implement me please.
        parent.add_child(child)
#

how do I put the parent into the tree

trim fiber
#

As far as I understand your parent must be already in the tree

#

:param parent: The parent node currently in the tree.

fiery cosmos
#

oh okay so you were asking me to make some changes in this part of code

trim fiber
#

For me this method should check that parent is really inside a tree, however it looks okay

#

I see the problem here

class Node:
    ...

    def add_child(self, child_node: 'Node') -> None:
        """
        Adds a child node to the list of children of this node.
        (HINT) this should also perform some _things_.
        :param child_node: The pointer to the child node to add to children.
        """
        self.children.append(child_node)

    ...
fiery cosmos
#

how do I set the parent of this child

trim fiber
#

child_node.parent = ...

#

Right?

fiery cosmos
#

Yeah but to what I do not have the parent node

trim fiber
#

What you put instead of dots ...?

#

If child_node is a child for self then what is self for child_node?

fiery cosmos
#

child_node.parent=self

trim fiber
#

Right, looks okay

fiery cosmos
#

@trim fiber the one that I asked you yesterday about swapping

#
        parent_a=subtree_a.parent
        parent_b=subtree_b.parent
        if parent_a is None or parent_b is None:
            return
        parent_a.children[parent_a.children.index(subtree_a)]=subtree_b
        parent_b.children[parent_b.children.index(subtree_b)]=subtree_a
#

I tried this

fiery cosmos
#

Traceback (most recent call last):
File "/home/tests/test_sample_tree.py", line 184, in test_can_swap_example
assert D.parent == A,
AssertionError: [tree.swap] Did not change parent.

trim fiber
#

Can you paste the test case?

fiery cosmos
#

yup

trim fiber
#

Excelent!

fiery cosmos
#
def test_can_swap_example(self):
        """
        Can you perform the swap in the comments?
        """

        A = Node(Colours.GREEN)

        B = Node(Colours.RED)
        C = Node(Colours.BLUE)

        D = Node(Colours.CYAN)
        J = Node(Colours.CYAN)
        K = Node(Colours.YELLOW)

        t = Tree(A)

        t.put(A, B)
        t.put(A, C)
        t.put(B, D)
        t.put(C, J)
        t.put(C, K)

        # Let's swap
        t.swap(D, C)

        # Let's check if it worked!
        assert D.parent == A, \
            "[tree.swap] Did not change parent."

        assert C.parent == B, \
            "[tree.swap] Did not change parent."

        assert D not in B.children, \
            "[tree.swap] Did not remove child from old parent."

        assert C not in A.children, \
            "[tree.swap] Did not remove child from old parent."

        assert C in B.children, \
            "[tree.swap] child incorrectly swapped to children list."

        assert D in A.children, \
            "[tree.swap] child incorrectly swapped to children list."
fiery cosmos
#

cool

trim fiber
#

Okay, first of all I don't see any updates on subtree.parent

#

Like subtree_b.parent = ...

#

Right?

fiery cosmos
#

yeah

#

s.9ov4rv4

#

sorrsorry my computer is havin some problems

trim fiber
fiery cosmos
#

so do I need to make these changes before or after I swap subteers

#

@trim fiber

trim fiber
fiery cosmos
#
 def update_node_colour(self, n: Node, new_colour: Colour) -> None:
        """
        Update the colour of a node.

        :param n: The nod e to change the colour of.
        :param new_colour: The new colour to change to.
        """
        # Call update_colour() on the node
        # TODO implement me please.
        n.update_colour(new_colour)
        if n.is_external()==True and n.parent!=None:
            while n.parent!=None:
                x=n
                n=n.parent
                t=Colour.cmp(x.propagated_colour,n.propagated_colour)
                if t==-1 :
                    n.propagated_colour=x.propagated_colour
                else:
                    pass
        else:
            pass
tropic sandal
#

I have a problem

print("hy)
#

C:\Users\DELL\Documents\Programme\python\venv\Scripts\python.exe C:/Users/DELL/Documents/Programme/python/etst.py
File "C:/Users/DELL/Documents/Programme/python/etst.py", line 1
print("hy)
^
SyntaxError: EOL while scanning string literal

Process finished with exit code 1

#

Idk why that dosen't work

#

If someone can help me

vocal gorge
old rover
lucid totem
#

ah, sorry

fiery cosmos
#

hey could someone help me with this problem

old rover
#

uh what’s the problem

fiery cosmos
#

HEY GUYS

#

umm

#

does anybody know how to do a binary search in Java or Python

#

@uneven geyser were u da one doing the guitar on the python discord lmao

stable lynx
#

pls help ^^^
-----BASIC MATH QUESTION----

also mine below
i have a rectangle that is recursivley being broken down into quadrants of 4 whereby each new quadrant has values X1,Y1,X2,Y2 (top left, bottom right) my math is so far working out to this below:

    NW = Rectangle(x1,                       y1,                          (x1 + x2)/2,                  (y1 + y2)/2)
    NE = Rectangle((x1 + x2)/2,           y1,                          x1 + x2,                       (y1 + y2)/2)
    SW = Rectangle(x1,                       (y1 + y2)/2,            (x1 + x2)/2,                   y1 + y2)
    SE = Rectangle((x1 + x2)/2,           (y1 + y2)/2,            x1 + x2,                        y1 + y2)

i did a test run in intellij debugger and my bad math is working out to:

              X1       X2      Y1      Y2

ROOT = 0 200 0 200
NE = 100 200 0 100 - GOOD
NE = 150 300 0 50 - BOTTOM RIGHT WRONG

in each rectangle what is the proper math for X1,Y1,X2,Y2 ? + pls msge me with a response so i see it

frank osprey
#

Hii could someone here help me with drawing an AVL tree /binary serach tree by hand?

#

Is this correct?

uneven jungle
#

@frank osprey looks right

frank osprey
uneven jungle
#

or wait

#

let me check first one...

#

yes, it should be ok. was hesitant on the root but it's a weighted so it has to be switched like this

frank osprey
#

okk great! Is the second one correct too?

uneven jungle
#

aren't only the leaves supposed to be annotated with 0?

frank osprey
#

I don't know, in the short example in class I saw the root was also annotated with zero when necessary...

#

(or parents)

frank osprey
# uneven jungle aren't only the leaves supposed to be annotated with 0?

now I am starting to think that it might not be correct... in class (the prof didn't explain us much about the rotations though) I think we rotated the nodes that weren't annotated with zero, if that makes any sense, so the root would change more and the newly added node would usually stay where it was added. From the resources I found online, well I used them for doing this problem and I had to make the rotations using the newly added node... idk

#

@uneven jungle

frank osprey
#

it might be this instead

fiery cosmos
#

hey could some helpme with this update_colour problem

#
    def update_colour(self, colour: Colour) -> None:
        """
        Updates the colour of the node.
        (HINT) if we don't give a colour, you shouldn't update it.
        :param colour: The new colour to set the node.
        """
        if colour is not None:
            self.colour=colour
            if Colour.cmp(colour,self.propagated_colour)==1:
                self.propagated_colour=colour
            else:
                pass
#
  def update_node_colour(self, n: Node, new_colour: Colour) -> None:
        """
        Update the colour of a node.

        :param n: The nod e to change the colour of.
        :param new_colour: The new colour to change to.
        """
        # Call update_colour() on the node
        # TODO implement me please.
        n.update_colour(new_colour)
        if n.is_external()==True:
            x=n
            while n.parent!=None:
                t=Colour.cmp(x.propagated_colour,n.propagated_colour)
                if t==1 :
                    n.propagated_colour=x.propagated_colour
                n=n.parent
#
   def test_update_colour_propagates(self):
        """
        Does the colour propagate when changed?
        """

        root = Node(Colours.CYAN)

        t = Tree(root)
        a = Node(Colours.BLUE)

        t.put(root, a)
        t.put(a, Node(Colours.RED))

        # It should now be red!
        assert Colours.RED.cmp(root.propagated_colour) == 0, \
            "[propagate] Your colour didn't propagate correctly."

        assert Colours.RED.cmp(a.propagated_colour) == 0, \
            "[propagate] Your colour didn't propagate correctly."

        t.update_node_colour(a.children[0], Colours.NYAN)

        assert Colours.NYAN.cmp(root.propagated_colour) == 0, \
            "[propagate] Your colour didn't propagate correctly."

        assert Colours.NYAN.cmp(a.propagated_colour) == 0, \
            "[propagate] Your colour didn't propagate correctly."
#

I am testing it against this

#

its failing this one

#
        assert Colours.NYAN.cmp(root.propagated_colour) == 0, \
            "[propagate] Your colour didn't propagate correctly."
grizzled roost
icy spruce
#

how likely will self-balancing trees and Dijkstra/A* come up on technical interviews?

fiery cosmos
#

what would a game bot that logs in on seperate proxies be considered under (channel wise)

#

For a website

old rover
#

only problem is that I didn't know it at the time

#

so I got screwed 🥴

icy spruce
#

which one did they ask?

old rover
#

I blame myself about it 🥴

vocal gorge
#

that's for dijkstra, it's pretty nice

main flower
#

Yeah

fluid swift
unique pecan
#

hey

#

How can I check if a string is within a response.get contents?

#
import requests
xxx = "xxx"
response = requests.get(str(xxx))
if xxx not in str(response.content):
    print("Fail!")
else:
    print("Success!")
#

What am I doing wrong?

fluid swift
unique pecan
#

Ohhhh

fluid swift
#

like

#

colorful

#

idk

unique pecan
#

^

fluid swift
#

hmmmm

#

thx

unique pecan
#

np

sudden rover
#

are linked lists slower than normal lists?

old rover
#

depends how you use them

spring jasper
#

As godlygeek said yes generally they are

old rover
#

if you need to insert a bunch of nodes very quickly into a data structure

#

linked lists are a good option

#

bc they're O(1) for insertion

spring jasper
#

They're O(1) near the edges

old rover
#

oh yeah

spring jasper
#

Not in the middle

old rover
#

yes

#

I should have said that

#

my bad

lean dome
#

And regular Python lists - dynamic arrays - are O(1) at one end, and O(N) at the other.

#

But for typical usage patterns, linked lists are one of the worst data structures, performance wise. A list, deque, or balanced tree is almost always a better choice

old rover
#

interviewers ask linked list questions bc they're easy

spring jasper
#

You should learn linked lists anyway

old rover
#

yes

#

they're a good intro to ds/algos

fiery cosmos
#

how do I do this one'

#
The tree contains a colour propagation, based on the hierarchy:

1. RED (R)
2. GREEN (G)
3. BLUE (B)
4. CYAN (C)
5. YELLOW (Y)

With **RED** being the strongest colour.

The tree:

Y
/
C G
\
R Y


Will produce the propagations:

R
/
R G
\
R Y

half crescent
#

Hi, I'm looking to do a reinforcement learning online course. I am doing this as a refresher. I am having trouble picking one because there are so many and they're all packed with sexy buzz words! I want a sound one which isn't for beginners and covers the general stuff and more! Any suggestions?

old rover
#

sexy buzz words 🥴

#

if you're asking about reinforcement learning in ML you might be better off asking in #data-science-and-ml

fiery cosmos
#

how do i recusre through a tree of given depth and starting point

spring jasper
#

Recurse which way

#

Thats incredibly vague

fervent saddle
#

Why does Python maintain insertion order in dictionaries by using a second array instead of doing a linked list kind of thing like Java does with LinkedHashMap? Do both ways have different strengths and weaknesses?

lean dome
#

They do. Python still has the linked list approach in the form of collections.OrderedDict - and the docs for it give some examples of places where it performs better

lean dome
arctic veldt
#

my problem is i have 24-bit color data (let's say a numpy uint8 array of [R, G, B] elements) and want to reduce it to 8-bit color data (uint8 array of RRRGGGBB), there's no clear way to do this with numpy without running a Python function over each element which is slow. any ideas besides mixing in some native speedups?

fervent saddle
#

Okay, that makes sense about the table rebuilds. And when is the 2 array version better? Is it faster for iteration since you’re accessing memory consecutively, while the linked list version jumps around from node to node?

#

And are there other major reasons besides that one?

lean dome
fervent saddle
#

Alright, thanks for finding that, I’ll read it

lean dome
#

To be clear - dict never used linked lists. dict has always used "open addressing" to handle hash collisions, rather than a linked list of collided key/value pairs. Previously it had a single sparse array maintained that didn't preserve insertion order. Later it got the two array approach, which preserves insertion order as a side effect, but is primarily beneficial because it's smaller and faster.

#

And later still the language changed to guarantee that the side effect of preserving insertion order was here to stay.

fervent saddle
#

collections.OrderedDict uses closed addressing?

#

Shouldn’t it be possible to do this with open addressing?

lean dome
#

No, it doesn't. It uses a linked list only to preserve the relative order of different keys

#

An ordered dict just holds a dict plus a linked list, and maintains them in sync with each other

#

Insertions insert to both, deletions delete from both, and the reordering operations only affect the linked list. Then, it iterates over key/value pairs in the dict in the order those keys appear in the linked list

fervent saddle
#

Alright, that makes sense. But one last thing is how does using 2 arrays save memory? It seems like it would take up more memory since it’s storing everything it did before, but also anther array which holds the indexes

#

Or do you mean that it saves memory over OrderedDict, not normal pre-3.6 dict?

lean dome
#

No, it saves memory over the normal, pre-3.6 dict. The old version had a big array of big elements, the new version has a small array of big elements, plus a big array of small elements.

fervent saddle
#

Because the hashed into array is just holding regular C number values instead of python objects?

lean dome
#

Well, instead of C pointers to objects, yeah

#

IIUC, in the old implementation, the big sparse array contained both a pointer to a key and a pointer to a value, which takes 16 bytes on a 64 bit system (8 bytes per pointer). Plus some metadata indicating whether the element has ever been used, which needs to take up another 8 bytes on a 64 bit system due to alignment requirements, for 24 bytes total per element in the big sparse array. At least - I may be missing something, but at least those 3 things are required.
In the new implementation, the big array holds only a single 64 bit number, so 8 bytes per element instead.

fervent saddle
#

Ok. And the array of large values only needs to over allocate enough to have amortized O(1) instead of enough to mitigate hash collision good enough, and that’s what makes the whole thing end up saving memory?

lean dome
#

Right, yep.

fervent saddle
#

Alright, I think everything makes sense now. Thanks for the help

fiery cosmos
#

    def is_coloured_to_depth_k(self, start_node: Node, colour: Colour, k: int) -> bool:
        """
        Checks whether all nodes in the subtree (up and including level `k`
            starting from the start node) have the same colour!

        (This checks node.colour)

        :param start_node : The node to start checking.
        :param colour: The colour to compare a node's colour to.
        :param k: The depth we should check until.

        === Examples ===

        (start)---> G
                   / \
                  G   G
                 /|   |
                G R   G
                  |
                  R

        is_coloured_to_depth_k(start, Colour.GREEN, 0) => True
        is_coloured_to_depth_k(start, Colour.RED, 0) => False
        is_coloured_to_depth_k(start, Colour.GREEN, 1) => True
        is_coloured_to_depth_k(start, Colour.GREEN, 2) => False
        """
#

could some one helpme in implementing this

#
  def __init__(self, colour: Colour) -> None:
        """
        Initialises the node with the required elements.

        :param colour: The colour of the node.
        """
        self.colour = colour
        self.parent = None
        self.children = []
        self.propagated_colour = colour
#

this is how i set up the node

#

@lean dome please could you help me out

lean dome
#

What have you tried?

fervent saddle
#

I thought of one other question: what makes new style dicts faster than old style dicts? I thought they would be slightly slower than old style dicts for looking up one single value by its key since it first needs to go to it through the hashed into array. Also, shouldn’t iteration not be any faster since, even though the memory is closer together, the computer recognizes and optimizes when memory addresses are being accessed in a pattern anyways?

fiery cosmos
#

HEY

#

HEY

#

HEY

old rover
#

?

fervent saddle
#

It’s Faaat Albert

lean dome
# fervent saddle I thought of one other question: what makes new style dicts faster than old styl...

the computer recognizes and optimizes when memory addresses are being accessed in a pattern anyways?
It does, but for iteration on old-style dictionaries, that pattern is a linear scan, which needed to read from every slot in the array to see if it held a value or not (since hash tables are kept mostly empty, as a collision avoidance strategy).
For a new style array, that pattern is still a linear scan, but instead of being a linear scan over a sparse array that's mostly full of items that need to be skipped, it's a linear scan over a dense array that's full of actual items that need to be emitted from the iteration.

#

what makes new style dicts faster than old style dicts? I
And, other than iteration, the benefit mostly comes from locality of reference, IIUC. Being smaller means that more of the dictionary fits into your L2 cache, which means that lookups against the dictionary are far faster. I think that's the primary reason it's faster despite the additional indirection (and an additional indirection, on modern hardware, is pretty cheap)

fervent saddle
#

Alright, now that part makes sense too. Thanks again for the explanations

buoyant lintel
#

klhiikop9ihuyubabyggggggggggggllllre

tranquil brook
#

Hey, anyone know an algorithm for displaying a vertex graph such that there is the least possible crossings between edges ? It would take the graph as a matrix coding the edges and spit out the coordinates of the vertices ideally (i’m just looking for ideas, not the actual code)

sand pilot
sand pilot
fervent saddle
#

I couldn’t resist it

agile sundial
analog ferry
#

is the correct way to refer to specific chunks of a memory mapped file using a memoryview?

lean dome
#

Depending on what specifically is in the file and what you're trying to do with it, there may be other equally reasonable options

analog ferry
#

@lean dome i have about 250k crypto hashes of the same type and i want to refer to them via buffers/indexes in a memory mapped file

lean dome
#

Well, you can't really do much with a memory view, besides copy data out of it into some other type

#

A memory view is basically just passing around a pointer and a length, but there's not much you can do directly with that.

analog ferry
#

@lean dome for me it would be ideal if python could simply view that memory map as a array of fixed size byte sets

lean dome
#

!e ```py
a = memoryview(b"abc")
b = memoryview(b"xabc")[1:]
print(a == b)

halcyon plankBOT
#

@lean dome :white_check_mark: Your eval job has completed with return code 0.

True
lean dome
#

That should basically just work, then.

analog ferry
#

@lean dome its still just a big char[] while id like to have a char[][HASHSIZE]

lean dome
#

That's what slicing a memoryview gives you - though you need to create multiple slices then, or slice it each time you want to extract a hash from it

#

Sounds like a list of memoryview objects might be the structure you're looking for, but that also might be pretty large. Otherwise, an object that holds a single memoryview and slices into it on demand will be much smaller, but has the overhead of creating new slices each time it's accessed

grizzled roost
old rover
#
class Employee:
  def __init__(self,first,last,pay):
    self.first = first
    self.last = last
    self.pay = pay
    self.email = first + "." + last + "@company.com"
  
  def fullname(self):
    return '{} {}'.format(self.first, self.last)
    


emp1 = Employee("Corey", "Schafer", 50000)




#

so uh

#

is .format just a different way of doing f strings?

fiery cosmos
#

yeah

wanton tinsel
#

Hi im trying to do a simple algorithm that can seperate a list of PNGs into 2 folders according to their dimension(vertical/horizontal)

strange tide
#

any clue what this function ALGO-X does? its written in pseudocode but the concept is similar as written in python 😄

agile sundial
#

what do you think @strange tide

strange tide
# agile sundial what do you think <@!465657905014767621>

well i see that B length of 1 and has the value 0 in it, L = 1, A is an array containing n elements, s = A[i] because B[j] = 0 (from line 1), and it appends s (or A[i] ) at array B. This is all i derived, but i keep combining these hints in order to come up with something but i can't think of anything..

old rover
#

ah yes this looks like CLRS

#

is it CLRS

#

I didn't know about dict dunder method before I watched the Schafer video

shell sorrel
#

help someone

old rover
#

this looks like hackerrank

#

is it hackerrank

shell sorrel
#

Ya

old rover
#

what have you done so far

shell sorrel
#

Ok nvm

#

I got the right

dapper sapphire
#

What is the height supposed to be of the following Tree:?

           11
        /      \
      6         15
    /   \      /  \
  3      8    13   17
 / \         / \     \
1   5       12  14    19
#

I am looking at two different implementations, one gives 4, other gives 3.

agile sundial
#

should be 3

dapper sapphire
#

ok thanks. And would the maximum depth be 4?

dapper sapphire
#

Actually never mind.
Height is calculated from root to leaf node on the longest path.
Depth is calculated from leaf node to root on the longest path.

main flower
# dapper sapphire What is the height supposed to be of the following Tree:? ``` 11 ...
dapper sapphire
main flower
#

👍

idle rose
dapper sapphire
#

So in this question:
https://leetcode.com/problems/maximum-depth-of-binary-tree/
for input root = [3,9,20,null,null,15,7]
maximum depth should be 2, instead of 3 as their example output shows?

lean dome
#

The standard definition of based on the number of edges, not the number of nodes

dapper sapphire
lean dome
#

Well, just the number of edges along the longest path, instead of the number of nodes along the longest path

#

The path made up of 3 -> 20 -> 7 is (tied for) the deepest, and it has only 2 edges (the normal definition of depth) but 3 nodes.

#

The number of nodes along a path is always one more than the number of edges

dapper sapphire
#

So here the longest path could be both 3, 20, 15 and 3, 20, 7?

#

oh!!!

lean dome
#

Yep. But either way that's 3 nodes, 2 edges

dapper sapphire
#

ok ok I see yeah you are absolutely number of nodes will always be one more then the number of edges:

       4
     /  \
    1    5
  /  \
 0    2

On the longest path on the left 4 -> 1 -> 0, we have 3 nodes(4, 1, 0), but we have two edges represneted by / or \

#

Ok I see why there exmaple output says 3 because they are using number of nodes instead of edges along that longest path.

#

That makes sense! Appreciate the help godlygeek!

minor cedar
#

im not sure which section to pick for help in anyone able to PM and look at my code?

midnight umbra
#

hey I have a general question.. what data structure should I use to search in O(1) time? (currently I am using lists and it takes O(n) time).. I want to have duplicate values conserved

main flower
#

Well, maybe you could use a hash table which allows for O(1) searching on average (and O(n) worst case)

#

But it depends on what you need exactly

#

Cuz other than that, searching in O(1) is pretty much impossible

#

But it depends on what you need

austere sparrow
#

that's why multidict is useful

stable pecan
#

Counter is in the standard library

austere sparrow
stable pecan
#

Does it need to?

austere sparrow
#

No, because it's a counter, not a multidict.

stable pecan
#

No, I mean did @midnight umbra need to have the order of his values conserved?

#

He didn't say

austere sparrow
#

well, let's ask Sku11y 🙂

glossy breach
#

Well it depends on what he is searching for

#

:v

amber heart
#

can anyone help me with this?

#

i am unable to understand how to proceed

gaunt forge
#

j

#

Oooh, I'll take a look

#

Checking it out. Hmmm

#

If a and b didn't exist, it would be trivial

#

There was a very similar problem in a advent of code last winter, trying to remember how I solved that

gaunt forge
spring jasper
#

Codeforces probably wont pass a naive solution

old rover
cloud moth
#

i tried every channels. no one answers

old rover
#

that doesn't necessarily you ask the question in multiple channels... bc we're all volunteers here

#

I’m not a mod tho so that’s all I’m going to say

cloud moth
#

ok i will delete it

gaunt forge
#

But it looks like they didn't respond so who knows

spring jasper
#

Must not be that important i guess 🤷

gaunt forge
#

Okay. So, in order to make a palindrome, it has to be the same forwards and backwards, right? My first step would be to have a pointer at each end traverse the string until they meet or pass in the middle.

#

Well, I guess my question should have been "How far have you gotten with your approach? Where are you stuck at?"

midnight umbra
#

i didnt know that was a thing in python

analog ferry
#

anyone aware of there is a way to let numpy walk trough an array of indirections, i have a inlined b+ tree where each tree node stores 16 potential next item references,

now what i want to do is have numpy split a input value into 4 bit numbers, and iterate the next item until its either 0 (not found) or has the last value (return that number)

stable pecan
#

I don't think so. I think numpy's array iterator always uses a constant stride. But maybe not, also maybe I don't understand this question.

analog ferry
#

@stable pecan basically i have a numpy array that is 2d - each row has 16 items - now when given a lookup key (which is in essence a hash digest) i want to do something like

current = 0
for nibble in input:
  current = array[current][nibble]
stable pecan
#

Yeah, I think the variable strides are gonna prevent a nice vectorization.

analog ferry
#

variable strides?

#

@stable pecan as far as i understood, the strides are constant

stable pecan
#

array[current][nibble] -> array[array[current][nibble]][next_nibble] Could probably be a stride of any length in both dimensions?

#

I might not understand b+ tree data structure

analog ferry
#

@stable pecan basically i have an array[*][16]

#

when given an input digest, i loop over all hex digits and look up the next current in the 16 element array for each of them

stable pecan
#
[1 . . . . .]
[. . 2 . . .]
[. . . . 3 .]

We could get numpy to efficiently iterate over 1, 2, 3 in above array because each read is the same distance in memory, but i'm imagining you want more random accesses of the array:

[1 . . 3 . .]
[. . . 2 . .]
[. . . . . .]

This I don't think we can coerce numpy to iterate over. But really, I'm unsure.

analog ferry
#

ok, thenj i'll go cython ^^

halcyon plankBOT
slow surge
#
a = int(input('Enter ID of the Ghoul: '))
if a == 1000:
    while a > 6:
        print(f'{a} - 7 = {a - 7}')
        a -= 7
        time.sleep(0.05)
    print('You are Ghoul ' * 1000)
elif a != 1000:
    print('You aren\'t Ghoul ' * 1000)```
agile sundial
#

do you have a question?

tropic cypress
#

can anyone help me with studying data structures and algorithms ?

dapper sapphire
#

Degenerate Tree, is that really a type of Tree?

#

Which is similar to a linked list.

keen hearth
#

It's a maximally unbalanced tree, with the greatest possible height for the number of nodes.

#

Since many tree algorithms have running times that grow with the height of the tree, this is a bad thing.

#

For a balanced tree, the height is O(log n) where n is the number of nodes. But for a degenerate tree, the height is Ω(n).

analog ferry
#

i beleive thats misuse of the O notation ^^

keen hearth
analog ferry
#

oh, ok, i'll need to change fonts ^^

keen hearth
#

Yeah, it looks like an underlined O on my machine.

dapper sapphire
#

Honestly, unbalanced or irregular tree would have been a better name. I just loled when I read degenerate.
But I can understand coming up with these data structures just uses a lot of mental energy that by the time they get to naming it, they were like ok, our name are Adelson, Velsky and Landis, lets name it AVL Tree.

keen hearth
lean dome
#

4 element linked list:

1 -> 2 -> 3 -> 4

4 element maximally unbalanced binary tree:

1
 \
  2
   \
    3
     \
      4

That's the same picture, just at a different angle.

dapper sapphire
#

I guess that's why we balance the tree?

lean dome
#

Yeah, because an unbalanced tree is no better than a linked list, and a linked list isn't very good

#

And yeah, "degenerate" is a math term. https://en.m.wikipedia.org/wiki/Degeneracy_(mathematics)

In mathematics, a degenerate case is a limiting case of a class of objects which appears to be qualitatively different from (and usually simpler to) the rest of the class, and the term degeneracy is the condition of being a degenerate case.The definitions of many classes of composite or structured objects often implicitly include inequalities. F...

#

Usually, it means a special case where an object regresses to a simpler type of object. A binary tree where all the left children are null degenerates into a linked list. A triangle where one of the sides is of length 0 degenerates into a line segment.

dapper sapphire
#

Actually I didnt know it was a math term. Thanks for mentioning that.

#

So a Tree's worst case would be O(n)

lean dome
#

Pretty much all the foundational data structures and algorithms are straight out of math departments.

lean dome
elfin sundial
#

hello guys, i had a question, i have this code that converts a array int a simple whole number

#

but my issue was that i didnt know how to remove the first element of the array and add the actual lenght of the array at the last position

#

of the array

#

this is the code

#
if __name__ == '__main__':
    n = int(input())
    k = [g for g in range(0,n)]
    k = str(k).replace(', ','').strip('[]')
    
    print(k, end="")
trim fiber
elfin sundial
#

isnt append pushing the array>?

trim fiber
#

!e

arr = ["a", "b", "c"]
arr.pop(0)
print(arr)
arr.append(len(arr))
print(arr)
halcyon plankBOT
#

@trim fiber :white_check_mark: Your eval job has completed with return code 0.

001 | ['b', 'c']
002 | ['b', 'c', 2]
elfin sundial
#

also i tried pop and then when i tried to print out the whole array, it just printed out 0

#

oh wow

trim fiber
#

Is it what do you want to do?

elfin sundial
#

i mean the append yeah defo but im not sure that im printing properly cos when i the first element, it doesnt print the whole number

#

it just prints 0

halcyon plankBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

elfin sundial
#

!e


if __name__ == '__main__':
    n = int(input())
    k = [g for g in range(0,n)]
    k = k.pop(0)
    print(k, end='')
    k = str(k).replace(', ','').strip('[]')
    
    print(k, end="")
halcyon plankBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

trim fiber
#

You cannot do k = k.pop(0) - it means that you want to get first value of an array k and set it to variable k

#

Just type k.pop(0) without k = ... part

elfin sundial
#

does it save the new array anyway

#

oh okay

trim fiber
#

Nope, it changes actual array (updates it under the hood)

elfin sundial
#

ight yeah understood, well thanks for that, i understand append a bit more

#

isnt append like push?

trim fiber
elfin sundial
#

so how does it just add to the end

trim fiber
elfin sundial
#

lol, okay nah its fine thanks anyway bruv

#
if __name__ == '__main__':
    n = int(input())
    k = [g for g in range(0,n)]
    k.pop(0) 
    k.append(int(len(k)+1))
    k = str(k).replace(', ','').strip('[]')
    
    print(k, end="")
trim fiber
elfin sundial
#

oh okay

#

i thought it would cause some sort of issues but now that i think about it , its a len function which idk why my dumbass thought anything to do with string

agile sundial
#

instead of doing that terrible string formatting just use join

#

!join

#

:/

#

!d str.join

halcyon plankBOT
#
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](#bytes "bytes") objects. The separator between elements is the string providing this method.
agile sundial
#

@elfin sundial

elfin sundial
#

what string itteration

#

also .join doesnt help me

agile sundial
#

yeah it does

elfin sundial
#

so i can replace k = str(k).replace(', ','').strip('[]') with .join

agile sundial
#

join let's you put an iterable together into a string

elfin sundial
#

i mean. that sounds very effecient. i can just peice my string together.

#

ill give it a try

agile sundial
#

one thing to note is that you can only join together strings, so you'll have to convert your elements before joining

stable pecan
#

inb4 python3.10 changes it

agile sundial
#

it'd be cool if it implicitly converted 😔

elfin sundial
#

but the thing is, i dont really need it tho

#

cos im jsut filtering a string

#

also im posititive that using join will just end up using more mem anyway

agile sundial
#

positive how?

elfin sundial
#

i modified a list through builtins, using join is just going to cause me to use more logic and expend more logic to pack it into the join function. im sure the way you are think is probs better than mine but im sure that when i do it i will need to define more variables to manage lists.

trim fiber
#

Even shorter

"".join(map(str, k))
elfin sundial
#

so ```py
"".join(map(str, k))

#

filters the brackets and removes the comma and space

trim fiber
elfin sundial
#

wow

trim fiber
#

!e

arr = [0, 1, 2]
print(arr)
arr = list(map(str, arr))  # list(...) only for pretty output
print(arr)
arr = "".join(arr)
print(arr)
halcyon plankBOT
#

@trim fiber :white_check_mark: Your eval job has completed with return code 0.

001 | [0, 1, 2]
002 | ['0', '1', '2']
003 | 012
elfin sundial
#

thats sick

#

need to look more into builtins

#

am i using the correct term? builtins?

stable pecan
#

map is a builtin, join is a str method

trim fiber
#

!d map

halcyon plankBOT
#
map(function, iterable, ...)```
Return an iterator that applies *function* to every item of *iterable*, yielding the results. If additional *iterable* arguments are passed, *function* must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see [`itertools.starmap()`](itertools.html#itertools.starmap "itertools.starmap").
elfin sundial
#

so much more to learn

jaunty loom
#

what is the time complexity of

min(some_list)```?
old rover
#

it's O(N)

#

linearly searches through the elements for the given value

#

(I think)

jaunty loom
#

oh ok

old rover
jaunty loom
#

oh thank you, didn't know that existed