#algos-and-data-structs

1 messages · Page 112 of 1

woeful gorge
#

The thing i can manually think of doing right now is something like

test_list=[] 
Result = False
for i in test_list:
    if condition(i) :
        result = True
        

grizzled schooner
#

@woeful gorge I think any() could work for that

lean dome
#

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

woeful gorge
#

Damnb these are some handy functions

#

Thanks guys

#

I should use map and filter etc morepithink

meager jetty
#
for x in things:
  if cod(x):
    v = x
    break
#

will be more efficient

lean dome
meager jetty
#

will be better than this result = any(filter(condition, test_list))

lean dome
#

Why would it?

meager jetty
#

why it won"t ?

lean dome
#

because that version does more work in Python and less in C, and doing more work in Python and less in C is slower.

fervent saddle
#

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?

meager jetty
#

ah ok im a noob 🙂

lean dome
#

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

meager jetty
#

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

fervent saddle
#

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

lean dome
#

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)

halcyon plankBOT
#

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

[10002, 10005, 10008, 10011, 10014]
lean dome
#

for instance. That's showing filter applied to an infinite iterator, itertools.count()

meager jetty
#

I thought filter was returning a list not an iterator ....

#

iterator should start with "i"

lean dome
#

!d filter

halcyon plankBOT
#
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.
lean dome
#

nope, it returns an iterator.

meager jetty
#

... on the other side you get only True as a result not the first True Item ..

lean dome
#

yeah, that's the behavior of any.

meager jetty
#

maybe im wrong ... let me look at doc

lean dome
#

nah, you're right. any doesn't return the first truthy item.

meager jetty
#

that is why I never used any ... we often need to do something with the first item ...

fervent saddle
#

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

meager jetty
#

really , how can you do that

fervent saddle
#

I was shown this just yesterday

meager jetty
#

x = any( cond(v), alist)

#

where do you put this walrus assigment in this

lean dome
#

!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)
halcyon plankBOT
#

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

21
lean dome
#

the parentheses around first := i aren't required, but I think it makes it a bit easier to read.

meager jetty
#

r = any(filter(lambda x: x==7, v))

#

so i need to plug a global somewhere into this lol

fervent saddle
#

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

meager jetty
#

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 ?

fervent saddle
#

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?

fervent saddle
#

#bot-commands message

#

It seems too close to call

#

So I guess it’s just whichever is more readable

fiery cosmos
#

Do adjacency matrices support adjacent node traversal? I've never used one

eager hamlet
heavy cloak
#

why is this invalid syntax

agile sundial
#

if i had to guess, missing parentheses

heavy cloak
#

I made sure theres nothin missing ill check again one sec

#

nvm u were right

#

lmao

jovial scarab
#

Is there any good dsa course in python online?

midnight vigil
#

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.

stable pecan
#

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

shadow topaz
#

um... what data structure would I use to implement a shopping cart?

#

is a linked list sufficient?

old rover
#

what if you want to access the last item in the shopping cart?

shadow topaz
#

so maybe a deque?

old rover
#

that can work since you can enqueue and dequeue on both sides (I think)

cloud moth
#

is math asked here?

old rover
#

uhhhh

#

if it's relating to algos/DS perhaps

#

like big O would be considered mathematical notation

cloud moth
#

it's related to ml. kind of very basic

old rover
fervent saddle
#

Is it possible to find the longest palindromic substring in O(n) time and O(1) space? Manacher’s Algorithm is O(n) space.

old rover
#
class Node:
  def __init__(self, value):
    self.value = value
    self.edges = []
#

what's the point of self.edges = []

#

this is for creating graphs btw

bleak quarry
#

How to convert Panda dataframe to list of dict?

old rover
bleak quarry
#

Yes

#

Sorry

#

But i founded the solution:

 data_frame.to_dict(orient='records')
old rover
lean dome
old rover
#

oh I didn't read further

#

my bad

agile sundial
#

i would assume is to store references to other nodes

old rover
#

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
agile sundial
#

a connection, yeah

old rover
#

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

agile sundial
#

weighting edges probably

#

that's not the entire function rightt

honest mantle
#

any good resources to learn about time and space complexity of a progm?

old rover
#

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

dim bolt
#

not sure if this is the right place. but can png's store more than just the pixel's coulour

old rover
dim bolt
#

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

old rover
#

🥴 yeah idk what half of the things you just said are

#

that sailed way over my head

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

old rover
#

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

honest mantle
old rover
#

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

honest mantle
#

if i didnt focused on data structures and algo will that be a prblm if i getin straight into webdev ?

old rover
#

🥴 I don't think you need ds/algos for web dev

agile sundial
#

yeah, not really

lean dome
#

you pretty much only need to know hash tables and dynamic arrays. Those are the two most important data structures.

old rover
#

I remember my friend told me that he had ds/algos questions for his web dev interview

agile sundial
#

and you don't need to know them in depth at all, just how to use them + when (although, some would say how==when 😔)

old rover
#

but that's only like one person

lean dome
#

well, how to use them, and when

agile sundial
#

no lol. it was a reference to me, because i didn't include "when" at first

honest mantle
#

am focusing too much on ds and algo still didnt learned any frameworks

#

like frameworks for webdev

old rover
#

uhhhh

#

I don't think I'm qualified to offer advice on that

old rover
#

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

spring jasper
#

If you wanna do webdev then learn flask/django/whatever

#

And javascript

old rover
#

am I emoji blocked now

#

apparently

honest mantle
lean dome
#

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.

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

fiery cosmos
old rover
#

am I just being stupid or something like are they supposedly very clear variable names?

#

what does "found" refer to?

lean dome
# old rover am I just being stupid or something like are they supposedly very clear variable...

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.

fiery cosmos
#

I agree, from_found is very confusing variable name

old rover
#

oof well

#

I can't tell all that

lean dome
#

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.

old rover
#

but what are they even finding

#

I don't get it

lean dome
#

the nodes to connect.

old rover
#

ohh

#

ok

lean dome
#

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.

old rover
#

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

lean dome
#

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.

old rover
#

oh ok

dapper sapphire
#

is there such a thing as protected method or property in python?

spring jasper
#

No

#

Theres no access modifiers in python

fiery cosmos
#

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

fiery cosmos
#

Like... your sending it to sql or like your trying to use sql in python

magic jolt
#

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

old rover
#

🥴

#

I guess we’ll never know

vocal gorge
magic jolt
vocal gorge
#

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.

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

dry crow
#

jk

old rover
#

lmao I was going to say you should say jk before they all come here and confront you

dry crow
#

LOL

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

agile sundial
#

it's a 2d matrix where if matrix[i][j] == 1 represents an edge between nodes i and j

agile sundial
#

a adjacency list is a 2d list where list[i] represents the neighbors of i

old rover
#

yeah this is too big brain

#

going to bed

eager hamlet
#

so i have no idea how to do this in n^3 time, any help? (ping 2 reply thx)

still sleet
#

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?

dapper sapphire
lean dome
#

at some things, and slower at others.

#

which was basically my point. 🙂

agile sundial
#

lists can do things that dicts can't, dicts can do things lists can't

dire quarry
#

Tony Stark

lean dome
#

sure - but for the things that both can do, one is faster than the other at that operation.

dire quarry
#

mutually exclusive

lean dome
#

like, you could choose to never use lists, and instead just use dicts with integer keys. But, uh, don't. 😄

dire quarry
#

its going on 5 minutes and Tony Stark still hasnt posted

#

im ready when you are

dapper sapphire
#

Yeah

dapper sapphire
dire quarry
#

your post

dapper sapphire
#

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.

lean dome
#

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

dapper sapphire
lean dome
#

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.

dapper sapphire
#

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

lean dome
#

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.

dapper sapphire
#

is the length of the key being hashed the same each time?

#

or does it get longer with more insertions?

lean dome
#

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.

dapper sapphire
#

ok

lean dome
#

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)

dapper sapphire
#

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.

lean dome
#

Yes.

drifting mantle
#

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?

grizzled roost
#

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
icy spruce
#

for merge sort we can choose to use any sorting algo such as bubble/selection/insertion.... etc?

vocal gorge
#

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.

icy spruce
#

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

vocal gorge
#

yup, pretty much.

#

and that comparison is just part of the merging part.

tiny oriole
#

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

onyx root
#

@tiny oriole your first picture uses an x range of [-1, 1] or so. You are plotting [-1000, 1000]

tiny oriole
#

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

@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

vocal gorge
#

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.

vocal gorge
old rover
#

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

vocal gorge
#

it is

#

in Python, it's just that, no difference from normal functions at all.

old rover
#

is it easy to pick up

#

I heard Guido said that he isn't particularly fond of lambda expressions

vocal gorge
#

anonymous functions are about the same in any language

old rover
#

what's an anonymous function

#

a function that's not defined with def?

#

that was a guess

vocal gorge
#

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)

old rover
#

I'll watch some videos + look at more resources

#

then I'll come back with questions

vocal gorge
#

in python, you just go from a function like

def f(a,b):
    return a + b

# to:
lambda a,b: a+b
old rover
#
lambda arguments: expression
vocal gorge
#

you could do f = lambda a,b: a+b, in fact, and that's pretty much equivalent to the full def (but discouraged)

old rover
#

so like lambda arguments are parameters

vocal gorge
old rover
#

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?

jolly mortar
#

it started getting into places it shouldn't be in tbh

old rover
#

oh I see

#
double = lambda x: x * 2

print(double(5))
#

in this case double would be the function

#

and x is the parameter

jolly mortar
#

yes

#

not really anonymous anymore lol

old rover
#

bc it has a function name

jolly mortar
#

yeah

old rover
#
lambda x: x * 2
#

so it could also be this too

jolly mortar
#
print((lambda x: x * 2)(5))
old rover
#

oh I see

#

ok

#

yeah that is pretty cool

#

yeah Guido wanted map(), filter(), and lambda out

jolly mortar
#

i've mostly used lambdas in map/filter, as the key in max/min/sort ||and #esoteric-python||

old rover
#

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
inland iron
#

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?

old rover
#

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?

jolly mortar
#

0 is falsy

#

any other length will be truthy

old rover
#

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

jolly mortar
#

i don't see the point of the if len(self.nodes) line tbh

#

if its empty the for would have no effect anyway

old rover
#

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

old rover
#

what is the point?

vocal gorge
#

it seems to me like you just want to do int on every element of these lists.

inland iron
vocal gorge
inland iron
#

Cause they were all originally strings

#

And i didnt just convert them all in the first place

vocal gorge
#

ah, I see.

old rover
#

am I right about this whole find_max_index thing

vocal gorge
#

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)

old rover
#

hey is the eulerian path an algorithm too?

#

why did they decide to teach the eulerian path instead of Dijikstra's algorithm

vocal gorge
old rover
#

is it related to Dijikstra's algorithm?

#

or are they two independent things

vocal gorge
old rover
#

fun times

inland iron
#

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

chilly fox
#

guys any tips for writing algorithms.Kinda tough for me

inland iron
#

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.

old rover
chilly fox
#

in general when i try to write one for problems

#

problems like the ones in competitive programming websites

#

@old rover

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

chilly fox
#

so you mean i get it by practice?

#

@old rover

old rover
#

yes

#

it takes practice

chilly fox
#

@old rover alrighty. Thanks man😎

old rover
#

it's like any standardized test you've ever taken the more you take those tests the better you get at figuring out tricks

fiery cosmos
#

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

wispy hare
#

@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```
fiery cosmos
#

Sorry this doesnt work

drowsy mason
#

@fiery cosmos can you send me the problem statement ... i felt its interesting

#

!!

fiery cosmos
#

Photo from Vv

#

Photo from Vv

old rover
#

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

vocal gorge
#

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

old rover
#

🥴

#

learn something new every day ig

#

what does it mean when he says breadth first search means you go wide

#

not deep

lean dome
#

That's literally the meaning of breadth.

old rover
#

yes

lean dome
#

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.

old rover
#

does curr stand for current

#

is that why they call it curr

mint jewel
#

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.

lean dome
lean dome
mint jewel
#

ah, my bad

#

essentially, None becomes empty and the tuples get converted according to function, creating the single result T

lean dome
#

looks like you're basically just looking for an iterative post-order traversal - right?

keen hearth
old rover
#

oh ok

old rover
#

nvm it seems like he's talking to lakmatiol

mint jewel
#

ah, so it just is that complex.

lean dome
#

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.

dapper sapphire
#

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.

mint jewel
#

ye, recursive data structures are really nice to deal with using recursion

mint jewel
old rover
#

🥴

#

this is a terrible explanation

#

how are you going to give letters to certain nodes and then give more letters to the same nodes

lean dome
#

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.

old rover
#

well I found it hard

eager forge
#

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.

lean dome
#

what do you mean by "the file structure is completely unknown"?

eager forge
#

It can be any file.

#

Is that a problem? 😟

lean dome
#

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?

eager forge
#

Yes.

lean dome
#

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?

eager forge
#

Yes, should work!

lean dome
#

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))
eager forge
#

ohhh. Thank you so much!!!!

vocal gorge
lean dome
#

yeah, you have been able to since Python 3.

vocal gorge
#

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

old rover
#

BFS and DFS is about as easy as in order, post order, and pre order traversal

lean dome
#

bytearray and bytes are pretty much interchangeable these days. The only big difference is that bytearray is mutable and bytes is immutable.

old rover
#

I don't know why I'm struggling

eager forge
#

Btw how do you get the syntax highlighting in Discord? ¯_(ツ)_/¯

lean dome
#

and of course you could also write the bytearray directly to a file, without the extra call to bytes

halcyon plankBOT
#

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.

eager forge
# lean dome !code

ohh that works? The colored highlighting is automatic? I never noticed that. Thanks a lot!

lean dome
#

It's automatic as long as you put "py" after the 3 backticks to start the code block, yeah.

eager forge
#

Ohh. Cool!

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

main flower
#

graph

lean dome
#

self always refers to the instance that an instance method is called on.

old rover
#

oh wow

#

Grokking actually has a good explanation

#

🥴

lean dome
old rover
#

I do know OOP

#

I just didn't know you could refer to self when you didn't have a def init

lean dome
#

Sure. This class has just inherited the __init__ from object, which basically does nothing.

old rover
#

normally I see a init with attributes

#

and then I see self.attribute = attribute

lean dome
#

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.

old rover
#

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

lean dome
#

sure.

old rover
#

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

lean dome
#

it's a search. The point of any search is to find something.

old rover
#

right

lean dome
#

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)

old rover
#

it also checks if the path to that node exists

#

from the starting node to the given node

lean dome
#

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.

old rover
#

ok

#

why does Grokking not decide to cover DFS

lean dome
#

how would we know? 😄

old rover
#

god knows

spring jasper
#

All of the tree traversals you posted here are dfs

old rover
#

oh

#

so it's not even that big of a deal

#

it just checks the levels of the graph

spring jasper
#

Or well, depth first traversals

old rover
#

like you would check the levels of a tree

lean dome
#

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

old rover
#

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

lean dome
#

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.

old rover
#

why does it search the nodes in a different order than if you use a queue? bc of the specific data structure's functions?

lean dome
#

because queue is first-in, first-out, and stack is last-in, first-out.

old rover
#

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

lean dome
#

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.

old rover
#

hm

#

it is starting to make more sense

dapper sapphire
#

What do you guys think of these data structures based interviews?

lean dome
#

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.

old rover
#

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

lean dome
#

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.

old rover
#

they could very well ask for help

main flower
#

but isn't that what people should do tho

old rover
#

not on a project that's assigned by the company for an interview

#

no

main flower
#

I mean, if he/she just copy pasted everything then that's bad

old rover
#

if you're asking for help it isn't a measure of your own skills then

main flower
#

Why

old rover
#

do I really have to explain why 🥴

#

the same way we don't help with school assignments or we offer minimal help

lean dome
# main flower but isn't that what people should do tho

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.

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

dapper sapphire
#

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

old rover
#

doesn't look like they are implementing a stack

#

in the code I sent

main flower
#

cuz they probably do it recursively

old rover
#

oh they are

#

ok

main flower
#

I never used a stack for dfs xd

lean dome
#

It's a recursive implementation. The stack they're using is the call stack.

old rover
#

what's a call stack 🥴

lean dome
# dapper sapphire I like you said necessary evil which I agree with. Because if companies didnt do...

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.

old rover
#

oh ok I see what a call stack is

lean dome
# old rover what's a call stack 🥴

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.

old rover
#

the call stack is made up of stack frames

#

oh

#

that's really cool

lean dome
#

that call stack is what's in charge of tracking where control will resume whenever a function returns.

old rover
#

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

lean dome
#

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.

old rover
#

so it just appends the entire thing to the end

#

ok

lean dome
#

!e ```py
a = [1]
b = [2, 3]
a.append(b)
print(a)

halcyon plankBOT
#

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

[1, [2, 3]]
lean dome
#

!e ```py
a = [1]
b = [2, 3]
a.extend(b)
print(a)

halcyon plankBOT
#

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

[1, 2, 3]
lean dome
#

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.

old rover
#

oh

#

oh it takes the elements of that list b

#

and then sticks it onto a

lean dome
#

right.

old rover
#

that's cool

old rover
#

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?

lean dome
#

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.

old rover
#

oh ok

dapper sapphire
#

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)
lean dome
#

sure, that looks reasonable. It can't handle duplicate values.

dapper sapphire
#

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
fiery cosmos
#

using regex, how can I make it return the next word or the content within parentheses (found in the next word) from matches?

old rover
#

does regex have to do w algos/DS

#

I suppose so

#

since it's a string searching algorithm

fiery cosmos
#

says math

#

so

old rover
#

I understand that's how graphs are normally represented

#

but I find that pretty confusing to look at

#

maybe it's just me

spring jasper
#

State machines, yuck

old rover
#

what is that 🥴

frigid tulip
#

that looks so complicated bruh

lean dome
#

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.

frigid tulip
#

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

lean dome
#

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

frigid tulip
#

omd i cannot believe i didnt think that through

frigid tulip
#

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

lean dome
# frigid tulip holy i cannot believe i didnt think that through i was thinking of some complica...

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
frigid tulip
#

wow that is insane. i would have never even come close to thinking of that.

frigid tulip
old rover
#

oh Eulerian is pronounced oilerian

#

not ewlerian

#

🥴

#

what's a degree in a graph

#

number of edges incident to the vertex???

agile sundial
#

yeah and people still pronounce his name wrong 😔 it's U ler smh

old rover
agile sundial
#

"edges", this means edges

#

"incident to" going into

lean dome
#

so, then, why did you ask?

agile sundial
#

"the vertex" the vertex

old rover
#

is the vertex the node?

#

or any node?

agile sundial
#

graphs are composed of vertices/nodes and edges

#

vertices sound cooler though

old rover
#

so it's just the amount of edges going into a node

lean dome
agile sundial
old rover
#

ok

lean dome
agile sundial
#

huh, how does that work

#

is that a definition thing?

old rover
#

what's a loop 🥴

lean dome
lean dome
agile sundial
#

huh, weird

old rover
#

this is a multigraph

agile sundial
#

the blue are loops

old rover
#

ohh

#

ok

old rover
#

YES

#

FINALLY

#

Dijkstra's algorithm makes an appearance

#

why am I excited about some random algorithm 🥴

agile sundial
#

it's famous lol

old rover
#

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

agile sundial
#

doesn't matter how you pronounce it if you understand it ¯_(ツ)_/¯

old rover
#

I was watching this video

#

and he said the numbers on the side mean the cost?

#

cost of what 🥴

#

cost of visiting the vertex?

eager hamlet
#

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

eager hamlet
old rover
#

hey this is kind of helpful

#

thanks

old rover
#

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

#

@alpine tide if you think I should add anything let me know

lean dome
#

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.

fiery cosmos
#

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?

lean dome
#

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
#

what's happening here?

#

I was thinking more on the lines of this?

lean dome
#

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

meager jetty
#

Finite state machine who accept your substring only

#

your machine accept "ccc" per exemple lol

lean dome
#

yes... that's valid for 2.3, isn't it?

fiery cosmos
#

I am just asking about the 3rd question. @meager jetty

#

I figured out 1st and 2nd one

#

but my solution seems way too simple.

fiery cosmos
lean dome
#

Like I said, I think you need 2 nodes, because you need to reject strings of length 0.

meager jetty
#

may be im wrong I was thinking all rules 1 and 2 together

#

if 3 is alone your answaer is correct

fiery cosmos
#

thanks

meager jetty
#

usually no string is not a string

#

but if you need to consider a noSting so u need 2 nodes

lean dome
#

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.

meager jetty
#

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

lean dome
#

I usually reason about DFAs in terms of regular expressions, and .* does accept an empty string, and ..* does not.

meager jetty
#

#\n

fiery cosmos
#

I am thinking the one with 2 nodes is wanted, since it specifically asked for symbols? and an empty string has none?

lean dome
#

right. I lean the same way.

fiery cosmos
#

yup. I am gonna go with that one. thanks @lean dome @meager jetty

meager jetty
#

but you alway have delimiter "\n" in our case

fiery cosmos
#

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

meager jetty
#

in an exam I will go with the 2 states .... because it detects the NoString 🙂

eager hamlet
glossy mulch
#

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)

dapper sapphire
#

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.

quasi basalt
#

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

old rover
#

please don't use that phrase

old rover
#

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

vocal gorge
vocal gorge
slim vault
#

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?

lean dome
#

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.

old rover
#

oh

#

what's up with infinity and Dijkstra's algorithm

#

Udacity says it's just a placeholder

lean dome
#

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.

vocal gorge
#

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)

agile sundial
#

using infinity means any weight you do assign it is smaller, so min(new_weight, inf) will be new_weight

old rover
#

oh ok

old rover
#

what's a greedy algorithm

#

it makes the best possible choice at each step of the problem

#

Dijkstra's algorithm is an example

vocal gorge
#

this term always annoyed me because I don't think it has a rigid definition

old rover
#

the MIT lecture I watched started w greedy algorithms and it lost me

#

peak finding?

vocal gorge
#

it's pretty much "algorithms that choose the locally optimal choice at each step and hopefully result in a globally optimal solution"

old rover
#

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

vocal gorge
#

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.

old rover
#

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

vocal gorge
#

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

old rover
#

so would a brute force algorithm be like trying out all password combinations before finding the right one

#

ok

lean dome
#

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

solar timber
old rover
#

MIT OCW starts w peak finding and talks about greedy algorithms

lean dome
#

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.

old rover
#

it’s pinned in the channel if you want to take a look

solar timber
#

Found it, thanks!

sudden garden
#

does anyone have any resources for directed graph datasets? very simple (i,j,w) values?

old rover
#

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

lean dome
#

That would be brute force, yeah.

old rover
#

ok then it makes sense ig

#

so there’s greedy algorithms and there’s brute force algorithms

#

is there another category of algorithms?

solar timber
old rover
#

@solar timber binary search

lean dome
#

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

old rover
#

you guess the middle alphabet

#

and then you either go up or down from there

solar timber
#

Oh yeah, I saw a video on that

agile sundial
#

that's only possible if you have more information than "it's a letter"

lean dome
solar timber
#

But wouldn't we need more input for binary search?

lean dome
#

Yes.

agile sundial
#

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

lean dome
#

You need not just "no", but "no, it's higher"

solar timber
#

C++ is the best language for brute force solutions, right?

lean dome
#

Any language that compiles to machine code will be about equally good. C, C++, Java, C#, Rust, Go, ...

solar timber
#

Okayy, but python isn't as efficient as Java for brute force solutions, right?

lean dome
#

Right.

solar timber
#

Thanks!

agile sundial
#

probably the worst of all the ones he listed

#

including the ...

solar timber
#

What do you mean?

agile sundial
#

it'll be slower than the languages that godlygeek listed

lean dome
#

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.

solar timber
#

Okayy

#

@lean dome can I ever ask you something on personal?

dapper sapphire
#

I came across this some time ago:

lean dome
solar timber
#

I'm participating in an Olympiad, and I would prolly have a lot of doubts...

vocal gorge
#

Perl is faster than C on that test? wtf

solar timber
vocal gorge
#

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

dapper sapphire
#

So there are different types of speed test.

#

But yeah I didnt buy it either that Perl is faster than C.

eager hamlet
#

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)

dapper sapphire
#

How would you add a list recursively?

grizzled schooner
dapper sapphire
#

Yeah if you have list = [1, 2, 3, 4]
Get the sum of the list recursively and return 10.

old rover
#

well you already know your base case

#

if the list is empty return 0

#

not so sure about the other part though

cerulean river
#

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.

grizzled roost
#
def add_list(l):
   return 0 if not l else l.pop() + add_list(l)
lean dome
#

Or:

def add_list(l):
    if not l:
        return 0
    rwturn l[0] + add_list(l[1:])
old rover
#

what does l[1:] do again

#

all the indexes past 1?

#

adds all the indexes of the list past 1?

grizzled roost
#

It creates a copy of the list from 1 to the last element

lean dome
#

Slices the list, creating a copy with every element but the first

old rover
#

oh

dapper sapphire
#

if not l checks if the list is empty?

#

wow man you guys did that pretty fast

lean dome
#

Yep. You could also do if len(l) == 0

lean dome
old rover
#

if you go to leetcode you can filter by recursion to practice

#

nvm I thought there would be some gigantic repo with recursion problems

dapper sapphire
#

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.

old rover
#

there also some decent problems in CTCI about recursion

#

page 130

#

yeah they probably did memorize solutions

analog ferry
#

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

dapper sapphire
old rover
analog ferry
old rover
#

oh

#

my bad it said tire

analog ferry
#

i did, too

old rover
#

idk what a trie is yet

analog ferry
#

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

lean dome
#

Also commonly used to implement a spell checker

analog ferry
#

i just want to store about 250k blobs content addressed in a file

dapper sapphire
old rover
#

I think my struggle is knowing where to call the function inside the function you're defining

dapper sapphire
#

I would say handle the base case first and then do recursion case.

old rover
#

yeah

#

that's how it's normally written anyways

#

base case first and then the recursion case

lean dome
#

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]

spring jasper
#

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

agile sundial
#

why do you need a hex literal

#

it doesn't matter what base it's represented as, the value is the same

#

@fiery cosmos

agile sundial
old rover
#

@agile sundial yes

agile sundial
#

yes

old rover
#

yes 🥴

agile sundial
#

?

old rover
#

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?

agile sundial
#

pretty much, yeah

old rover
#

oh cool it has recursion problems too

#

so just about anyone can join? do they need an invitation?

agile sundial
#

you can set it to either

old rover
#

oh ok

old rover
agile sundial
#

it's not an anime

old rover
#

oh

#

what's a lookup table?

agile sundial
#

a hashmap, probably

old rover
#

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

lean dome
#

memoization is remembering the inputs and outputs of a function call, and reusing them on future calls with the same arguments.

old rover
#

yay I have reached traveling salesman

#

np-hard

split knoll
old rover
#

yeah that is pretty cool

brave oak
#

it's a lot more common in purer FP languages

#

because they tend to use pure functions more

old rover
#

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

dapper sapphire
#

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

lean dome
#

yep, but more efficient - it saves the copy.

dapper sapphire
#

Ok convert an integer to a string recursively with any base:
hint: ||string = "0123456789ABCDEF"||

cloud moth
#

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?

dapper sapphire
#

Reverse a string recursively

lean dome
dapper sapphire
#

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]

icy spruce
#

do interviewers test you on radix sort

lean dome
#

It seems like it would be fair game, but I don't think it's a very common thing to ask about

fiery cosmos
#

not usually

rancid ruin
sudden garden
#

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

minor birch
#

Hi

sudden garden
#

I found a way to do it, I store "i" as key, and (j,w) pair as a value

vocal gorge
#

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

old rover
#

What’s a digraph

vocal gorge
#

sometimes it's how "directed graph" is shortened

#

not to be confused with hypergraphs 😛
https://xkcd.com/2036/

old rover
#

Hahahaha edge lord 🥴

#

oh digraphs just means the edges have arrows

sudden garden
#

pretty much what I did...

#

I stored the distances (weights) in the same HashMap, not as a separate list

misty plume
#

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

sudden garden
#

keep a counter attribute in your element and every time you visit an element, increment the counter, do whatever condition checks with your counter

misty plume
#

hmm that can be done without adding any collection_

#

?

sudden garden
#

assuming your element or each graph node is an object, you can just add another instance variable like a counter

misty plume
#

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

misty plume
sullen summit
#

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

vocal gorge
#

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

misty plume
#

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

meager jetty
#

and implement my kindof dijkstra shortest path ...

misty plume
#

hmm I see, but I don't think that helps me in this specific case 🙂

#

🙂 *

#

😦 *

meager jetty
#


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

dry terrace
#

no cap

meager jetty
#

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)
misty plume
meager jetty
#

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

old rover
#

what does the acceptance % mean in leetcode?

half lotus
#

The ratio of accepted solutions to all submitted solutions

old rover
#

oh

#

ok

umbral plaza
#

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

old rover
#

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

#

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.

umbral plaza
#

oh i see

old rover
#

If I had this sorted list: [1,2,3,4,5]

#

and I wanted you to guess the number I was thinking of