#algos-and-data-structs
1 messages · Page 112 of 1
@woeful gorge I think any() could work for that
In the case, any plus a generator expression.
result = any(i for i in test_list if condition(i))
Or, ```py
result = any(filter(condition, test_list))
Damnb these are some handy functions
Thanks guys
I should use map and filter etc more
No, it won't.
will be better than this result = any(filter(condition, test_list))
Why would it?
why it won"t ?
because that version does more work in Python and less in C, and doing more work in Python and less in C is slower.
I think it depends on how you can do it, right?
If everything is equal, filter should be faster. If you have to use a lambda function with filter but you don’t without using filter, not using filter would be faster. Right?
ah ok im a noob 🙂
either filter or the generator expression might be faster than the other depending on what the condition function is, but both will be faster than the explicit for loop
my guees was ... filter will iterate on all elements of the list, and return a list of all true, any will iterate to find the first true ...
I thought my loop iterate and break at the first true condition ...
If it really is if condition(x):, then filter should be faster. But if it’s something like if x < 5:, and you were forced to have the filter function be lambda x: x < 5, then not using filter would be faster. That’s what a stackoverflow answer said
filter does not greedily return a list. Instead, it returns an iterator over filtered values.
which allows it to be used with infinite iterators, even.
!e ```py
import itertools
def keep(x):
return x > 10000 and x % 3 == 0
counter = itertools.count()
filtered_counter = filter(keep, counter)
first_5 = list(itertools.islice(filtered_counter, 5))
print(first_5)
@lean dome :white_check_mark: Your eval job has completed with return code 0.
[10002, 10005, 10008, 10011, 10014]
for instance. That's showing filter applied to an infinite iterator, itertools.count()
I thought filter was returning a list not an iterator ....
iterator should start with "i"
!d filter
filter(function, iterable)```
Construct an iterator from those elements of *iterable* for which *function* returns true. *iterable* may be either a sequence, a container which supports iteration, or an iterator. If *function* is `None`, the identity function is assumed, that is, all elements of *iterable* that are false are removed.
Note that `filter(function, iterable)` is equivalent to the generator expression `(item for item in iterable if function(item))` if function is not `None` and `(item for item in iterable if item)` if function is `None`.
See [`itertools.filterfalse()`](itertools.html#itertools.filterfalse "itertools.filterfalse") for the complementary function that returns elements of *iterable* for which *function* returns false.
nope, it returns an iterator.
... on the other side you get only True as a result not the first True Item ..
yeah, that's the behavior of any.
maybe im wrong ... let me look at doc
nah, you're right. any doesn't return the first truthy item.
that is why I never used any ... we often need to do something with the first item ...
You can use walrus operator for that
It will let you use the value outside of the generator expression’s scope, they set it up that way with that specifically as one of the reasons
really , how can you do that
!e You'd need to use the generator expression version.
if any((first := i) for i in range(100) if i % 3 == 0 and i % 10 == 1):
print(first)
@lean dome :white_check_mark: Your eval job has completed with return code 0.
21
the parentheses around first := i aren't required, but I think it makes it a bit easier to read.
r = any(filter(lambda x: x==7, v))
so i need to plug a global somewhere into this lol
You need parentheses for some reason in a function call, unless you put parentheses around the whole generator expression
Idk why
or if you’re assigning a variable to a generator
v = [2,3,5,7,11]
nope like this r = any(filter(lambda x: (g:= x)==7, v))
so how is it working with any and filter ?
I think you also maybe could pass filter to next
test = ("a", "b", "1", "c")
print(next(filter(str.isdigit, test), None))```
It prints 1
And if the "1" wasn’t there, it would print None
I wonder which would be preferred if you didn’t need the first value, and all strings were definitely not empty, using next or using any?
#bot-commands message
It seems too close to call
So I guess it’s just whichever is more readable
Do adjacency matrices support adjacent node traversal? I've never used one
https://codeforces.com/contest/1174/problem/D
what does this have to do with prefix sums? i have no clue where to even start with this problem (ping 2 reply thx)
if i had to guess, missing parentheses
Is there any good dsa course in python online?
So I am trying to write a python recursive code that prints a tree node arranged like in the figure in the to print format
def ef(t):
if t is None:
return None
else:
if t.left.left is not None:
return (t.left.left.data + t.left.data+ t.left.right.data) + t + (t.right.left + t.right.data + t.right.right.data)
This is what I have so far, I could only hardocode,I don't know how to make the code flexible
please help.
can you show me t
well, you can define a to_string method in your binary operator class, or better yet use pythons __str__ method to print the structure you want:
In [1]: class BinOp:
...: def __init__(self, left, right):
...: self.left = left
...: self.right = right
...:
...: def __str__(self):
...: return f"({self.left} {self.operator} {self.right})"
...:
...: class Plus(BinOp):
...: operator = "+"
...:
...: class Divide(BinOp):
...: operator = "/"
...:
...: class Pow(BinOp):
...: operator = "^"
...:
In [2]: print(Pow(Plus(9, 0), Divide(12, 4)))
((9 + 0) ^ (12 / 4))
@midnight vigil
um... what data structure would I use to implement a shopping cart?
is a linked list sufficient?
what if you want to access the last item in the shopping cart?
so maybe a deque?
that can work since you can enqueue and dequeue on both sides (I think)
is math asked here?
uhhhh
if it's relating to algos/DS perhaps
like big O would be considered mathematical notation
it's related to ml. kind of very basic
if it's related to ML try out #data-science-and-ml
Is it possible to find the longest palindromic substring in O(n) time and O(1) space? Manacher’s Algorithm is O(n) space.
class Node:
def __init__(self, value):
self.value = value
self.edges = []
what's the point of self.edges = []
this is for creating graphs btw
How to convert Panda dataframe to list of dict?
#data-science-and-ml would be good for that

What do you mean? It creates an instance attribute called "edges", and initializes it to be an empty list.
i would assume is to store references to other nodes
yeah
an edge is like the arrow from one node to another
right?
def insert_edge(self, new_edge_val, node_from_val, node_to_val):
from_found = None
to_found = None
for node in self.nodes:
if node_from_val == node.value:
from_found = node
if node_to_val == node.value:
to_found = node
a connection, yeah
I'm a bit confused by what from_found and to_found is
also if edges are just connections/arrows then what's new_edge_val
any good resources to learn about time and space complexity of a progm?
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...
Nick doesn't go into exceptional detail or anything
but he does get the basic concept down
if you want a very mathy and science heavy explanation of time complexity/space complexity you can try out CLRS
not sure if this is the right place. but can png's store more than just the pixel's coulour
I don't think it's the right place but are you talking about this stuff for game dev? bc then it might be suited for #game-development
well its not really game dev but ill ask there
i dunno i cant tell if its a bug or if its intended. im reading a png of a height map and PIL seems to be reading the height the data is representing instead of the pixel's coulour
and i dont know how they did that
no that's not the entire function
def insert_edge(self, new_edge_val, node_from_val, node_to_val):
from_found = None
to_found = None
for node in self.nodes:
if node_from_val == node.value:
from_found = node
if node_to_val == node.value:
to_found = node
if from_found == None:
from_found = Node(node_from_val)
self.nodes.append(from_found)
if to_found == None:
to_found = Node(node_to_val)
self.nodes.append(to_found)
new_edge = Edge(new_edge_val, from_found, to_found)
from_found.edges.append(new_edge)
to_found.edges.append(new_edge)
self.edges.append(new_edge)
this is the entire function
it's just a decent chunk of code of a topic I haven't fully grasped
so
CLRS?
thx
it is often considered the "Bible" of data structures and algorithms
and it's used by a lot of universities
but if you don't like reading gigantic scientific language books then you probably won't like it
and i have a doubt,should i more focus on dp,recursion,backtracking.... or just starting learning frameworks ?
I wouldn't know bc I don't really do dynamic programming yet
but in general the best way to get the most out of a concept is by focusing on it
so if you want to learn what big O is in time complexity and space complexity the most logical path would be to start learning data structures and algorithms to go with it
^ again this is just all my opinion
if i didnt focused on data structures and algo will that be a prblm if i getin straight into webdev ?
🥴 I don't think you need ds/algos for web dev
yeah, not really
you pretty much only need to know hash tables and dynamic arrays. Those are the two most important data structures.
I remember my friend told me that he had ds/algos questions for his web dev interview
and you don't need to know them in depth at all, just how to use them + when (although, some would say how==when 😔)
but that's only like one person
well, how to use them, and when
is this a reference to me 🥴
no lol. it was a reference to me, because i didn't include "when" at first
am focusing too much on ds and algo still didnt learned any frameworks
like frameworks for webdev
y
bc I don't do web dev 🥴
not yet at least
but if you want to go into web dev you should be learning frameworks
i like to learn webdev as a side i like to getinto ml or data science
the only two data structures that every programmer must know are dynamic arrays (like Python's list type) and hash tables (like Python's dict type). You need to know that appending things to the back end of a list is fast, and accessing things anywhere in a list by index is fast, but removing things from the start or middle of a list is slow. And you need to know that inserting things into a dict is fast, as is looking them up or removing them by key. Not as fast as a list, but still pretty fast.
def insert_edge(self, new_edge_val, node_from_val, node_to_val):
from_found = None
to_found = None
for node in self.nodes:
if node_from_val == node.value:
from_found = node
if node_to_val == node.value:
to_found = node
if from_found == None:
from_found = Node(node_from_val)
self.nodes.append(to_found)
if to_found == None:
to_found = Node(node_to_val)
self.nodes.append(to_found)
new_edge = Edge(new_edge_val, from_found, to_found)
from_found.edges.append(new_edge)
to_found.edges.append(new_edge)
self.edges.append(new_edge)
what is this monstrosity
all of those conditionals just to insert a number into a list of edges?
what is from_found and to_found even
I can't even figure out what they mean
Challenging problem on codechef I got send by @quasi fog : https://www.codechef.com/APRIL21C/problems/WTRSORT for anyone up to the task 😄
I think this is fitting for this channel since you need to write an algo for it 😄 ?
am I just being stupid or something like are they supposedly very clear variable names?
what does "found" refer to?
They do have very clear variable names. The def line of this function tells me a lot. It tells me that this is representing a graph with weighted edges, because the new edge that will be created has a value associated with it. Instead of taking a reference to a pair of nodes that this new edge will be between, it takes the values of those nodes, meaning that it will need to search for nodes with those values, and add the edge to each of the nodes that it finds.
I agree, from_found is very confusing variable name
node_from would have been a better name than from_found, and node_to would have been a better name than to_found, but by keeping found in the name they were trying to emphasize the search that it's performing.
the nodes to connect.
they know the values that the nodes that will be connected must have, but they don't know what those nodes are. They need to search for them.
so node from_val_ is where the edge starts
and node_to_val is what it connects to
and from_found and to_found_ are used to find the nodes needed to connect them
node_from_val is the value held by the node that the new edge will start from.
node_to_val is the value held by the node that the new edge will end at.
oh ok
is there such a thing as protected method or property in python?
how can I transform sql syntax into a dictionary?
example:
"UPDATE db(table1, table2) VALUES(mydata, mydata1)"
output:
{"UPDATE": ["db", "table1", "table2], "WHERE": ["mydata", "mydata1"]}
basically what i am trying to do is a sql syntax handler
Like... your sending it to sql or like your trying to use sql in python
I'm creating a linked list of custom objects, where I sort the list nodes first based on the object's points (assigned by the bodybuild, such as obese or underweight), and then based on their bmi (so I want the object first grouped by their body build, and then their bmi within that group)
this is my linked list class:
`class Node:
def init(self):
self.data = None
self.next = None
class LinkedList:
def init(self):
self.head = None
def addNode(self, data):
curr = self.head
if curr is None:
n = Node()
n.data = data
self.head = n
return
if curr.data.points == data.points and curr.data.condition == 'underweight':
while curr.data.bmi < data.bmi:
if curr.data.bmi > data.bmi:
n = Node()
n.data = data
n.next = curr
self.head = n
return
curr = curr.next
elif curr.data.points == data.points and curr.data.condition != 'underweight':
while curr.data.bmi > data.bmi:
if curr.data.bmi < data.bmi:
n = Node()
n.data = data
n.next = curr
self.head = n
return
curr = curr.next
if curr.data.points < data.points:
n = Node()
n.data = data
n.next = curr
self.head = n
return
while curr.next is not None:
if curr.next.data.points < data.points:
break
curr = curr.next
n = Node()
n.data = data
n.next = curr.next
curr.next = n
return
def __str__(self):
data = []
curr = self.head
while curr is not None:
data.append(curr.data)
curr = curr.next
return "[%s]" %(', '.join(str(i) for i in data))
def __repr__(self):
return self.__str__()`
def __init__(self):
self.data = None
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def addNode(self, data):
curr = self.head
if curr is None:
n = Node()
n.data = data
self.head = n
return
if curr.data.points == data.points and curr.data.condition == 'underweight':
while curr.data.bmi < data.bmi:
if curr.data.bmi > data.bmi:
n = Node()
n.data = data
n.next = curr
self.head = n
return
curr = curr.next
elif curr.data.points == data.points and curr.data.condition != 'underweight':
if curr.data.bmi < data.bmi:
n = Node()
n.data = data
n.next = curr
self.head = n
return
if curr.data.points < data.points:
n = Node()
n.data = data
n.next = curr
self.head = n
return
while curr.next is not None:
if curr.next.data.points < data.points:
break
curr = curr.next
n = Node()
n.data = data
n.next = curr.next
curr.next = n
return
def __str__(self):
data = []
curr = self.head
while curr is not None:
data.append(curr.data)
curr = curr.next
return "[%s]" %(', '.join(str(i) for i in data))
def __repr__(self):
return self.__str__()```
found out how to format it easier, same code
what?
What's your actual question? You haven't asked anything.
So I am able to sort the linked list by the points, but not with the BMI also, how would I be able to sort the list with both?
I'd suggest you take the code determining which of two nodes should be first out into a function; that'd make it much easier to work with.
def get_edge_list(self):
edge_list = []
for edge_object in self.edges:
edge = (edge_object.value, edge_object.node_from.value, edge_object.node_to.value)
edge_list.append(edge)
return edge_list
before edge is appended to edge_list is it a tuple?
also what is the point of the function why do you have to get the edge list
this code reminds me that "machine learning is just a bunch of nested if elses"
jk
lmao I was going to say you should say jk before they all come here and confront you
LOL
def get_adjacency_list(self):
max_index = self.find_max_index()
adjacency_list = [None] * (max_index + 1)
for edge_object in self.edges:
if adjacency_list[edge_object.node_from.value]:
adjacency_list[edge_object.node_from.value].append((edge_object.node_to.value, edge_object.value))
else:
adjacency_list[edge_object.node_from.value] = [(edge_object.node_to.value, edge_object.value)]
return adjacency_list
def get_adjacency_matrix(self):
max_index = self.find_max_index()
adjacency_matrix = [[0 for i in range(max_index + 1)] for j in range(max_index + 1)]
for edge_object in self.edges:
adjacency_matrix[edge_object.node_from.value][edge_object.node_to.value] = edge_object.value
return adjacency_matrix
what's an adjacency list and an adjacency matrix?
an adjacency list could be the nodes that are close to the edge
but what's adjacency matrix
it's a 2d matrix where if matrix[i][j] == 1 represents an edge between nodes i and j
a adjacency list is a 2d list where list[i] represents the neighbors of i
https://codeforces.com/problemset/problem/607/B
ik it's range dp
and there's 2 possible recurrence relations
- standard splitting and summing where
- a prefix and the suffix combine to form a palindrome and there's some in the middle
for but 2 there's n^2 possibilities if it's smth like
11111111111111111111111111111111111111111
so i have no idea how to do this in n^3 time, any help? (ping 2 reply thx)
Introduction to Algorithms, 3rd Edition (The MIT Press) by Thomas H. Cormen
Is this a good book on Algorithms? The reviews seem good, does anyone here have experience with this book?
so are list faster than dict?
lists can do things that dicts can't, dicts can do things lists can't
Tony Stark
sure - but for the things that both can do, one is faster than the other at that operation.
mutually exclusive
like, you could choose to never use lists, and instead just use dicts with integer keys. But, uh, don't. 😄
Yeah
Ready for what?
your post
ok. Yeah I'm done.
I mostly use dictionaries to get O(1) access to things for searching, so from there I assumed they are fast at everything, which seems isnt the case.
they are O(1) for basically every important operation, though that's O(1) with a large constant, which makes them slower than things that are O(1) with a small constant
the high up-front cost of hashing the keys makes them slower in practice for some operations, since that's a fixed, up-front cost to dict lookups
By high up-front cost of hashing the keys, do you mean the computation that goes into it?
yes. Computing a hash is relatively slow and expensive.
for instance, computing the hash for a key being looked up in a dictionary is O(1) with respect to the size of the dictionary - computing the hash of one key doesn't get slower just because the dictionary has more keys in it. But, computing the hash of a key is O(n) with respect to the size of that key. It's not free.
so let's say you wanted to store the following and you had to look up for these values:
"John", "Steve", "Adam"
it would be better to store them in a list than a dictionary because it's 3 elements?
Oh ok
so storing in a dictionary is O(n) because you have to compute the hash
hashing is O(n), where n is the length of the key being hashed. storing in a dictionary is O(1), because n is the number of items in the dictionary.
is the length of the key being hashed the same each time?
or does it get longer with more insertions?
that is, the time taken to hash a key is independent of the size of the dictionary the key is going to be inserted into, but not independent of the size of the key.
ok
it does not - the hashing step doesn't know anything at all about the dictionary
first you hash your key, which needs to process your entire key and come up with a hash code for it. That operation is linear with the length of the key, since it needs to look at the entire key.
Then, you take that hash code, and you insert it into the dictionary along with the key and value. That operation takes O(1) best case, O(n) worst case (when every key has hashed to the same code)
Oh my God, I think I'm starting to get it now.
so if we have:
dictionary = {"John": True}
then we are generating a hash for the key that's John. And generating this hash is O(n). And as you said n is the length of the key being hashed.
Yes.
hello i have a question about RSA encryption
its about the value of 'e'
and written on the formula is that the value for e must be 1 < e < totient and gcd(totient,e) == 1
so for example if number 10 and 30 both pass the condition is it safe to use any of those two values for e?
I have a code in O(m*n). How do I optimize it?
def solution(cake_count, flavor_count, cake_starts, cake_ends, flavors):
cakes = [[] for _ in range(cake_count)]
flavors_length = len(flavors)
for j in range(flavors_length):
for i in range(cake_starts[j], cake_ends[j] + 1):
cakes[i - 1].append(flavors[j])
perfect_cake = list(range(1, flavor_count + 1))
well_prepared = 0
for cake in cakes:
if cake == perfect_cake:
well_prepared += 1
return well_prepared
if __name__ == '__main__':
print(solution(5, 1, [1, 2], [1, 2], [1, 1])) # 2
print(solution(5, 3, [1, 1, 4, 1, 4], [5, 2, 5, 5, 4], [1, 2, 2, 3, 3])) # 3
print(solution(6, 4, [1, 2, 1, 1], [3, 3, 6, 6], [1, 2, 3, 4])) # 2
print(solution(3, 2, [1, 3, 3, 1, 1], [2, 3, 3, 1, 2], [1, 2, 1, 2, 2])) # 1
print(solution(5, 2, [1, 1, 2], [5, 5, 3], [1, 2, 1])) # 3
for merge sort we can choose to use any sorting algo such as bubble/selection/insertion.... etc?
you can not do any sorting at all - 1-element lists are already sorted.
it's an optimization to instead split only down to chunks of some small fixed length, which are sorted via a O(n^2) sorting algorithm, but it's not necessary.
oh nvm that's a stupid question since after dividing all the way we just compare one 1-element array against another 1-element array, and that's the sorting part
i have this simple program to plot polynnomials
import matplotlib.pyplot as plt
def quadratic(x):
x = float(x)
return 4*x**4 - 3*x**2
quadpoints = []
for p in range(-1000, 1001):
quadpoints.append([p, quadratic(p)])
tmpx = [i[0] for i in quadpoints]
tmpy = [i[1] for i in quadpoints]
plt.plot(tmpx, tmpy)
plt.show()
it should return
but instead i get
@tiny oriole your first picture uses an x range of [-1, 1] or so. You are plotting [-1000, 1000]
i needed to make the step smaller instead of the range bigger
lul
its working
thanks
import matplotlib.pyplot as plt
import numpy as np
def quadratic(x):
return 4*x**4 - 3*x**2
quadpoints = []
rnge = np.arange(-1, 1, 0.00001)
for r in rnge:
quadpoints.append([r, quadratic(r)])
tmpx = [i[0] for i in quadpoints]
tmpy = [i[1] for i in quadpoints]
plt.plot(tmpx, tmpy)
plt.show()
@still sleet this is all my opinion, but it really depends on you
CLRS is a book that uses a lot of scholarly/academic language
and it goes very in depth
if you don’t like reading like big textbooks I wouldn’t recommend it
consider using linspace instead of arange
np.linspace(-1,1,10000) would get you 10000 evenly spaced points from -1 to 1, no need to calculate the step yourself. That's what's often used for plotting.
also, if you're using numpy, you might as well just do vectorized operations:
import matplotlib.pyplot as plt
import numpy as np
def quadratic(x):
return 4*x**4 - 3*x**2
X = np.linspace(-1, 1, 100000)
Y = quadratic(X)
plt.plot(X, Y)
plt.show()
do I need to know how lambda works for ds/algos
isn't it just a quick way to write a function 🥴
in like one line
is it easy to pick up
I heard Guido said that he isn't particularly fond of lambda expressions
anonymous functions are about the same in any language
what's an anonymous function
a function that's not defined with def?
that was a guess
a function without a name - some object that can be called (maybe with arguments)
(in some languages, functions aren't objects (you can't reference a function), but anonymous functions still are)
in python, you just go from a function like
def f(a,b):
return a + b
# to:
lambda a,b: a+b
lambda arguments: expression
you could do f = lambda a,b: a+b, in fact, and that's pretty much equivalent to the full def (but discouraged)
so like lambda arguments are parameters
yeah
oh 🥴 then I don't get why people hate it so much
I guess the more complicated it becomes the harder it is to read?
it started getting into places it shouldn't be in tbh
oh I see
double = lambda x: x * 2
print(double(5))
in this case double would be the function
and x is the parameter
bc it has a function name
yeah
print((lambda x: x * 2)(5))
oh I see
ok
yeah that is pretty cool
yeah Guido wanted map(), filter(), and lambda out
i've mostly used lambdas in map/filter, as the key in max/min/sort ||and #esoteric-python||
I didn't read his blog so I don't know why he wanted them out
def find_max_index(self):
max_index = -1
if len(self.nodes):
for node in self.nodes:
if node.value > max_index:
max_index = node.value
return max_index
So, i have a bunch of ordered lists that contain ints and floats, and i need to use the numbers in the lists for some multiplication, but they all have to be ints to do that. How can i iterate through the lists and detect if the item is an int or a float and change them to be an int or a float accordingly?
you can use the length as something in an if statement?
like just the length of something alone?
what conditional is that? like if the length exists?
oh so basically what I said
ok
what's the point of even finding the max index?
I just hate how Udacity just chucks all this code at me w 0 explanation and 0 comments
i don't see the point of the if len(self.nodes) line tbh
if its empty the for would have no effect anyway
find max index of what
it seems like they set the value of a node equal to the max index
so max index is now the value of the node?
can't you use lambda for literally everything if you wanted to
make every function you ever coded like 2-3 lines
can't be very readable tho
again about this you're not really finding the max index how do you compare an index to a value and then set the value equal to the index
what is the point?
Which part of this do you have trouble with?
it seems to me like you just want to do int on every element of these lists.
Aaaaaand i just realized i can convert all of it to floats and it will work fine
(also, how come they need to have the same type anyway? float*int multiplication in python gives the same result as if that int was manually casted to float before multiplying)
Cause they were all originally strings
And i didnt just convert them all in the first place
ah, I see.
am I right about this whole find_max_index thing
that said, in case you do need this one day, you can do it like:
for i,el in enumerate(lst):
try:
lst[i] = int(el)
except ValueError:
try:
lst[i] = float(el)
except ValueError:
raise ValueError(f"lst[{i}] is {el}, and could be converted to neither an int nor a float!")
@inland iron
(using exception handling for this is the Python way to do this, in many languages it's instead suggested to check the validity with the right methods. In Python, that'd be str.is_digit for ints, but for floats it's more complicated)
hey is the eulerian path an algorithm too?
why did they decide to teach the eulerian path instead of Dijikstra's algorithm
The eulerian path is a path in a graph. 😛 Finding it takes an algorithm, yes.
I haven't studied how to find eulerian cycles, but it doesn't look like they are at all related to Dijkstra:
https://en.wikipedia.org/wiki/Eulerian_path#Constructing_Eulerian_trails_and_circuits
fun times
Okay, another issue i have. I have multiple floats that i outputted from a for loop and assigned them all one variable. How do i find the sum of all these floats (when i have one variable representing the iterables, which makes it not an iterable) ? I need a sort of counter thing in which for each loop in the for loop, you add the next number to the total and so on, idk
guys any tips for writing algorithms.Kinda tough for me
Cause im coding a sort of paint job calculator, in which there are ordered values in input.txt that represent the h, w, l, and number of coats for each room, as well as the cost per square foot of paint, and HST as well. Ive done all the calculations for this except the subtotal and tax. All the values are to be outputted to output.txt in a sort of chart/reciept.
what specific algorithm?
in general when i try to write one for problems
problems like the ones in competitive programming websites
@old rover
well
when I do leetcode questions I give myself 20 minutes
and if those 20 minutes pass and I have barely written any questions
I look at the discussions for solutions
then I take a break for a while
and come back to it and try to write the solution on my own
also please don't try doing like 20 leetcode questions in one day
it is not a fun time and you will likely end up burning yourself out really badly
@old rover alrighty. Thanks man😎
it's like any standardized test you've ever taken the more you take those tests the better you get at figuring out tricks
Can anyone direct me toward s the concept being used here
You are given an array of speed of cars at i th position , cars are arranged on a linear line
Determine the minimum number of cars whose speed need to be increased so ther are no collison
N=3,v=[1,2,1]
Output 1
My intuition is that we need to find the minimum number of changes to make the array increasing
@fiery cosmos I think that this solution can work:
cnt = 0
for i in range(1, len(arr)):
if arr[i] < arr[i-1]:
arr[i] = arr[i-1]
cnt += 1
return cnt```
Sorry this doesnt work
so you can use DFS and BFS not only on graphs
but you can use it on trees too
or strings
that's pretty cool
Trees are graphs, though.
https://en.wikipedia.org/wiki/Tree_(graph_theory)
In graph theory, a tree is an undirected graph in which any two vertices are connected by exactly one path, or equivalently a connected acyclic undirected graph.
In graph theory, a tree is an undirected graph in which any two vertices are connected by exactly one path, or equivalently a connected acyclic undirected graph. A forest is an undirected graph in which any two vertices are connected by at most one path, or equivalently an acyclic undirected graph, or equivalently a disjoint union of trees.A pol...
🥴
learn something new every day ig
what does it mean when he says breadth first search means you go wide
not deep
That's literally the meaning of breadth.
yes
In a breadth first search, you search left to right first, before descending. In a depth first search, you search top to bottom before left to right.
is there a nice way to make this function iteratively.
Tree = Optional[tuple[Tree, ElemType, Tree]]
def cata_tree(empty: T, function: Callable[[T, ElemType, T], T] tree: Tree) -> T:
if tree is None:
return empty
left, value, right = tree
return function(cata_tree(empty, function, left), value, cata_tree(empty, function, right))
``` (pseudocode in the types)
everything I come up with essentially involves making a tiny interpreter.
yes.
I can't make sense of your last line here. Your recursive calls to cata_tree don't pass enough arguments.
ah, my bad
essentially, None becomes empty and the tuples get converted according to function, creating the single result T
looks like you're basically just looking for an iterative post-order traversal - right?
Yeah. The trees you're used to seeing are rooted trees -- trees with one of the nodes chosen as the root.
oh ok
are you talking to me here or lakmatiol
nvm it seems like he's talking to lakmatiol
ah, so it just is that complex.
yeah. You're basically replacing the call stack that the interpreter maintains for you with an explicit stack that you maintain in your code.
the Morris Traversal one is wild, though. I hadn't seen that one before.
There may be easier ways to do it if you don't need to maintain the exact order that the recursive one makes the calls in, though.
I recently started learning about Trees and I'm still new to it, but having looked at how some of the Tree methods are done, they seem a lot cleaner with recursion.
ye, recursive data structures are really nice to deal with using recursion
https://paste.pythondiscord.com/uzugesanok.py it seems to work. Now to rewrite it in haskell.
Learn the basics of graph search and common operations; Depth First Search (DFS) and Breadth First Search (BFS). This video is a part of HackerRank's Cracking The Coding Interview Tutorial with Gayle Laakmann McDowell. http://www.hackerrank.com/domains/tutorials/cracking-the-coding-interview?utm_source=video&utm_medium=youtube&utm_campaign=ctci
🥴
this is a terrible explanation
how are you going to give letters to certain nodes and then give more letters to the same nodes
I agree that it would have been nicer to use letters and numbers, or greek letters and latin. But it's not too hard to follow.
well I found it hard
I have a little bit of a problem. I am currently working on a project, where I need to convert a file, read in binary mode, to a list of integers. But I also need to reverse that and get the same output as the input file. The file structure is completely unknown. I already tried using the int.from_bytes() function to convert the whole bytestring (?) I get into an integer at once, then converted the integer to a string, splitted it into a list. From there I was able to use the values and just convert them back to integers, when I needed it. The problem was the backwards. There I took the strings, converted them to integers and put them back together. The problem now is, that if I try to use the int.to_bytes function I get an overflow error.
Then I thought about first splitting the bytes I read and then converting them to ints, so if I do that backwards the int.to_bytes function has smaller things to work with, but after I converted the bytes to a string and splitted it I didnt find a possibility to make integers out of it.
I am not a very experienced programmer, so please patient with me and if possible choose the long forms for solution instead of super compact ones, because in the end I want to understand it of course.
Any answer is appreciated and if you need more info, it would be a pleasure for me to give it. And of course, if I make any mistakes correct me please. I am using Python 3.8.5. You dont wanna see my code btw its trash and not readable for people, that didnt create it. Rn its more an experiment. If I find a solution I will do a clean up of course.
Thanks already for reading this novel!
I hope this is the right channel, if not I am sorry and I will move that.
what do you mean by "the file structure is completely unknown"?
OK - so you just want to turn a binary file into a list of integers, and a list of integers back into a binary file?
Yes.
so a binary file contains a bunch of bytes. Each byte holds a number between 0 and 255. It's trivial to turn an N byte file into a list of N integers, each between 0 and 255. And the reverse is trivial, too.
would that work for you?
Yes, should work!
well, then, easy peasy. To take a binary file and turn it into a list of integers:
with open("filename.ext", "rb") as f:
ints = list(f.read())
To take that list of integers and turn it back into a file:
with open("filename.ext.new", "wb") as f:
f.write(bytes(ints))
ohhh. Thank you so much!!!!
TIL you can make a bytes instance like this
yeah, you have been able to since Python 3.
what's bytearray used for, then? I suffered with it every time I needed to work with bytes, yet apparently a list of ints works too
BFS and DFS is about as easy as in order, post order, and pre order traversal
bytearray and bytes are pretty much interchangeable these days. The only big difference is that bytearray is mutable and bytes is immutable.
I don't know why I'm struggling
Btw how do you get the syntax highlighting in Discord? ¯_(ツ)_/¯
but yeah, back in the Python 2 days, using bytearray would have been the easiest way to do this.
Python 2.7.17 (default, Apr 15 2020, 17:20:14)
[GCC 7.5.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> bytes([48,49,50])
'[48, 49, 50]'
>>> bytes(bytearray([48,49,50]))
'012'
and of course you could also write the bytearray directly to a file, without the extra call to bytes
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
ohh that works? The colored highlighting is automatic? I never noticed that. Thanks a lot!
It's automatic as long as you put "py" after the 3 backticks to start the code block, yeah.
Ohh. Cool!
class Graph(object):
def dfs_helper(self, start_node):
"""The helper function for a recursive implementation
of Depth First Search iterating through a node's edges. The
output should be a list of numbers corresponding to the
values of the traversed nodes.
ARGUMENTS: start_node is the starting Node
REQUIRES: self._clear_visited() to be called before
MODIFIES: the value of the visited property of nodes in self.nodes
RETURN: a list of the traversed node values (integers).
"""
ret_list = [start_node.value]
start_node.visited = True
edges_out = [e for e in start_node.edges
if e.node_to.value != start_node.value]
for edge in edges_out:
if not edge.node_to.visited:
ret_list.extend(self.dfs_helper(edge.node_to))
return ret_list
so over here self refers to what
the object?
graph
self always refers to the instance that an instance method is called on.
This is the very, very basics of OOP in Python. If you don't already understand this, then you should probably spend some time learning Python OOP, rather than DS&A. A lot of things will make a lot more sense once you understand how instance methods and instance attributes work.
I do know OOP
I just didn't know you could refer to self when you didn't have a def init
Sure. This class has just inherited the __init__ from object, which basically does nothing.
sure. But here, there are no instance attributes, so there would be nothing for __init__ to do, so there's no need to have it.
right
so in Grokking it says BFS is designed to answer two questions
Is there a path from node A to node B?
and what is the shortest path from node A to node B
sure.
they use going from Twin Peaks to the Golden Gate Bridge as a shortest path example
that makes sense
which one gets you to the golden gate bridge with the smallest amount of steps
so it's less about actually logging what the value of each node is
but it's more about seeing what the shortest possible path is
it's a search. The point of any search is to find something.
right
for BFS in particular, all the nodes 1 away from the start are searched, then all the nodes 2 away, then all the nodes 3 away, etc - so not only does it find a way to reach the node it's looking for, but also it finds the shortest way (or one of the shortest ways)
it also checks if the path to that node exists
from the starting node to the given node
well, yeah - that's just the special case of "we searched the entire connected graph without finding the node you searched for"
if any paths from the start node to the searched node exist, it finds you one of the shortest ones. Otherwise, it tells you that no path exists.
how would we know? 😄
god knows
All of the tree traversals you posted here are dfs
Or well, depth first traversals
like you would check the levels of a tree
possibly they decide to leave it as an exercise to the reader. It's basically the same algorithm, except with a stack instead of a queue
time to ask an even dumber question
why a queue for a breadth first search and not a stack?
queues allow you to enqueue and deque
stacks push and pop
because if you use a stack, it searches the nodes in a different order than if you use a queue. It becomes a depth first search instead of breadth first.
why does it search the nodes in a different order than if you use a queue? bc of the specific data structure's functions?
because queue is first-in, first-out, and stack is last-in, first-out.
right
bc the first thing you put in the stack it gets pushed to the bottom as you add more items
like dirty plates
or pancakes
first-in, first-out means that if you add all of the children of a node to the queue, then all of their children, etc you search them in that order. Breadth-first.
last-in, first-out means that if you add all of the children of a node to the stack, then you pop one to work on, it will be one of the most recently added ones. Then you'll repeat that, and descend into one of that child's most recently added ones. You go to the children of a node before you've ever popped that node's siblings off the stack.
That's depth-first.
What do you guys think of these data structures based interviews?
I think they're basically a necessary evil. Data structures are pretty much the one thing that every CS graduate is taught, in approximately the same way, and about which they can demonstrate their knowledge in 20 minutes or so. There aren't very many other level playing fields on which junior developers can be assessed.
The downside to them is that, for most programmers, the job doesn't really need much DS&A, so we're testing the candidates on a thing that they learned, but won't need very often.
yeah I agree with godlygeek
I can't name an alternative to DSA to testing someone's ability
maybe projects? but a 30 minute project sounds trivial
the other kind of interview that works pretty well is a take-home assignment that the candidate is asked to implement. But that has some big disadvantages, too - it biases towards people who have more time to work on it, and leaves you with no assurance that they did the work themselves.
they could very well ask for help
but isn't that what people should do tho
I mean, if he/she just copy pasted everything then that's bad
if you're asking for help it isn't a measure of your own skills then
Why
do I really have to explain why 🥴
the same way we don't help with school assignments or we offer minimal help
I guess it depends on what you mean. Is that what people should do to have the highest chance of getting the job? Yeah, probably. The only real downside from the candidate's point of view will be potentially getting a job that they find they can't actually do. But from the company's perspective, they'd prefer to hire someone who needs less help to do the job, since training someone and providing them with necessary help is expensive.
def dfs_helper(self, start_node):
"""The helper function for a recursive implementation
of Depth First Search iterating through a node's edges. The
output should be a list of numbers corresponding to the
values of the traversed nodes.
ARGUMENTS: start_node is the starting Node
REQUIRES: self._clear_visited() to be called before
MODIFIES: the value of the visited property of nodes in self.nodes
RETURN: a list of the traversed node values (integers).
"""
ret_list = [start_node.value]
start_node.visited = True
edges_out = [e for e in start_node.edges
if e.node_to.value != start_node.value]
for edge in edges_out:
if not edge.node_to.visited:
ret_list.extend(self.dfs_helper(edge.node_to))
return ret_list
I like you said necessary evil which I agree with. Because if companies didnt do DS type interviews, then they would likely give some sort of take home project. And if you get 10 interviews you have 10 take homes and also as you said this would be a bias towards people who have more.
But I guess you prepare for DS once and the same concepts would get utilized in all 10 interviews
yeah, exactly.
cuz they probably do it recursively
I never used a stack for dfs xd
It's a recursive implementation. The stack they're using is the call stack.
what's a call stack 🥴
The interviewers also don't want to see you fail. It's boring for them to be stuck in a room for an hour watching someone try to do something and failing at it, or going down a path that the interviewer knows will never work, or whatever. So, good interviewers will be giving you hints when you get stuck, and guiding you in the right direction, etc. They'd prefer that you figure out the algorithm to implement on your own, but if you're not getting ti they'll probably help you figure out the algorithm, and just want to see you implement it. Or even point out bugs in your implementation to see if you can fix them.
oh ok I see what a call stack is
You can imagine function calls as a stack. They're actually implemented that way under the hood. Whenever you call a function, the function that was executing is pushed aside, and the new one starts running. When that new one returns, that call is popped off the stack, and control resumes in the previous function, which is now back at the top of the stack.
that call stack is what's in charge of tracking where control will resume whenever a function returns.
got it
if not edge.node_to.visited:
ret_list.extend(self.dfs_helper(edge.node_to))
what's .extend
oh it's legit
it adds all elements to the end of the list
ok
just never seen it used before
a.extend(b) is the same as ```py
for e in b:
a.append(e)
append takes a new element and puts it on the end of the list. extend takes a sequence of elements and puts all of them on the end of the list.
!e ```py
a = [1]
b = [2, 3]
a.append(b)
print(a)
@lean dome :white_check_mark: Your eval job has completed with return code 0.
[1, [2, 3]]
!e ```py
a = [1]
b = [2, 3]
a.extend(b)
print(a)
@lean dome :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3]
append takes the whole list and sticks it as a single new element. extend takes each item of the list and sticks it on as a separate element.
right.
that's cool
what does a depth first search do that a breadth first search can't?
like what questions does it answer?
if a BFS is designed to answer what the shortest path to a given node is and whether not the path exists, what does a DFS do?
It can answer whether any path exists, or whether any path of length <= N exists (by putting a limit on how deep it's allowed to descend)
and in cases where the graph is much wider than it is deep, DFS can require much less temporary memory than BFS would.
oh ok
Is this how someone would usually implement a Tree insert method:
class Node:
def __init__(self, value):
self.value = value
self.left_child = None
self.right_child = None
class BinarySearchTree:
def __init__(self):
self.root = None
def _insert(self, new_value, current):
if new_value < current.value:
if current.left_child is None:
current.left_child = Node(new_value)
else:
self._insert(new_value, current.left_child)
elif new_value > current.value:
if current.right_child is None:
current.right_child = Node(new_value)
else:
self._insert(new_value, current.right_child)
def insert(self, new_value):
if self.root is None:
self.root = Node(new_value)
return
current = self.root
self._insert(new_value, current)
sure, that looks reasonable. It can't handle duplicate values.
No it cant handle duplicates
And I have came across the below implementation for insert_left and insert_right:
class BinaryTree:
def __init__(self, value):
self.value = value
self.left_child = None
self.right_child = None
def insert_left(self, value):
if self.left_child == None:
self.left_child = BinaryTree(value)
else:
new_node = BinaryTree(value)
new_node.left_child = self.left_child
self.left_child = new_node
def insert_right(self, value):
if self.right_child == None:
self.right_child = BinaryTree(value)
else:
new_node = BinaryTree(value)
new_node.right_child = self.right_child
self.right_child = new_node
a_node = BinaryTree('a')
a_node.insert_left('b')
a_node.insert_right('c')
b_node = a_node.left_child
b_node.insert_right('d')
c_node = a_node.right_child
c_node.insert_left('e')
c_node.insert_right('f')
d_node = b_node.right_child
e_node = c_node.left_child
f_node = c_node.right_child
print(a_node.value) # a
print(b_node.value) # b
print(c_node.value) # c
print(d_node.value) # d
print(e_node.value) # e
print(f_node.value) # f
which seems like they always update the left or right to whatever the newer inserted value is.
Having thought about this, I think that self.root should never change, so in the below self.root would always stay 4:
# 4
# / \
# 2 6
# / \ / \
# 1 3 5 7
using regex, how can I make it return the next word or the content within parentheses (found in the next word) from matches?
does regex have to do w algos/DS
I suppose so
since it's a string searching algorithm
I understand that's how graphs are normally represented
but I find that pretty confusing to look at
maybe it's just me
State machines, yuck
what is that 🥴
that looks so complicated bruh
Pretty much all software is a state machine. Making the states and transitions between them explicit can sometimes make it much easier to reason about what's happening.
I am really weak into this stuff and i've spent like an hour fumbling over this. How would i make a function that accepts starting level, and the final level you want and output the amount of coins you'd recieve?
Im sorry if it seems trivial but I seriously cannot figure it out
The dead simple way is to use a loop, though it's not very efficient. ```py
def coins_collected(starting_level, final_level):
count = 0
for level in range(starting_level, final_level + 1):
if level < 48:
count += 65
elif level < 70:
count += 35
else:
count += 12
return count
omd i cannot believe i didnt think that through
thank you so much
holy i cannot believe i didnt think that through i was thinking of some complicated list system i cant believe it. its late here cant think straight. tysm
The complicated, faster way is to compute how many levels are overlap with each range, and then multiply those out by the number of coins per level in that range.
def coins_collected1(starting_level, final_level):
levels_at_65 = max(min(final_level + 1, 48) - max(starting_level, 1), 0)
levels_at_35 = max(min(final_level + 1, 70) - max(starting_level, 48), 0)
levels_at_12 = max(min(final_level + 1, 100) - max(starting_level, 70), 0)
return levels_at_65 * 65 + levels_at_35 * 35 + levels_at_12 * 12
wow that is insane. i would have never even come close to thinking of that.
thank you for your help dude. I appreciate it alot its helping me get better at what am doing.
oh Eulerian is pronounced oilerian
not ewlerian
🥴
what's a degree in a graph
number of edges incident to the vertex???
https://en.wikipedia.org/wiki/Degree_(graph_theory) explains it well.
yeah and people still pronounce his name wrong 😔 it's U ler smh
well yeah that's where I got the definition from 🥴
so, then, why did you ask?
"the vertex" the vertex
so it's just the amount of edges going into a node
https://en.wikipedia.org/wiki/Graph_theory
A graph in this context is made up of vertices (also called nodes or points) which are connected by edges (also called links or lines).
yeah
ok
with loops counted as 2, apparently.
what's a loop 🥴
apparently, as https://en.wikipedia.org/wiki/Degree_(graph_theory) puts it -
In graph theory, the degree (or valency) of a vertex of a graph is the number of edges that are incident to the vertex, and in a multigraph, loops are counted twice.[1]
a vertex with an edge to itself.
huh, weird
the blue are loops
YES
FINALLY
Dijkstra's algorithm makes an appearance
why am I excited about some random algorithm 🥴
it's famous lol
oh it's pronounced "Dykstra's"
not deekstra's
🥴
I may have embarrassed myself on a software dev internship interview by calling it "deekstra's" algorithm
doesn't matter how you pronounce it if you understand it ¯_(ツ)_/¯
Step by step instructions showing how to run Dijkstra's algorithm on a graph.
Sources:
- Algorithms by Dasgupta, Papadimitriou & Vazirani [https://code.google.com/p/eclipselu/downloads/detail?name=algorithms.pdf]
LinkedIn: https://www.linkedin.com/in/michael-sambol-076471ba
I was watching this video
and he said the numbers on the side mean the cost?
cost of what 🥴
cost of visiting the vertex?
yall know about the longest increasing subsequence problem
like given an array of integers you have to find the, well, longest increasing subsequence
is there an adaption for pairs
like an array of pairs and you have to find the longest subsequence (a_1, b_1), (a_2, b_2)...
so that a_i < a_i + 1 and b_i < b_i + 1 always
uh idk if this is relevant
but i found this one here: https://www.redblobgames.com/pathfinding/a-star/introduction.html
the most helpful for shortest paths
the author uses grids as examples but it's easily generalizable to graphs
This book is great for those who want an introduction into using algorithms and data structures in Python. There are plenty of implementations included for all the data structures and algorithms discussed in the book. The topics range from big O notation to graphs. Here's the link: https://runestone.academy/runestone/books/published/pythonds3/index.html
An interactive version of Problem Solving with Algorithms and Data Structures using Python.
@alpine tide if you think I should add anything let me know
is the assumption that the dictionary has many keys in it, most of which already conform with the naming convention?
then why is it important that it be done in place?
The easiest way to do it in place would be something like ```py
for k in list(the_dict.keys()):
new_k = fix_naming(k)
the_dict[new_k] = the_dict.pop(k)
but that'll be slower and more work than just building a brand new dictionary would.
new_dict = {fix_naming(k): v for k, v in the_dict.items()}
yep.
yeah, that's a dictionary comprehension.
is the 3rd question here really as simple as I think it is? Like is it just a single accepting node and nothing else?
and is "any symbol" here, supposed to mean just a, b, c?
I think that means that it wants any string of length 1 or greater, composed of only a, b, and c characters
strings where any symbol (out of the alphabet) appears are lexicographically correct, but not strings where no symbol from the alphabet occurs
@fiery cosmos ^
so I think for 2.3, you want a DFA with 2 nodes - a start state, and an accepting state, where you transition from the start state to the accepting state on a or b or c, and where the accepting state transitions to the accepting state on a or b or c
Finite state machine who accept your substring only
In the theory of computation, a branch of theoretical computer science, a deterministic finite automaton (DFA)—also known as deterministic finite acceptor (DFA), deterministic finite-state machine (DFSM), or deterministic finite-state automaton (DFSA)—is a finite-state machine that accepts or rejects a given string of symbols, by running through...
your machine accept "ccc" per exemple lol
yes... that's valid for 2.3, isn't it?
I am just asking about the 3rd question. @meager jetty
I figured out 1st and 2nd one
but my solution seems way too simple.
this one here
Like I said, I think you need 2 nodes, because you need to reject strings of length 0.
may be im wrong I was thinking all rules 1 and 2 together
if 3 is alone your answaer is correct
I didn;t think of that
thanks
usually no string is not a string
but if you need to consider a noSting so u need 2 nodes
well, I could be wrong. The answer they're looking for is either 2 nodes with a transition from the starting state to the accepting state on A/B/C and a transition from accepting to accepting on A/B/C, or one node that's both starting and accepting, with a transition back to itself on A/B/C
I'm not 100% sure which of those two it wants.
It's been a while since I learned this stuff, but I believe the empty string is a valid string in a language, and I believe that the wording of this problem suggests it must not be accepted.
usually a NoString with a delimiter is not the same has a NoString
#
#
here you have 3 str (from the pareser point of view
\n
\n
I usually reason about DFAs in terms of regular expressions, and .* does accept an empty string, and ..* does not.
#\n
I am thinking the one with 2 nodes is wanted, since it specifically asked for symbols? and an empty string has none?
right. I lean the same way.
yup. I am gonna go with that one. thanks @lean dome @meager jetty
but you alway have delimiter "\n" in our case
well the symbols here do not specify any delimiters. it is restricted to only a,b and c, so I don't think I really need to worry about that
in an exam I will go with the 2 states .... because it detects the NoString 🙂
http://www.usaco.org/index.php?page=viewproblem2&cpid=529
i did this problem with hashing, but is it possible to do this with kmp? if so, how?
i have a potentially obscure question that i don't know how to search for due to its odd structure.
so i have a class Test __getter__ (and setter) method that returns (and sets) an attribute which itself is an instance of some other class.
how can i set attributes of the attribute?
class Child:
def __init__(self, v):
self.v = v
class Test:
def __init__(self, vals):
self.vals = vals
self.i = 0
@property
def child(self):
return self.vals[self.i]
how do i set Test(...).child.v through the child property?
(actually should i put this in a help channel?)
(nevermind, sorry about this: implementing the getter as-is is enough to already do that)
so the following Tree height method wouldnt work if the Tree isnt binary?
def __height(self, current, current_height):
if current is None:
return current_height
left_height = self.__height(current.left_child, current_height + 1)
right_height = self.__height(current.right_child, current_height + 1)
return max(left_height, right_height)
def height(self):
if self.root is None:
return
current = self.root
current_height = 0
return self.__height(current, current_height)
Above code wouldnt work on some Tree like below:?
8
/ \
1 10
/ \ / \
0 7 9 12
/
6
And if we get asked to calculate the height of a Tree, the Tree in most cases would be a Binary Search Tree?
wait, I didnt realize, but I actually drew a Binary Search Tree.
I would need values to convey that the right side of the node doesnt exist?
oh actually I'll edit the Tree
ok do you think you could look at the editted Tree now.
lol I'm such a newb, where am I missing the leaf at the bottom to the right of it?
after 9 and 12?
8
/ \
1 10
/ \ / \
0 7 9 12
/ /
-1 6
This would work fine
I think so.
Actually let me look at the code again.
And do a mental walk down of all recursive calls that are happening.
Ok so I see what's happeneing every call to left would also have access to right child because it's in the stack.
i need help
i need to turn a column of values with something like 1,000 instead of 1000 into floats but i still get chunks of strings left there
i try this
for i in training_set:
if isinstance(i[0], str):
i[0] = i[0].replace(',', '')
i = float(i)```
and heres what it gives me when i print it
[['93.7400']
['100.8800']
['97.1100']
...
[23.9641]
[24.1245]
[24.0525]]```
its i[0]=float(i[0])
please don't use that phrase
what does a directed graph mean again
the edges have a direction from one vertex to another
something like this?
what does the concept of "weight" mean in a graph? it just looks like numbers on the edges to me
if that's all I need to know then I'm ok ig
pretty much. For example, a weighted graph might be used represent points in space with distances between them.
yea I think it's just an abstract value
can we say that it represents the cost of traversing the edge, or is that not strictly true?
Graph theory doesn't assign a meaning to the weights, but the particular graph might. Usually they represent the cost of moving from one vertex to the other.
oh
what's up with infinity and Dijkstra's algorithm
Udacity says it's just a placeholder
That might be distances (like for a mapping algorithm) or costs (what's the cheapest way to get from a to b if train tickets cost X, bus tickets cost Y, and these transfers are available to me), etc.
usually when you have tasks like "find shortest (that is, with lowest total weigth) path between these points", there are some constraints that the weights must fullfill in order for the problem to make sense. For example, there must not be a cycle with a negative total length (because then you can loop over that cycle forever and get an arbitrarily low path length, up to minus infinity)
it just means you haven't assigned a weight to that node yet
using infinity means any weight you do assign it is smaller, so min(new_weight, inf) will be new_weight
oh ok
what's a greedy algorithm
it makes the best possible choice at each step of the problem
Dijkstra's algorithm is an example
this term always annoyed me because I don't think it has a rigid definition
it's pretty much "algorithms that choose the locally optimal choice at each step and hopefully result in a globally optimal solution"
so uh not to ask a stupid question or anything
but don't a lot of algorithms already do that?
is bubble sort considered a greedy algorithm?
I googled it and it turns out insertion sort is considered a "kind of greedy algorithm"
I'm still unsure how choosing the most optimal choice is considered "greedy"
I guess that's just the name
it's more like, uhh
one example I know is the task of giving a certain amount of change using coins of different denominations, such that the number of coins used is minimized
greedy choice: give out the highest coin you can currently give out until you're done. It turns out, this gets you the optimal result only in some cases - it depends on the denominations.
and the way denominations are in most countries is such that it does work.
oh
yeah they use the knapsack problem
like you put the heaviest things in the knapsack
what's the difference between a greedy algorithm and a brute force algorithm
not at all similar - brute force is guaranteed to find the optimal solution (because it examines all solutions), it's just, well, not feasible
greedy algorithms are the naive ones - they are usually very fast, it's just that they can also be very wrong in some problems
so would a brute force algorithm be like trying out all password combinations before finding the right one
ok
Brute force just means "try every possibility until you find one you're satisfied with". You may try all possibilities, guaranteeing you find the best one, or you may stop when you find any solution, if you're equally happy with any solution
The basic structure of a brute force algorithm is that it's set up to be able to enumerate every possible solution to the problem
Which MIT lecture?
MIT OCW starts w peak finding and talks about greedy algorithms
In the password guessing case, it would try every one letter password, from a to z, then every two letter, from aa to zz, them every 3 letter... It has no smarts about what passwords are likely, it just tries everything.
it’s pinned in the channel if you want to take a look
Found it, thanks!
does anyone have any resources for directed graph datasets? very simple (i,j,w) values?
@lean dome so if someone asked you to guess what letter they had in mind
would you just guess every letter?
That’s brute force right?
That would be brute force, yeah.
ok then it makes sense ig
so there’s greedy algorithms and there’s brute force algorithms
is there another category of algorithms?
Though, what's a better way to guess what letter they have in mind?
@solar timber binary search
There's a Family Guy episode where Peter is trying to remember some phone number, so he tries 111-1111, then 111-1112. That's brute force
Oh yeah, I saw a video on that
that's only possible if you have more information than "it's a letter"
Or, guess all 26 letters, but guess them from most common to least. Or from least common to most, if you think your friend probably picked X
But wouldn't we need more input for binary search?
Yes.
if your friend just says "it's a letter" you can't do binary search
there has to be some ordering to the thing you're searching
You need not just "no", but "no, it's higher"
C++ is the best language for brute force solutions, right?
Any language that compiles to machine code will be about equally good. C, C++, Java, C#, Rust, Go, ...
Okayy, but python isn't as efficient as Java for brute force solutions, right?
Right.
Thanks!
What do you mean?
it'll be slower than the languages that godlygeek listed
CPython - the most common Python interpreter - is pretty slow at CPU bound stuff.
Slower than nearly every common language.
That's not much of a problem for real world applications, because libraries like numpy do a lot of the number crunching type things outside of Python code, where they can be faster
And, most real world applications spend most of their time waiting on IO, not executing on the CPU.
I came across this some time ago:
You can ask, but I don't promise to answer 😄
I'm participating in an Olympiad, and I would prolly have a lot of doubts...
Perl is faster than C on that test? wtf
Haha... Thanks!
that's actually really weird
I'm not buying all Javas being slower than Python
(also, haven't heard of GCJ before, and it surpises me that it's so bad)
so basically, this plot seems weird without context
This is the actual link https://raid6.com.au/~onlyjob/posts/arena/
So there are different types of speed test.
But yeah I didnt buy it either that Perl is faster than C.
so say i had a sequence
a_1, a_2, ...a_i
and i wanted to find the LIS (longest increasing subsequence) and i did find it using the N log N approach
but then say i changed a random element a_x to increase by y
how would you find the length of the new LIS given the previous sequence and its LIS info in just O(1)?
for context, i'm doing this problem here: https://oj.uz/problem/view/CEOI18_glo
(ping 2 reply thx)
How would you add a list recursively?
wdym by "add a list"? find the sum of it?
Yeah if you have list = [1, 2, 3, 4]
Get the sum of the list recursively and return 10.
well you already know your base case
if the list is empty return 0
not so sure about the other part though
Hey so this might be a little late but when I took discrete math in college, I found the trev tutor on youtube really helpful. Also https://www.slader.com/textbook/9781259676512-discrete-mathematics-and-its-applications-8th-edition/?utm_source=Google&utm_medium=cpc&utm_campaign=12084177490&utm_content=116062271173&utm_term=%2Bdiscrete %2Bmathematics %2Band %2Bits %2Bapplications&matchtype=b&gclid=EAIaIQobChMI3d709q_l7wIVZsyzCh1OpQZeEAAYASAAEgL0MPD_BwE was really helpful at times. Also math does not really change at least such fundamental concepts so you can use a source regardless of age as long as it is credible.
def add_list(l):
return 0 if not l else l.pop() + add_list(l)
Or:
def add_list(l):
if not l:
return 0
rwturn l[0] + add_list(l[1:])
what does l[1:] do again
all the indexes past 1?
adds all the indexes of the list past 1?
It creates a copy of the list from 1 to the last element
Slices the list, creating a copy with every element but the first
oh
Yep. You could also do if len(l) == 0
Once you get used to formulating recursive algorithms, something this simple will come easily
if you go to leetcode you can filter by recursion to practice
nvm I thought there would be some gigantic repo with recursion problems
If someone can do some advanced DS&A question that involves recursion, but they cant do questions like these, it would make me wonder if they just memorized solutions.
there also some decent problems in CTCI about recursion
page 130
yeah they probably did memorize solutions
anyone aware of a nice binary~~ tire ~~ trie implementation for python, i want something that effectively stores and provides a lookup tables for hash values to a struct of 2 numbers
I'll check out CTCI, yeah leetcode didnt have a lot of recursion problems.
binary tire? you mean binary tree right
trie
i did, too
idk what a trie is yet
its a effective method for lookup into prefix trees (which is a nice to have if your lookup key is hashes)
because instead of all the full hashes, you get to store a more space effective lookup tree
Also commonly used to implement a spell checker
i just want to store about 250k blobs content addressed in a file
try that on for size too
why is it that when I see a recursion problem I can think of the base case pretty easily
but I can't think of the rest
Thanks, I'll look at it. I dont wanna say base case is simple, but rest of it starts to get confusing when you are mentally trying to keep track of all the recursive calls that are happening, at least that's the case for me.
I think my struggle is knowing where to call the function inside the function you're defining
I would say handle the base case first and then do recursion case.
yeah
that's how it's normally written anyways
base case first and then the recursion case
Either py files = [open(p) for p in paths] or ```py
files = list(map(open, paths))
Or ```py
files = [p.open() for p in paths]
int("123456", 16)
Nvm that would turn it decimal
Ok well
You could use hex and int
Or i guess you could just do that lmao
Looks kinda weird and hackish
why do you need a hex literal
it doesn't matter what base it's represented as, the value is the same
@fiery cosmos
if you don't check the base case first you'll enter an infinite recursion right away
@agile sundial yes
yes
yes 🥴
?
how is Udacity doing dynamic programming in like 3 minutes
god knows
is the only benefit of binarysearch that you can do the problem with people?
pretty much, yeah
oh cool it has recursion problems too
so just about anyone can join? do they need an invitation?
you can set it to either
oh ok
what anime is your pfp from
it's not an anime
a hashmap, probably
yeah I thought so too
what's memoization? storing calls for a function?
is it used in recursion too?
I've seen some articles about recursion where memoization comes up
Udacity says it's storing precomputed values
memoization is remembering the inputs and outputs of a function call, and reusing them on future calls with the same arguments.
yeah exactly, you basically store computed values and later use them rather than recomputing again
yeah that is pretty cool
it's a lot more common in purer FP languages
because they tend to use pure functions more
oh ok
I heard Google asks functional programming questions
oh my god guys
I finished the Udacity course 🥴
finally
how many leetcode questions should I be doing in a day?
or is that like entirely dependent on the person
probably what I said
ok several hours later I added all elements in a list recursively:
def add_list(num_list, i=0):
if i == len(num_list):
return 0
return num_list[i] + add_list(num_list, i + 1)
looks a lot similar to what godlygeek did
yep, but more efficient - it saves the copy.
Ok convert an integer to a string recursively with any base:
hint: ||string = "0123456789ABCDEF"||
After doing one-hot codes, i think
1 2 3
1 becomes 1 0 0
2 becomes 0 1 0
3 becomes 0 0 1
is this what one-hot codes is?
Reverse a string recursively
That's a fun one. Have you tried it?
Yeah, it was a lot similar to add_list. I find recursive way easier than a loop
def reverse_string(string, i=0):
if i == len(string):
return ""
return reverse_string(string, i + 1) + string[i]
I think the only thing is keeping in mind that the recursive function call comes first so you can get characters from the stack and then string[i]
do interviewers test you on radix sort
It seems like it would be fair game, but I don't think it's a very common thing to ask about
not usually
Yes, that is correct I believe
can someone help me out with dijkstra algorithm? I need a way to represent a weighted digraph, I tried a hashmap but I don't think that will work
Hi
hashmaps are a valid way
I found a way to do it, I store "i" as key, and (j,w) pair as a value
map each node's number to a list of numbers of nodes that the node can be reached from; that's a common way
and also store a list of distances
What’s a digraph
sometimes it's how "directed graph" is shortened
not to be confused with hypergraphs 😛
https://xkcd.com/2036/
pretty much what I did...
I stored the distances (weights) in the same HashMap, not as a separate list
hello there, can I ask something about graphs? I basically need to check if an element from a graph is visited more than once
but I'm not sure how to do so and how to make it efficient
keep a counter attribute in your element and every time you visit an element, increment the counter, do whatever condition checks with your counter
assuming your element or each graph node is an object, you can just add another instance variable like a counter
i have a g = [] and then I fill it inside a for loop with a, b = map(int, input().strip().split()) g[a].append[b]
and then g[b].append[a] so that it's bidirectional
so I don't think I can add instances that easily no?
hey so I've got a project for calculus where we're supposed to code something that makes use of integrals. my idea was to make an M&M sorting robot, so i coded a script that would take an image like this:
and convert it to this
then my plan was to use integrals to find the area of each shape by finding the area under the curve
but all I've got is a list full of red, green, and white pixels
is there an algorithm that can get me the points along the border of each m&m?
my thought was that on a grid of pixels, only pixels touching exactly two other pixels of the same color would be pixels on the border
but even if that were true (and I suspect it's not) an algorithm to find that seems like it would be really slow
it'd be kind of a weird idea instead of, you know, just counting the pixels 😛
we're supposed to code something that makes use of integrals
you could make something like a PID controller
I can't solve the problem still, I have to get how many nodes are visited more than one time and so far I'm trying to do something with keys, but I can't really understand if I'm doing it more or less right
g = {'Values': [],
'Weights': []}
for i in range(n):
g['Values'].append([])
g['Weights'].append([])
for i in range(m):
a, b = map(int, input().strip().split())
g[a].append(b)
g[b].append(a)
def dfsRec(g, visited, v):
visited[v] = True
for adj in g[v]:
if not visited[adj]:
dfsRec(g, visited, adj)
def dfs(g, c):
n = len(g)
counter = 0
store = []
visited = [False] * n
dfsRec(g, visited, 0)
for was_visited in visited:
if 2 in g['Weights']:
counter = counter * c
store.append(counter)
print(len(store) * c)
dfs(g, c)
I planned on storing the weight 2 elements on the store list, and multiply the c parameter by the length of that store list
that's what the problem requires me to do, but I can't even understand how to get those nodes at first
I played with graphs a little bit there #help-peanut message
and implement my kindof dijkstra shortest path ...
g = {}
g['s']={'a':7,'b':2,'c':3}
g['a']={'b':3,'d':4,'s':7}
g['b']={'a':3,'d':4,'h':20,'s':2}
g['c']={'l':2,'s':3}
g['d']={'a':4,'b':4,'f':5}
g['f']={'d':5,'h':3}
g['g']={'e':2,'h':2}
g['h']={'b':20,'f':3,'g':2,'e':4}
g['i']={'l':4,'j':6,'k':4}
g['j']={'l':4,'i':6,'k':4}
g['k']={'i':4,'j':4,'e':5}
g['l']={'i':4,'j':4,'c':2,'m':1}
g['m']={'l':1,'n':1,'o':2}
g['n']={'m':1,'o':1,'p':2}
g['o']={'m':2,'p':1,'n':1}
g['p']={'n':2,'o':1}
g['e']={'k':5,'g':2}
start='s'
stop='e'
start='s'
stop='e'
sorry it was not shortest path ...
I will paste it in 2secs
no cap
v = []
p = [[start,0]]
while len(p):
xx = p[0][1]
pp = [[s,x] for s,x in p if x == xx ]
vv = [[s,x] for s,x in pp if s.endswith(stop)]
if len(vv):
v = vv
break
p = p[len(pp):]
for s,x in pp:
p.extend( [[s+n,x+d] for n,d in g[s[-1]].items() if not n in s ] )
p = sorted(p, key=lambda x: x[1])
i = 0
print(v)
I don't even understand what it does, I'm quite new to programming
the graph g map into the dictionary
well the first section is a dictionary of dictionary representing the graph. I guess you should understand that. 🙂
what does the acceptance % mean in leetcode?
The ratio of accepted solutions to all submitted solutions
i want to start data structure and algorithm can any body tell me about what it is and how should i start and how is it useful
a data structure is just something you store data in
a list is a data structure
a dictionary is also a data structure
an algorithm is just a function that does something
printing hello world in a function can be called an algorithm
how you start depends on you. If you like textbooks, try reading Introduction to Algorithms, 3rd Edition. If you like more informal books, try Grokking Algorithms or this book https://runestone.academy/runestone/books/published/pythonds3/index.html.
data structures are useful bc you're going to be dealing with some sort of data with code most of the time and finding the most efficient container helps.
oh i see