#algos-and-data-structs
1 messages · Page 113 of 1
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
ohh data structure and algorithm is the way of solving a problem in aoptimized way
yes
i see i will try it then
oh before you do that
you should learn what big O is
Show Support
Patreon - https://www.patreon.com/nick_white
PayPal - https://paypal.me/nickwwhite?locale.x...
Become A Member - https://www.youtube.com/channel/UC1fLEeYICmo3O9cUsqIi7HA/join
Social Media
Twitch - https://www.twitch.tv/nickwhitettv
Twit...
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)
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
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
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)?
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
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
With 1000 items it would take you 9.98 so 10 steps, this relationship is logarithmic with base 2
it's approximated
but it gives you a nice idea
2 to the 7 is somewhat close to 100
Its not an approximation, its ceil(log2(n))
It rounds up the decimal to the closest integer
oh
Python equivalent is like int(n+1)
That example is true if you assume n is not an integer
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
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
I think #software-architecture suits this question
alright, thank you
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 😦
He's not wrong though
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
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.
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)
There are definitely cases where you need to be aware of it, but I'm the vast majority of cases your sizes are far too small.
you can call the 3 arg form of the property constructor
I don't really disagree that you'll almost never use it but if you need it you need it and if you ever want to work on big complex problems you're gonna need it.
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
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
Ye
I’ve heard game developers have to worry about time complexity a lot. But maybe that’s untrue
@fervent saddle depends on the game. If you have a lot of things, yes
I think this is wrong 🙂
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}')
I have encountered very few cases where improving bigO moved the program from not realtime to realtime. But I do agree that one should know it.
@onyx root yeah I agree he could work on his phrasing a bit
it’s a pretty nice topic to know
well, he's sponsored by a place that says they will help you with interviews
@onyx root yeah that whole algo expert io garbage
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
Ned’s blog is also a pretty good source to learn big O too
he has one blog post about it
pretty well written
Yes
#user-interfaces or by opening a help channel - #❓|how-to-get-help
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
yes
if you want if/else in list comps you basically use a ternary
so thing if condition else other_thing
!warn 734499019962712154 Don't post random videos in our server.
:incoming_envelope: :ok_hand: applied warning to @fiery cosmos.
yo k i just heard about https://bugs.python.org/issue41972
does it basically guarantee linear complexity?
for string contain operation
or idk the work
in operator
https://csacademy.com/contest/archive/task/bfs-dfs
so in this problem i don't really get the 1st sample case
why are the edges 35, 52, and 56 needed?
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
What level is that
!resources you can try your hand here and then pick up fluent python
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Is good amount of java supposed to imply that he knows ds/algorithms?
Apparently its for intermediate python users, not really sure what that means tho
thanks
yeah like intermediate
I basicly know all variables
i dont know if thats still beginner though lmao
knowing variables is barely knowing a language
i feel like trading algorithms should be closer to data science than computer science
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
Sure, just a sec
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)
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.
a += b means a = a + b, not a = b + a
no I wouldn't consider variables 25% of a language
It's pretty impossible to rate your own knowledge of anything objectively. Unknown unknowns.
Like i said i know more but if i listed all the things i know out it would be kong
Obv i dont know alot
Do you know looping mechanisms, conditionals, recursion, classes, etc
I'd say thats the basics of python tbh
Yeah thats what i was thinking im like right after the basics
I mean that course was expensive i better have learned something 😂
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
Yeah ive been messing around with those concepts
I never learned it in java but i was able to call api’s
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 🙂
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
Can you write example input and expected output?
if you don't have a pre-existing function which does that you could always make your own lambda with whatever logic you want
What does "sort a list of dicts alphabetically" mean
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
}
]
sorted(input, key=lambda d: d["name"])?
If you wanna sort by multiple keys afaik your lambda just needs to return a tuple
If I just use normal sort by key, 100000-109999.7z comes before 20000-29999.7z.
How about it?
input.sorted(key=lambda entry: entry["name"])
input.sorted(key=lambda entry: len(entry["name"]))
>>> 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}]
sorted(input, key=lambda d: (len(d["name"]), d["name"]))```
Sorts by length of the value first, then lexicographically
Looks perfect!
Thanks, I'll try that! :D
this does return
eh
leh
lleh
olleh
for the hello input
reversed += char does also work with the output h
he
hel
hell
hello
my anaconda gives an error:
HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/main/win-64/current_repodata.json
are there any solutions for this
Looks more like #tools-and-devops 
Are you sure that you have internet connection? How about flushing local DNS cache?
I have a function as a variable. How can I call that function with variables?
I don't think that reverses the string
yeah i know.
>>> foo = print
>>> foo("ABC")
ABC
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
- this is a huge dog
- this is a giant dog
maybe a set
how do i index it?
Im trying to pass "huge" and get synonyms big, large, giant etc
you can’t index sets
sorry I’m not sure that I understand exactly what you’re trying to do
i want to confirm that two sentences are equivalent
- this is a huge dog
- this is a giant dog
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
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
ah
I guess you could use a dictionary, like
big = {“huge”, “large”, etc}
d = {“large”: big}
could anyone please how come this is valid? how does it work?
yeah, i thought about it but heres the problem,
with that way, i cant index words like "huge" and get "big" without making every value also become a key, which will greatly inflate the dictionary,
if i cant find any other method then ill either go with collection of sets or the dense dictionary, but i was hoping for a better approach XD
you are fetching two values to get a tuple (internally) returning (c, a)
then setting index 0 and 2 to be = (c, a)
thus swapping the result
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
yes, seems that way, thanks for help though ^^
@pliant heath got it. thanks a lot.
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?
https://csacademy.com/contest/archive/task/bfs-dfs
so in this problem i don't really get the 1st sample case
why are the edges 35, 52, and 56 needed?
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
uh no?
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
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
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
sets as in no duplicates and unordered?
yes
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)
That would take care of part Am right?
the shuffle should handle the frequencies too
should I try this or my computer is gonna freeze?
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
ah, forgot the import
I feel like I understimated how slow shuffling is, this may not finish within reasonable time
it just finished
wow, still going for me
94143280```
you can use ```py
import itertools
from collections import Counter
Counter(x for y in itertools.islice(combs, 10000) for x in y)
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
it happens
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
both numbers?
what do you mean?
make sure that both numbers are sampled
which numbers?
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
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
I will explore that. Thank you
https://csacademy.com/contest/archive/task/bfs-dfs
so in this problem i don't really get the 1st sample case
why are the edges 35, 52, and 56 needed?
so I got really bored and was looking at this medium article: https://medium.com/outco/reversing-a-linked-list-easy-as-1-2-3-560fbffe2088
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
I think that's the point
@oblique panther yeah it’s been a long day
see if you can code it 
if you have a working linked list implementation, it should be pretty straightforward.
@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
that wouldn't be the first step in my solution.
if you set the head to None, how can you go from there? You've lost your reference to the first node.
also if this is a singly linked list, that changes it a lot
Yeah, that would work if you have access to both head and tail.
How would you do it if you dont have access to tail?
Actually, I never tried it. But what swapping makes sense.
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
That wouldn't work at all - that would give you a head.next of None and a tail.prev of None, which ain't right.
I think they meant swapping the prev/next pointers
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
None <- head(0) <-> 1 <-> 2 <-> tail(3) -> None
https://csacademy.com/contest/archive/task/bfs-dfs
so in this problem i don't really get the 1st sample case
why are the edges 35, 52, and 56 needed?
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.
has anyone read graph algorithm book from neo4j?
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.
I posted this question in a more clear way on stackoverflow in case someone wants to check it out
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
Have you tried anything?
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
Node can have any number of subtrees?
Yeah as you can see in th constructor of node it contains a list of children
I am just want to be sure
So do you have method which adds a child?
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)
Why is it an object method if you don't use self?
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
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}")
@trim fiber :white_check_mark: Your eval job has completed with return code 0.
001 | x = x, y = y
002 | x = y, y = x
but would it swap the subtree as well
Oh, just image that you have subtree x and y, then
x.children, y.children = y.children, x.children
How about it?
subtree_a.children,subtree_b.children=subtree_b.children,subtree_a.children
I tried this didnt work
@trim fiber
What is the result?
it didnt pass the test case
Yep however I am at work so I can write when I have free time
Each node has .parent property, right?
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
Is it working? I think that you should swap subtree_a with subtree_b in subtree_a.parent.children and make same operation for subtree_b
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
Look at .index and .insert methods of list class
!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)
@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']
Just a quick demo
but here we are swapping between two different list sometimes as well
SWAP(D, C)
A
/ \
D B
\
C
/ \
J K
I just showed simple demo
When you use node.parent.children you can swap objects between different lists
I just did that it didnt work
Show me your code
subtree_a.parent.children,subtree_b.parent.children=subtree_b.parent.children,subtree_a.parent.children
Where you have .insert like in my example?
why do I have to use .insert
Because you need to update position of one child, not every
could you please show me the code i am confused
the list of children is an unorderd list anyway
I can come back later, I am at work now
okay
whats the height of this tree, i think im losing my mind
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
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
that doesnt make sense, why does a tree of 1 node have height 0
thats like a list of 1 element having length 0
Math, man.
One could argue that a tree with no edges is zero dimensional, like a point, and therefore has no height
@spring jasper log2(1) = 0 🙂
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
So, have you tried to solve it?
seems ez to me. find given nodes, swap children.
wow they literally given subtree as well.
just replace children
Like I said before
Can I ask for questions on here? or is this taken
If it's related to a channel's topic go ahead!
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
Busy day for me
Could you explain what have you tried? How it works?
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
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)
but how do i determine that the loops run O(n) times ?
the inner loop runs length - gap times, which is length (1 - 1/shrink_rate), which is O(length)
and the outer loop?
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.
You probably want to claim a help channel and provide a code sample (this isn't really the channel for this)
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
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?
you probably want #game-development
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
That's still part of game development - you're deciding what mechanics to use.
hey could anyone help me with this problem
Hm?
confused why this is invalid
It looks so complex, maybe use some brackets
it should be
.join((i.lower() if i.isupper() else i) for i in x)
the syntax is definitely invalid. For one, you have for i in x twice.
I think that we can always use i.lower(), right?
nah, isupper returns True if the entire string is upper
so what this does is:
- if the string is fully uppercase, it lowercases it.
- Otherwise, returns unchanged, even if it's
lIkEtHaT

of course, it might not be what was intended, but switching it to just lower would change the behaviour.
Right, I assumed that i is always a character
ah, good point, then yeah
Then it can be "".join(map(str.lower, x))
or just x.lower() ?
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
Can you show your code?
import turtle
turtle.forward(5)```
When you look at available example you can see turtle.done() execution
https://docs.python.org/3/library/turtle.html
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
This is not a Modmail thread.
Right
how to close?
No need to close
It's topical chat
When you acquire help channel then you should close 😉
can you also modify the short cuts?
in pycharm
like to run the file press f5
instead of shift f10
You can enter settings and change then I think, I am not master of PyCharm
You can ask on #editors-ides
Visit this chat and ask them about it 😉
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
is there a functional-style group-by in python?
I don't know why you mean by functional-style 
!docs functools.reduce
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)
Something like that?
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]]
!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
!e
def reducer(aggregated, element):
if element == "and":
aggregated.append([])
else:
if len(aggregated) == 0:
aggregated.append([])
aggregated[-1].append(element)
return aggregated
import functools
print(functools.reduce(reducer, [3, 100, "and", 8, 1000], []))
@trim fiber :white_check_mark: Your eval job has completed with return code 0.
[[3, 100], [8, 1000]]
However this function looks awful
[*map(lambda x: ([*map(int, x)]) , list(map(str.split, ' '.join(map(str, [3, 100, "and", 8, 1000])).split("and"))) )] as does my approach
Do you want to find one-line solution?
somewhat
I wanted something subjectively more beautiful
I mean your function is at least readable
which is good
whoms't
why is Schafer covering getters and setters in Python
🥴
I thought that was unpythonic
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"
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
is that talking about the self parameter?
You can use itertools.groupby for that so why not
mmmm, sure, but self is used in other places too. i don't think that explanation is adequate.
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]]
yeah you're right
You can probably fix that lambda up too
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
that's good then
I kind of knew that already
but this is helping me clear up my doubts
Because theyre not that important
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
how do i make a unmute command
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
Dicts can already take tuples as keys
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}
yeah - but it would be a pita to loop through the whole dict
is there a better alternative to either of the above solutions?
Why would you loop through it to check if a key exists
I don't get the idea behind this solution
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
Why not
{
"small": [1,2,3],
"big": [4,5,6]
}
how would i access "small" if i have 2?
Oh, my b misunderstood
You could just have each number be a key
You dont have to put them in a tuple
thanks - but it would be more worth it to use this approach than to store each key seperately, i could do that as a last resort but am just looking for a more elegant solution
thanks either way :))
Why is it more worth
file size and also i want to be able to modify the value easier
That means you gotta loop over the keys and then loop over the items in the tuple
It sounds like O(keys * key_size)
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
What are you trying to do exactly
a "translator" between user input shorthand to longhand. there are many ways the user can enter something which aren't logically connected
@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
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)
You need to use recursion and check for child in every children node
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'
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)
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:
Can you paste whole Node and Tree classes? I don't know which methods should be in which classes
Or just write that this method is for this class
You are trying to call .remove_child method on Tree object
yeah
Tree object doesn't have .remove_child method, right?
I tries parent as well
However root property has
why does it have self in the method then
To use self.root?
okay
You need to take tree's root and remove its child
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)
It seems that your child has no parent
Yeah why is that
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:
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
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 = ...
= what
What is the parent for this child?
I am trying to give you my support, not the solution 
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
As far as I understand your parent must be already in the tree
:param parent: The parent node currently in the tree.
oh okay so you were asking me to make some changes in this part of code
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)
...
how do I set the parent of this child
Yeah but to what I do not have the parent node
What you put instead of dots ...?
If child_node is a child for self then what is self for child_node?
child_node.parent=self
Right, looks okay
@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
And it works?
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.
Can you paste the test case?
yup
Excelent!
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."
Give me a second
cool
Okay, first of all I don't see any updates on subtree.parent
Like subtree_b.parent = ...
Right?
No problem
I think that it doesn't matter however you can do it after to have clean code
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
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
missing ". Also, not really a question for #algos-and-data-structs, see #❓|how-to-get-help on claiming a help channel.
Scope creep is fun, isn't it?
not sure if this belongs in here
ah, sorry
hey could someone help me with this problem
uh what’s the problem
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
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
Hii could someone here help me with drawing an AVL tree /binary serach tree by hand?
Is this correct?
@frank osprey looks right
Okay, thank you so much!
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
okk great! Is the second one correct too?
aren't only the leaves supposed to be annotated with 0?
I don't know, in the short example in class I saw the root was also annotated with zero when necessary...
(or parents)
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
it might be this instead
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."
how likely will self-balancing trees and Dijkstra/A* come up on technical interviews?
what would a game bot that logs in on seperate proxies be considered under (channel wise)
For a website
well I had an internship interview and they asked me that
only problem is that I didn't know it at the time
so I got screwed 🥴
which one did they ask?
that's for dijkstra, it's pretty nice
Yeah
How can i send message like this?
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?
how do I send a message like yours?
np
are linked lists slower than normal lists?
depends how you use them
As godlygeek said yes generally they are
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
They're O(1) near the edges
oh yeah
Not in the middle
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
interviewers ask linked list questions bc they're easy
You should learn linked lists anyway
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
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?
sexy buzz words 🥴
if you're asking about reinforcement learning in ML you might be better off asking in #data-science-and-ml
how do i recusre through a tree of given depth and starting point
He went to #help-bagel
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?
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
In particular, Python's normal dict can't efficiently reorder items - you could do it by deleting and reinserting items, but that costs extra time and space, and forces unnecessary table rebuilds (since deleted items take up space in the table)
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?
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?
I suspect you'll get a better answer in #data-science-and-ml - more numpy people hang keep up with that channel
https://medium.com/junior-dev/python-dictionaries-are-ordered-now-but-how-and-why-5d5a40ee327f gives a good explanation - it's faster and smaller than what Python was doing previously.
Alright, thanks for finding that, I’ll read it
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.
collections.OrderedDict uses closed addressing?
Shouldn’t it be possible to do this with open addressing?
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
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?
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.
Because the hashed into array is just holding regular C number values instead of python objects?
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.
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?
Right, yep.
Alright, I think everything makes sense now. Thanks for the help
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
What have you tried?
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?
?
It’s Faaat Albert
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)
Alright, now that part makes sense too. Thanks again for the explanations
klhiikop9ihuyubabyggggggggggggllllre
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)
dont do this, please. Keep it topical in these channels
same with you
I couldn’t resist it
this would better be suited for #async-and-concurrency
is the correct way to refer to specific chunks of a memory mapped file using a memoryview?
That seems like a reasonable way to do it.
Depending on what specifically is in the file and what you're trying to do with it, there may be other equally reasonable options
@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
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.
@lean dome for me it would be ideal if python could simply view that memory map as a array of fixed size byte sets
!e ```py
a = memoryview(b"abc")
b = memoryview(b"xabc")[1:]
print(a == b)
@lean dome :white_check_mark: Your eval job has completed with return code 0.
True
That should basically just work, then.
@lean dome its still just a big char[] while id like to have a char[][HASHSIZE]
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
Guys any help? https://projecteuler.net/problem=254
I have a solution but it's not efficient. What's the process to make it efficient.
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?
yeah
Hi im trying to do a simple algorithm that can seperate a list of PNGs into 2 folders according to their dimension(vertical/horizontal)
any clue what this function ALGO-X does? its written in pseudocode but the concept is similar as written in python 😄
what do you think @strange tide
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..
ah yes this looks like CLRS
is it CLRS
I didn't know about dict dunder method before I watched the Schafer video
Ya
what have you done so far
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.
should be 3
ok thanks. And would the maximum depth be 4?
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.
I think this could be a good answer to your question: https://stackoverflow.com/questions/2603692/what-is-the-difference-between-tree-depth-and-height
Thanks that's what I was looking at that made me realize how height and depth gets calculated.
👍
hi, i need some assistance on passing a variable to a function located in a separate file. does anyone have a minute to take a look at my code and explain me what's up? thanks. 🙂 https://pastebin.com/pRRW7Aiz
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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?
Yeah:
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
That's the definition they're using, though that's not the standard definition.
The standard definition of based on the number of edges, not the number of nodes
By edges you mean, 3, 9 on the left, and 3, 20, 15 and 3, 20, 7 on the right?
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
Yep. But either way that's 3 nodes, 2 edges
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!
im not sure which section to pick for help in anyone able to PM and look at my code?
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
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
You can't use a normal dict, because it doesn't allow multiple values in order. E.g. [1, 1, 2, 3, 1, 4, 5, 2]
that's why multidict is useful
Counter is in the standard library
It can't differentiate between [1, 1, 2] and [1, 2, 1]
Does it need to?
No, because it's a counter, not a multidict.
No, I mean did @midnight umbra need to have the order of his values conserved?
He didn't say
well, let's ask Sku11y 🙂
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
Are you looking for an optimized solution at this time or are you having trouble with the naive approach?
Codeforces probably wont pass a naive solution
I don't think a NN question belongs in this channel. try #data-science-and-ml
i tried every channels. no one answers
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
ok i will delete it
Probably not, but it's usually a good start. I'm also not sure if this person is looking to just solve this or looking to pass the benchmarks.
But it looks like they didn't respond so who knows
Must not be that important i guess 🤷
naive approach
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?"
yes that was needed... i used that hash function lol
i didnt know that was a thing in python
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)
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.
@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]
Yeah, I think the variable strides are gonna prevent a nice vectorization.
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
@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
[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.
ok, thenj i'll go cython ^^
Hey @slow surge!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
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)```
do you have a question?
can anyone help me with studying data structures and algorithms ?
Degenerate Tree, is that really a type of Tree?
Which is similar to a linked list.
Yep. It's a tree where each node has at most one child.
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).
i beleive thats misuse of the O notation ^^
Zoom in, it's an omega 😄
oh, ok, i'll need to change fonts ^^
Yeah, it looks like an underlined O on my machine.
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.
Yeah, I think the term 'degenerate' is a bit of an anachronism. It comes from mathematics where it is quite often used.
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.
Yeah, that's exactly how I had pictured it in my head.
I guess that's why we balance the tree?
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.
Actually I didnt know it was a math term. Thanks for mentioning that.
So a Tree's worst case would be O(n)
Pretty much all the foundational data structures and algorithms are straight out of math departments.
Yep.
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="")
Remove with .pop(0), add with .append(len(arr))
isnt append pushing the array>?
!e
arr = ["a", "b", "c"]
arr.pop(0)
print(arr)
arr.append(len(arr))
print(arr)
@trim fiber :white_check_mark: Your eval job has completed with return code 0.
001 | ['b', 'c']
002 | ['b', 'c', 2]
also i tried pop and then when i tried to print out the whole array, it just printed out 0
oh wow
Is it what do you want to do?
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
You are not allowed to use that command here. Please use the #bot-commands channel instead.
!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="")
You are not allowed to use that command here. Please use the #bot-commands channel instead.
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
Nope, it changes actual array (updates it under the hood)
ight yeah understood, well thanks for that, i understand append a bit more
isnt append like push?
Yep, it's something like push
so how does it just add to the end
I don't understand, just use .append(...) to add something to the end of the list 
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="")
You can omit int(...) here int(len(k)+1) and just write len(k)+1
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
instead of doing that terrible string formatting just use join
!join
:/
!d str.join
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.
@elfin sundial
yeah it does
so i can replace k = str(k).replace(', ','').strip('[]') with .join
join let's you put an iterable together into a string
i mean. that sounds very effecient. i can just peice my string together.
ill give it a try
one thing to note is that you can only join together strings, so you'll have to convert your elements before joining
inb4 python3.10 changes it
it'd be cool if it implicitly converted 😔
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
positive how?
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.
Your solution
str(k).replace(', ','').strip('[]')
Using .join solution
"".join(str(num) for num in k)
Even shorter
"".join(map(str, k))
so ```py
"".join(map(str, k))
filters the brackets and removes the comma and space
It maps list of ints to list of strings and then join list of strings into one string
wow
!e
arr = [0, 1, 2]
print(arr)
arr = list(map(str, arr)) # list(...) only for pretty output
print(arr)
arr = "".join(arr)
print(arr)
@trim fiber :white_check_mark: Your eval job has completed with return code 0.
001 | [0, 1, 2]
002 | ['0', '1', '2']
003 | 012
thats sick
need to look more into builtins
am i using the correct term? builtins?
map is a builtin, join is a str method
!d map
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").
so much more to learn
what is the time complexity of
min(some_list)```?
oh ok
I just found this but: https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt
oh thank you, didn't know that existed