#algos-and-data-structs

1 messages Β· Page 144 of 1

trim obsidian
#

Ahh no issues hopefully some angel guides me

austere sparrow
#

I can give you an interesting problem if just one is good for you.

trim obsidian
#

For now sure send me one but irl need a path way Those MIT videos i dont think give very hard deep dive

agile sundial
#

do you need a book? there are plenty of websites with algos problems

austere sparrow
#

@trim obsidian
You're given the following configuration (a parameter to your program, to be more precise) (first picture for an example):

  1. A triangular board (on the left)
  • all the cells are connected into one big "island"
  • the board contains a set of "ports"; a port is a red circle attached to one of the outer edges
  • the board is symmetric across the horizontal axis (including the ports)
  1. An alphabet of shapes with adapters (blue circles) and connections between them.
  • the connections can be between any of the adapters
  • one adapter can have more than one connection (like E and F).
  • an adapter never connects to itself
  • a shape can contain any positive number of triangles, but they're all connected into one piece

There is the concept of a path. A path is a way of filling (partially or fully) a board with the provided shapes (second picture for an example)).

  • the shapes can be rotated, but not flipped (i.e. A and B are distinct shapes)
  • the shapes cannot overlap
  • an adapter must be connected to either a port or another adapter (pretend that fluid is flowing through the path)
  • a port, however, may be left unconnected
  • the path must be symmetric across the board's symmetry axis (in its shape -- the pieces may be completely different)

Inside a path, there is a thread. A thread is a set of adjacent shapes that forms a line from one port to another. For example, in the sample path there are two threads: one from the top-left port to the bottom-right port, the other from the bottom-left to the top-right port.

  • Every shape on a path must belong to at least one thread. In other words, "loops" are not allowed.

You task is, given a configuration and a positive integer K, find all paths that occupy exactly K triangles on the board.

trim obsidian
#

Cool seems intresting

austere sparrow
#

to be clear, I don't have a solution or a test suite πŸ™‚

shut breach
fiery cosmos
#
def main():
    A = ['a','b','c'] 
    result = P(A) #calculates power set
    print(result) #prints the result
    sorted_result = sorted(result, key = len)
    print(sorted_result) 
    
def P(A):
    if A == []:               
        return [[]]          
    element = A[len(A) - 1]   
    A_ = A[:len(A) - 1]       
    singleton = [element]     
    return adjoin(P(A_), singleton) + P(A_)

def adjoin(A,singleton):
    result = []
    for subset in A:
        result.append(subset + singleton)
    return result

main()
haughty mountain
#

places like hackerrank and codeforces have a ton of problems you can filter by difficulty

fiery cosmos
fiery cosmos
fiery cosmos
odd island
#

Can someone recommend me good Data Structure and Algorithm Book?

fiery cosmos
#

hm there's just one book

#

we need better pins here.

odd island
lethal radish
old rover
#

Big O notation is the way to measure how software program's running time or space requirements grow as the input size grows. We can't measure this using absolute terms such as time in seconds because different computers have different hardware hence we need a mathematical way to measure time complexity of a program and Big O is that mathematical...

β–Ά Play video
#

also a good video series

haughty mountain
#

wtf is O(log^n)?

old rover
#

i believe he means O (log N)

haughty mountain
#

not a good first impression, ngl

fiery cosmos
old rover
fiery cosmos
#

theoretical and on board.

old rover
#

sorry algymr

#

i think i messed up here and named two cols as "created_at"

old rover
#

my code school?

fiery cosmos
#

uhm no he way totally algo guy. no coding.

old rover
#

he had stuff explaining big O

fiery cosmos
#

Abdul Bari

old rover
#

yes

#

that was him

#

or wait

#

no

#

ohhh

fiery cosmos
#

oh! yeah I like that guy.

old rover
#

i know who you're talking abt

old rover
#

yep yep

#
new_df = data.groupby(["created_at"])["is_blocked"].value_counts().to_frame()

pd.to_datetime(new_df["created_at"])

new_df["created_at"]
#

!pastebin

halcyon plankBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

old rover
#

so using the documentation i created a dataframe where the columns are the ["created at col"] and then the ["is blocked"] call and the counts for each

haughty mountain
#

the inequalities up top in the thumbnail are kinda disturbing, but looks reasonable otherwise

#

ok, I don't like that he calls Θ the "average bound"

#

it means bounded on both sides

#

if anything it's the exact bound

#

if f(x) is in O(g(x)) and Ω(g(x)), then it is in Θ(g(x))

#

overall good intro though

marsh kernel
#

hey i have a few quick questions about this code, I have been pointed to this chat :)

austere sparrow
#

depends on what S is πŸ™‚

marsh kernel
#

oh shoot! i forgot to mention the input variable S is a string haha my bad

#

i would assume of any size?

austere sparrow
#

well, what do you think about its complexity?

marsh kernel
#

i would asume it is in o(n) time, but i could be horribly wrong lol

austere sparrow
#

what is n here?

marsh kernel
#

hmm

marsh kernel
#

that's my interpretation of it

austere sparrow
marsh kernel
#

yes

#

i agree with that

marsh kernel
austere sparrow
#

@marsh kernel So if S is the string 'abcde', how many times will the if S[j] == S[k]: line run?

marsh kernel
#

5 times

#

for the 5 letters

agile sundial
#

how do you figure that?

austere sparrow
# marsh kernel 5 times

First it will compare a to b. Then it will compare a to c. Then a to d. Then a to e.
Then it will compare b to c, b to d and b to e.
And so on.

marsh kernel
#

ohhh i see

#

so its exponential?

austere sparrow
#

Why?

#

So how many is it for 5?

marsh kernel
#

5^5 times? since we are comparing each letter with eachother?

austere sparrow
marsh kernel
#

oh yeah you have a point..

#

i see

austere sparrow
#

So on the first iteration of the outer loop we make 4 steps. On the next 3, and so on. So we get 4 + 3 + 2 + 1.

marsh kernel
#

ahhh i understand

austere sparrow
#

Are there any restrictions on what characters the string contains?

marsh kernel
#

as long as they aren't the same character, it returns true

#

i believe that's the only restriction

austere sparrow
#

alright

#

so let's assume the worst case scenario (the function returns True).

#

As you can probably imagine, first we're going to check the full string (n - 1), then a smaller one (n - 2), then an even smaller one (n - 3), and eventually a string of size 1.

#

So in total it's going to be (n - 1) + (n - 2) + (n - 3) + ... + 1

#

For simplicity, let's take n + (n - 1) + (n - 2) + ... + 1 because it turns out it doesn't matter.

#

Have you ever seen a sum like this? @marsh kernel

marsh kernel
#

oh yes something like that

#

i forget the formal name of it but yes

austere sparrow
#

So what does n + (n - 1) + (n - 2) + ... + 1 compute to?

marsh kernel
#

hmm im not too sure

austere sparrow
marsh kernel
#

they will result in the same thing

austere sparrow
#

hm?

#

well, let's look at it from another direction

#

What is 1 + 6?

#

And what is 2 + 5?

marsh kernel
austere sparrow
#

so 1 + 2 + 3 + 4 + 5 + 6 = (6 * 7) / 2 = 21

#

(because the sum of the rows ends up as double the sum)

#

So if we take the general sum and do the same:

(n - 1) + (n - 2) + (n - 3) + ... + 1
1       + 2       + 3       + ... + (n - 1)

Each column will add up to n, and we have n - 1 columns. Therefore,

(n - 1) + (n - 2) + (n - 3) + ... + 1 = (n * (n - 1)) / 2
marsh kernel
#

hmm okay i see

#

interesting

#

okok i see where you are coming from here

#

i think i can try to solve it sorry again for the stupid long responses, its incredibly late rn and my internet has been hot garbage.

young merlin
#

i have a question, two for loops doesnt change the complexity right?

#

when they are nested

agile sundial
#

it depends what you're doing with them

open moth
#

May I ask about python

flint raven
#

what should i use to detect images in python for a game

#

it must detect players

#

in fortnite

bronze shoal
#

nums[:] = nums[:k][::-1]+nums[k:][::-1]

So if I have a nums array, and I want to reverse it from starting to a given point k, and then from k to the end. for eg-
[3,4,5,6,7,8] with k = 2 becomes [4,3,8,7,6,5]

Does my above code runs in O(1) space or does it uses extra space?

lean walrus
#

it builds 5 extra lists

storm night
#

I'm trying to find the bug in my attempt at a LC problem.

The problem:

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

 

Example 1:

Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].

Example 2:
Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]

My attempt:

    def sortedSquares(self, nums: List[int]) -> List[int]:
      i = 0
      j = len(nums) - 1
      result = []

      while i <= j:
        left = nums[i] ** 2
        right = nums[j] ** 2
        if left > right:
          result.append(left)
          i += 1
        elif left < right:
          result.append(right)
          j -= 1
        else:
          # Equals
          result.append(left)
          result.append(right)
          i += 1
          j -= 1

      return result[::-1]

Explanation: I am setting pointers on each side of the list, and move them towards the center. This effectively lets me grab the highest values (because squaring each number makes numbers towards the ends larger, so each side should contain the largest values)

The problem is I am unable to find whats wrong with my attempt.

For reference the input of
[-4,-1,0,3,10]

Has my code outputting [0,0,1,9,16,100]

That's one too many 0's haha

topaz scroll
#

is space complexity S(9n) a valid way to show 9 arrays or should it be just S(n)??

austere sparrow
haughty mountain
jolly mortar
austere sparrow
#

yup

austere sparrow
haughty mountain
austere sparrow
haughty mountain
#

oh

#

well, square and merge halves I guess

austere sparrow
#

yeah

haughty mountain
#

though in practice the call to sorted is likely faster than merging in python

#

because python code slow compared to calling into C internals

austere sparrow
#

well, at some input size merging will become faster

haughty mountain
haughty mountain
#

timsort finds decreasing/increasing sequences and merges them

#

that's kinda hilarious, ngl

austere sparrow
#

@haughty mountain hm, indeed, that seems to be the case

haughty mountain
#

yay for knowing python internals good enough to do silly things

austere sparrow
#

seems like the "fast" merge (in Python) is about twice as slow for big lists

haughty mountain
#

yeah I saw ~2x as well

#

I wonder how well pypy would do

storm night
#
      result = []
      i = 0
      j = len(nums) - 1
      # Loop breaks when the "center" pivot has been crossed
      while i <= j:
        left = nums[i] ** 2
        right = nums[j] ** 2
        # Quit if we are looking at the same element (center)
        if left == right and i == j:
          result.append(left)
          break
        if left > right:
          result.append(left)
          i += 1
        elif left < right:
          result.append(right)
          j -= 1
        # Covering cases where I'm comparing -2 and 2, Without the else clause it will infinite loop
        else:
          # Equals
          result.append(left)
          result.append(right)
          i += 1
          j -= 1
      # Return the results list flipped, since I added in numbers from largest to smallest
      return result[::-1]  
#

ahaha

haughty mountain
storm night
#

Okay that is fair, and probably explains why my current solution is slower than my solution in 2019 where I just squared and sorted

haughty mountain
#

timsort collects increasing and decreasing sequences and merges them, just like the annoying to write merging code would

#

except it's in C

storm night
#

ahh

#

Do you think I'd be able to get away with that explanation in an interview?

#

"Square them and sort. It's just as fast"

haughty mountain
#

if you can explain why, yes

austere sparrow
#

if an interviewer accepts "it's faster" without a benchmarking session, run away πŸ™‚

haughty mountain
#

I would be very happy with that answer since it shows very good python knowledge

austere sparrow
austere sparrow
#

it is false

storm night
#

whoa

#

that's unexpected tbh

agile sundial
haughty mountain
#

well "it's linear and probably faster because C" is a very good answer imo

austere sparrow
# storm night that's unexpected tbh

That's because of how it's implemented in CPython: if the input is not a list or a tuple, it will first collect all the results into an internal array. So the generator will not provide any memory or speed advantage.

storm night
#

ah that's something I'll have to remember and kinda just take for granted

austere sparrow
#

in reality, it doesn't really matter in application code

haughty mountain
austere sparrow
#

yep

haughty mountain
#

pretty == good

cerulean drift
austere sparrow
# austere sparrow in reality, it doesn't really matter in application code

because

  1. The expression that's computed inside the comprehension will probably take more time than the joining itself
  2. If you are concatenating a really large (tens of megabytes) string, there's a good chance you've already gone terribly wrong: you probably should have been writing lazily to a socket or file handle.
haughty mountain
#

it would be fun explaining

s = ''
for bleh in thing:
    s += bleh
```is O(n) in cpython in an interview
austere sparrow
#

i think these interview questions are a waste of time anyway

#

(most of the time)

haughty mountain
#

interview questions can both be good or bad πŸ€·β€β™€οΈ

storm night
#

kjsdfsds this is so hard for me

haughty mountain
#

it's hard to pick good questions to ask in an interview, believe me...

austere sparrow
#

asking trivia questions in an interview is already bad enough πŸ™‚

storm night
#

I heard that most companies shouldn't be interviewing by asking these kinds of algo / data structure questions anyway (with exceptions of course). Thus the perfect interview is a "lets code together on a current problem the company is working on"

austere sparrow
#

yep

#

or better, a code review

storm night
#

but everyone wants to copy big tech interviews for some reason

haughty mountain
#

but trivia can pop up

storm night
#

A lot of companies require 5-6 rounds and kinda mimic the Google interview process. They claim to offer the same benefits without the same pay ehehe

haughty mountain
autumn bison
#

how would I add two strings next to each other so

AAA
BBB

becomes

AAAAAA
BBBBBB
#

I've tried

def add_next(inp):
    inp = inp.split('\n')
    arr = [0] * len(inp)
    for i in range(len(inp)):
        arr[i] = str(inp[i])*2
    return "\n".join(arr)
#

which works once but when I do it on itself it starts going funky and missing out lines

#

this is for AOC day 2 2020

#

(I know I'm a tad bit late to the party)

agile sundial
#

just do the_string * 2

autumn bison
#

but when you have newlines it goes from

AAA
BBB

to

AAA
BBB
AAA
BBB
agile sundial
#

ah

#

i didn't realize that was one string

#

it's a little more complicated but it's the same idea

#

split by "\n" then multiply each line by 2

autumn bison
agile sundial
#

probably, but it looks much more complicated than it has to be

autumn bison
#

it makes an array split by \n and then multiplies each part by two

agile sundial
#

your code doesn't work?

#

it seems it does, at least on that test data

autumn bison
#

so

["AAA", "BBB"]

becomes

["AAAAAA","BBBBBB"]
#

and then joins them by a newline

#

when I run it on itself I get this

#

it starts missing stuff out

agile sundial
#

which aoc did you say this was for? πŸ€” day 2 of 2020 does not look like this problem

autumn bison
#

oh day 3 I mean

agile sundial
# autumn bison

i'm guessing it looks like this because it's wrapping the ends of the lines onto a newline

#

try turning that feature off

autumn bison
#

how?

#

you mean don't join it at a newline?

agile sundial
#

i don't think it's your code's fault, but the terminal or editor or whatever you're looking at the output in

autumn bison
#

ok

topaz scroll
#
tour_df.loc[tour_df['Stage_Type'] == 'RR', 'Stage_Type'] = 0
tour_df.loc[tour_df['Stage_Type'] == 'ITT', 'Stage_Type'] = 1

Is there a way to make this in 1 sentence, now it has a Timecomplexity of 2n but I think its possible to reduce this to n

fathom zealot
#

just read that tuples can be used as keys in python dictionaries... does that mean the corresponding value or values will belong to one element in the tuple or the entire tuple?

agile sundial
#

the entire tuple

#

and they can only be used if all the elements in it are hashable

fiery cosmos
# fiery cosmos that is true. so what is wrong with frozensets over here?

It’s just less convenient and the output will end up looking weird, sets will be useful say in a depth first traversal problem, since searching for items (as in checking if it exists in the set) would be O(1). Since I’m not checking if an element exists, and want the output to look nice, I chose lists

slim crest
#

Thanks @haughty mountain (kinda procastinated this project)

dark aurora
#

(it doesn't matter both hold the same value) i am just curios, no purpose really

austere sparrow
#

I was just trying to find out what you mean by "equally important"

dark aurora
haughty mountain
#

so

min(D)*(len(D) - 1) + (sum(D) - min(D))
halcyon plankBOT
#

Hey @frail gyro!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

ripe knoll
#

can I get help on this question?

#

The grass has dried up in Farmer John's pasture due to a drought. After hours of despair and contemplation, Farmer John comes up with the brilliant idea of purchasing corn to feed his precious cows.
FJ’s N cows (1≀N≀105) are arranged in a line such that the ith cow in line has a hunger level of hi (0≀hi≀109). As cows are social animals and insist on eating together, the only way FJ can decrease the hunger levels of his cows is to select two adjacent cows i and i+1 and feed each of them a bag of corn, causing each of their hunger levels to decrease by one.

FJ wants to feed his cows until all of them have the same non-negative hunger level. Please help FJ determine the minimum number of bags of corn he needs to feed his cows to make this the case, or print βˆ’1 if it is impossible.

INPUT FORMAT (input arrives from the terminal / stdin):
Each input consists of several independent test cases, all of which need to be solved correctly to solve the entire input case. The first line contains T (1≀T≀100), giving the number of test cases to be solved. The T test cases follow, each described by a pair of lines. The first line of each pair contains N, and the second contains h1,h2,…,hN. It is guaranteed that the sum of N over all test cases is at most 105. Values of N might differ in each test case.
OUTPUT FORMAT (print output to the terminal / stdout):
Please write T lines of output, one for each test case.
Note that the large size of integers involved in this problem may require the use of 64-bit integer data types (e.g., a "long long" in C/C++).

SAMPLE INPUT:
5
3
8 10 5
6
4 6 4 4 6 4
3
0 1 0
2
1 2
3
10 9 9
SAMPLE OUTPUT:
14
16
-1
-1
-1

#

For the first test case, give two bags of corn to both cows 2 and 3, then give five bags of corn to both cows 1 and 2, resulting in each cow having a hunger level of 3.

For the second test case, give two bags to both cows 1 and 2, two bags to both cows 2 and 3, two bags to both cows 4 and 5, and two bags to both cows 5 and 6, resulting in each cow having a hunger level of 2.

For the remaining test cases, it is impossible to make the hunger levels of the cows equal.

keen hearth
#

Hey @ripe knoll

#

One thing to think about is: does it matter which order you perform the operations in?

#

By operation, I mean the operation of reducing two adjacent cows' hunger levels by 1.

lean dew
#

I am starting to learn DSA, I know searching and sorting algos and linked list. But idk where to head next.
does anybody have resources to learn from or any suggestions

jolly mortar
#

if you learnt about linked lists surely you know all about heads and nexts :P

#

check out the pins in this channel for resources

lean dew
#

Thanks

stark axle
#

hey

#

can we crack passwords by python?

#

pls reply it is urgent

slim crest
#

and yes it is

stark axle
slim crest
haughty mountain
# ripe knoll The grass has dried up in Farmer John's pasture due to a drought. After hours of...

If you're ok with a log factor you can binary search the answer. I.e. you can easily check if X could be the answer.

You can only lower the leftmost number by decrementing it and its right neighbor. Decrement until the leftmost number is correct. Now move over and treat the neighbor as the leftmost animal and do the same thing.

One caveat, if N is even if X is an ok answer X-1 is as well, but if N is odd you can only reduce X to X-2, so you need to check odd and even answers independently.

dark aurora
haughty mountain
# dark aurora Thanks a lot, this works, care to explain? What does a star mean?

a star graph, one center node connected to all other nodes https://en.wikipedia.org/wiki/Star_(graph_theory)

In graph theory, a star Sk is the complete bipartite graph K1,k: a tree with one internal node and k leaves (but no internal nodes and k + 1 leaves when k ≀ 1). Alternatively, some authors define Sk to be the tree of order k with maximum diameter 2; in which case a star of k > 2 has k βˆ’ 1 leaves.
A star with 3 edges is called a claw.
The star S...

dark aurora
#

so in 7 3 3 5, i would add up 7+3, 3+3, 3+5, and 5+7 and subtract (5+7)

#

i think i get it

haughty mountain
stark axle
empty cobalt
#

Hey All!

Not sure if this is the right place to post this, so if it's in the wrong spot, please point me to the right one πŸ™‚

I am trying to understand the difference between Python instance variables and static variables in a class. Take this example:

class Foo:
  food: str
  
  def __init__(self, topping: str):
    self.topping=topping

f = Foo("pepperoni")

>>> f.topping # gives me 'peopperoni', as expected
>>> f.food # Gives an error: AttributeError: 'Foo' object has no attribute 'food'
>>> f.food = "pizza"
>>> f.food # Gives me 'pizza'

I come from a more strict OOP background and this still puzzles me. Can someone explain? πŸ™

austere sparrow
halcyon plankBOT
#

@austere sparrow :white_check_mark: Your eval job has completed with return code 0.

42
austere sparrow
#

!e
There are also class variables.```py
class Foo:
baz = 1

foo1 = Foo()
foo2 = Foo()
foo2.baz = 3
print(foo1.baz)
print(foo2.baz)

When you look up an attribute, it's first looked up among the instance variables, then among the class variables. One noteworthy case of this is methods: a method is just a function stored in a class variable
halcyon plankBOT
#

@austere sparrow :white_check_mark: Your eval job has completed with return code 0.

001 | 1
002 | 3
fiery cosmos
#

hm so static variables in say java are equivalent to class variable in python iirc.

austere sparrow
#

I don't know Java, but sounds about right

fiery cosmos
empty cobalt
#

@austere sparrow Thank you for the ELI5 πŸ™‚

It's what I thought, just wan't sure

fiery cosmos
#
class MyClass {
  public static int i = 5;
}

class MyClass {
  i = 5
}

these both can be considered same

in python you change them by using class name.

MyClass.i = 6

but if you do

x = MyClass() # created object
x.i = 7 

Now that's an instance variable.

austere sparrow
halcyon plankBOT
#

@austere sparrow :white_check_mark: Your eval job has completed with return code 0.

001 | 1 1 1
002 | 2 2 2
003 | 5 5 5
004 | 15 5 5
empty cobalt
#

Ok, cool! So,. is there a "Rule-Of-Thumb"? LOL

#

ie. Treat class varaibles as static and instance varaibles as ephemeral?

fiery cosmos
#

uhm so we can use them by instance too! but they are supposed to have some value. okay i made some mistake in above sentences.

#

regardless, yeah class variables are eq to static variables in java. or same for cpp too iirc.

halcyon plankBOT
#

@nimble glade :x: Your eval job has completed with return code 1.

001 | Please input color name to get hex code 
002 | (If you get any errors try typing colors with small leters like 'blue' instead of 'Blue'): Traceback (most recent call last):
003 |   File "<string>", line 14, in <module>
004 | EOFError: EOF when reading a line
austere sparrow
#

the tail of a singly linked list always points to None
That is correct. But not every linked list has a tail πŸ™‚

#

!e
Here's a normal linked list:

class Node:
    def __init__(self, label, nxt):
        self.label = label
        self.nxt = nxt

    def print_chain(self):
        node = self
        while node is not None:
            print(node.label)
            node = node.nxt

    def __str__(self):
        return "<Node {0!r}>".format(self.label)

node_c = Node("c", None)
node_b = Node("b", node_c)
node_a = Node("a", node_b)
node_a.print_chain()
halcyon plankBOT
#

@austere sparrow :white_check_mark: Your eval job has completed with return code 0.

001 | a
002 | b
003 | c
austere sparrow
#

!e
And here is a list with a cycle:
Here's a normal linked list:

class Node:
    def __init__(self, label, nxt):
        self.label = label
        self.nxt = nxt

    def print_chain(self):
        node = self
        while node is not None:
            print(node.label)
            node = node.nxt

    def __str__(self):
        return "<Node {0!r}>".format(self.label)

node_c = Node("c", None)
node_b = Node("b", node_c)
node_a = Node("a", node_b)

node_c.nxt = node_a

node_a.print_chain()
halcyon plankBOT
#

@austere sparrow :x: Your eval job has completed with return code 143 (SIGTERM).

001 | a
002 | b
003 | c
004 | a
005 | b
006 | c
007 | a
008 | b
009 | c
010 | a
011 | b
... (truncated - too many lines)

Full output: too long to upload

austere sparrow
#

It could be the result of an error, yes. Sometimes it's intentional. I haven't encountered a case in Python where this would be useful (or in fact, where a linked list which is not a collections.deque would be used)

ember sedge
#

Hey friends, I am trying to learn about Dequeues by building one from scratch with the methods shown in the image. Before implementing though, I am trying to conceptually understand how the Dequeue works when adding to the front and the back. I understand how Stacks and Queues work, having built my Queue using a Circular Buffer pattern (not at Linked Lists yet). Does anyone here have a good understanding of Dequeues that could help me to think through a few method calls? I am thinking I can mock a few method calls and say what I think will happen to the indicies, and we can go from there.

desert cedar
#

Consider the amount of options there are for each spot in the list: 6.

#

For a the numbers goes down by one every time since there's no repetition allowed.

#

For b the number stays the same.

#

repetition is allowed. So no matter what, the second one is still 6 etc

#

It's 6 options for each of the four entries in the list.

#

You multiply them to get the final answer

#

In the first spot it can be one of 6 numbers, same for the 2nd 3rd and 4th. So the result is 6 * 6 * 6 * 6, or 6 ** 4

#

Yes

#

Yes, 6 * 5 * 4 * 3

fiery cosmos
#

it is

#

Yeah (even with 2 letters you can form 36 words, so gotta be more than 15)

#

yep

desert cedar
#

Good

#

There's no limit on questions.

#

It's not.

#

So when checking for how many options there are it's basically only 1 option for the first spot in the list. You ignore this when calculating the amount of lists.

#

After that, all of the spots have 6 options.

#

So the combinations are calculated similar to question b

fiery cosmos
#

What would your answer to b have been if it said length-3 instead of length-4?

#

And how many of those can you chuck a T in front of ducky_tube

desert cedar
#

It would

fiery cosmos
#

Why not all 216 of them?

#

to make a 4 letter word with T in front

desert cedar
#

It's 3 spots with 6 options, making the total amount of options 6 * 6 * 6

#

Or 216 as you said earlier

#

permutations since the order matters

desert cedar
#

What's the question?

#

Get all combinations with 2 aces
Get all combinations
divide them

#

@cobalt mirage

fiery cosmos
#

how does heapq.nlargest work if python's heap is a min heap?

#

couldn't the largest(s) be one of many leafs

stable pecan
#

there's private functions in the library for max replace and max pop, you can see them if you use dir(heapq):

In [2]: dir(heapq)
Out[2]: 
...
 '_heapify_max',    
 '_heappop_max',    
 '_heapreplace_max',
 '_siftdown',
 '_siftdown_max',
 '_siftup',
 '_siftup_max',
...
fiery cosmos
halcyon plankBOT
#

Lib/heapq.py line 521

def nlargest(n, iterable, key=None):```
lilac cave
#

o

smoky dew
#

what's the easiest way of storing a data tree's links? is there a better one than having a dict for each node containing all the nodes it's linked to?

haughty mountain
#

most of the time iteration over children is enough, so list works great then

smoky dew
#

i think the term "tree" is wrong in that context

#

because it's not only made of parents and children, just nodes linked together without any rule really

haughty mountain
#

a graph then

smoky dew
#

i guess..

warped beacon
#

I needed a bit of help with working with regex. I've got a list of around 27k words but a few have additional characters. How do I get rid of all words that have characters other than [A-Za-z'-]? re.match() doesn't seem to get the job done for some reason.

haughty mountain
#

or re.match with the inverted character class [^A-Za-z'-]

warped beacon
haughty mountain
#

^your_regex$

warped beacon
#

hmm, I'll run that too. Thanks for the help

misty lance
#

So i have these number codes

6045781131337478
6045781168538519
6045781182894559
6045781161998991
6045781175566321
6045781144342648
6045781177536934
6045781159941565
6045781184246154
6045781118873354

And i want to sort them like, if the last 2 digits of the code is that or that then seperate all the code in to category

misty lance
#

So each row has one full code/digits and i want to do like if the full code ends with 78 then add it to category 78 and i want to do it to all of them

fiery cosmos
#

and so on?

misty lance
#

Oh yes

fiery cosmos
#

hm alright, are you aware of default dict?

misty lance
#

But will it take every row of the selection?

misty lance
fiery cosmos
misty lance
#

What is dict?

fiery cosmos
fiery cosmos
#

or should i explain?

misty lance
#

Oh yeah ik

#

but can you explain a bit

fiery cosmos
#

hm so in a nutshell its a key value kind data structure.

{
  78: [60000078, 7000078]
}

here 78 is a key, and the list assigned to it is a value.

#

so you want key as the last 2 digits.

#

its just hashmap or json if you're aware about them.

#

um you are there right?

misty lance
#

Yea yea

#

But how can I assign it to watch for the last two digits?

fiery cosmos
#

but let's take one step at a time.

#

!e

a = [15, 17, 18]
d = {}
for i in a:
  key = i%10
  d[key] = i
print(d)
halcyon plankBOT
#

@fiery cosmos :white_check_mark: Your eval job has completed with return code 0.

{5: 15, 7: 17, 8: 18}
fiery cosmos
#

hm so that's how we do it.

#

except you would want a list over here. for values.

#

!e

a = [15, 17, 18]
d = {}
for i in a:
  key = i%10
  d[key] = i
print(d[5]) # you can access the values at key like this
halcyon plankBOT
#

@fiery cosmos :white_check_mark: Your eval job has completed with return code 0.

15
pure schooner
#

anyone online?

drowsy bear
#

does python factorial function use iteration or recursion?

halcyon plankBOT
#

Modules/mathmodule.c line 1903

/* Divide-and-conquer factorial algorithm```
jolly mortar
#

The algorithm is described here

fiery cosmos
#

how do i change directory on pycharm

jolly mortar
shut breach
#

@jade oak by "basics" i mean how to use basic data structures like hash tables, arrays, linked lists, stacks, queues, etc

#

and some simple algorithms that go along with them, like sorting, graph search, binary search (all of these will be covered in an intro textbook)

#

and then what it means for an algorithm to be efficient, along with big-O notation

#

this will give you the basic ideas for how to write algorithms to solve problems efficiently, and a sense of when something is definitely the wrong way to go about it

#

there are some resources in the pins btw

lean dome
#

@jade oak there's some pinned messages in this for resources for learning data structures and algorithms in a structured way

#

If you want to get a software dev job, learning big O notation will be very helpful for you.

#

It's actually used in industry. When we talk about the performance of algorithms, we do use big O to talk about it

#

That's the most math heavy part of learning data structures and algorithms, and it is very useful to learn

bright geyser
#

Hi Everyone! I am trying to solve a problem in python recursion which says "Find all combinations of a list of numbers with a given sum"
Below is my code:-

`def combinationSum(arr,sum, index,temp):

# Iterate from index to len(arr) - 1
    for i in range(index, len(arr)):
        if(sum == 0):
    
            # Adding deep copy of list to ans
            #ans.append(list(temp))
            return temp

        # checking that sum does not become negative
        if(sum - arr[i]) >= 0:

            # adding element which can contribute to
            # sum
            temp.append(arr[i])
            combinationSum(arr, sum-arr[i], i, temp)

            # removing element from list (backtracking)
            temp.remove(arr[i])

print(combinationSum([2,3,5], 17, 0, []))`

Now, the problem is that when I reach the desired result i.e. '[2, 2, 2, 2, 2, 2, 2, 3]' the loop does not stop when infact when the 'temp' list becomes the desired result it should return temp.

Could anyone please help me out with this.

haughty mountain
#

this is a bit clunky using a global list, but it works

answer = []

def combinationSum(arr, sum, index, temp):
    if sum == 0:
      answer.append(list(temp))
      return

    for i in range(index, len(arr)):
        if sum - arr[i] >= 0:
            temp.append(arr[i])
            combinationSum(arr, sum-arr[i], i, temp)
            temp.pop()

combinationSum([2,3,5], 17, 0, [])
for comb in answer:
  print(comb)
```a neater way would be to turn this into a generator function like
```py
def combinationSum(arr, sum, index, temp):
    if sum == 0:
      yield list(temp)
      return

    for i in range(index, len(arr)):
        if sum - arr[i] >= 0:
            temp.append(arr[i])
            yield from combinationSum(arr, sum-arr[i], i, temp)
            temp.pop()


for comb in combinationSum([2,3,5], 17, 0, []):
  print(comb)
bright geyser
haughty mountain
haughty mountain
bright geyser
haughty mountain
#

what part of it? conceptually the generator code and the one that append to a global list are pretty similar

#

do you know about generator functions in general?

bright geyser
#

No. I don't know about the generator part. That is why I want to understand.

bright geyser
haughty mountain
#

generator functions are functions that are lazily evaluated, they run until a yield, at which point they return control (and optionally a value) back to the calling code, a simple example of an infinite iterator that produces numbers 0, 1, 2, 3... is

def counter():
  i = 0
  while True:
    yield i
    i += 1
#

when I call counter() nothing is executed yet, I get a generator object back

In [7]: g = counter()

In [8]: g
Out[8]: <generator object counter at 0x7fe6a17e3c30>
haughty mountain
#

when I call next on it I it runs until the next yield and it yields a value

In [9]: next(g)
Out[9]: 0
#

I could also loop over the generator just like any other sequence container

bright geyser
#

Also, I want to know the best practice for recursion. I want to understand it more. So, what advice or information will you give?

haughty mountain
#

but it's infinte, so maybe not the best idea

#

wrt the generator function from earlier, when we find something with the right sum we yield a copy of the list, the yield from combinationSum(...) in the code that calls the function recursively is essentially just a shorter way of saying

for comb in yield from combinationSum(...):
  yield comb
#

so just yield the elements from the call back out of the function

haughty mountain
bright geyser
haughty mountain
#

recursion in the end is just expressing a problem as other instances of itself, in this case you express the solution in terms of itself, but for a smaller sum, and starting at a later index when looking at elements to add

#

if you have any specific questions I can answer, but it's kinda hard to know what to say about recursion in general

bright geyser
haughty mountain
#

modelling a problem as recursion doesn't necessarily mean you have functions calling themselves, but just that the problem is defined in terms of itself, e.g. the Fibonacci numbers are defined such that F(n) = F(n-1) + F(n-2) but you don't need to use recursive functions to make use of the recursive definition of the Fibonacci numbers, you can start with a list [0, 1] and then append new elements that are just the sum of the previous two

#

!e

F = [0, 1]
for _ in range(10):
  F.append(F[-1] + F[-2])
print(F)
halcyon plankBOT
#

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

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
haughty mountain
#

In many ways, using recursive functions have a bunch of drawbacks like performance, especially in python. So if you can make use of the recursive relation in other ways it's often a good idea

#

(Though sometimes using recursive functions is just the simplest way to get things done)

bright geyser
haughty mountain
#

recursion itself is a very broad subject, I suspect the best way to get a feel for things is to solve problems and try to implement the recursive definition in different ways, maybe as recursive function calls (maybe with memoization) or iteratively like in the example of Fibonacci

#

different ways of implementing the problem have different strengths and drawbacks

bright geyser
#

Can anyone help me finding the problem in the code. Below is my code:-
`def check_sum(sum, i, arr):
def recursive(chk):
if chk == sum:
return True
elif chk < n:
for num in arr:
chk += num
if recursive(chk):
return True
chk -= num
return False
# Starts the accumulator from 0,

return recursive(0)

print(check_sum(17,0,[2,3,5]))`

The function should return True if there exists a combination of numbers from arr that add up to 'n' and False if none exists.

haughty mountain
#

this should use sum right?

elif chk < n:
#

also, this method is going to fail badly when the target sum gets larger when the answer isn't reached quickly or at all

#

actually, you don't even need big

#

target 101, array [2,4,6] is already very slow

bright geyser
# haughty mountain also, this method is going to fail badly when the target sum gets larger when th...

Okay! What about this one:
`def check_sum(target, i, arr):
c1 = []
s = sum(arr)
if s % 2:
return 0 # sum must be even for it to work at all
half = s // 2
result = sum_count(arr, half)
c1.append(result)
if c1 == []:
return False
else:
return True

def sum_count(arr, target): # number of combinations out of lst that sum to total
if not arr: # base c
# ase
return int(target == 0) # empty lst and total 0 -> return 1
# recur: add ways with first element and ways without
return sum_count(arr[1:], target) + sum_count(arr[1:], target - arr[0])`

haughty mountain
#

this is a different problem?

#

where the target is sum/2?

#

(leaving the unused arguments in the function makes it pretty annoying to read)

bright geyser
haughty mountain
#

the target parameter is unused though?

#

and there is the half sum

bright geyser
#

okay. I have removed it now. Let's see if it is solved.

haughty mountain
#

like, the solution you had posted says [2] works, which is clearly wrong

bright geyser
#

oh okay. sorry for the misunderstanding.

plain fiber
#

Can anyone tell me difference between logn and nlogn

agile sundial
#

exactly a factor of n

plain fiber
#

So nlogn is bad?

agile sundial
#

it depends on the other options

#

n log n is bad if you can do it in O(1).

#

n log n is good if the only other choices are n^2

fiery cosmos
#

O(logN) takes time proportional to log2(N), so for N=64 that's 6 time units. O(NlogN) is proportional to N * log2(N), so for N = 64 it's 384 time units.

#

But that's still way better than N^2 = 4096

fiery cosmos
#

I like to stress how the difference between N and NlogN now is really not that crazy much. If N is a 32 bit number they differ by a factor of 32 at most. Wayy better than N^2

jolly mortar
#

hm i didnt really think about that

#

always thought of it as a better N^2 lol

fiery cosmos
#

Right? Like would you rather count to 32 or 4 billion

young merlin
#

I just started codeforces, and im wondering if participating in Div2 is a risk?

plain fiber
#

Yeah sorry mb i forgot to reply cause i was in college

fiery cosmos
#

given 2 sets of basis, how do we find that they both span on same subspace?
please ping me if replied.

young merlin
#

c++ error: expected primary-expression before '==' token

#
if (numbers[i][x]) == (numbers[j][x]){
fiery cosmos
#

The whole thing needs parens around it afaik (you can remove the 2 inner ones)

#

But this channel and server is for Python help 🐍

young merlin
lost marlin
#

Hello so I'm new in programming and i got stuck in a problem help would be highly appreciated

user=input("enter user = ")
passwd=input("enter password = ")
if user=='Ann' and passwd=='123':
    print("|| Access Granted ||")   
    print("|| Welcome Ann ||")
    print("1:shoe billing")
    print("2:show result")
else:
    print("|| Access Not Granted ||")
# Here is the problem -- if access not granted i wanna loop the command to the  ("enter user = ") line
kindred sage
#

Seems u r trying to heck

gray sorrel
kindred sage
#

Yaeh

#

@gray sorrel yaeh

fiery cosmos
#

That’s why cpp better

fiery cosmos
jolly vector
#

Hello, is anyone from Iran here?

raven kraken
#

Hey guys any suggestions for Graph algorithms I am having a hard time learning them, specially the implementation of Topological sort.

lucid orbit
real blaze
#

hello all, can I please get some clarification on the time complexity of the str.replace method? answers on stackoverflow seem to not be conclusive.

austere sparrow
lethal radish
pearl silo
#

I'm tryna design a queue like structure with automatic destructor. Sorta like a conveyor line. As data comes onto the structure it should pass the value to a list of attached listeners who can manipulate it by moving it to a different queue, "flicking" it (removing), or operating on it. Does anyone know of anything like that, that already exists and has good O values for Insert, Change and Removal operations?

#

if data hits the end of the listeners it should be dropped off the end and discarded automatically

shut breach
#

and are you saying that items should be able to be removed from the back of the queue?

pearl silo
#

IDK what i meant by Change in this context now that i think of it. Data on the structure should be immutable. I think it was because i was thinking of taking the value and moving it to a different structure as a structure-bound task

#

and yes, once the list of callback listeners is exhausted i want it to drop the value

#

but it can take an arbitrarily large amount of data

#

as I want to use it sort of as a general purpose structure for the paradigm I wish to use for this project. Reactive Programming (sorta like functional programming but dealing with streams of data). It's a Rendering engine so it could have only a few items or it could have millions

#

so I'm tryna keep it as thin as possible

#

Do i just want a linked list with a "crawling" function that iterates over it one by one and deletes the pointer when it moves?

#

Thanks @shut breach! You figured it out for me

halcyon plankBOT
#

Hey @misty lance!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

misty lance
pearl silo
misty lance
pearl silo
#

np

vital latch
#

I need some help with this simple problem

fiery cosmos
#

The average would be the sum of all comparisons over all leaves divided by the number of leaves.

fiery cosmos
cerulean river
#

hey

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        prev = None
        curr = head
        def rec(previous, current):
            if current is None:
                return previous
            else:
                temp = current.next
                current.next = previous
                previous = current
                current = temp
                return rec(previous, current)
        return rec(prev, curr)

I was just practicing recursion, can this be considered the recursive way to reverse a linked list? I got it right on LeetCode with this submission.

fiery cosmos
#

looks recursive to me

short oyster
#

Hello, i am having an algorithmic problem in one of my university project.
I need to do an algorithm that search a string dictionary of for example 100 words and output a notepad file with each sentence having 4 of that words.
For example, Andrew, Philip, Jonas, Peter
Andrew Philip Jonas Peter
Andrew Jonas Philip Peter
Andrew Philip Peter Jonas
....
it looks like an N! situation
(Permutations without repetitions)

I am not asking for the full code of course, i am just wondering if this wont make a memory problem...
Is there anything premade on internet? anyone knows?
Thank you very much.

cerulean river
#

While on the topic, which questions do you recommend that would solidly my understanding of recursion

exotic rain
#

Hey, anyone ever used LMFit python package to do model fitting?

#

I do not know where to ask my question (SE got 0 answers)

fiery cosmos
fiery cosmos
fiery cosmos
exotic rain
#

Anyone uses pretty_errors?

exotic rain
#

Is there a way to configure the package so that it is the same in all python environments?

zenith berry
#

are there any built in search algorithms? (like linear, binary, jump, etc.)??

agile sundial
#

there's binary search built in

#

!d bisect

halcyon plankBOT
#

Source code: Lib/bisect.py

This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over the more common approach. The module is called bisect because it uses a basic bisection algorithm to do its work. The source code may be most useful as a working example of the algorithm (the boundary conditions are already right!).

The following functions are provided:

zenith berry
fiery cosmos
#

how to analyze loops and discover a run time formula

#

"""

FORMULA: floor((n - m)/k) + 1 only use when m <= n and k >= 1

THEOREM: d - 1 <= n < d iff d - 1 = floor(n) where d is an integer

It calculates the number of iterations of the following loop


i = m
while i <= n:
i = i + k


HOW ITS DERIVED

STEP 1: (j - 1) * k + m <= n < j * k + m where j is the jth iteration (note: i = (j - 1) * k + m )
STEP 2: (j - 1) * k <= n - m < j * k
STEP 3: (j - 1) <= (n - m)/k < j
STEP 4: (j - 1) = floor((n - m)/k) used the theorem mentioned
STEP 5: j = floor((n - m)/k) + 1

"""

potent pond
#

hello I am making a minimax search tree with each node having 3 child nodes I have created 3 layers but cant figure out the way to add a fourth layer.

#

class Choice:
def init(self, left, center,right):
self.left = left
self.center=center
self.right = right

class Terminal:
def init(self, value):
self.value = value

def minimax(tree, maximising_player):
if isinstance(tree, Choice):
lv = minimax(tree.left, not maximising_player)
rv = minimax(tree.right, not maximising_player)
if maximising_player:
return max(lv, rv)
else:
return min(lv, rv)
else:
return tree.value
tree = Choice(
Choice(
Terminal(9),
Terminal(5),
Terminal(2),
),
Choice(
Terminal(-3),
Terminal(-2),
Terminal(1),
),
Choice(
Terminal(3),
Terminal(-4),
Terminal(1),
),
)
print(minimax(tree, True))

#

can anyone suggest a way to add a fourth layer

fiery cosmos
#

What could be the issue when you get this error after you try to do something with your dataframe? never seen this before: py Python38\lib\site-packages\pandas\core\generic.py", line 1534, in __nonzero__ raise ValueError( ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Its structured normally, with only 2 rows, column names and values.

#

Only thing i can come up with is that the dataframe column names have underscores "_" in them. But that cant be it?

lean junco
#

How do you guys remember algos such as Kadanes Algorithm

#

its so simple yet i cannot reproduce it when i need in an exam or so

#

is learning the only way to go?

austere sparrow
#

can you show your code perhaps?

stark axle
#

Pls help me what to do

#

Now

#

@north socket

#

@austere sparrow

#

@latent grotto

latent grotto
#

write print("hello world")

stark axle
#

Where to write?

latent grotto
#

why u randomly tags peoples

stark axle
#

Sorry

latent grotto
#

and why in this channel

stark axle
latent grotto
#

ask in python general and ask what ur question is

stark axle
#

Ok

#

Where is general chat

austere sparrow
stark axle
unkempt patio
#

I'm super struggling to do in pandas what is second nature in SQL πŸ˜„

#

I don't know why I'm finding it so difficult...

nocturne oak
#

Hey someone know why the Python Version 3.9 is invalid?(Its PyCharm)

storm night
#

Is there an easy way to approach doing leetcode? I find myself unable to get a solution for a long time sometimes

#

actually I think there was a reddit thread recently that advocated looking at solutions and studying them first

#

that is probably controversial though

fiery cosmos
lethal radish
lethal radish
storm night
#

thank you I'll do that

#

one thing I noticed is that the solutions on LC are very fancy, is that what the employers really expect? or should I be more detailed with naming and being more explicit with declaring variables etc

glossy breach
tight patio
#

how to create a graph like this

fiery cosmos
#

in python?

tight patio
#

yea
networkx

#
graph = { 
   'a' : ['e','b'],
   'b' : ['f', 'c'],
   'c' : ['b', 'd','f'],
   'd' : ['e', 'f', 'c'],
   'e' : ['d', 'd', 'a']
}

should i use a dictionary like this

fiery cosmos
#
G = {'a':['e','d'],
     'b':['f','c'],
     'c':['f','b'],
     'd':['f','c'],
     'e':['a','d'],
     'f':['b','c','d']}

tight patio
#

hmm

tight patio
#

ooh my bad

fiery cosmos
fiery cosmos
#

also we need a second dictionary for the weights

tight patio
#

so

G = nx.Graph(graph)
tight patio
#

how to do weight

fiery cosmos
#
weights = {frozenset(('a','e')): 3,
           frozenset(('a','b')): 2,
           frozenset(('e','d')): 8,
           frozenset(('b','c')): 7,
           frozenset(('c','d')): 9,
           frozenset(('c','f')): 4,
           frozenset(('d','f')): 4,
           frozenset(('f','b')): 1}
#

this is if we have an undirected graph

#

its one method

fiery cosmos
#

whats with the nx?

tight patio
#

networkx
that what recommend

#

to use

fiery cosmos
#

to draw the graph?

tight patio
#

ye

fiery cosmos
#

i just use turtle

#

i need to look up the documentation if i wanna use networkfx

tight patio
#

is turtle a standerd library?

fiery cosmos
#

its here on this site

#

if your required to use the networkfx library

#

then you'll have to loop through and add the edge weights

fiery cosmos
#

when i was doing networks in my class

#

i used that

#

but obviously you gotta make it from scratch

tight patio
#

oh yea
feel like networkx easier

fiery cosmos
#

you have to code all the time

#

and think about it all the time

#

for a while until it truly clicks

tight patio
#

ig
idk why my course start with graphs first
i thought we are gonna be doing algorithms firsts

#

thx a lot for ur help

#

imma need to watch more videos about grapha

fiery cosmos
#

@cunning stump

#

@cunning stump

fiery cosmos
storm night
#

the most common interview questions also involve graphs/trees apparently!

tight patio
haughty mountain
ivory yacht
#

You don't really need a specific article explaining how to do them in Python specifically, it'd just be a class really.

haughty mountain
#

for real world problems you can often represent/reduce it to a graph problem, which are super well studied

#

it's one of the most useful abstractions in cs

#

I use adjacency lists for pretty much all things graphs

#

i.e. just a list C where C[i] contains a list of nodes reachable from node i

tight patio
#

nvm its dictionary

haughty mountain
#

it's the same kind of thing yes

tight patio
#

oh ok

haughty mountain
#

most of the time I tend to map node names to integers before I work with them

silver robin
#

Hey all , I am planning to sell my GFG course on DSA + problem solving. I have recently bought it, but not done anything on it. I am not planning on using it anymore. It could be useful to someone else instead.
The course has a detailed curriculum on DSA and contest and problems specific to each topic as well for better practice.
This is the course https://practice.geeksforgeeks.org/courses/dsa-self-paced?vC=1
Anyone interested please DM me.

slender patrol
#

Hi guys any one can help me with arrays?

cerulean elk
cerulean elk
slender patrol
#

i want to save a elements on matrix

#

if i have a

void calcul( (void*) a, b){
pointer to a
pointer to b

save on a matrix mat[100][50]

tight patio
open moth
#

Is there anyone interested joining this code challenge

#

If you interested in joining please DM

final lintel
#

hello

hollow thistle
#

hello

raven mirage
#

Hi

final lintel
#

go minecraft

#

5 o'clok PM

lean junco
#

why is morris traversal faster then recursion???

#

theres doesnt seems any difference to me

#

while loop is now using stack, is that it

agile sundial
#

you can use threading to speed it up

#

it's not really faster intrinsically

jolly mortar
#

iterative solutions generally have better perf than recursive ones

lean junco
#

i meant the space

#

the space in morris is O(1)

#

but O(n) in normal recursion

#

i dont agree with this too

lean junco
#

the perf

agile sundial
#

because of the extra links between nodes, you just keep following links through the tree

#

you don't need a stack to store anything

lean junco
#

okay

vocal valley
#

hey someone can help me to simplify something (i hope to be in the good channel):

i have a list=['a','b','c']
and i want to do something like this but with a longer list :
if list[0] not in 'test' and list[1] not in 'test' .... :

can i use a loop in my if to do that better ?

rustic salmon
#

can you elaborate more

vocal valley
#

that script can do what i want :


abc = ['a','b','c']

def fonction(component):
    for i in abc:
        if i in component:
            return False
    return True

if fonction('word'):
  pass```

so I want to know if we can write my function in one line.
rustic salmon
#

prolly with list comprehension

#

tell me what you want to do again

#

@vocal valley

vocal valley
#

yes i think that's it but i dont achieve to do so

#

so that's code is wrong :

return True if (i not in 'word' for i in abc) else False```
rustic salmon
#

ternary

vocal valley
#

i don't understand what's ternary mean

rustic salmon
rustic salmon
#

in one linme

#

line

halcyon plankBOT
#

@rustic salmon :warning: Your eval job has completed with return code 0.

[No output]
rustic salmon
#

your code does nothing

vocal valley
#

!e

halcyon plankBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*

vocal valley
#
abc = ['a','b','c']

def fonction(component):
    for i in abc:
        if i in component:
            return False
    return True

print(fonction('words'))```
#

!e py

#
abc = ['a','b','c']

def fonction(component):
    for i in abc:
        if i in component:
            return False
    return True

print(fonction('words'))```
halcyon plankBOT
#

@vocal valley :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'py' is not defined
vocal valley
#

ty lol

#

ok so that's return True

#

and if in do fonction('all') that's return False it is exactly waht i want because i want to use this boolean return in my if statement

#

so i search to do de function fonction in just one line

rustic salmon
#

its returning true because the i is not in abc

vocal valley
#

because all the i are not in abc

#

no caracters in my words are in abc

#

i want to select just the words if this word have no a no b and no c

rustic salmon
#

i don't think i quite understand what you want to do.

vocal valley
#

i want to verify if no one of the caracters in my list abc are in my word

rustic salmon
#

oh

#

1 sec

#

like this?

vocal valley
#

try main('all') pls

rustic salmon
#

its false because its looking to see if the whole word is in list

vocal valley
#

ah no no no xyz must return True not False

#

my function "fonction" works perfectly

halcyon plankBOT
#

@rustic salmon :white_check_mark: Your eval job has completed with return code 0.

True
rustic salmon
#

is that what you want it to do?

vocal valley
#

yeah words has no a nob and no c so that's return True

vocal valley
rustic salmon
#

ah ok

vocal valley
#

loul t'es franΓ§ais ?

rustic salmon
#

i don't know french

vocal valley
#

ok no problem

rustic salmon
#

not sure if you can do it in one line. i am trying though. it might be 2-3 lines

vocal valley
#

ok

rustic salmon
#

im sorry, but im not quite sure how to do this. i will keep trying though

vocal valley
#

ok no problem if you don't achieve to do that i will just use my function ^^

rustic salmon
#

ok

#

maybe someojne else will come around and help you

fiery cosmos
rustic salmon
#

well there you go

vocal valley
#

Thx

haughty mountain
lean walrus
#
return not any(map(container.__contains__, iterable))
green robin
#

Hey there, I need help.

#

Hey, I need help. Im trying to program the Pascal's triangle. I dont know how to put the numbers in a logic order (see other screenshot) any solutions??

fiery cosmos
#

there are multiple ways

#

first pascals triangle is actually a recursively defined function

#

and the triangle itself is the plot of that function

#
pascal(n,0) = 1
pascal(n,n) = 1
pascal(n,r) = pascal(n - 1, r - 1) + pascal(n - 1, r)
#

there is another recursive definition

#

that can be used to make a version of the program using only loops

#

let me know if you still have questions

fiery cosmos
#
the other recursive definition takes advantage of another fact 
pascal(n,r) = choose(n,r)

the pascal triangle function is equivalent to the choose function, however, what is the choose function?

the choose function is the following

choose(n,r) = (n!)/(r!(n - r)!)

where n! means n factorial if your familiar with that
for example 5! = 5 * 4 * 3 * 2 * 1
#
the choose function can be defined recursively
for example we need find a way to 
relate 
choose(n,r) = (n!)/(r!(n - r)!)
with 
choose(n, r - 1) = (n!)/((r - 1)!(n - (r - 1))!)

we can see that with the following fact

choose(n,r) = (n!)/((r - 1)!(n - r + 1)!) * (n - r + 1)/r

which is 

choose(n,r) = choose(n, r - 1) * (n - r + 1)/r

now we have a new recursive function 

choose(n,0) = 1
choose(n,r) = choose(n, r - 1) * (n - r + 1)/r

but this one can be implemented iteratively unlike the other version
#
def pascals_triangle(num_rows = 10):
  for n in range(num_rows):
    current_position = 1
    print(current_position, end = " ")
    for r in range(1, n+1):
      current_position *= (n - r + 1)/r
      print("{:4d}".format(int(current_position)), end = " ")
    print()
fiery cosmos
cyan halo
#

Hey guys, I need help for y'all.

#

I'm new to python, please suggest some free resources to learn data structures and algorithms skills in python. Thanks in advance.

halcyon plankBOT
#

Hey @lean dew!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

#

Hey @lean dew!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

lean dew
#

what more functions should I add ?

haughty mountain
#

splice to merge two linked lists in O(1)?

elfin pecan
#

Any good books for dsa?

#

to give you some idea, I am good at string,array based problems but usually have trouble dealing with trees and graph based problems

#

like close to intermediate i would say

#

so based on that level what are the books recommended by you guys?

fiery cosmos
fiery cosmos
fiery cosmos
#

how to become good at algorithms and data structure?

#

Maybe start by watching the MIT 6.006 course in the pins ducky_wizard

#

Also, coding challenges, reading books

eager gulch
#

please take a look at this problem and its answer:

#

and here's the answer:

#

the thing that I can't understand is that it has 2 returns in a function . isn't that if function returns a value python will stop reading the rest of the function lines?

#

what am I misunderstanding?

#

can someone please explain this?

#

thanks alot

fiery cosmos
#

!e py def outer(): def inner(): return "foo" return inner() + "bar" print(outer())

halcyon plankBOT
#

@fiery cosmos :white_check_mark: Your eval job has completed with return code 0.

foobar
eager gulch
#

I understand the 2 upper returns (0 or 1) but when dfs runs and returns 1 or 0 then it is going to continue and read the rest lines?

#

for example

fiery cosmos
#

no, the dfs function ends itself immediately when it hits a return

eager gulch
#

if it checks the conditions and for e.g returns 1 then why should continue and read visited.add or per += ....

#

I thought it would end the func before even reading that lines

fiery cosmos
#

It will continue to those lines if both the if conditions are false

#

the code inside an if block never gets run if the condition is false

eager gulch
#

yeah I know it but still somethings wrong with me

#

I had to think about it

#

thanks for your answers btw

fiery cosmos
#

sure discre3Comfy

eager gulch
#

I get it bro, I just run the vscode debugger and saw how the algorithm's working

eager gulch
#

I need a serious help if anyone who's good at algorithms can help

#

I really wanna be good at solving problems but i cant

#

i try solving leetcodes easy problems (graph ones)

#

but even the easy ones I can't solve

#

I don't know where to start where am I doing wrong. if anyone has any advices I will be thankful

rustic salmon
#

just keep grinding. At first it seems like you are getting no where but you will get it eventually

#

Go easy on yourself

weary gyro
#

if u want i can give u a website, they teach you every topic of ds algo very good but they do programs in java

#

if your python basics are good then u can just code in python like whatever they teach u

#

its free

rustic salmon
#

Java to Python isn’t the easiest transition in terms of syntax…

weary gyro
#

logic is same

#

they teach u the logic

#

u just have to code on that logic

rustic salmon
#

yeah true

hot vale
#

interesting

lean dew
eager gulch
# weary gyro its free

I will be thankful then, yeah I know the syntax of cpp and as I've seen before java and cpp are a bit similar . I can convert the syntax myself if I know the logics correctly

weary gyro
#

go to resources

eager gulch
#

Thanks Alot man

weary gyro
#

do you speak Hindi?

lean dew
#

Also is there any in-built function like __add__ for getting index like list does i.e list[i] ?

eager gulch
weary gyro
#

ok then you can look to their solutions and Mark all the topics there

#

once you complete all the topics there then you can go on leet code

eager gulch
#

πŸ‘Œ ❀️

lean dew
#

Can i use it for getting slicing input as well

#

Like [1:3]?

haughty mountain
lean dew
#

got the index thing worked out, now just have to think about this slicing

barren hazel
#

could anyone give me a suggestion maybe of how I would go about making a pcb autotracer? I don't actually need an autotracer, I'm just trying to generate pixel art images of PCBs. I was thinking maybe an alteration of A*, but I've gotten a few comments that that may not be the best way to go

Edit: not looking for an answer, necessarily, but maybe a direction on where to look for ideas

bitter wigeon
#

Image manipulation perhaps...use color thresholds to define the trace

#

Then save the trace as a monochrome image use that to make the pixel art

haughty mountain
haughty mountain
nocturne tapir
fiery cosmos
#

So we can simplify 2 ^((n-1)/2) + 2 ^((n-2)/2) into 2 * 2 ^((n-2)/2) because second expression is less than first?

haughty mountain
#

it's not a simplification, it's another inequality

#

but what they are doing is replacing 2^((n-1)/2) with 2^((n-2)/2)

#

which is clearly smaller

fiery cosmos
#

Is there a strict way to make a neural network cause idk if mine is

haughty mountain
#

I would probably have done a more direct approach since there is nothing stopping you from just factoring out 2^(n/2)

2^((n-1)/2) + 2^((n-2)/2) =
2^(n/2) / sqrt(2) + 2^(n/2) / 2 =
2^(n/2) * (1 / sqrt(2) + 1 / 2) >
2^(n/2)
nocturne tapir
#

this looks interesting; it seems there is almost no results when searching for closed path generation algorithms :(

fiery cosmos
haughty mountain
#

but yeah, this is just a >= b >= c implying that a >= c

fiery cosmos
haughty mountain
haughty mountain
#

or what part is confusing?

fiery cosmos
#

That how you ended up with second line

#

Did you forget to put parenthesis something there in second line?

#

2^(n/2) / sqrt(2) + 2^(n/2) / 2 =

#

I don't get how did you get that

#

@haughty mountain

#

I don't get why instructor said

#

So, now we can say, this is another algorithm, it should work just as well, but, how fast is it? Well, how many lines of code did you use?
There are three lines of code at the beginning, and there's a return statement at the end, so that's four lines of code. Next up we have this for statement that we run through n minus one times, and each time we have to execute two lines of code. So adding everything together we find out that t of n is something like 2n plus two.

haughty mountain
fiery cosmos
#

Next up we have this for statement that we run through n minus one times
Did he fail to say that we run it n minus two?

fiery cosmos
haughty mountain
#

it is n-1 times. F[0], ... F[n] is n+1 terms

fiery cosmos
#

So my assumption is that it's n - 2 because we run for loop from 2 to n

haughty mountain
#

it includes 2 and n

#

say n=4, then the loop is over 2, 3, 4

#

i.e. not python range(2, n)

#

but range(2, n+1)

fiery cosmos
#

Hmmm, but why it's not in the end 2 * (n -1) + 4

#

4 because if we remove for loop and statement inside it, then there are 4 lines

#

@haughty mountain

haughty mountain
#

counting lines of code is a kinda weird exercise, ngl

haughty mountain
#

same thing

fiery cosmos
rustic perch
#

I've seen this device, it's a usb, it can see your passwords so don't use a public pc with a suspicious usb

weary gyro
#

oh my

nocturne tapir
weary gyro
tight patio
#

why is every squre number is open
for locker problem

#

ooh is it bc they have odd number of factors
so example 9

#

factors are 1,3,and 9

#

for the first time door open
and 3rd time door close
and 9th time door open

fiery cosmos
#

I want to take an input string and see if it's similar to another string.

find strings similar to: "apple"
match case 1 "pple"
match case 2 "paple banana pie banna cherry"
dont match "rocks"

I thought about using Levenshtein distance, but that will match case 1 but not case 2... unless I made the edit distance longer then the length of the string "apple" itself (which would then match anything). What's the algo I'm looking for?

fiery cosmos
halcyon plankBOT
fiery cosmos
#

Solved the tower of hanoi

#

Sadly it doesn't let me post my python file :<

#

But I posted the recursive function

#

Set U to be {L,C,R} for left, center, right columns

spiral needle
#

Nice!

fiery cosmos
#

Set F to be {L} and set T to be {R} , and n is an integer

spiral needle
#

ok..

fiery cosmos
spiral needle
#

as long as u did it, it's good

#

^^

fiery cosmos
fiery cosmos
ancient echo
#

Hello

#

Hi

bitter wigeon
#

Oh wow a warrior for peace

narrow sky
#

quick question. i am pretty new to python and i know it has many different uses

#

i am using python more for data analysis, which is the channel that data analysis falls under?

#

thank you

vital valley
#

hi guys, i'm trying to binary search a target, where the target might not exis tin the array. and if it doesn't exist, it just returns the neighbor to the left

#
        while low < high:
            mid = low + (high - low) // 2
            
            if arr[time] < target:
                low = mid + 1
            else:
                high = mid
        return arr[low]
#

can anyone help me why this doesn't logically work

#

i'm trying to do it w/o having a literal checking statement saying :
"if the target is greater than the left neighbor, but less than the right neighbor, then return"

zealous stirrup
#

any tips ?

shut breach
#

tips on what?

nocturne tapir
#

Is there a way to use pathfinding algorithms like A* to generate a closed path, where the start and end point are the same?

vocal gorge
# nocturne tapir Is there a way to use pathfinding algorithms like A* to generate a closed path, ...
#

if you have obstacles, you might be able to use a similar approach anyway, by making some random waypoints and pathing from each to the next one

nocturne tapir
#

Hmm I don't think so, this method wouldn't give me much variability in the paths generated

#

This is the kind of thing I'm after, only that instead of generating an A -> B path it would loop itself back to A without intersecting itself

vocal gorge
#

hmm, and also have a significant length, or something like that?

nocturne tapir
#

Length wouldn't matter too much since the size of the grid/number of obstacles could be controlled parametrically, the ultimate goal for me is to replicate the functionality of the add-on from this reddit post. Right now I'm just trying to get the random shape generation from the first few seconds of the gif on this page https://www.reddit.com/r/blender/comments/ip2ute/created_random_race_track_generator_in_blender/

reddit

147 votes and 9 comments so far on Reddit

β–Ά Play video
vocal gorge
#

hmm, I actually wonder if complexity is literally just the number of turns

#

not quite, but might be similar

nocturne tapir
#

oo that could be close; my initial thought was that it was just grid size

#

I'm beginning to think its not a grid with pathfinding but some other algorithm. So frustrating to try and reverse engineer

vocal gorge
#

one idea:

  1. n times, randomly generate a length in some limits. Consider turning either left or right from last segment. If one of the directions would lead to an intersection, choose the other. If both, ???
  2. Then close the curve by a straight line segment
    This idea seems like it'd commonly lead to ugly long closing segments at the end
#

another idea, and I feel like it's closer to what they are doing, is to maintain a path that's always closed, and gradually make it more complex

#

e.g. start with a simple square. Then repeatedly choose a random segment and replace it with |_|, say, or something like that. That guarantees a closed path, and self-nonintersection is also easy to get (check if changing the segment would lead to an intersection - if so, try again to randomly chose a different segment to replace)

nocturne tapir
#

Hmm possibly. so kinda like this post? https://answers.unity.com/questions/394991/generate-closed-random-path-in-c.html I'll have to figure out how to approach this in a blender-friendly way, this project is gonna be way harder than I initially thought

haughty mountain
flat wave
#

if I have an object with a bunch of attributes, is there a way to loop through them....like object[attribute]

haughty mountain
flat wave
#

I suppose I could have 15 lines, each just 'att1 = object.att1'

#

but wondering how to do it with a loop, even if it's not as readable

haughty mountain
#

df['column_name']

flat wave
#

Just wondering if there's a way to do this or not πŸ™‚

#

I can figure out how to handle the df

haughty mountain
#

what is it you're trying to look up exactly? columns by name?

#

do you have some code example?

flat wave
#

I'm looking to loop through object attributes

#

'att1 = object.att1'

#

but for like 15 of them

#

it looks like this

#

crv_comp_gauge.integrate_checkpoint()

haughty mountain
#

these?

flat wave
#

this is not pandas

#

this is just python

#

I have objects

#

I'm trying to retrieve attributes

#

crv_comp_gauge.period_timestamp()

haughty mountain
#

oh, retrieving stuff to put in a dataframe from a class?

flat wave
#

just please ignore the df

#

sure

#

crv_comp_gauge.dict.keys()

#

dict_keys(['_project', '_build', '_sources', 'topics', 'selectors', 'signatures', 'bytecode', '_owner', 'tx', 'address', 'decimals', 'integrate_checkpoint', 'user_checkpoint', 'claimable_tokens', 'claimable_reward', 'claim_rewards', 'claim_historic_rewards', 'kick', 'set_approve_deposit', 'deposit', 'withdraw', 'allowance', 'transfer', 'transferFrom', 'approve', 'increaseAllowance', 'decreaseAllowance', 'set_rewards', 'set_killed', 'commit_transfer_ownership', 'accept_transfer_ownership', 'minter', 'crv_token', 'lp_token', 'controller', 'voting_escrow', 'future_epoch_time', 'balanceOf', 'totalSupply', 'name', 'symbol', 'approved_to_deposit', 'working_balances', 'working_supply', 'period', 'period_timestamp', 'integrate_inv_supply', 'integrate_inv_supply_of', 'integrate_checkpoint_of', 'integrate_fraction', 'inflation_rate', 'reward_contract', 'reward_tokens', 'reward_integral', 'reward_integral_for', 'admin', 'future_admin', 'is_killed', '_initialized'])

#

I want the results of each of those

haughty mountain
#

getattr, but it's terrible

flat wave
#

hmm

haughty mountain
#

any reason this is a class rather than a dict with only the stuff you want? or is this come existing thing you don't control that you just want to extract data from?

flat wave
#

yeah its existing

#

it's from a blockchain

#

hmm

#

it's not doing the actual contract call

#

getattr(crv_comp_gauge, 'period_timestamp')

#

<ContractCall 'period_timestamp(uint256 arg0)'>

haughty mountain
#

I guess it's a function or similar?

flat wave
#

oh hold on

#

getattr(crv_comp_gauge, 'period')

#

<ContractCall 'period()'>

#

crv_comp_gauge.period()

#

24602

#

so it's only actually running the contract call when I use .period()

haughty mountain
#

tbh, I would probably just write the 15 or so things you care to extract

flat wave
#

yeah

#

just wondering if this is possible

#

out of curiosity at this point

haughty mountain
#

if it's all functions you can just call whatever you get from getattr

flat wave
#

getattr isn't running the function tho

haughty mountain
#

yes

#

it returns the function

flat wave
#

how do I run the returned function

haughty mountain
#

getattr(obj, 'attr')()

#

just call it

#

like a normal function

flat wave
#

oh cool

#

I was trying .() at the end

haughty mountain
#

.__call__() would work, but that's even more terrible

flat wave
#

hmmm

#

not sure how to use that

haughty mountain
#

you don't want to

flat wave
#

lol

haughty mountain
#

it's what doing () calls

flat wave
#

ahhh

haughty mountain
#

f.__call__(x) and f(x) are the same thing

flat wave
#

is there a way to scroll through each of the attributes

#

and tell if they are dictionaries or calls or whatever

haughty mountain
#

you can look at type of it

flat wave
#

can you type them all at once?

#

or have to do each seperately

haughty mountain
#

I mean, use a loop or equivalent

flat wave
#

?

#

each would be crv_comp_gauge.topics

#

crv_comp_gauge.topics.foo

#

crv_comp_gauge.topics.foo1

haughty mountain
#

but you're quickly making things very much harder, rather than just typing the handful of fields you want

flat wave
#

there's just a lot of fields

#

and I don't want to have to manually check each

haughty mountain
#
[type(getattr(obj, attr_name)) for attr_name in obj.__dict__]
#

err

flat wave
#

lol

#

this is perfect!

haughty mountain
#

or just look at the values in __dict__ rather than getattr

#
[type(attr) for attr in obj.__dict__.values()]
flat wave
#

this is great, thank you!

haughty mountain
#

in the end this kind of thing

[attr for attr in obj.__dict__.values() if some_condition_you_write(attr)]
#

||but you didn't get this code from me...||

flat wave
#

lol

#

talking to you was like slowly trying to convince you to teach me locked away spells

haughty mountain
#

not a bad description

#

I mean, digging into these kinds of things can be fun for understanding, but as code it's pretty darn terrible

flat wave
#

I don't really know why it's bad other than its ugly

#

but seems to work its purpose

marble forge
#

Hi, I haven't taken an actual algorithms and data structures course. Would you guys recommend any books or resources in particular?

fiery cosmos
#

See the pins ducky_party

marble forge
#

thank you

#

not sure if I'll ever need to reverse a binary tree, but I'm applying for a masters in CS next month and this feels like something I should know lmao

haughty mountain
#

i.e. just recursively do it

marble forge
#

yea people use it as a meme for the kind of thing that is asked on interviews

fiery cosmos
#

where the algorithms at

fiery cosmos
#

does anyone here knows pyqt5 ?

jolly mortar
silk tangle
#

Does anyone here know how to create a tree structure for an IDDFS (Iterative Deepening Depth First Search when each node on the tree is a class object?

#

Im having issues making the next layer of the tree.

#
#Searches using DFS on each layer.
def depthFirstSearch(frontierParam, treeParam, visitedStatesParam, endState , depth):
    #Used as our frontier.
    frontier = frontierParam

    visitedStates = visitedStatesParam

    #visitedStates set.
    tree = treeParam

    while len(frontier) > 0:
        #Pop the current state from the head of the queue.
        currentState = frontier.pop()

        #Compare the currentState's state to the goalState.
        #if currentState.state not in visitedStates:
        if currentState.state == endState:
            #print("Depth: " + str(currentState.depth))
            return currentState, visitedStates

        if not currentState.visited:
            #Generate the childs children so the search can continue. 
            #This creates a part of the next layer of the tree.
            #Only create the children if the depth of the child is equal to the current depth.
            #We only need to do this once per layer but we need to check because we visit each node many times over.
            if currentState.depth == depth:
                currentState.generateChildList()

            #Add the children to the visitedStates set to remake the frontier for the next DFS search.
            #Children must be added after the currentStates position to keep the order.
            for child in currentState.childrenList:
                #Add children to the parent/child dict.
                tree[currentState] = child
                #visitedStates.append(child)
                #Set the childs parent to the current state.
                child.parent = currentState

        #Some action such as adding elements to the visitedStates set we only want to do one time.
        if currentState not in visitedStates:
            #Add the currentState to the visitedStates.
            visitedStates.append(currentState)

    return None, visitedStates

#Generates the child layers. Formulates the stack before calling DFS on it.
def Iterative_deepening_dfs(startState, endState):
    #Var to keep track of the current depth.
    depth = 0

    #Class instance for the found state.
    foundState = None

    #Bool for the goal state being found.
    found = False;

    #Used as the stack data structure.
    frontier = deque([startState])

    visistedStates = set()

    #Tree structure. Self | Children
    tree = dict()

    while not found:    
        #Search the tree for the goal state using DFS.
        foundState, visitedStates = depthFirstSearch(frontier, tree, visitedStates, endState, depth)

        #Check to see if foundState is not None.
        if foundState not None:
            return foundState

        #Increase the depth before the next iteration.
        depth += 1

    return foundState
#

Here is my code so far

#

I was going to try and use the dictionary to create the tree at each new layer but I am having a hard time doing that.

#

Because I dont know which node goes in what order.

silk tangle
#

Here is my Board class.