#algos-and-data-structs

1 messages Ā· Page 121 of 1

foggy mirage
#

Help please

#

I'm breaking down

#
    def put(self, num):
        if self.base:
            if num < self.base:
                if self.left is None:
                    self.left = Node(num)
                else:
                    self.left.put(num)

            elif num > self.base:
                if self.right is None:
                    self.right = Node(num)
                else:
                    self.right.put(num)

        else:
            self.base = num
#

what is put purpose?

#

It does nothing

knotty magnet
#

if it does nothing, then why is there so much code

foggy mirage
knotty magnet
#

why do you think it does nothing?

foggy mirage
#

like when I remove it , it only makes 2 pair of children and stops

foggy mirage
#

like

#

def put():
    put()
#

which makes no sense to me

#

at all

knotty magnet
#

can you write a recursive function to calculate the factorial of a number?

#

without looking anything up, except maybe what factorial is

foggy mirage
#

um

#

no

knotty magnet
#

try it

foggy mirage
#

maybe like

#
def fac(num)
    num * fac(num)
 
knotty magnet
#

you have to return it also

#

it will also keep recursing forever, so you need to add a base case

#

essentially, what you want to do when you stop recursing, and when

grizzled whale
#
def f(n):
  if n == 0: return 1
  return n*f(n-1)
elfin pecan
#

There are always some problems which require some mathematical approach or some different approach
like for max subarray sum we use Kadane's Algorithm
Some of the new approaches are mostly learnt by practice but is there any resources(like repositroy,video collection) where such ideas are available at once like the sliding window technique and the non mainstream topics but might help in better approach towards problem?

last fulcrum
#

There was a question from amazon on rotating an image or 2D array 90 degrees.
Per my understanding, column 1 should become row 1. How can I easily translate this to code?

#

`
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
the output should be

rotateImage(a) =
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]
`

runic tinsel
#

transpose after reversing

last fulcrum
#

Words I don't understand šŸ˜‚

runic tinsel
#

[*map(list, zip(*a[::-1]))]

last fulcrum
#

Yea I'm still confused. Maybe this question is too much for me?

runic tinsel
#

just look at where indices come from

#

the result is ```
2,0 1,0 0,0
2,1 1,1 0,1
2,2 1,2 0,2

#

to make a nested loop that sets cells in the new array to these values from the original, find a formula that makes 2,1,0 from 0,1,2

last fulcrum
#

Ok thanks

fiery cosmos
#

pinga

distant mauve
#

Hi to all Pythoneers.

glacial sail
fiery cosmos
#

I have a sorted array, and want to insert one more item into the array such the resulting array remains sorted.What is an Efficient way to insert a number into a sorted array of numbers?

shut breach
humble mauve
fiery cosmos
fervent saddle
#

It will end up being O(n) no matter what because you have to shift all the further values over by 1

#

There’s no way to insert into an array faster than O(n)

#

Doing some kind of binary search to find the right position might make it faster on average, but there’s no way to avoid O(n)

honest sleet
#

Can anybody provide best resources to learn DS Algo?

rustic glacier
# honest sleet Can anybody provide best resources to learn DS Algo?

Well for what if just in general I recommend trying out codehs but like java and python witch ever your preference is java is going to be a lot harder to understand and master while python is easier because python is easier language if you don't like codehs just look up best websites to learn DSA

keen hearth
honest sleet
honest sleet
keen hearth
honest sleet
#

Got it thanks.

#

Brilliant sites, thanks to whoever made or shared them.

stiff mango
#

I just made my own function that converts strings to ints without using the int function or anything similar

#

!e ```py
def str_to_int(string):
n = 0
for i, place in enumerate(string[::-1]):
n += "0123456789".index(place)* 10**i
return n

print((str_to_int("25")))

halcyon plankBOT
#

@stiff mango :white_check_mark: Your eval job has completed with return code 0.

25
stiff mango
#

!e ```py
def str_to_int(string):
return sum(("0123456789".index(place)* 10**i for i,place in enumerate(string[::-1])))

print((str_to_int("25")))

halcyon plankBOT
#

@stiff mango :white_check_mark: Your eval job has completed with return code 0.

25
stiff mango
#

Is this how it works (in theory) under the hood? I know python uses C for stuff like that, but is this how it is implemented there?

stiff mango
#

K

knotty magnet
#

you're using str.index to find the place when you could just use simple math, so there's no way that's how it's implemented

stiff mango
#

!e print(ord("0"))

halcyon plankBOT
#

@stiff mango :white_check_mark: Your eval job has completed with return code 0.

48
stiff mango
#

!e ```py
def str_to_int(string):
n = 0
for i, place in enumerate(string[::-1]):
n += (ord(place)-48)* 10**i
return n

print((str_to_int("25")))

halcyon plankBOT
#

@stiff mango :white_check_mark: Your eval job has completed with return code 0.

25
stiff mango
#

@knotty magnet is that what you mean?

knotty magnet
#

no

stiff mango
#

And what "simple math" do you mean?

knotty magnet
#

division?

stiff mango
#

And where would division come into play? What would you devide to get from the string representation to the number?

knotty magnet
#

you wouldn't use the "0123456789" string in the first place

stiff mango
knotty magnet
#

yeah, that looks ok

brave oak
#

!e

def str_to_int(string):
    n = 0
    for i, place in enumerate(string[::-1]):
        n += (ord(place)-48)* 10**i
    return n

print(str_to_int("-1"))
halcyon plankBOT
#

@brave oak :white_check_mark: Your eval job has completed with return code 0.

-29
brave oak
#

@stiff mango

cyan verge
#

what are simple uses cases for queues and stacks

brave oak
cyan verge
#

I see. just looked it up. what about stacks?

#

or do they both apply?

brave oak
#

or you can parse with a stack

#

example

#

Python's indentation levels

#

notice how

#

the last level of indentation is the first to be dedented

cyan verge
#

I haven't even thought about indentation like that. that's an interesting application

fiery atlas
#

Is there any thing I can look at if I wanted to output a csv file for a log file? I search in google but too complicated for me

last fulcrum
#

Python has hacky one liners for DS & A. Are these generally accepted in interviews?

For example rotating an array by 90 degrees. Someone did this.

rotateImage = lambda a: zip(*a[::-1])

#

Another did this.

def rotateImage(a): return list(zip(*reversed(a)))

jolly mortar
#

assigning a lambda to a variable in general is considered bad practice

last fulcrum
#

I think all these would be frowned upon. I'm thinking the solution should work in every language.

#

How can I improve this solution I wrote up?

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        """ Returns the index of the two values that gives you the target"""
        
        count = 0
        for value_1 in nums:
            count += 1
            for value_2 in nums:
                if value_1 + value_2 == target:
                   return list((nums.index(value_1), nums.index(value_2)))
#

This is On2. Very bad lol

last fulcrum
fiery cosmos
runic spade
#

Can someone help me setup matplotlib on visual studio code?

runic spade
compact perch
#

Hii I'm nee here could anyone give me best learning material for DATA STRUCTURE AND ALGO

astral pulsar
#

Given 5 audio files, if i want to split them into 3 chunks, 2 2 1 would be a naive split because the 5 audio lengths could be very different. I need to split it into 3 1 1 if the former 3 audio files have about the same combined length as the 4th or 5th. In other words, I need to create chunks that optimize items' combined length instead of item count. What would be the name of the algorithm I should look up if I want an implementation for this?

fiery cosmos
proper canyon
#

Hi guys, I've got a question, how do I measure the algorythmic complexity of this recursive factorial function?

#

I mean, I have just one recursive call so it would be 1^n? That does not make sense to me

fiery cosmos
#

For a given n how many total function calls does it make? Say for n = 4?

woven oar
#

Can anyone point me in the direction of some material on search algorithms? In particular I'm trying to figure out how to search a massive CSV file for relevant search terms input by a user. For example, I have a CSV file with thousands of rows of food items from the USDA. Currently I'm using the "if x in y" to perform my search. An example of a current issue is if the person types in blueberry, the CSV file has items listed as "blueberry" and "blueberries" and only returns the one typed. I want both returned, and I'm not sure if this is just an exercise in creating a function to search for both singular and plural items for each item entered, or if there is a better method.

proper canyon
#

So it'd be n-1

fiery cosmos
#

Yeah, or O(n) time complexity

proper canyon
meager slate
#

but regex could be slow if the file is massive

loud trail
# woven oar Can anyone point me in the direction of some material on search algorithms? In ...
#

this is also a thing but its quite old, so maybe borrow its ideas but maybe dont rely on it https://pypi.org/project/Whoosh/

#

you could also load the data into sqlite and use the FTS5 extension

#

oh finally you might want to try several different inflections of a word, see https://pypi.org/project/inflect/

keen hearth
#

In SQL you can 'index' a column of the table, allowing fast lookup of rows by that attribute. You will also be able to access the same data quickly from multiple instances of your application without having to load it into memory multiple times.

woven oar
#

Thank you all for the great suggestions, there's a lot to digest here, but this looks like a good starting point. Thanks again.

woven oar
runic niche
#

hi i have a pretty simple question in #help-chocolate if anyone has free time

last fulcrum
#

Does leetcode usually have bad test cases?

#

My code failed even though it should pass the test case

fiery cosmos
#

I don't think I've ever had problems

fiery cosmos
last fulcrum
#

Q

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

#

My code

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        buy = sys.maxsize
        sell = -(sys.maxsize)

        for day in prices:
            if day < buy:
                buy, sell = day, day
            if day > sell:
                sell = day

        if sell > buy:
            return sell - buy
        else:
            return 0
#

Wrong test case.
[2,4,1]
This test case says it should return 2.
It should rather return 0 because the person would buy on day 2. Day 2 has the value of 1. After 1 the array ends. There is no profit to be made here, thus the answer should be 0. Please redo the test case. Thanks.

fiery cosmos
#

Can't you buy on 2 and sell on 4, thus earning 4-2=2 pithink

#

Iirc this kind of problem requires dynamic programming AlexHmm

#

But i could be totally wrong there

last fulcrum
#

šŸ‘

simple mist
#

hey guys! any recommendation where can i start learn data struct and algo.... also some prerequisites too. Thanks!

vivid matrix
#

https://www.amazon.com/Algorithm-Design-Jon-Kleinberg/dp/0321295358 is the best I have found about algorithms. Of course you can go back to masters i. E. Introduction to algorithms https://en.m.wikipedia.org/wiki/Introduction_to_Algorithms

Introduction to Algorithms is a book on computer programming by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The book has been widely used as the textbook for algorithms courses at many universities and is commonly cited as a reference for algorithms in published papers, with over 10,000 citations documented on ...

humble beacon
#
tuple_list = [('234', 3, 2, 1, 3, 5), ('123', 3, 2, 1, 3, 5), ('143', 3, 2, 1, 3, 5), ('2343', 3, 2, 1, 3, 5)]

I want to find the tuple where index 0 == 123... how can i do this the most efficiƫnt way.. note that i have a tuple list of 12k items.

Is there an optimal way? It has to be fast.

#

Is there an algorithm for this?

slim vault
#

I don't think you can do better than linear search here

#

the question is whether you'd want to stop after finding the first one, or find all where the number matches

#

if you're going to be searching for records often, it may be worth it to build a more appropriate data structure, such as a dictionary mapping from each tuple's index 0 to the whole record

fiery cosmos
halcyon plankBOT
#

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

(3, 2, 1, 3, 5)
slim vault
#

yeah, but keep in mind that this is only worth it for repeated lookups

#

for a one-off lookup, a linear search should be faster even if you're looking for the very last element (i.e. worst case)

fiery cosmos
#

I think they mentioned in general they need to do it a bunch

slim vault
#

okay, then a dict sounds good 😌

frail sentinel
#

what does the deferent between interators and function generators and when does we use it ??

#

I've confused in this point and I cant understand them. Pleas help me

loud trail
#

but the short version: an iterator is anything that can be iterated over (kind of)

#

an iterable is something that can be turned into an iterator

#

a generator is a specific kind of iterator

frosty coral
#

What do you recommend me to read to improve my logic?

simple mist
simple mist
dapper sapphire
#

can we do string concatenation by using list comprehension for following:

        for key in (dictionary):
            output_string = output_string + dictionary[key]
#

List comprehension is not faster than a for loop? It just makes it more readable in some cases?

fiery cosmos
#

''.join(dictionary.keys()) would be fastest I expect, and shorter

#

But yeah, in general, loop vs comprehension speed is similar if they do the same work

dapper sapphire
#

Yeah, I figured I could use an array and then do "".join(array)

drifting drum
#
You're given two arrays of numbers, say array A and array B with the numbers being in the range -10^6 to 10^6
Furthermore, the length of the two arrays is <= 1000. They both have equal lengths, too.

Now you're supposed to pick some indices between 0 and len(A), as many as you like. (Need not pick consecutive indices).
Suppose you pick k of them, a1, a2, ...ak.

Now you find Value V = (A[a1] + A[a2] .... + A[ak])^2 + (B[a1] + B[a2] + .... B[ak])^2.
You're supposed to find the maximum possible value V.

So my thoughts are you could probably do a greedy
where if A[i] and B[i] are both positive, you certainly must pick them
if they're both negative, don't pick them, it's not going to increase our value
In the event of one of them being positive and one of them being negative, get the value before and after adding those numbers and see which's better
So that's the greedy approach that comes to my mind
Is there perhaps a better way of doing this?

topaz pulsar
drifting drum
#

Think of it this way

#

you've picked some indices, the sum(without being squared) of array A is S1, and sum(without being squared) of array B is S2

#

now suppose you pick index x and A[x] is negative, B[x] is also negative

#

so your previous value V was = S1^2 + S2^2

#

Now, A[x] is negative, so S1 +A[x] < S1.
Also B[x] is negative, so S2 + B[x] < S2.

And so (S1 + A[x])^2 < S1^2 and (S2 + B[x])^2 < S2^2

So (S1 + A[x])^2 + (S2 + B[x])^2 < S1^2 + S2^2

#

And actually

#

if |A[x]| is larger than S1 itself

#

you might as well not pick the elements you have picked in S1

#

But yeah

#

it boils down to

#

either pick all positives

#

either pick all negatives

#

or you pick a combination of both which is the tricky part

drifting drum
topaz pulsar
drifting drum
#

yeah you don't disregard them entirely, but you do disregard them when only picking positives

#

Perhaps I've just expressed everything in a very messy way

topaz pulsar
#

yeah, don't worry I get what you mean, I may of just misunderstton your original comment

drifting drum
#

nah going back and reading what I wrote, I can see what I said was not implying in any way about the separate cycles of picking only numbers of one sign, so that's on me šŸ˜…

last fulcrum
#

Should I implement a queue in Python using collections.deque or a circular array?

austere sparrow
#

Should I implement a queue in Python
probably not šŸ˜„

#

well, unless you want to learn how to implement a queue

#

The advantage of deque is that it can grow and shrink as much as you want, and you won't need to resize the storage

last fulcrum
#

Nice. I was of the opinion you'll be asked to implement a queue or stack yourself.

austere sparrow
#

You can look into CPython's source code if you want to see how deque is implemented.

#

It's something like a linked list of small (64) arrays.

last fulcrum
#

I saw a linked list implementation of a queue and stack on the web. People are really doing everything themselvesšŸ˜… .

wary spear
#

Hi I am currently trying to convert a list of objects to a dictionary

I have got an object with two properties object.key and object.value and I want to map that list to a dict like

from
list = [object[0], object[1], etc]
to
dict = {object[0].key : object[0].value, object[1].key : object[1].value, etc}

Hope this is understandable if not please try to explain what was unclear. Would be great if someone could help me

tame edge
#

This the weakness of me .

This channel

loud trail
#
data_lst = [thing1, thing2, thing3]
data_dct = {thing.key: thing.value for thing in data_lst}
wary spear
#

dicti = dict((x.key, x.value) for x inlist)

#

already found something (:

loud trail
#

i'd recommend the dict comprehension instead, but that does work too

wary spear
#

What is the difference?

loud trail
#

clearer intent, imo

#

technically should be a bit faster but that's not really relevant

lean musk
#

Game Crash is problem ?

hidden rapids
#

Where do I get started to learn data structures and algorithms?

#

I tried leetcode but had real trouble in the very first problem and had to refer to the solution

#

Any help is much appreciated

runic tinsel
#

you have a problem, you see the solution you won't have this problem later

hidden rapids
#

Yes but it doesn't feel as efficient

#

Because I spend like 3-4 hours on a problem just stuck

runic tinsel
#

i think that's pretty much optimal

hidden rapids
#

I see

#

That makes sense then

#

If that's how you learn I'm down for that

runic tinsel
#

i guess it would be optimal if you know you're trying to do something within your capabilities, if you don;t understand the solution, that's wasted time

#

some sort of intuition whether something is way too hard to attempt is necessary

hidden rapids
#

@runic tinsel yeah that's what I felt. If it's something I can comprehend and work towards little by little, even if it's 50 percent of the solution, then I'm satisfied

dapper sapphire
#

I'm working on a project that utilizes async routines where index and length is used to create the progress bar. And I see the progress bar constantly fluctuate.

This reminded me of loading screens in games where the loading percentage would fluctuate.
For example: loader would be at 42% and then it would dip down to 20% and then it would jump to 74% and so on. So the async routines could be the reason why the progress percentage would fluctuate?

coral horizon
#

what does this thing I'm looking at mean?

#

can someone tell me about going on about understanding it

#

I know the log in that.

dapper sapphire
#

If we have foo, bar, and foobar. How many combinations are there in pairs (of 2 and 3), are there 4 combinations?

1. foo & bar
2. foo & foobar
3. bar & foobar
4. foo & bar & foobar
fiery cosmos
#

yep, if order doesn't matter

vocal gorge
#

C(3,2)+C(3,3) = 3+1 = 4, yes

dapper sapphire
vocal gorge
#

C(n,k) being the binomial coefficient (number of ways to take k objects from n). You are interested in 2- and 3-element combinations of 3 elements, so C(3,2) + C(3,3).

#

C(n,k) = n!/(k!*(n-k)!) in general

fiery cosmos
#

Often called "n choose k" sometimes like nCk yes

dapper sapphire
#

Interesting how so many things can boil down to a math equation.

fiery cosmos
#

https://leetcode.com/problems/valid-triangle-number/ the only thing I know for now in this question is that we should sort and apply two pointers but I dont understand how to get all combinations using it, anyone ?

dapper sapphire
#

Why are some python methods inconsistent.

#

We can do llist.reverse(), but we cant do string.reverse(), we have to do "".join(reversed(string))

#

I guess other programming languages are like this too.

#

Actually never mind I see what's happening

dapper sapphire
#

How can we create a copy of a list? We cant just simply do the following lol:

list1 = list2
#

because changing one changes the other.

#

I have also tried:

list1 = list2.copy()

Which works, but if it's done inside a method then modifying list1 will also modify list2.

fiery cosmos
#

How do you mean pithink

#

there's also slicing which looks confusing list1 = list2[:]

#

and copy module .deepcopy if you need to recursively copy the items

dapper sapphire
#

Run the following:

llist = [[1,1,0],[1,0,1],[0,0,0]]
llist2 = llist.copy()

llist.pop()
# llist2.pop()

print(llist)
print(llist2)

And you get

[[1, 1, 0], [1, 0, 1]]
[[1, 1, 0], [1, 0, 1], [0, 0, 0]]
#

Now if you do:

from typing import List

class Solution:
    def __flip(self, number: int) -> int:
        if number == 0:
            return 1
        return 0

    def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
        llist = A.copy()
        for inner_list in llist:
            inner_list.reverse()
            for index in range(len(inner_list)):
                inner_list[index] = self.__flip(inner_list[index])
        return llist

image = [[1,1,0],[1,0,1],[0,0,0]]
image2 = Solution().flipAndInvertImage(image)
print(image2)
print(image)

You get:

[[1, 0, 0], [0, 1, 0], [1, 1, 1]]
[[1, 0, 0], [0, 1, 0], [1, 1, 1]]
lean dome
#

you're looking for copy.deepcopy(). list.copy() makes a shallow copy, meaning it doesn't copy things inside the list

dapper sapphire
#

I dont get intellisnse for copy.deepcopy()

lean dome
#

have you done import copy ?

dapper sapphire
#

Oh I cant use it then.

lean dome
#

!e ```py
import copy
llist = [[1,1,0],[1,0,1],[0,0,0]]
llist2 = llist.copy()
llist3 = copy.deepcopy(llist)

print(f"{llist=}")
print(f"{llist2=}")
print(f"{llist3=}")

print(f"{llist[0] is llist2[0]=}")
print(f"{llist[0] is llist3[0]=}")

halcyon plankBOT
#

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

001 | llist=[[1, 1, 0], [1, 0, 1], [0, 0, 0]]
002 | llist2=[[1, 1, 0], [1, 0, 1], [0, 0, 0]]
003 | llist3=[[1, 1, 0], [1, 0, 1], [0, 0, 0]]
004 | llist[0] is llist2[0]=True
005 | llist[0] is llist3[0]=False
lean dome
#

both llist2 and llist3 seem like they're identical to llist, but the elements of llist2 are the same lists as are inside llist, while the elements of llist3 are copies of the lists inside llist

dapper sapphire
#

Actually that does work

#

So then for https://leetcode.com/problems/flipping-an-image/

from typing import List

class Solution:
    def __flip(self, number: int) -> int:
        if number == 0:
            return 1
        return 0

    def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
        for inner_list in A:
            inner_list.reverse()
            for index in range(len(inner_list)):
                inner_list[index] = self.__flip(inner_list[index])
        return A

image = [[1,1,0],[1,0,1],[0,0,0]]
image2 = Solution().flipAndInvertImage(image)
print(image2)
print(image)

Would this be reasonable? I just dont like modifying in-place unless the question asks for it.

#

lmao llist = A.copy() doesnt do anything because I'm modifying the same list.

#

Should I manually create a copy of the list first?

last fulcrum
#

???????. They clearly said use a deep copy

#

Any copy you create would be shallow. They are referring to the same address in memory.

dapper sapphire
last fulcrum
fiery cosmos
#

You may be over-complicating that problem a bit šŸ˜… you can do it in one line with a nested list comprehension

#

How do you do a code spoiler pithink

#

||return [[1 - x for x in row[::-1]] for row in image]||

dapper sapphire
last fulcrum
dapper sapphire
#

What would be external library? Something that you have to pip install?

last fulcrum
#

Yes. from typing import List is an example of a an inbuilt one.

dapper sapphire
last fulcrum
last fulcrum
fiery cosmos
#

I just wrote it OhIPanda

last fulcrum
#

I was asking about the original you refactored.

dapper sapphire
last fulcrum
fiery cosmos
last fulcrum
#

Is it right to use one line like that in an interview?

#

I don't think so

dapper sapphire
#

If one liner is too complicated, then no.

last fulcrum
#

I'll list my reasons why I think it should not be so. But as always, this is a subjective issue.

dapper sapphire
#

I personally dont like list comprehensions.

last fulcrum
#
  1. It shows you know how to code, but then you're using what we call hacks and tricks. Most of these things do not work in other languages, and companies are generally looking for solutions that work in other languages, since it's highly likely you might work with other languages.

  2. You would solve the problem early, thereby allowing the interviewer to give you even harder problems.

fiery cosmos
#

I really don't think showing you know a language or doing questions fast are bad in an interview šŸ˜…

#

You can always explain and show that there are other ways to write equivalent code 02shrug

last fulcrum
# fiery cosmos I really don't think showing you know a language or doing questions fast are bad...

Not necessarily bad, you are just inviting more pressure and hard questions unto yourself. See it as your aim is to do anything to maximise your chances of getting job, not showing that you know how to do this really fast. It's the same thing as the interviewer giving you a question you learnt just a few days before the interview. Of course you can breeze through, but would that really help your chances?

last fulcrum
fervent saddle
#

I’ve heard that suggestion too lol, that if you already know the answer then you should act like you’re coming up with it on the spot so you’ll look cooler

dapper sapphire
#

I have heard you should give the less optimized solution first, so when they ask you to optimize it, you can show them the optimized way. Is that also true??

#

A friend's friend had an interview at Google and he did the optimized way, then they asked him to optimize it and he couldn't because it was already optimized.

last fulcrum
#

šŸ˜‚

dapper sapphire
#

No honestly!! I was like wait what you can't be serious

last fulcrum
#

Except cheating and lying

last fulcrum
#

They want the best

dapper sapphire
dapper sapphire
fervent saddle
#

Maybe they meant optimizations not as in time/space complexity

#

But as in for the computer

#

idk

lean junco
lean junco
#

why my kadanes algo able to overcome its limitation ......lol

#

it shouldnt work but it does

#

??

lean junco
#

i figured it myself

#

dont bother now

last fulcrum
#

Anyone here with a leetcode premium subscription? If this is wrong to ask here please remove.

vapid cedar
#

Hey I am badly inneed of suggestion in detecting pattern from historical data

#

can i have a chance to speak with anyone

#

is there any api or module for detecting pattern , i have looked up talib

#

except that , i just need to detect upwards and downwards and straight line pattern

#

šŸ™‚

granite cliff
#

hello guys I wanna learn and master data structure and algorithms, i have already queried youtube and I have found something but I wanna find something that is efficient since its a critical subject to learn.

granite cliff
frail fjord
#

Hello. I have a question that has been boggling me for the past few days. I'm trying to figure out how to remove background noise for a dictation project that I have been working on. What are some ways to integrate background noise reducing libraries into my project. Also, is it possible to use Nvidia's Broadcast for integration by any chance?

#

well this is an algo chat and my question relates to algorithm libraries for noise reduction

dark bear
#

I keep getting the index out of range error when using pointers to iterate a list or array instead of for loops. Any tips or hints how I can remember to not get this error?

fiery cosmos
junior wind
#

Can anyone help me get started with DSA

#

I am new to it so idk where to start from. if anyone can give some good recommendations about courses or youtube channels it will be awesome

ivory yacht
#

There's a few pinned here.

junior wind
#

btw is there any good youtube channel if you know, I don't wanna get to wrong one cuz there are infinite number of videos on that

wild river
#

i have a doubt with functions

#

can anyone help me?

leaden magnet
#

hello

wild river
#

hi

leaden magnet
#

i have a problem can you help me?

onyx root
leaden magnet
#
from sys import path

path.append('..\\modules')

import module

zeroes = [0 for i in range(5)]
ones = [1 for i in range(5)]
print(module.suml(zeroes))
print(module.prodl(ones))

#
Traceback (most recent call last):
  File "c:\destop\python\Pcap course\module 5\main.py", line 5, in <module>
    import module
ModuleNotFoundError: No module named 'module'
knotty magnet
#

there doesn't look to be a module with that name

leaden magnet
#

yes but if i put the absolute path works

#

my problem is i don't understand how works relative and absolute paths

#

i think i am missing something

keen hearth
# leaden magnet my problem is i don't understand how works relative and absolute paths

Hello šŸ™‚ I believe a relative path in sys.path would be relative to the current working directory, which is where you run the code from (not where the file is located). In this case, if your current working directory is "module 5", then I think ..\modules would refer not to the "modules" folder contained within "module 5", but a "modules" folder contained within "Pcap course". Long story short, you want to use the path .\modules instead.

#

I'm not 100% sure that's the issue though. Try it out and let me know šŸ˜„

leaden magnet
snow bridge
#

instead of 'import module' try 'import modules'

keen hearth
#

You would need to change to the directory containing the file. Or, make the path relative to the file.

leaden magnet
#

oh

keen hearth
#

I think this should work: ```py
from pathlib import Path
p = Path(file)
sys.path.append(p.parent / 'modules')

leaden magnet
#

now it works i open the entire folder and what you say fisrt time worked

#

thank you

keen hearth
#

Oh right.

keen hearth
leaden magnet
keen hearth
#

It might save you the hassle of having to navigate to the folder each time.

#

(Assuming it works šŸ˜…)

leaden magnet
keen hearth
# leaden magnet umm

Ah, I made a mistake: ```py
from pathlib import Path
p = Path(file)
sys.path.append(str(p.parent / 'modules'))

#

Items in sys.path currently have to be strings.

#

There's a pull-request pending in python to allow Path objects in sys.path.

leaden magnet
#

yes is works

#

thank you so much

#

i am trying to figure this thing out from a week

#

XD

keen hearth
leaden magnet
#

yes but perseverence is the key

#

now i know a little more then yesterday and tomorrow i hope i will know little more than today

#

thank you again

lyric burrow
#

i was solving this problem on leetcode
i wonder how they made it faster

fiery cosmos
#

Some trick with reduce might be possible rooHmm But your solution looks fine 02shrug

#

LeetCode times vary. You hit submit once and you are faster than 99% and click it again and it changes to 20% rooDerpy

knotty magnet
#

itertools.accumulate

dim snow
#

do you have a book you recomend to learn algorithms?

keen hearth
analog ferry
#

Anyone aware of a fun to use geometric constraint resolver for python

I want to plan woodworking details and freecad/cad query seem horrendous

lyric burrow
#

how can i optimize this?

fiery cosmos
#

hint: sort it

knotty magnet
#

ya gotta put spoilers on that yo

runic tinsel
#

sorting doesn't help much

knotty magnet
#

why not?

#

brings it down from n^2 to n log n

runic tinsel
#

you need the answer in the original order

#

[3,4,2,3]
[2,3,3,4]
like, i sorted them and i saved the original list

idle marsh
runic tinsel
#

now i need that [0,1,1,3] in the order of [1,3,0,1]

#

i got "faster than 90.39%"

#

"faster than 99.16%"

#

sorting is the first step after all

#

99.83 lol

knotty magnet
#

are you just running the same code over and over until you get a lucky run

runic tinsel
#

yes

#

it varies a lot

#

i thought i cheesed it with returning a genexp, but it was just a lucky run

knotty magnet
#

what if you do gc.disable()

#

that would probably give you a better chance of getting a good run

runic tinsel
#

i don;t really have stuff that would be colledcted

fiery cosmos
#

That way with the Counter is neat. Should be easier (or at least the same) to sort that compared to the original array

#

my trick was to hang onto the indices by sorting a list of tuples (value, index) ```py
class Solution(object):
def smallerNumbersThanCurrent(self, nums):
ordered = sorted((n, i) for i, n in enumerate(nums))

    smaller_counts = [None] * len(nums)
    last_n, last_i = ordered[0]
    smaller_counts[last_i] = 0
    for index, (n, i) in enumerate(ordered):
        if n == last_n:
            smaller_counts[i] = smaller_counts[last_i]
        else:
            smaller_counts[i] = index
        last_n, last_i = n, i
        
    return smaller_counts```
#

But it feels bulky Thonk

knotty magnet
#

should probably spoiler that

#

eh, he already has a sol nvm

fiery cosmos
#

how do you spoiler code blocks? rooDerpy

knotty magnet
#

||```py
e

fiery cosmos
#

I was trying the other day and /spoiler nor || seemed to work rooHmm

knotty magnet
#

take a screenshot like frowny did i guess, lol

fiery cosmos
#

well meh

knotty magnet
dapper sapphire
#

How important would it be to know list comprehension??

#

I dont think someone would fail you just because you didnt use list comprehension or dont know it.

#

But wondering what other people think.

knotty magnet
#

it's useful, but it's just a slightly more expressive way of saying the same thing you can already say

#

if someone asks you specifically about it, i guess you would need to

dapper sapphire
#

Wondering what people think of this if it's clean and expressive enough leetcode 1816:
https://leetcode.com/problems/truncate-sentence/

class Solution:
    def truncateSentence(self, s: str, k: int) -> str:
        string_list = s.split()
        truncated_string_list = string_list[:k]
        truncated_string = " ".join(truncated_string_list)
        return truncated_string
runic tinsel
#

this can't be done with a list comprehension though

dapper sapphire
#

No this question is apart from list comprehension

#

I wanted to know what people though it if its clear enough.

knotty magnet
dapper sapphire
#

Oh my bad sorry lol. Yeah I think so too, it's sort of like .join

fiery cosmos
#

Splitting it over 4 lines seems excessive. One or two like return ' '.join(s.split()[:k]) feel less daunting to read imo 02shrug

#

or use applicable names like words instead of string_list

dapper sapphire
dapper sapphire
#

Actually can we compare list comprehension with join. Where list comprehension is done for a list, but join is done for a string.

knotty magnet
#

depends what comparison you're trying to make i guess

lyric burrow
severe osprey
#

Help me understand the concept of the solution

lyric bramble
#
    out =0
    iter_= 0
    start,end,y_match = False,False,False
    i = 0
    while i <len(s):
        if (s[i] == "x") and (end is False):
            start = True
        if (s[i] == "y") and (start == True):
            y_match = True
        if (s[i] == "x") and (start==True) and (y_match==True):

            out +=1+iter_
            iter_ +=1
            y_match = False
        i+=1
    return out```
#

is this right?

#

can someone help me with this?

jovial sphinx
#

Problem:
Given a coordinate on a 199x199 Cartesian plane which marks the starting position of a cube, find the shortest route to the centre (0, 0) which would result in the cube having the same side facing up as it did at its starting position.
Anyone has any idea how to approach & solve this (kind of) problem (which relates to Mahattan distance)??

keen hearth
#

A brute-force approach would be to do a search (e.g. breadth-first search) on the state-space of the problem. That is, a state comprises a coordinate (the location of the cube), and a number representing the orientation of the cube (the side initially facing up could point in six possible directions).

#

An A* search would probably work reasonably well here, using the manhattan distance as a heuristic (as it always gives an optimistic estimate of the remaining distance).

#

Constraint relaxation (removing constraints from the problem) is often a good approach to coming up with search heuristics.

jovial sphinx
#

šŸ¤”

#

In the actual task, brute force for any coordinates giving a Manhattan distance of 5 or larger is not allowed. Back-propagation is also not allowed.

#

I'm pretty sure search algorithms such as A* involve back-propagation(correct me if I'm wrong), so what would be a more "mathematical" approach to this problem?

jovial sphinx
#

Also, if anyone is kind and willing enough to code me a solution to this problem via any method I would really really appreciate that >w<

small flax
#

Should everyone know FizzBuzz?
I personally think the pythonic 1 liner at the end is too cheeky.

https://youtu.be/02RjoAnW2kg

In this video, I attempt the infamous FizzBuzz coding Interview problem.
I break any particular programming interview problem in the following 4 parts:

  1. Describe Problem
  2. Ask Questions and clarify the problem with examples
  3. Thinking Out Loud \ Draw\brainstorm the solution
  4. Code the solution

---------------------------------------------...

ā–¶ Play video
knotty magnet
#

you don't have to memorize it, but if you can't create a solution given the description of the problem..

small flax
keen hearth
#

Such tests started to become used in interviews as companies found they were receiving many applications for programming roles from people who had zero prior knowledge or experience in programming.

keen hearth
unborn sundial
#

!e

from dataclasses import dataclass
from datetime import datetime
import json


def hide_field(field) -> str:
    return "**redacted**"


def format_time(field_timestamp: datetime) -> str:
    return field_timestamp.strftime("%Y-%m-%d %H:%M")


def show_original(event_field):
    return event_field


class EventSerializer:
    def __init__(self, serialization_fields: dict) -> None:
        self.serialization_fields = serialization_fields

    def serialize(self, event) -> dict:
        return {
            field: transformation(getattr(event, field))
            for field, transformation in self.serialization_fields.items()
        }


class Serialization:
    def __init__(self, **transformations):
        self.serializer = EventSerializer(transformations)

    def __call__(self, event_class):
        def serialize_method(event_instance):
            return self.serializer.serialize(event_instance)

        event_class.serialize = serialize_method
        return event_class


@Serialization(
    username=str.lower,
    password=hide_field,
    ip=show_original,
    timestamp=format_time,
)
@dataclass
class LoginEvent:
    username: str
    password: str
    ip: str
    timestamp: datetime


a = LoginEvent('a','b','c',datetime.now())
print(a.serialize())
halcyon plankBOT
#

@unborn sundial :white_check_mark: Your eval job has completed with return code 0.

{'username': 'a', 'password': '**redacted**', 'ip': 'c', 'timestamp': '2021-06-27 16:29'}
unborn sundial
#

huh. classes can be decorated too.

fiery cosmos
#

can someone explain why sets are faster than lists when checking for a key

#

i know its about the o notation

#

but why cant lists be searched in the same way as sets

keen hearth
#

So, in theory, finding an element in a hash-table doesn't depend on the number of elements in the hash table.

fiery cosmos
#

im intermediate in py but havent touched algos

#

are algorithms essential

#

since nothing ive done yet required them

#

everything is built in

keen hearth
#

I'd say basic knowledge of algorithms is fairly essential. You might want to check out some of the pinned resources.

fiery cosmos
#

ive thought bubble sort

#

was requested in this year's final exams

#

but bubble sort is pretty dum

keen hearth
#

Oh right. Sorting algorithms are often used as a way to introduce the concepts behind the analysis of algorithms.

fiery cosmos
#

im hoping to get into a programming uni

#

there will be algorithms

#

i guess

mental parcel
#

No cap you could learn it all online quicker and cheaper

fiery cosmos
#

yea ik i just need a degree

mental parcel
#

Fair

fiery cosmos
#

to prove ik something

#

im only 16 and ive coded for 4 years but who believes me

#

atleast a github portfolio may help

#

not sure

mental parcel
#

Yea, I cant say much. I'm at uni

fiery cosmos
mental parcel
#

I think a public portfolio is good

#

Ah well, im off anyway

analog ferry
#

anyone aware of a recent usable geometric solver for python that allows to declare materials and their properties/relation

mint jewel
analog ferry
mint jewel
#

Rhinoceros can also do something along those lines, but it may also be not powerful enough, and also is not free.

#

but that is all I know of in this category

dapper sapphire
#

Where's the max function in python github repo?

#

When I do Go to definition it takes me to builtins.pyi

#

And what's the time complexity of max function in python?

#

And the time complexity O(n log(n)) is product of n and log(n) => n * log(n)?
But we just say O n log n or O of n log of n?

halcyon plankBOT
#

Python/bltinmodule.c line 1844

builtin_max(PyObject *self, PyObject *args, PyObject *kwds)```
vocal gorge
#

it's almost certainly implemented the normal way:

def max(iterable):
    cur = None
    for el in iterable:
        if cur is None or el > cur:
            cur = el
    return cur
#

the actual code involves using the key and also a lot of checks

dapper sapphire
#

Yeah I think implementing a max is simple. I wanted to see if the time complexity would be less than O(n). But I dont think less than O(n) would be possible since we would have to look at each element.

Implementing a sort is a real challenge, as long as it's not naiive sort(with nested for loop). Is it called bubble sort?

analog ferry
#

@dapper sapphire what is the context of what yu are doing, im udner the impression you litter lower level details without explaining the intent, which leads to a xy problem

dapper sapphire
analog ferry
#

do you have some more detaills, common solutions are partial sort/selection sort

#

for example find the largest element + its index, and then find the largest element of the concat of the lements before it and after it using islice

dapper sapphire
#

Initially I thought I'll use max, but that would just give us the largest number.

And then I thought of using sort to get the second largest number. So from there I figured I could skip max and just use sort to sort the list and get largest and second largest number by doing [-1] and [-2] slicing. Other things I mentioned went on a tangent.

mint jewel
#

look into the heapq module

#

though I am not sure how efficient it is for just 2 numbers

#

the most efficient way is probably just writing out the sizable for loop yourself, but there is quite a bit of logic there. For simplicity, sorting and indexing is best

fervent saddle
#

!e ```py
test = "xxyyx"
x_list = test.replace("y", " ").split()
x_count = sum(map(len, x_list))
substrings = 0

for x_section in x_list:
x_count -= len(x_section)
substrings += x_count * len(x_section)

print(substrings)```

halcyon plankBOT
#

@fervent saddle :white_check_mark: Your eval job has completed with return code 0.

2
fervent saddle
#

This is my idea, but it might be wrong and there might be a nicer way to do it

#

But if it’s right then it should at least pass the time test because it’s O(n)

analog ferry
#

@fervent saddle is the input always well-formed? - if yes just find the count of xy sequences in the string

fervent saddle
#

The description says the string always has only x and y characters

analog ferry
#

is it allowed to use regex?

fervent saddle
#

I’m not really sure, I couldn’t find the webpage for it

analog ferry
#

(as far as i understood you are looking for all occurences of "xy+x"

fervent saddle
#

All occurrences of x + something + x where something has at least one y

analog ferry
#

the regular expression for that is xy+x

fervent saddle
#

Ok yeah, I see what you’re saying now

#

regex is built-in so I guess you could use it unless it specifically says not to

analog ferry
#

as far sa i understood, the task given requires the regex xy+(?=x) (the lookahead assertion ensures the x wont be consumed so it

so i believe a re.findall("xy+(?=x)", "xxyyx") could do (untested yet

dapper sapphire
#

oh ok.

meager jetty
#

... max heap ...

dapper sapphire
#

So if we do:

for key in sorted(dictionary):
  ...
  ...

Does usage of sorted in the loop mean dictionary would get sorted each time the loop runs? Or does the python interpreter optimizes this routine, sorts it once and does it sort it again?

mint jewel
#

The thing on the right of in will only ever run exactly once

dapper sapphire
#

Oh wow ok I didnt know that. Thanks a lot!!

knotty magnet
#

!e

for x in [print("hi"), 2, 3, 5]:
  print(x)
halcyon plankBOT
#

@knotty magnet :white_check_mark: Your eval job has completed with return code 0.

001 | hi
002 | None
003 | 2
004 | 3
005 | 5
dapper sapphire
late fable
#

How do I start learning data structures

covert swallow
#

I'm not sure if this is the right channel to ask about classes in python but I think it covers data structs. What's the right way to add value to a class? On init or post_init?

e.g. I have a Person class on on init, its asking for name and email address. If neither is provided, it leaves those fields as empty. If we want to add a value to it, it would be to add it in the params of the class like so: Person("Bob", "bob@email.com")

Another approach is to add the the values in a method in the Person class like so:

p = Person()
p.create("Bob", "bob@email.com")

Which is a better approach? Or at least considered as best practice?

meager slate
#

your p.create is exactly the job of the __init__, so move that code to to __init__

covert swallow
meager slate
covert swallow
#

So init name, then .addEmail("bob@email.com") after

meager slate
#

you can add all the validation in the init itself

covert swallow
#

Yeah I'm using dataclasses so:

from dataclasses import dataclass

class Person:
  name: str
  email: str

Person("Bob", "bob@email.com")

However, my problem is validating the data on init

meager slate
#

then don't use dataclasses, just use a normal init

covert swallow
#

Isn't it the same? How do you validate on normal init?

#

So far, I've found that I can validate post_init

#

It looks dirty but it works

meager slate
meager slate
covert swallow
#

And that caused me to doubt myself if it was better to just create a separate method specifically for each data validation (for phone numbers, addresses, email addresses, etc)

meager slate
#

you can make validatiors and then validate from init

#

for example

#
class Person:
    def _validate_name(self):
      if self.name == 'bob':
          raise ValueError('Sorry Bob.')
    
    def __init__(self, name):
       self.name = name
       self._validate_name()
bob = Person('bob')
covert swallow
#

Correct me if I'm wrong, prefix _ to a function name would make it private right?

meager slate
meager slate
#

no one's gonna stop me from accessing that method from outside

covert swallow
#

True but it won't be able to be called in a separate file easily right? Something like app._validate_name()? I've yet to try this

meager slate
#

!e ```py
class F:
def _am_i_private(self):
print('No')

f = F()
f._am_i_private()

halcyon plankBOT
#

@meager slate :white_check_mark: Your eval job has completed with return code 0.

No
meager slate
#

we all just agree that we wont mess with things starting with underscores

covert swallow
#

Good to know!

#

OK I think I got it properly designed... I hope. Thanks @meager slate

meager slate
#

šŸ‘

foggy depot
#

what would be the best method to find the indexes of the first x occurrence of an element in a list
example
list = [1,2 ,1,1,4,5,6,1,2,1]
here i want to find the indexes of the of the first three "1"
what would be the best way of doing this

fiery cosmos
#

Loop through from the start normally and save the 1 indexes, but stop when you get x of them

supple coyote
#

Hello My dear fello geeks Im new to the Discord Sorry If Im Wrong, I face one problem while practising backtracking algorithm in python I cant find what the problem is please help to find... https://stackoverflow.com/q/68162305/15982124 This is Link Please help to solve this Thank You

dapper sapphire
haughty wave
#

i'm creating an application but i don't understand why this code doesn't work, a button should come out with hello kivy world

#

KV = """
Screen:

MDRectangleFlatButton:
   text: "Hello kivy world!"
   pos_hint: {"center_x": 0.5 "center_y": 0.5}

"""

lyric burrow
#

what things do i need to keep in mind while preparing for programming interviews in python opposed to c++

silk breach
#

Could anyone help me with coding the a* pathfinding algorithm

#

I'm pretty sure I understand how the algorithm works, I just can't figure out how to code it

keen hearth
#

Have you already tried implementing breadth-first and depth-first search, and seen how you can switch from one to the other just by changing out the data structure used for the frontier? (a stack for dfs, and a queue for bfs)

#

A* search is similar, except that you use a priority queue for the frontier. The priority of an node in the queue should be the sum of the path cost to reach that node and a heuristic estimate of the remaining cost to reach a goal.

fiery cosmos
#

I'd say A* is more similar to best first. while in bfs and dfs there are no heuristics, best first seems more nearer. and as LX said, if you have coded bfs then A* will be easier. and about prio queue. since you're using python, prio queue are built in so they come in handy.

terse pewter
#

why this result returns 3 instead of 4 (main() returns 3 and +1 should equal 4?

def abc():
    return dfe()

def dfe():
    return main()+1

def main(x=2):
    c=3
    return c

print(main(abc()))

OUTPUT : 4

jolly mortar
#

you're printing main(abc()), main always returns 3

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.

terse pewter
#

I want to access main()'s c value in dfe(), how can i achieve this?

    return dfe()

def dfe():
    return c+1

def main(x=2):
    c=3
    return c , x

print(main(abc()))```
jolly mortar
#

you can't access a function's local variable from outside the function

terse pewter
dapper sapphire
#

Is this pretty much how we get minimum value in python?:

#

!e

import sys
minimum_value = -sys.maxsize
print(minimum_value)
halcyon plankBOT
#

@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.

-9223372036854775807
vocal gorge
dapper sapphire
#

sort of like int_max, int_min

vocal gorge
#

Python ints are infinite-sized, they can represent any value you have the memory for, and have no min/max value or infinities. Float infinity can be obtained with float("inf").

dapper sapphire
#

I just needed a small enough number to perform comparison with some data. Data given could have -1 upto -1000, so -sys.maxsizeseems reasonable.

vocal gorge
#

You could use negative float infinity, -float("inf").

#

it compares lower than any int or float.

jolly mortar
#

except itself

dapper sapphire
#

!e

min_inf = -float("inf")
print(float("inf"))
print(-float("inf"))

print(min_inf == (-float("inf")))
halcyon plankBOT
#

@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.

001 | inf
002 | -inf
003 | True
dapper sapphire
half lotus
lyric burrow
#

how do i check if num1 and num2 don't point to the same location in memory?

knotty magnet
#

is keyword

lyric burrow
#

i did say is not , is it not correct?

knotty magnet
#

probably

lyric burrow
#

i also tried ! is but that didn't work either

fervent saddle
#

Are you sure you want to do that?

#

What does it want you to do?

lyric burrow
lyric burrow
fervent saddle
#

Oh yeah, I see what you’re trying

lyric burrow
#

oh wait

fervent saddle
#

What’s happening is python uses the same int objects for values from -5 to 256, and also for literals in the code with the same values

lyric burrow
#

i can check it with nums.index(num1) != nums.index(num2)

#

but

#

nah, i don't see how that will work

#

when num1 = num2

fervent saddle
#

enumerate might help

fervent saddle
#

If both numbers are the same values then they’ll be the same objects

lyric burrow
#

oh

#

i'll try enumerate

fervent saddle
#

I should say CPython does this

#

It might be different with other implementations

#

But yeah, this seems like a good place to use enumerate

lyric burrow
fervent saddle
#

Yeah, CPython is regular python

lyric burrow
#

i mean, i've seen how data structures like list and dictionary are implemented in C

#

and used by python

#

is that what CPython is?

fervent saddle
#

CPython is written in C, yeah

glossy zephyr
#

Hi guys, I want compare a date in the past and verify it if has 24 hours later or 1 day +.
how is the best approach to do it?

lyric burrow
fervent saddle
#

So you know what index you’re on

lyric burrow
#

i can't really figure out how do i do that with enumerate(iterable, start)

fervent saddle
#

The first value in each tuple will be the current index

vocal gorge
#

the common usage pattern is for i, el in enumerate(lst): or something like that.

spiral fractal
#

Anyone know a simple graph dfs algo

spiral fractal
#

plz dm me

calm spade
#

How do i convert a string list ("[data]" / '[data]') to a normal list ([data])

spiral fractal
#

is this right? def switchLst(data1, data2): res = [] for data_1, data_2 in zip(data1, data2): res.append(int(data_1)/int(data_2)) return res

keen hearth
karmic axle
#

hi

#

my name is Vansh Khera

#

and i like to code :D

#

i want to pc professional for my project

#

but its paid :C

keen hearth
karmic axle
#

i live in india

#

i have a school email

#

but it shows that its not valid :(

#

me

#

just jking

fiery cosmos
#

can some one help me? With .py to .exe

dapper sapphire
#

So to perform comparison on data type can we use either == or is operator?

#

!e

value = "This is a test"

print(type(value) is str)
print(type(value) == str)

print(type(value) is "str")
print(type(value) == "str")
halcyon plankBOT
#

@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.

001 | <string>:6: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | True
003 | True
004 | False
005 | False
deft scaffold
#

hello guys
i have this return:

{'AggregateEvaluationResults': [{'EvaluationResultIdentifier': {'EvaluationResultQualifier': {'ConfigRuleName': 'OrgConfigRule-REQUIRED_TAGS-ruleID', 'ResourceType': 'AWS::CloudFormation::Stack', 'ResourceId': 'arn:aws:cloudformation:sa-east-1:123456789101:stack/stackname/9stack-id'}, 'OrderingTimestamp': datetime.datetime(2021, 6, 3, 17, 10, 15, 66000, tzinfo=tzlocal())}, 'ComplianceType': 'NON_COMPLIANT', 'ResultRecordedTime': datetime.datetime(2021, 6, 10, 17, 42, 48, 860000, tzinfo=tzlocal()), 'ConfigRuleInvokedTime': datetime.datetime(2021, 6, 10, 17, 42, 48, 624000, tzinfo=tzlocal()), 'AccountId': '12345678', 'AwsRegion': 'sa-east-1'},

How can I access the ResourceId?
I've try for some tutos to access** nested dict** but without much successs
Here's the code that i've tried

for key in response:
     for items in response[key]:
         for item in items['EvaluationResultIdentifier']['EvaluationResultQualifier']['ResourceId']:
             print(item, '\n')
 # print(response["AggregateEvalutionResults"]["EvaluationResultIdentifier"]["ResourceID"])
response Example:
vocal gorge
fiery cosmos
#

How can i calculate this?

#

Jeffrey J. McConnell, Analysis of Algorithms: an Active Learning
Approach , 2001 PAGE 52

dapper sapphire
#

!e

value_string = "This is a string"
value_list = ["This is a list"]

print("Below should be True")
print(isinstance(value_string, str))
print(isinstance(value_list, list))

print("\nBelow should be False")
print(isinstance(value_string, list))
print(isinstance(value_list, str))
halcyon plankBOT
#

@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.

001 | Below should be True
002 | True
003 | True
004 | 
005 | Below should be False
006 | False
007 | False
dapper sapphire
#

We would use isinstance because that's more common then directly comparing data type with type(variable)?

vocal gorge
#

though for the specific case I mentioned, the nicest way would be to check if isinstance(thing, collections.abc.Sequence) (or MutableSequence, or whatever other "interface" you need)

deft scaffold
dapper sapphire
#

So in if isinstance(thing, collections.abc.Sequence) thing would be a variable that for example, could be a "string", [list], or {set} etc.

collections.abc.Sequence would be str, list, set

#

Oh you literally meant collections.abc.Sequence because that's an actual module! Sorry about that.

#

!e

import collections

value_string = "This is a string"
value_list = ["This is a list"]
print(isinstance(value_list, collections.abc.Sequence))
print(isinstance(value_string, collections.abc.Sequence))
#

But the above will return:

True
True

For both list and a string

half lotus
#

Why did you write "but"? How is it different from your expectations or requirements?

dapper sapphire
#

I misunderstood.

ConfusedReptile has a specific and different use case, so they have to use collections.abc.Sequence.

I am trying to identify if something is a list or a string, then in that case, it would be isinstance(variable, list) or isinstance(variable, str)

last fulcrum
#

I'm trying to implement a linked list. I get this error. Would like some help

#

AttributeError: 'NoneType' object has no attribute 'next'

#

This is the code

#

if current.next is None:

brisk saddle
#

current itself is None then. @last fulcrum

last fulcrum
#

There is a None in my list

#

When I was testing

#

But still this error

brisk saddle
#

your problem is probably coming from the fact that set current to the next node at the beginning.

#

at some point down the line, your code reaches the last Node.

#

from there, it then sets the variable to the last Node's next node, which will always be None.

#

then you perform the check, which is causing the error.

last fulcrum
#

This line though

#

while current: current = current.next

#

That means while current is valid, move to the next value of current

#

Once it becomes None, quit

#

Or?

brisk saddle
#

yes, but if current is set to the actual last Node, it will still run, set the next Node to None, then it errors.

last fulcrum
#

So you're saying I should timeout before the last node so that the actual next would be none?

brisk saddle
#

ehm, i said nothing about what you should do. i only pointed out the flaw in your code.

#

what is the purpose of this?

last fulcrum
#

To implement a linked list

#

I need to create one for interview questions

brisk saddle
#

should have been more specific, what is the purpose of the code you sent?

last fulcrum
#

To insert at the tail.

Here's the full thing

#
    def insert_at_tail(self, element: Union[str, int, None]):
        """
        Inserts an element at the back of the linked list, thereby making it become the tail.
        """
        current = self.head

        while current:
            current = current.next

        if current.next is None:
            self.tail = self.Node(element)
            current.next = self.tail
            self.size += 1
brisk saddle
#

so an append operation.

last fulcrum
#

I doubt it's called append, but yes

brisk saddle
#

it is.

#

i think you misunderstand one of the benefits of a Linked List. Linked Lists have O(1) insertions and deletions on the head and tail of the List.

last fulcrum
#

Thay have O(1) if you know the position also

brisk saddle
#

O(1) operations in this case are achieved by having fields stored in the Linked List object that store the head and tail. you are essentially performing an O(n) search for the last node, when you should have a reference to the head and the tail stored somewhere in the Linked List object.

last fulcrum
#

I wrote the code for that, but I can't even make this work so that's useless

brisk saddle
#

why would it be useless?

last fulcrum
#

Because at the moment I'm struggling to get the tail. That is why i used this

brisk saddle
#

well that is something we can work to fix here. do you have a head and tail field in your Linked List?

last fulcrum
#

Yes. I'll post

brisk saddle
#

so what is the purpose of creating this function when you could just use the tail field?

last fulcrum
#
class SinglyLinkedList:
    """
    Implements a Singly Linked List.
    """

    class Node:
        """
        Initializes the node class for storing an element and it's next value.
        """
        __slots__ = 'element', 'next'

        def __init__(self, element: Union[str, int, None] = None, next=None):
            self.element = element
            self.next = next

    def __init__(self):
        """
        Sets the head of the list and it's size
        """
        self.head = self.Node()
        self.tail = None
        self.size = 0

    def insert_at_head(self, element: Union[str, int, None]):
        """
        Inserts an element at the front of the linked list, thereby making it become the head.
        """
        if self.head is None:
            self.head = self.Node(element)

        self.head = self.Node(element, self.head)
        self.size += 1

    def insert_at_tail(self, element: Union[str, int, None]):
        """
        Inserts an element at the back of the linked list, thereby making it become the tail.
        """
        current = self.head

        while current:
            current = current.next

        if current.next is None:
            self.tail = self.Node(element)
            current.next = self.tail
            self.size += 1

    def print_linked_list(self):
        """
        Prints all the elements of the linked list.
        """
        if self.size == 0:
            return None

        current = self.head
        while current is not None:
            print(current.element)
            current = current.next
last fulcrum
#

I just wrote it in my book

#

Even then it's not right

brisk saddle
#

oh, well.. implement it. :p
are you having problems implementing the O(1) operations, or something, so you resorted to using the code you have now?

last fulcrum
#

Yes. I'm having problems always getting the tail. So I just decided to iterate through the list.

#

Far easier

#

And I got problems with that

#

So I came for help

brisk saddle
#

at the start, when the Linked List only has one Node, head and tail should essentially point to the same Node.

last fulcrum
brisk saddle
#

oh, then this is a problem with how you are pulling off insertion at the tail in general, not specifically when you already have Nodes in the Linked List.

brisk saddle
last fulcrum
#

So as you keep on adding to head the tail is still that last value

brisk saddle
#

yup!

last fulcrum
#

Ok. I'll implement it.

brisk saddle
#

second, insertion at the tail should follow these steps:

- make a new node
- if the Linked List is empty (LinkedList.head == None, or you have an internal ``length`` variable that is ``0``), then you
set the head, and tail to the new node
- if the Linked List is *not* empty (LinkedList.head != None, or an internal ``length`` variable is > 0), then you
set the ``next`` property of the *current* tail to the Node you *just made*, and set the new Node as the tail.
- set the value of the Linked List to whatever you want
#

or, put simpler:

  • if the Linked List is empty, set the head and tail to the new Node

  • if it is not empty, set the current tail's next node to the new node, and set the tail field to the new node.

last fulcrum
#

Thanks

brisk saddle
#

got it working?

last fulcrum
#

Yet to implement

#

I'll ping you

brisk saddle
#

alrighty

last fulcrum
brisk saddle
#

sick, everything working?

last fulcrum
brisk saddle
#

sup?

last fulcrum
#

This prints the elements and also prints None

#

It's not supposed to do that

#
    def print_linked_list(self):
        """
        Prints all the elements of the linked list.
        """
        if self.size == 0:
            return None

        current = self.head
        while current is not None:
            print(current.element)
            current = current.next
#

Maybe I should do while current

brisk saddle
#

no, that is the same thing more or less. just different way of writing it.

last fulcrum
#

Ah. Should I paste the full code?

brisk saddle
#

no i think we can go off this.

#

just trying to visualize it in my head.

#

could you show your output? @last fulcrum

last fulcrum
#

`
l = SinglyLinkedList()

l.insert_at_head(9)
l.insert_at_head(7)
l.insert_at_tail(2)

print(l.print_linked_list())
`

brisk saddle
#

ah alright.

#

oh, you know what, that is not because of your function.

#

it is because you are printing whatever print_linked_list returns. your function does not return anything, so print will print None.

last fulcrum
#

I think that is it

brisk saddle
#

send the code.

last fulcrum
#

I just need to call the function

#

Without print

brisk saddle
#

yeah

last fulcrum
#

Thank you @brisk saddle

brisk saddle
#

no problem!

cinder bloom
#

Any good courses or books for learning Data Structures and Algorithms in Python?

dapper sapphire
#

There are also some other resources in pinned area.

crystal prawn
remote carbon
#

Hi everyone, not sure I am in the correct room here but I am looking for some tutelage with hand tracing. I am just learning python while taking a cmpsc 101 class and having trouble with a hand trace assignment with if and elif constructs. I know how the program works out but just don't really understand how to put it into a table. is there a good site that anyone can point me to with some examples?

cinder bloom
cinder bloom
last fulcrum
cinder bloom
last fulcrum
# cinder bloom Alright, one more thing, I'm learning DSA for interviews so I can use this book ...

Yes you can. I'm also learning for interviews so you can DM me if you need help or want to solve together.

Here's the plan I made and use.

  1. Go through every chapter in the book. Be detailed, take notes, make sure to really understand the data-structure or algorithm.
    It's big O, runtime, etc.

  2. After every chapter in the book, solve questions on Leetcode and this site https://app.codesignal.com/interview-practice
    Solve only questions based on what you've learnt for the chapter.

  3. If you don't understand a question, try to solve it using hints. If you still don't understand it, then look at the solution.
    Understand it. Then come and solve the question again in a few days time.

  4. Use various other resources.(Ex: Cracking the coding interview.)
    Things are explained better by different people. YouTube is your best friend.

  5. After you have finished the book, solve these 75 questions.
    https://www.teamblind.com/post/New-Year-Gift---Curated-List-of-Top-75-LeetCode-Questions-to-Save-Your-Time-OaM1orEU
    Then buy Leetcode premium and solve the questions for the company you want to go to. I don't recommend doing any easy
    questions at this stage. Do all those while going through the book.

  6. Use flashcards to help you with your notes while solving the questions at stage 5. You'll be asked those questions at the interview.

  7. Good luck lol.

lyric burrow
#

what would be the difference in time and space complexity between

for i in range(len(array)-1):
    array[i]```
and 
```py
for ele in array:
    ele```
cinder bloom
# last fulcrum Yes you can. I'm also learning for interviews so you can DM me if you need help ...

Oh, I am using this site https://www.pepcoding.com/resources/ , It has almost 1200 questions, all of them curated and selected personally by top tutors and they have helped many people get placed into FAANG, The teachings and solutions are in Java but almost all of the questions are taken from Leetcode and a simple google search with the question title gets the leetcode link and I can get it's solution in Python, Thanks for the resources and the help!

fervent saddle
scarlet sleet
spice sundial
#

does anyone know about the Apriori algorithm

placid flicker
spice sundial
#

yes have a project based on Apriori algorithm

placid flicker
#

I'm not familiar with that repo. Is your input data tab-seperated as stated in the readme?

spice sundial
#

yes .tsv file

spice sundial
placid flicker
#

Yeah but that's written in Haskell though, not python

#

I can't help you any further without an error message. Maybe try asking the author

spice sundial
#

okay let me try hard enough

lunar jacinth
#
class Node:
        def __init__(self):
                self.data = None
                self.previous = None
                # self.next = None
                # introduce a 'next' node for doubly linked list
        def get(self):
                return self.data
        def getPrev(self):
                return self.previous
        def setPrev(self,previous):
                self.previous = previous
        def set(self,data):
                self.data = data
        node = property(get,set)
        prev = property(getPrev,setPrev)

# Convert Singly Linked List to Doubly Linked List
class SList:
        def __init__(self):
                self.tail = None
                # self.head = None
                # introduce 'head' node for double link
        # appends to tail of list
        def Append(self,data):
                pdata = Node()
                pdata.node = data
                if (self.tail == None):
                        self.tail = pdata         
                else:
                        pdata.prev = self.tail
                        self.tail = pdata
        # prepends to head of list
        def Prepend(self,data):
                newNode = Node(data)
                head = self.tail
                while head.previous is not None:
                        head = head.previous
                head.previous = newNode # this is just a stub
        # inserts data after found data
        def InsertAfter(self,find, data):
                if not find:
                        return
                newNode = Node(data)
                newNode.previous =  find.previous
                find.previous = newNode
#

Could someone help me with the insertafter method?

frosty cobalt
#

2n, log n, log log n, n2, n, √n , n!, n3, n3/2, n log n, en+1, n2 log n

#

can anyone sort this in accending order

knotty magnet
#

this seems like homework

reef remnant
#

log log n, log n, n2, n, 2n, n3, n3/2, en+1, n2 log n, √n, n!

knotty magnet
#

how is sqrt n second greatest, when n and n^2 exist

#

@reef remnant

reef remnant
#

shhhh

knotty magnet
#

half of those are out of order

reef remnant
#

you're right it does seem like homework

tranquil tangle
bold panther
#

@frosty cobalt go to an online graph site and plug them all in

bold panther
#

That isn’t right

#

Lol

frosty cobalt
#

i know

bold panther
#

Ok

frosty cobalt
#

but still she/he helped

bold panther
#

Sorry dawg you can’t just put homework here and expect people to do it for you

#

We provide help. Not handouts

fiery cosmos
#

How can i get a certain amount n numbers between two numbers x and y (x<y), but most of them have to be close to y
For example if i want 50 numbers between 1 and 100, i would get: 1 10 70 80 85 90 91 92 93...

vocal gorge
#

why this specific distribution?

fiery cosmos
#

i need it

#

not exactly like the example tho

#

just the same way

#

i can think about log but don't know how to do it

vocal gorge
#

well, if you can write down the formula for the probability distribution, it's possible to sample values from that distribution (by generating a random value from 0 to 1, then plugging that into the (numerically or analytically) inversed cumulative distribution function)

#

so just make up some probability density function that's:

  1. Only nonzero from x to y
  2. Mostly concentrated close to y.
#

Though I guess I need to first ask... why do you want such a distribution?

tender atlas
#

Cracking with interview code books is only helpfull for any tech interview?

exotic wigeon
# fiery cosmos How can i get a certain amount n numbers between two numbers x and y (x<y), but ...

For example you could have a normal distribution with mean of y and dispersion of your choice. For any sampled number t greater than y just use -(t-y)+y = 2y - t (I mirrored t around y) and if the result is less than x you can just sample again.
The resulting distribution will have more numbers around y and if you have enough IRL time you will be able to calculate the average amount of samples needed to get a distribution of n values depending on dispersion you chose.

#

... it can be done by calculating a probability of getting outside of [x, 2y-x] range with your distribution. Look at 'confidence intervals'

past escarp
#

if i want my function to return 2 int values i do; return int1,int2

#

but i want to assign those values to 2 variables in 1 line of code

#

i,j = func(), for some reason doesnt work

vocal gorge
#

this is hardly #algos-and-data-structs. However, tuple unpacking allows doing exactly what you wrote; you simply return a tuple of two ints from the function.

past escarp
vocal gorge
#

that's how you can unpack a tuple of two elements into two variables, yes

past escarp
#

arigato sensei

scenic hawk
#

.topic

grand havenBOT
#
**No topics found for this channel.**

Suggest more topics here!

lunar jacinth
#
        def Delete(self,data):
                curr = self.head
                while curr is not None:
                        if curr.data ==  data:
                                if curr.previous is not None:
                                        curr.previous.next = curr.next
                                        curr.next.previous = curr.previous
                                else:
                                        self.head = curr.next
                                        curr.next.prev = None
                        curr = curr.next
``` I'm trying to give it a given node to delete...is anyone experienced enough in doubly linked lists to let me know whats wrong here?
wheat kiln
#

how to answer this?

keen hearth
lunar jacinth
keen hearth
lunar jacinth
#
       l = SList()
        l.Append(3)
        l.Append(4)
        l.Append(5)
        l.Append(6)
        l.Prepend(10)
        l.Append(2)
        l.Append(9)
        l.InsertAfter(4, 45)
        l.InsertBefore(2,30)
        l.Delete(2)
        l.Count()
        l.Output()
lunar jacinth
keen hearth
#

Sure

#

Use this:

#

!paste

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

lunar jacinth
lunar jacinth
#

never mind, fixed. the count method is still messed up a little though

keen hearth
lunar jacinth
#

but i got my delete method working

#

its just this count method now

valid slate
#
def make_maze(draw, start):
    visited = [start]
    stack = [start]
    current_node = start
    while len(stack) > 0:
        nodes = []
        for neighbor in current_node.neighbors:
            if neighbor not in visited:
                nodes.append(neighbor)
        if len(nodes) > 0:
            node_chosen = random.choice(nodes)
            current_node.make_barrier()  # make color black
            node_chosen.make_barrier()
            current_node = node_chosen
            visited.append(node_chosen)
            stack.append(node_chosen)

        else:
            node = stack.pop()
            current_node = stack[-1]

        draw()

I'm trying to make a maze generator
but something is off
can somebody help me?

wise sierra
#

is it important to know the implementation of hash table?

#

or is it enough just to know about it and to know how to use in

fervent saddle
#

It’s probably good to understand the idea behind it

#

And maybe the idea behind open and closed addressing

wise sierra
#

thanks bro

brisk saddle
#

are there any situations where you would not want an ordered dictionary?

#

i am implementing a dictionary and i am thinking about making it ordered, but if there are situations where an unordered idctionary is necessary, i might want to make that behavior toggle-able or something.

fiery cosmos
#

I guess if you don't need it to be ordered and the unordered implementation is faster/ more memory efficient etc.

fervent saddle
#

I think if you want the order to be randomized then you randomize something in the hash formula like they do with strings

#

Otherwise, the order isn’t really random, it’s just arbitrary

#

if that’s what kind of thing you’re thinking of

serene panther
#

true

runic tinsel
#

If you're using reasonably new python, you can't create an unordered dictionary

brisk saddle
#

i think you misunderstand. i was not talking about Python's built-in dictionary. i was talking about implementing my own.

#

specifically, using a Hashtable.

runic tinsel
#

Ah ok

tender atlas
#

One of my friend gives me a task

#

Create a algo to calculate Tendering BOQ deviation

dawn pebble
#

Hi, I had a question regarding Leetcode # 28. Implement strStr().
`
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0

    for i in range(len(haystack) - len(needle) + 1):
        char_window = haystack[i:i+len(needle)]
        if char_window == needle:
            return i
    
    return -1

`
this is the algorithm I wrote. Specifically, I'm confused regarding the time complexity of the algorithm. I'm guessing it's O(n) but I'm not sure how the slice function in python3 is implemented under the hood. Can anyone share their insight on this? Thank you.

#

is the time complexity O(n*k)?

fiery cosmos
#

regardless of how slice works, if char_window == needle: will need to potentially compare every character in needle, so yeah that part is O(k), for O(n*k) overall

#

but if k is small that's basically O(n) bongoCat

#

btw as you may know this task is what ||str.find|| does

dawn pebble
#

ah okay. thank you!

#

yeah, after coding the solution I saw people use str.find. It sort of defeats the purpose of the problem but I filed it away in my memory

ivory yacht
vocal gorge
austere sparrow
#

@dawn pebble your solution is O((H - N) * N) where len(haystack) = H and len(needle) = N because you're making H - N iterations and comparing two strings of size N

vocal gorge
#

(with an exception of [:] which for strings, since they are immutable, does nothing and just returns the original string)

fiery cosmos
vocal gorge
#

a string is a sequence of chars just like a list is a sequence of... anything, but it's not implemented as a list, and doesn't have to behave exactly the same

fiery cosmos
#

ok

#

It seems that df[:] has also no effect

#

i.e. give just the df as output

vocal gorge
#

like, df[:] is df?

fiery cosmos
#

pandas DataFrame

vocal gorge
#

I mean, is it exactly the same object (df[:] is df returns true), not a copy?

fiery cosmos
#

for a copy, one need to write df.copy(deep=True), then you would get a copy, otherwise just a pointer to the original df

#
dfCopy = df

any changes on dfCopy would result in changes of df as well

vocal gorge
#

this is always another reference to df regardless of what object it is, I'm asking about [:]

vocal gorge
#

!e

import pandas
df = pandas.DataFrame([1,2,3,4,5])
print(df[:] is df)
halcyon plankBOT
#

@vocal gorge :white_check_mark: Your eval job has completed with return code 0.

False
knotty magnet
#

weird, i thought it'd take numpy's stance: create a view

vocal gorge
#

or at least a different object

#

yeah, it may well be a view

knotty magnet
#

ah, nevermind, my thought makes no sense

vocal gorge
#

!e

a = "hello"
print(a[:] is a)
halcyon plankBOT
#

@vocal gorge :white_check_mark: Your eval job has completed with return code 0.

True
vocal gorge
#

for strings though, [:] is optimized and, since they are immutable, just does nothing and returns the object

knotty magnet
#

how often is that used though, seems like a waste of time to implement

vocal gorge
#

for that matter:

import copy
copy.copy(a) is a # True
fervent turtle
#

Any cp coder here ,I want big help
I can't even solve easy problems .

fiery cosmos
#

interessting

#

now the next question is, what is quicker copy via [:] or .copy(deep=True)

#

got it

#

df = pd.DataFrame(np.random.randint(0,100,size=(10000000, 40)), columns=list('ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD'))
%timeit af = df[:]
%timeit df2 = df.copy(True)

#

first method take 119µs
sedond 3.81s

onyx root
fiery cosmos
# onyx root they do different things, don't they?

Not sure.
I read somewhere that the safest way to copy a data frame is the latter one. However, the first method seems to create a copy as well. Maybe this ā€œdeep =Trueā€ thing does stuff which might not be required (necessarily)

keen hearth
keen hearth
fiery cosmos
keen hearth
fiery cosmos
#

yeah

valid slate
#
def make_maze(draw, start):
    visited = [start]
    stack = [start]
    current_node = start
    while len(stack) > 0:
        # pygame.time.delay(10)
        # time.sleep(0.1)
        unvisited_nodes = []
        for neighbor in current_node.neighbors:
            if neighbor not in visited:
                unvisited_nodes.append(neighbor)

        if len(unvisited_nodes) > 0:
            node_chosen = random.choice(unvisited_nodes)

            node_chosen.make_barrier()
            current_node.make_barrier()
            # current_node.maze_lines(node_chosen)

            current_node = node_chosen
            visited.append(node_chosen)
            stack.append(node_chosen)

        else:
            node = stack.pop()
            node.make_open() # color: green
        draw()
#

This doesn't work for some reason it backtracks the whole grid

#

here is a vid

queen ruin
#

um hope this is the right place, so i heard about reindent.py that auto indents correctly, is there a way to run them on strings?

tawdry ibex
#

Is there a way to make a value in a module that is persistent ex:
import module as m
m.value = 100
then later I can re-import the module in another script and value will be 100

queen ruin
tawdry ibex
#

because i have a "plugin" module which is required in mutiple places
but i want it to only load plugins/addons once instead of reloading every time it has to be imported

tawdry ibex
#

ok so @queen ruin i tried pickler with a empty dict

folder = f'{__path__[0]}'
with open(f'{folder}/events.pickle',"w") as file:
    pickle.dump({},file,protocol=_pickleLevel_)```
and got ```py
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/walksamator/github/McPy/classes/plugin/event/__init__.py", line 16, in _reset_
    pickle.dump({},file,protocol=_pickleLevel_)
TypeError: write() argument must be str, not bytes```
#

anyone know why it failed to pickle it

lean dome
#

pickle is a binary format, not text.

runic estuary
#

night guys, what's the difference between a 3 node cluster in a red black tree and a four node cluster?

wintry oracle
#

I just asked a data structure algorithm question in #help-avocado if anybody here can lend a hand to help šŸ™‚

brisk saddle
#

evening.

icy tendon
#

Hi I need help with splitting with more than one word in a single go Thanls

#

Like I have a string having div and span and I want to split by every div and span

last fulcrum
halcyon plankBOT
#

@fiery cosmos Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!

placid flicker
#

!e

url = b"https://i.redd.it/2qy7unjo2j331.png"

url_cleaned = str(url, "utf-8")
print(url_cleaned)
halcyon plankBOT
#

@placid flicker :white_check_mark: Your eval job has completed with return code 0.

https://i.redd.it/2qy7unjo2j331.png
placid flicker
#

@fiery cosmos

fiery cosmos
#

Thanks man!

placid flicker
#

A string with an b in front of it is a bytestring

fiery cosmos
#

right

fiery cosmos
#

and BTW I have another question

#

the code above runs successfully, but some memes have a question mark (?) which prevents then from being saved, so how do I strip the question mark from the name?

last fulcrum
#

For a doubly linked list with only one node, would the next value point to None and the previous value also point to None?

knotty magnet
#

yes

last fulcrum
# knotty magnet yes

Why? Should the previous value not point back to the head? Like a circularly linked list.

vocal gorge
#

so is it a circularly linked list or not?

#

for a circularly double-linked list, you'd just have one node with both next and prev fields pointing to itself

last fulcrum
#

No circular in it.

vocal gorge
#

Well, then no, the first node would have a None prev and the last one would have a None next. If there's only one node, those two are the same node.

last fulcrum
#

Ok. Thank you. Just wanted to be sure because I saw someone say otherwise.

analog siren
#

with regex how can you do 1 or 3 of an element and not {1,3} which is 1, 2, 3

vocal gorge
#

(?:.{1})|(?:.{3}) would be one way, but not sure if it's the right one

analog siren
#

that would make it so that you would 2 right?

vocal gorge
#

this matches either 1 of . or 3 of ., yeah

analog siren
#

it works perfectly once i switched the 3 and 1 around thanks

sharp gull
#

Traceback (most recent call last):

pandas_datareader._utils.RemoteDataError: Unable to read URL: https://finance.yahoo.com/quote/TSLA/history?period1=1356993000&period2=1577917799&interval=1d&frequency=1d&filter=history
Response Text:
b'<!DOCTYPE html>\n <html lang="en-us"><head>\n <meta http-equiv="content-type" content="text/html; charset=UTF-8">\n <meta charset="utf-8">\n <title>Yahoo</title>\n <meta name="viewport" content="width=device-width,initial-scale=1,minimal-ui">\n <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">\n <style>\n html {\n height: 100%;\n }\n body {\n background: #fafafc url(https://s.yimg.com/nn/img/sad-panda-201402200631.png) 50% 50%;\n background-size: cover;\n height: 100%;\n text-align: center;\n font: 300 18px "helvetica neue", helvetica, verdana, tahoma, arial, sans-serif;\n }\n table {\n height: 100%;\n width: 100%;\n table-layout: fixed;\n border-collapse: collapse;\n border-spacing: 0;\n border: none;\n }\n h1 {\n font-size: 42px;\n font-weight: 400;\n color: #400090;\n }\n p {\n color: #1A1A1A;\n }\n #message-1 {\n font-weight: bold;\n margin: 0;\n }\n #message-2 {\n display: inline-block;\n *display: inline;\n zoom: 1;\n max-width: 17em;\n _width: 17em;\n }\n </style>\n <script>\n document.write('<img src="//geo.yahoo.com/b?s=1197757129&t='+new Date().getTime()+'&src=aws&err_url='+encodeURIComponent(document.URL)+'&err=%<pssc>&test='+encodeURIComponent('%<{Bucket}cqh[:200]>')+'" width="0px" height="0px"/>');var beacon = new Image();beacon.src="//bcn.fp.yahoo.com/p?s=1197757129&t="+new Date().getTime()+"&src=aws&err_url="+encodeURIComponent(document.URL)+"&err=%<pssc>&test="+encodeURIComponent('%<{Bucket}cqh[:200]>');\n
</script>\n </head>\n <body>\n <!-- status code : 404 -->\n <!-- Not Found on Server -->\n <table>\n <tbody><tr>\n <td>\n <img src="https://s.yimg.com/rz/p/yahoo_frontpage_en-US_s_f_p_205x58_frontpage.png" alt="Yahoo
Logo">\n <h1 style="margin-top:20px;">Will be right back...</h1>\n <p id="message-1">Thank you for your patience.</p>\n <p id="message-2">Our engineers are working quickly to resolve the issue.</p>\n </td>\n </tr>\n </tbody></table>\n </body></html>'

#

i am getting this error

#

pls help

last fulcrum
dapper sapphire
#

So there isnt a way to make index 0 again with a for loop, we would have to use a while loop for that?

#

!e

for i in range(10):
    if i == 4:
        i = 0
    print(i)
halcyon plankBOT
#

@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
005 | 0
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
grizzled schooner
knotty magnet
#

if it's more complex, there's no way to reset it like you said, you'd have to use a while loop

#

although maybe you could do something like this

sub = 0
for x in range(20):
  if x == 10:
    sub += x
  x -= sub
  # do loop things
```but that seems annoying
fervent saddle
#
x = iter(range(10))
cycles = 0
for n in x:
    if n == 4:
        cycles += 1
        if cycles == 5:
            break
        x.__setstate__(0)
    print(n)
print("done")```
There’s this, but iirc it’s meant for pickling, so it’s probably not a good idea to do it even if it happens to work right now.
knotty magnet
#

interesting, how does __setstate__ work?

fervent saddle
#

It sets the state of something in the iterator, I guess

#

I’m not really sure what it does internally. Someone showed it to me when I was asking the same question

knotty magnet
#

!e

x = iter(range(5))
cycles = 0
for n in x:
    if n == 4:
        cycles += 1
        if cycles == 2:
            break
        x.__setstate__(0)
    print(n)
print("done")
halcyon plankBOT
#

@knotty magnet :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 0
007 | 1
008 | 2
009 | 3
010 | done
knotty magnet
#

interesting

keen hearth
#

__setstate__ has something to do with pickling, but I've never learned what.

runic estuary
#

Is the black height of the RBT above 2? and the tree height 4? I understand that the height is the longest path from root

dapper sapphire
#

Maybe while loop is a simple clean approach. And __setstate__ is interesting

fervent saddle
#

It’s interesting but it’s probably better to not use it since it wasn’t made to be used like that

sage coral
#

I'm gonna make a snake AI with genetic algorithm (or something like it), and I'm trying to plan out the nn. Ideally I just have binary values for inputs, but I'm struggling to figure out how I can fit data about the snake's body in a binary value. Any suggestions on how to do this?

last fulcrum
#

Apart from BST, what other trees are there and should I learn them? (Are they as important as BST?)

knotty magnet
#

there are a few more specialized trees for searching that you'll only probably see in competitive programming, like segment trees

#

you could also look at the self balancing BSTs, like red-black or AVL

vocal gorge
austere sparrow
#

but I don't know anything in depth about those