#algos-and-data-structs
1 messages Ā· Page 121 of 1
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
if it does nothing, then why is there so much code
That's why I'm asking
why do you think it does nothing?
like when I remove it , it only makes 2 pair of children and stops
Because it is being called from inside itself
like
def put():
put()
which makes no sense to me
at all
can you write a recursive function to calculate the factorial of a number?
without looking anything up, except maybe what factorial is
try it
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
def f(n):
if n == 0: return 1
return n*f(n-1)
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?
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]]
`
transpose after reversing
Words I don't understand š
[*map(list, zip(*a[::-1]))]
Yea I'm still confused. Maybe this question is too much for me?
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
Ok thanks
pinga
Hi to all Pythoneers.
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?
iterate over the array until you find the spot, then insert
Similar logic to insertion sort. find the right place, insert new element, then right shift all elements to the right, should be linear since the array is already sorted
that would be O(n), I want the fastest and the most effective way, binary search does it in O(logn) but the code is quite complicated and will take time to write it, I have written it before and it takes me like around 15 mins so i wanted something that is quicker but equally faster
@humble mauve
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)
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
Check out the pinned messages in this channel.
How to do that?
I'm looking for some free resources.
There's a button up at the top right of the Discord client shaped like a push-pin.
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")))
@stiff mango :white_check_mark: Your eval job has completed with return code 0.
25
!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")))
@stiff mango :white_check_mark: Your eval job has completed with return code 0.
25
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?
K
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
!e print(ord("0"))
@stiff mango :white_check_mark: Your eval job has completed with return code 0.
48
!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")))
@stiff mango :white_check_mark: Your eval job has completed with return code 0.
25
@knotty magnet is that what you mean?
no
And what "simple math" do you mean?
division?
And where would division come into play? What would you devide to get from the string representation to the number?
you wouldn't use the "0123456789" string in the first place
I didn't in this implementation
yeah, that looks ok
!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"))
@brave oak :white_check_mark: Your eval job has completed with return code 0.
-29
@stiff mango
what are simple uses cases for queues and stacks
task queue
certain data structures can be traversed with stacks
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
I haven't even thought about indentation like that. that's an interesting application
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
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)))
assigning a lambda to a variable in general is considered bad practice
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
Hint: use a set.
Thanks
Better yet a dict to keep track of the index 
Can someone help me setup matplotlib on visual studio code?
Im good now. ty
Hii I'm nee here could anyone give me best learning material for DATA STRUCTURE AND ALGO
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?
https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/ I tried heap but I failed, it is supposed to involve binary search but I dont get how, anyone?
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
For a given n how many total function calls does it make? Say for n = 4?
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.
Ohhhh I get it
So it'd be n-1
Yeah, or O(n) time complexity
Thank you š
you can use re to match both the singular and plural
but regex could be slow if the file is massive
-
looping in python is slow. solution: use pypy, graalpython, or cython if you just need to loop over lines of a text file quickly, or use pandas to read the csv into a data frame, which does the looping "internally" and therefore can be a lot faster.
-
data structures. i think full-text search algorithms often index the text using a trie data structure, to efficiently provide "search-as-you-type" functionality. see https://stackoverflow.com/a/50206518/2954547
-
you might need to apply "stemming" or "lemmatizing" to get a "base" word to use for searching. examples include https://www.nltk.org/api/nltk.stem.html (the multi-language
SnowballStemmeris often a good default, orWordNetLemmatizerfor english) and spacy https://shyambhu20.blogspot.com/2020/11/how-to-do-lemmatization-using-spacy.html
A trie seems like it would work for small strings, but not for large documents, so not sure (1-100's of pages of text). Maybe it is possible to combine an inverted index with a suffix tree to get the
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/
I would also recommend loading the data into an SQL database, and storing word-stems for lookup.
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.
Thank you all for the great suggestions, there's a lot to digest here, but this looks like a good starting point. Thanks again.
FYI, this added two lines of code and is working flawlessly so far. Why didn't I think of looking for this sooner?!
next time, you will!
hi i have a pretty simple question in #help-chocolate if anyone has free time
Does leetcode usually have bad test cases?
My code failed even though it should pass the test case
I don't think I've ever had problems
You might be printing instead of returning or something 
I'll post the code. Look at it for me
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.
Can't you buy on 2 and sell on 4, thus earning 4-2=2 
Iirc this kind of problem requires dynamic programming 
But i could be totally wrong there
š
hey guys! any recommendation where can i start learn data struct and algo.... also some prerequisites too. Thanks!
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
Algorithm Design: 9780321295354: Computer Science Books @ Amazon.com
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 ...
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?
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
!e this is a way to construct and lookup with a dict everyone keeps mentioning```py
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)]
d = {t[0]: t[1:] for t in tuple_list}
lookup = '123'
print(d[lookup]) #<- super fast O(1)```
@fiery cosmos :white_check_mark: Your eval job has completed with return code 0.
(3, 2, 1, 3, 5)
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)
I think they mentioned in general they need to do it a bunch
okay, then a dict sounds good š
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
an iterator is more general than a generator function
it can be very enlightening to read https://docs.python.org/3/library/collections.abc
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
What do you recommend me to read to improve my logic?
same here.
ah yes.. one first book in algorithm. Tbh, my friend use to recommend me this but thanks for the effort man.... appreciated
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?
''.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
Yeah, I figured I could use an array and then do "".join(array)
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?
why not pick negative numbers? something like (-10 + -7 + -8) ^ 2 is positive after all
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
So,
What I was saying above was that when you're picking all positives, don't pick indices x such that both arrays have negatives at that index(Because you'll pick them when you're picking all negatives in another iteration perhaps)
this is what i was getting at, just because S1 +A[x] < S1, that doesn't always mean (S1 +A[x])^2 < (S1)^2, I don't have a full solution but was just trying to make sure you are aware that you can't just disregard indicies that would give you negatives for both numbers
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
yeah, don't worry I get what you mean, I may of just misunderstton your original comment
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 š
Should I implement a queue in Python using collections.deque or a circular array?
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
Nice. I was of the opinion you'll be asked to implement a queue or stack yourself.
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.
I saw a linked list implementation of a queue and stack on the web. People are really doing everything themselvesš .
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
This the weakness of me .
This channel
use a for loop?
data_lst = [thing1, thing2, thing3]
data_dct = {thing.key: thing.value for thing in data_lst}
i'd recommend the dict comprehension instead, but that does work too
What is the difference?
clearer intent, imo
technically should be a bit faster but that's not really relevant
Game Crash is problem ?
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
that's learning though
you have a problem, you see the solution you won't have this problem later
Yes but it doesn't feel as efficient
Because I spend like 3-4 hours on a problem just stuck
i think that's pretty much optimal
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
@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
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?
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.
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
yep, if order doesn't matter
C(3,2)+C(3,3) = 3+1 = 4, yes
What is this formula and how does it work?
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
Often called "n choose k" sometimes like nCk 
Interesting how so many things can boil down to a math equation.
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 ?
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
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.
How do you mean 
there's also slicing which looks confusing list1 = list2[:]
and copy module .deepcopy if you need to recursively copy the items
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]]
you're looking for copy.deepcopy(). list.copy() makes a shallow copy, meaning it doesn't copy things inside the list
I dont get intellisnse for copy.deepcopy()
have you done import copy ?
Oh I cant use it then.
!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]=}")
@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
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
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?
???????. They clearly said use a deep copy
Any copy you create would be shallow. They are referring to the same address in memory.
Yeah, but I dont think I can import a library in an interview. Otherwise deepcopy is a pretty good solution to create a copy.
You can. It's a built in. How else would we be able to use defaultdict and a deque?
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 
||return [[1 - x for x in row[::-1]] for row in image]||
Oh we can import libraries, thanks for mentioning that. Yeah, I'll import copy so I can use deepycopy
There is a distinction. This is an inbuilt library. I don't know if you can import external libraries.
What would be external library? Something that you have to pip install?
Yes. from typing import List is an example of a an inbuilt one.
So if it's in cpython, it's built in and we can use it:?
https://github.com/python/cpython/tree/main/Lib
Yep. Read the documentation to see more
Where is this code from?
I just wrote it 
I was asking about the original you refactored.
Read the documentation about what?
To see what other builtin modules there are
I didn't refactor. I did the leetcode Tony posted https://leetcode.com/problems/flipping-an-image/
Oh. That was the question I asked the last time
Is it right to use one line like that in an interview?
I don't think so
It depends
If one liner is too complicated, then no.
I'll list my reasons why I think it should not be so. But as always, this is a subjective issue.
I personally dont like list comprehensions.
-
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.
-
You would solve the problem early, thereby allowing the interviewer to give you even harder problems.
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 
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?
Maybe showing the one liner after using the long way around is better.
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
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.
š
No honestly!! I was like wait what you can't be serious
I would look at the time honestly. More time, do unoptimized first. Less time, do optimized first. Anything to help you pass.
Except cheating and lying
Yea Google likes to fail people
They want the best
How can one cheat and lie on a whiteboard?
I have to say I like this approach actually
Maybe they meant optimizations not as in time/space complexity
But as in for the computer
idk
dont wanna type again please see this
why my kadanes algo able to overcome its limitation ......lol
it shouldnt work but it does
??
Anyone here with a leetcode premium subscription? If this is wrong to ask here please remove.
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
š
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.
Check the pins
thank you that is exactly what i wanted
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
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?
I doubt that Nvidia has an API for broadcast. Noise reduction is a very large field and there's already many various filters you can apply to your data. Everything from simple low-pass filters to highly complex filters that I don't understand.
Look into scipy they already have a few filters implemented.
thanks, ill look into it
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
There's a few pinned here.
thanks , I just checked them out
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
hello
hi
i have a problem can you help me?
ask!
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'
there doesn't look to be a module with that name
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
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 š
unfortunately don't work š¦
instead of 'import module' try 'import modules'
I see the current working directory is your user folder?
You would need to change to the directory containing the file. Or, make the path relative to the file.
oh
I think this should work: ```py
from pathlib import Path
p = Path(file)
sys.path.append(p.parent / 'modules')
now it works i open the entire folder and what you say fisrt time worked
thank you
Oh right.
Did you also try this? š
It might save you the hassle of having to navigate to the folder each time.
(Assuming it works š )
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.
yes is works
thank you so much
i am trying to figure this thing out from a week
XD
Ah, sorry to hear that. That's so frustrating!
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
Some trick with reduce might be possible
But your solution looks fine 
LeetCode times vary. You hit submit once and you are faster than 99% and click it again and it changes to 20% 
itertools.accumulate
do you have a book you recomend to learn algorithms?
Maybe return list(itertools.accumulate(nums))?
Anyone aware of a fun to use geometric constraint resolver for python
I want to plan woodworking details and freecad/cad query seem horrendous
how can i optimize this?
hint: sort it
ya gotta put spoilers on that yo
sorting doesn't help much
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
Which website is that?
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
are you just running the same code over and over until you get a lucky run
yes
it varies a lot
i thought i cheesed it with returning a genexp, but it was just a lucky run
what if you do gc.disable()
that would probably give you a better chance of getting a good run
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 
how do you spoiler code blocks? 
||```py
e
I was trying the other day and /spoiler nor || seemed to work 
take a screenshot like frowny did i guess, lol
well meh
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.
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
Slightly more expensive way? Do you mean list comprehension is slightly more expensive than list comprehension?
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
this can't be done with a list comprehension though
No this question is apart from list comprehension
I wanted to know what people though it if its clear enough.
i said expressive. list comp is slightly more expressive (when it's simple enough)
Oh my bad sorry lol. Yeah I think so too, it's sort of like .join
Splitting it over 4 lines seems excessive. One or two like return ' '.join(s.split()[:k]) feel less daunting to read imo 
or use applicable names like words instead of string_list
actually plus 1 for words. I wholeheartedly agree
Actually can we compare list comprehension with join. Where list comprehension is done for a list, but join is done for a string.
depends what comparison you're trying to make i guess
it's leetcode
Help me understand the concept of the solution
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?
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)??
Interesting problem! Well without the constraint (that the same side must be facing up) the length of the shortest path would be the manhattan distance. But it seems you need to be a little more clever than that.
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.
š¤
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?
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<
Should everyone know FizzBuzz?
I personally think the pythonic 1 liner at the end is too cheeky.
In this video, I attempt the infamous FizzBuzz coding Interview problem.
I break any particular programming interview problem in the following 4 parts:
- Describe Problem
- Ask Questions and clarify the problem with examples
- Thinking Out Loud \ Draw\brainstorm the solution
- Code the solution
---------------------------------------------...
you don't have to memorize it, but if you can't create a solution given the description of the problem..
True. A memorized solution is easy to tell these days unless youāre a great actor
I think when people focus on FizzBuzz specifically they're missing the point. It was only ever intended as an example of a test of basic programming competency.
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.
Here's where it originates: https://blog.codinghorror.com/why-cant-programmers-program/
Hmm
Well if the source is far enough away from the target, it may be that you can always find a manhattan-distance length path using some kind of simple algorithm. You might want to get a dice and try rolling it around on a grid to help you visualise it better.
!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())
@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'}
huh. classes can be decorated too.
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
Sets are implemented as hash tables. Essentially, a hash table uses a function (called a hash function) to calculate a number (called the hash of the key). The items are stored in an array; the hash determines where (at which index) a given key will be stored in that array.
So, in theory, finding an element in a hash-table doesn't depend on the number of elements in the hash table.
im intermediate in py but havent touched algos
are algorithms essential
since nothing ive done yet required them
everything is built in
I'd say basic knowledge of algorithms is fairly essential. You might want to check out some of the pinned resources.
ive thought bubble sort
was requested in this year's final exams
but bubble sort is pretty dum
Oh right. Sorting algorithms are often used as a way to introduce the concepts behind the analysis of algorithms.
No cap you could learn it all online quicker and cheaper
yea ik i just need a degree
Fair
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
Yea, I cant say much. I'm at uni
guess this is #career-advice
anyone aware of a recent usable geometric solver for python that allows to declare materials and their properties/relation
https://www.freecadweb.org/ has python scripting, it is the closest tool I know of, if I am understading your question right
FreeCAD, the open source 3D parametric modeler
its not cappable of the things i want to do
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
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?
I came across this that says, O(n):
https://stackoverflow.com/questions/5454030/how-efficient-is-pythons-max-function
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?
Python/bltinmodule.c line 1844
builtin_max(PyObject *self, PyObject *args, PyObject *kwds)```
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
Thanks for the link. But why did you link to that branch instead of main branch?
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?
@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
Litter, as in trash talk, how so? But that wasnt my intent. But if someone felt offended I apologize.
I was just trying to find largest and second largest number in a list. So I thought of using max this would give the largest number, and then I thought of using sort so we can just access the last and second last/largest element.
that is a much better context than just the bits you use to implement (with what you wrote it was unclear what you try to do
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
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.
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
Thatās wrong, it doesnāt give the same output with the example string
!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)```
@fervent saddle :white_check_mark: Your eval job has completed with return code 0.
2
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)
@fervent saddle is the input always well-formed? - if yes just find the count of xy sequences in the string
The description says the string always has only x and y characters
is it allowed to use regex?
Iām not really sure, I couldnāt find the webpage for it
(as far as i understood you are looking for all occurences of "xy+x"
All occurrences of x + something + x where something has at least one y
the regular expression for that is xy+x
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
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
I'm not sure...

oh ok.
... max heap ...
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?
The thing on the right of in will only ever run exactly once
Oh wow ok I didnt know that. Thanks a lot!!
!e
for x in [print("hi"), 2, 3, 5]:
print(x)
@knotty magnet :white_check_mark: Your eval job has completed with return code 0.
001 | hi
002 | None
003 | 2
004 | 3
005 | 5
I had a similar idea, but thought of passing in a function after in. But what you did is a lot better and straight forward.
How do I start learning data structures
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?
your p.create is exactly the job of the __init__, so move that code to to __init__
Thanks. So I assume you mean that if I have to create a method, it should be to return a different data or mutate any self data if needed?
__init__ initializes your object,, by setting any attributes needed (by mutating self)
I guess for names would be fine in the init but I don't think there's an easier way to handle emails into the Person object since it needs to pass the regex first
So init name, then .addEmail("bob@email.com") after
you can accept these arguments in the init, so ```py
class Persom:
def init(self, name, email):
self.name = name
self.email = email
bob = Person('Bob', 'bob@protonmail.com')
you can add all the validation in the init itself
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
then don't use dataclasses, just use a normal init
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
def __init__(self, name, email):
self.name = name
if not validate(email):
raise ...
i just learnt that you can __post_init__ in dataclasses so, that would work too
yeah thats what I did
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)
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')
Hmm... How do I include a _validate_name() function in unittest?
Correct me if I'm wrong, prefix _ to a function name would make it private right?
im not very familiar with unittest, sorry
not really, by convention its considered as private but nothing is actually private
no one's gonna stop me from accessing that method from outside
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
!e ```py
class F:
def _am_i_private(self):
print('No')
f = F()
f._am_i_private()
@meager slate :white_check_mark: Your eval job has completed with return code 0.
No
we all just agree that we wont mess with things starting with underscores
Good to know!
OK I think I got it properly designed... I hope. Thanks @meager slate
š
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
Loop through from the start normally and save the 1 indexes, but stop when you get x of them
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
yes it will be the best way
There are some good resources that are pinned.
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}
"""
what things do i need to keep in mind while preparing for programming interviews in python opposed to c++
You are looking for #user-interfaces channel.
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
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.
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.
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
you're printing main(abc()), main always returns 3
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.
oh thanks got it ))
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()))```
you can't access a function's local variable from outside the function
somebody offered this solution and worked !
def dfe():
c,x = main()
return c+1
Is this pretty much how we get minimum value in python?:
!e
import sys
minimum_value = -sys.maxsize
print(minimum_value)
@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.
-9223372036854775807
Minimum value of what?
sort of like int_max, int_min
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").
I just needed a small enough number to perform comparison with some data. Data given could have -1 upto -1000, so -sys.maxsizeseems reasonable.
You could use negative float infinity, -float("inf").
it compares lower than any int or float.
except itself
!e
min_inf = -float("inf")
print(float("inf"))
print(-float("inf"))
print(min_inf == (-float("inf")))
@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.
001 | inf
002 | -inf
003 | True
I am performing an != is not equal to comparison.
So I guess -float("inf") also works and I could use either. Thanks!
Please stop. If you want to get help see #āļ½how-to-get-help
how do i check if num1 and num2 don't point to the same location in memory?
is keyword
i did say is not , is it not correct?
probably
i also tried ! is but that didn't work either
not so much
it wants me to return the indexes of the numbers, when added up equal to the target value, provided the indexes of those numbers are not the same
Oh yeah, I see what youāre trying
oh wait
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
i can check it with nums.index(num1) != nums.index(num2)
but
nah, i don't see how that will work
when num1 = num2
enumerate might help
how would that affect it tho?
If both numbers are the same values then theyāll be the same objects
I should say CPython does this
It might be different with other implementations
But yeah, this seems like a good place to use enumerate
python does work on cpython, right?
Yeah, CPython is regular python
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?
CPython is written in C, yeah
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?
how do i use it tho?
So you know what index youāre on
i can't really figure out how do i do that with enumerate(iterable, start)
The first value in each tuple will be the current index
the common usage pattern is for i, el in enumerate(lst): or something like that.
Anyone know a simple graph dfs algo
plz dm me
How do i convert a string list ("[data]" / '[data]') to a normal list ([data])
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
If you have the code for a python list contained within a string, then you need to evaluate that string, using either eval (very unsafe if the string is user-provided) or ast.literal_eval (a safer limited alternative). If the string contains a JSON list, e.g. received from an API, then you should parse it using json.loads.
hi
my name is Vansh Khera
and i like to code :D
i want to pc professional for my project
but its paid :C
No way around that I'm afraid. Although I think they make it available for free for students.
i live in india
i have a school email
but it shows that its not valid :(
me
just jking
can some one help me? With .py to .exe
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")
@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
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:
sure, types are singletons, so no reason not to use is. That said, comparing types exactly isn't a very common thing to do in general - usually you need isinstance or issubclass instead.
How can i calculate this?
Jeffrey J. McConnell, Analysis of Algorithms: an Active Learning
Approach , 2001 PAGE 52
So something like following:
!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))
@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
We would use isinstance because that's more common then directly comparing data type with type(variable)?
Yeah, since in most cases you care about whether something "acts like a list", for which you can check whether it's an instance of list or its subclass with isinstance. It's rare to care about what something's exact type is.
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)
print(response['AggregateEvaluationResults'][0]['EvaluationResultIdentifier']['EvaluationResultQualifier'].get("ResourceId"))
got it
I dont understand the nicest way would be to check...:
I mean when I type the if statements, I would have the if. I just left it out in the above. Am I missing something?
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
Why did you write "but"? How is it different from your expectations or requirements?
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)
Thanks for pointing to isinstance!
I think this is one of the good use cases where type and isinstance would work differently:
https://stackoverflow.com/a/1549814
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:
current itself is None then. @last fulcrum
while current:
current = current.next
if current.next is None:
self.tail = self.Node(element)
current.next = self.tail
self.size += 1
There is a None in my list
When I was testing
But still this error
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.
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?
yes, but if current is set to the actual last Node, it will still run, set the next Node to None, then it errors.
So you're saying I should timeout before the last node so that the actual next would be none?
ehm, i said nothing about what you should do. i only pointed out the flaw in your code.
what is the purpose of this?
should have been more specific, what is the purpose of the code you sent?
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
so an append operation.
I doubt it's called append, but yes
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.
Thay have O(1) if you know the position also
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.
I wrote the code for that, but I can't even make this work so that's useless
why would it be useless?
Because at the moment I'm struggling to get the tail. That is why i used this
well that is something we can work to fix here. do you have a head and tail field in your Linked List?
Yes. I'll post
so what is the purpose of creating this function when you could just use the tail field?
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
I have not implemented it as I said above
I just wrote it in my book
Even then it's not right
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?
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
i think i misunderstand something here. you already have the tail, it is stored in the tail field in your Linked List..
at the start, when the Linked List only has one Node, head and tail should essentially point to the same Node.
That is wrong. Tail is None. It does not link to the other elements of the linked list.
Take for example me inserting 4,3,2,1
One should become the tail. But that is not possible in my code
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.
first off, make sure you do this, so assuming the List is not empty, you can always have access to the tail, and because of this, always keep it consistent with the actual tail during append operations.
Ok
So as you keep on adding to head the tail is still that last value
yup!
Ok. I'll implement it.
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.
Thanks
got it working?
alrighty
Done
sick, everything working?
I think so. Just one more question
sup?
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
no, that is the same thing more or less. just different way of writing it.
Ah. Should I paste the full code?
no i think we can go off this.
just trying to visualize it in my head.
could you show your output? @last fulcrum
7 9 2 None
`
l = SinglyLinkedList()
l.insert_at_head(9)
l.insert_at_head(7)
l.insert_at_tail(2)
print(l.print_linked_list())
`
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.
I assigned a variable to it right now and still got None
I think that is it
send the code.
You're right
I just need to call the function
Without print
yeah
Thank you @brisk saddle
no problem!
Any good courses or books for learning Data Structures and Algorithms in Python?
I found this helpful for Linked Lists:
https://runestone.academy/runestone/books/published/pythonds3/index.html
An interactive version of Problem Solving with Algorithms and Data Structures using Python.
There are also some other resources in pinned area.
I recommend this https://www.amazon.com/Computer-Science-Distilled-Computational-Problems/dp/0997316020 @cinder bloom *
Computer Science Distilled: Learn the Art of Solving Computational Problems [Ferreira Filho, Wladston, Pictet, Raimondo] on Amazon.com. FREE shipping on qualifying offers. Computer Science Distilled: Learn the Art of Solving Computational Problems
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?
I know about this but the explanations in this book seem a little basic, any other books or resources?
Does this book explain concepts in Python? The reviews on Amazon say it's a really condensed and a book for basics.
Use what I use. Honestly, it's the best book for learning DS & A.
Data Structures and Algorithms in Python [Goodrich, Michael T., Tamassia, Roberto, Goldwasser, Michael H.] on Amazon.com. FREE shipping on qualifying offers. Data Structures and Algorithms in Python
Alright, one more thing, I'm learning DSA for interviews so I can use this book for that purpose right?
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.
-
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. -
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. -
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. -
Use various other resources.(Ex: Cracking the coding interview.)
Things are explained better by different people. YouTube is your best friend. -
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. -
Use flashcards to help you with your notes while solving the questions at stage 5. You'll be asked those questions at the interview.
-
Good luck lol.
CodeSignal is the most advanced assessment platform on the market. Simulate a realistic coding environment with features engineers use on the job every day.
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```
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!
Theyāre both the same complexities
None? I can see no difference.
Awesome
does anyone know about the Apriori algorithm
Yes, do you have a question about that?
yes have a project based on Apriori algorithm
https://github.com/ymoch/apyori
I have tried running this script but the results.txt is coming same as the input tsv
I'm not familiar with that repo. Is your input data tab-seperated as stated in the readme?
yes .tsv file
do you have any project based on this algorithm
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
okay let me try hard enough
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?
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
this seems like homework
log log n, log n, n2, n, 2n, n3, n3/2, en+1, n2 log n, ān, n!
shhhh
half of those are out of order
you're right it does seem like homework
@frosty cobalt go to an online graph site and plug them all in
i did it,
thank u
š
i know
Ok
but still she/he helped
Sorry dawg you canāt just put homework here and expect people to do it for you
We provide help. Not handouts
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...
why this specific distribution?
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
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:
- Only nonzero from x to y
- Mostly concentrated close to y.
Though I guess I need to first ask... why do you want such a distribution?
Cracking with interview code books is only helpfull for any tech interview?
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'
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
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.
sry for that, doing a data structure problem just encountered it there, so it should work how i wrote it ?
that's how you can unpack a tuple of two elements into two variables, yes
arigato sensei
.topic
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?
how to answer this?
At a glance, it looks ok to me. What happens when you test it?
When I test it out, nothing seems to delete
What does the test-case look like?
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()
my count doesn't seem to work either for some reason. I could paste my code if you want?
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.
sure, linked it.
never mind, fixed. the count method is still messed up a little though
Hmm, well I can't see anything wrong with the function itself, so it would seem that the structure of the linked-list is getting messed up somehow. Do you have a way to visualise this structure?
i dont
but i got my delete method working
its just this count method now
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?
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
Itās probably good to understand the idea behind it
And maybe the idea behind open and closed addressing
thanks bro
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.
I guess if you don't need it to be ordered and the unordered implementation is faster/ more memory efficient etc.
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
true
But it's not an option?
If you're using reasonably new python, you can't create an unordered dictionary
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.
Ah ok
One of my friend gives me a task
Create a algo to calculate Tendering BOQ deviation
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)?
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) 
btw as you may know this task is what ||str.find|| does
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
You might want to look up string finding algorithms by the way, thereās a number of different methods which pre-process the needle to allow skipping past sections of the haystack. str.find of course does this.
https://en.wikipedia.org/wiki/String-searching_algorithm
and yes, slicing a string or list is O(k) time like you were worried - it creates a new list/string rather than a "view" into the original one.
@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
(with an exception of [:] which for strings, since they are immutable, does nothing and just returns the original string)
same for lists if I'm not wrong however a string is a list of chars......
Nope, for lists [:] creates a shallow copy of the entire list.
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
like, df[:] is df?
pandas DataFrame
I mean, is it exactly the same object (df[:] is df returns true), not a copy?
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
this is always another reference to df regardless of what object it is, I'm asking about [:]
looks like no, it does create a copy:
!e
import pandas
df = pandas.DataFrame([1,2,3,4,5])
print(df[:] is df)
@vocal gorge :white_check_mark: Your eval job has completed with return code 0.
False
weird, i thought it'd take numpy's stance: create a view
ah, nevermind, my thought makes no sense
!e
a = "hello"
print(a[:] is a)
@vocal gorge :white_check_mark: Your eval job has completed with return code 0.
True
for strings though, [:] is optimized and, since they are immutable, just does nothing and returns the object
how often is that used though, seems like a waste of time to implement
for that matter:
import copy
copy.copy(a) is a # True
Any cp coder here ,I want big help
I can't even solve easy problems .
you are right, it make a proper copy [:] for DataFrames
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
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)
I believe df[:] is equivalent to df.copy(deep=False). The default value of deep is True.
Selecting a slice of a dataframe without doing a deep-copy is sort of like creating a "view" into that dataframe. If you change values in the slice, the original dataframe will be modified also.
yes, deep=False is even quicker with 96µs
Well that's probably random-error. I think it is literally the same operation as [:].
yeah
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
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?
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
i would use a simple pickle or json or a common file..
simple pickle
explain
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
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
you need to open the file with mode "wb", not "w"
pickle is a binary format, not text.
night guys, what's the difference between a 3 node cluster in a red black tree and a four node cluster?
I just asked a data structure algorithm question in #help-avocado if anybody here can lend a hand to help š
evening.
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
Open a help channel. This channel is for Discussion of general computer science, algorithms, mathematical concepts, data structures as they relate to solving problems with Python.
Check #āļ½how-to-get-help for more information.
@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!
!e
url = b"https://i.redd.it/2qy7unjo2j331.png"
url_cleaned = str(url, "utf-8")
print(url_cleaned)
@placid flicker :white_check_mark: Your eval job has completed with return code 0.
https://i.redd.it/2qy7unjo2j331.png
@fiery cosmos
Thanks man!
A string with an b in front of it is a bytestring
right
I got it
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?
For a doubly linked list with only one node, would the next value point to None and the previous value also point to None?
yes
Why? Should the previous value not point back to the head? Like a circularly linked list.
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
It is a doubly linked list.
No circular in it.
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.
Ok. Thank you. Just wanted to be sure because I saw someone say otherwise.
with regex how can you do 1 or 3 of an element and not {1,3} which is 1, 2, 3
Not a question for #algos-and-data-structs, really, but oh, realised what you're asking[13]
(?:.{1})|(?:.{3}) would be one way, but not sure if it's the right one
that would make it so that you would 2 right?
this matches either 1 of . or 3 of ., yeah
it works perfectly once i switched the 3 and 1 around thanks
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
Why are you posting this here? Can't you read the banner or can't you see #āļ½how-to-get-help ?
Your question should not be answered because you can't follow even basic instructions.
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)
@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
maybe you could use itertools.cycle?
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
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.
interesting, how does __setstate__ work?
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
!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")
@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
interesting
__setstate__ has something to do with pickling, but I've never learned what.
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
Thanks I think using for loop to set index to 0 would end up becoming more work.
Maybe while loop is a simple clean approach. And __setstate__ is interesting
Itās interesting but itās probably better to not use it since it wasnāt made to be used like that
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?
Apart from BST, what other trees are there and should I learn them? (Are they as important as BST?)
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
I've seen (https://www.youtube.com/watch?v=v7EJX38gG-E) this done by feeding the NN the data about the cells in a square around the snake's head, and also stuff like the position of the target.
Database engines use B-trees, and HAMT is also a cool data structure (it's an immutable hashmap with efficient operations)
but I don't know anything in depth about those
