#algos-and-data-structs
1 messages ยท Page 141 of 1
Okay got it thank you so much for your time.
I think maintaining the 10 max numbers and updating it as you iterate through the array might be faster
so O(n * 10) is faster than O(n * logn) ig
Isn't heapify of o(nlogn) which comes from adding every element having o(logn)
i forget exactly how but heapify can be implemented in O(n)
Not really aware. Refs would be appreciated.
the heap method is O(n+ 10log(n)), which is the same as O(n)
its not O(n logn), if n log n was feasible we could just sort the list
I didn't know heaps could be initialized in O(n) ๐ thanks for the information
Wow it's a long answer. Thanks for the ref. I'll read it.
Hey guys, I have some problems with a leapcode problem I'm working on. I am not very experienced with OOP (simply because I chose not to learn it). It is a BT (data structure) problem and I have issues with some specifics. First of all, in the function isCousins(), it introduces a new type, TreeNode(). As a relative beginner to OOP, I do not understand how to convert the TreeNode object to a list, or to interpret it as a list as part of my problem. I would really appreciate help ๐
from what i can see here TreeNode represents a node on your binary tree, and node.left, node.right are two another TreeNodes representing its children
You don't need to convert it to list. You need to find x and y in your bst and see if they have same parent.
Yep. I have little knowledge with binary trees.
I dont understand how to obtain a node, inter a node or replace a node.
Wait forget my definition of cousin btw. They have defined it differently.
It's an easy leetcode problem, but I dont have a great knowlege of recursion related to binary trees and class creation.
Also this is a bt and not bst. So yeah. Let's see. You know what is bt right?
I see. Well i mean i would not jump directly to this problem if i would not have knowledge of classes.
It was in an assessment
But it wasnt an important assessment or exam or anything
quick select also works, not sure if it'd be faster
hm
- If you only seek the top 5 elements out of an array, then the binary heap is likely to beat QuickSelect, irrespective of how many elements I have. The binary heap will fit in one or two cache lines, and the log k factor will be small.
- If I keep k at a sizeable 128, but I increase substantially the size of the array, then QuickSelect will start to win big.
- However, if I keep increasing the array size, the benefits of QuickSelect might start to fade. Indeed, QuickSelect will start to operate in RAM whereas the binary heap will remain in CPU cache. QuickSelect will become increasingly limited by potentially expensive cache misses.
- QuickSelect still has the worst case quadratic-time scenario that could be triggered by really bad input data. The binary heap is more likely to provide consistent speed.
(https://lemire.me/blog/2017/06/14/quickselect-versus-binary-heap-for-top-k-queries/)
ยฏ_(ใ)_/ยฏ easiest to just profile ig
that would require implementing both ๐
does numpy have a heap thing
I know it has np.partition
wait that uses introselect
that's pretty much quickselect
uh hi, so essentially for bfs i should use stack right? and dfs, i should be using recursion, i believe?
bfs needs a queue because the vertex you pushed in the earliest is the one you visit next
you can implement dfs via recursion yeah
and also via stacks
recursion uses a stack still, the call stack
ah right
(at least conceptually)
in some languages, recursion does get nice optimizations
maybe I should add a macro to add "(in python)" ๐
Any advice for learning algorithms? Im currently reading "Dive Into Algorithms" right now
Is there a built in function on method, where we can do a comparison that would return diffs of two strings?
Example:
string1 = "This is a test to see how does it work"
string2 = "This is a testofsorts to see how does it work"
diff1, diff2 = some_method(string1, string2)
diff1 >> test
diff2 >> testofsorts
I can see some complexity involved, if one string is longer than the other string, overlapping diffs might also be an issue.
So I didnt want to build it up from scratch if something like this already exists.
!d difflib
Source code: Lib/difflib.py
This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce information about file differences in various formats, including HTML and context and unified diffs. For comparing directories and files, see also, the filecmp module.
difflib, specifically.. ndiff sounds like it'd work for you
the functions there work on lists of strings. You seem to want diffs of entire words, so split your string into words and use that as the input.
oh sweet!! I'll look at difflib. Thank you!!
Both dfs and bfs can be implemented using almost exactly the same code, but you'd need a list/stack/lifo queue for dfs search and queue for bfs
def search(start_node: Node) -> Iterable[Node]:
structure = DataStructureOfYourChoice()
structure.add(start_node)
while structure:
node = structure.get()
yield node
for edge in node.edges:
structure.add(edge)
just started programming today and confused why this script isnt working
Name_Getter = input("What's your name :\n")
Lgth_Getter = (len(Name_Getter))
a = "there are "
b = + str(Lgth_Getter)
c = + "in your name"
d = a + b + c
print(d)
The unary + operator has no meaning on strings, so + str(Lgth_Getter) fails
Is there any way to ask for input but not validate the input? I want to make a bot, just for fun, that asks what you want on your burger and asks for input but doesnt actually value what the input is, he just has to want any input. I can send the code if necessary
Don't try to use unary + on strings. I don't really see what you mean by trying it, here.
this whole time i thought they were needed to show variables with print
Perhaps you meant += and not = +?
๐
No, you can print anything using print
So this is my code, don't wonder, the text is german. After "Welches Fleisch?" I dont want the code to value any specific input, just any input. How do I do that?
I dont want the code to value any specific input, just any input. - What do you mean?
I dont want any specific input, I just want the program to continue after it got input, no matter what it said
But then it wouldnt wait for input right
I want it to only continue after it got any input. If it didnt care about input it would just continie
Yess
Well
Kinda
Normally, I would say if Antwort == "word":
But I want the input, in this case "word" to not matter so whatever I send him he continues
You want to check if input is not empty? ๐
Just try to explain what kind of input you want to get
So the program asks me what kind of meat I want on the burger ("Welches Fleisch") And then asks for input. I give him any input, even if it makes no sense at all. The program only checks if it got input, doesnt matter what the input said and then continues with the code
Its pretty hard to explain further but Im trying my best
Even empty string would do?
e.g. "" or " "
What do you mean?
I give him any input, even if it makes no sense at all. - program should accepts empty strings too?
Nope, it has to be something
Just check for it's truthiness:
value = input("Input something: ")
value = value.strip()
if value:
print(f"Got value! - {value}")
All strings with length greater than 0 are truthy
You might want to use str.strip to strip any whitespace characters from your string
I probably should've said this early, but I'm pretty new to coding and especially python so I have never used strip and don't know how it works
No worries!
You can always read documentation for specific methods:
https://docs.python.org/3/library/stdtypes.html?highlight=str strip#str.strip
I really don't understand anything of that, even with the internet and trying to figure out how strip works. Could you perhaps simplify that program so I understand it? Or is that the simplest version?
You could just omit using strip, are you familiar with strings?
Strings are just sequence of characters, they can represent any textual data
You said this
Could I program it so it continues after I press enter
So I can type whatever I want and after I press enter it continues
So I'm completely avoiding the input value in form of text and just concentrating on if I pressed enter or not, no matter what I was typing
I think I'll just scrap that and write a lot of code featuring every possible outcome
That'll be fun
: |
Yes, just ignore value you're getting from input
How
Well, I did it now with if or
So no ignoring the value
Just multiple answers
Not what I wanted exactly but its fine
Thanks tho!
Your indentation is off
i started python today
idk what any of those means
what about as words
like
zero
didnt work
There shouldn't be any spaces before variable names
worked thanks!
just got another error
so how would u go about it if u were to make a script that separates the number and adds it
example
36
3+6
=9
what does it mean?
srry for wasting your time!
Does anybody know if this sorting algorithm has a name? Just made it up, trying to figure out if it is something new or not.
def weirdsort(li):
if not li:
return []
list_of_sorted_lists = [[li[0]]]
for i in li[1:]:
for sorted_list in list_of_sorted_lists:
if sorted_list[-1] <= i:
sorted_list.append(i)
break
if sorted_list[0] >= i:
sorted_list.insert(0, i)
break
else:
list_of_sorted_lists.append([i])
combined_sorted_list = []
while any(list_of_sorted_lists):
# this could be made a lot more efficient in a lower level language
combined_sorted_list.append(min(list_of_sorted_lists, key=(lambda i: i[0])).pop(0))
list_of_sorted_lists = [li for li in list_of_sorted_lists if li]
return combined_sorted_list
essentially you loop through the list a single time, turning it into a few sorted sub-lists
and then you merge the sub-lists by finding the smallest value over and over and re-building the list
I know it's not better than quicksort or any of the accepted sorting algorithms but I think it's kinda neat
Did some sample tests and it uses 101058ish one-to-one number comparisons to sort a random 10000 element list
insertsort took 20x as long and used 23683794 one-to-one number comparisons (235x as many)
obviously there will be some variations and I am making my algorithms teacher very sad by measuring complexity like this but
I don't think insertsort is a good comparison
If there aren't any existing algorithms that are too similar I'm ok with that, have been wanting to come up with my own algorithm since I started CS
even if it's not very good :-)
hey guys is this bubble sort?
def bubble_sort(array:list):
sorted = False
iterations = 0
while not sorted:
iterations = iterations + 1
for i in range(0,len(array)-1):
# Sort the list
if array[i] > array[i+1]:
temp = array[i]
array[i] = array[i+1]
array [i+1] = temp
sorted = True
# Check to see if list is sorted
for i in range(0,len(array)-1):
if array[i] > array[i+1]:
sorted = False
break
print('\n',iterations,'iterations')
return array
# [1,9,3,4,2,1]
if __name__ == '__main__':
data = [9,3,4,2,1,3,5,10,-1,23,120,1,-3,2]
a = bubble_sort(data)
print(a)
i wrote myself without looking at the book im reading. The books shows a different method
you dont need to return array, that's just extra space
but i think yeah it is bubble sort, even though id prefer two for loops (its shorter code)
def bubble_sort(elements):
iterations = 0
for i in range(len(elements)-1):
iteration += 1
swapped = False
for j in range(len(elements)-1-i):
if elements[j] > elements[j+1]:
elements[j], elements[j+1] = elements[j+1], elements[j]
swapped = True
if not swapped:
break
print(iterations)
I see.
Hey, I need some help, I had an assignment writing an algorithm with O(n) complexity and i can't decide if I done it right, can I send the code here?
what kind of algorithm?
I'm supposed to go through an array P and build array S such that s = { k | k <= index and P[j] <= P[index] such that j = i - k +1,..., i }
Is that good ?
and they advised to use stack to make it O(n)
hi community, can someone lead me into the right direction: i have a dataset with duplicate values, so at the moment I use df.groupby.sum() to deal with the issue. The problem is that some columns require other operatons than sum (in my case I would also need to average values, not only add them) and I have to drop them altogether. is there a way to perform sum() on some columns and average the other columns with df.groupby? Thank you!
Kunal Kushwaha
If I might make a suggestion, the best first step would be to write down what you are trying to do in english. Trying to decypher mathspeak and write code at the same time makes things a lot harder, especially because you can easily overlook some important details.
this seems vaguely related, I bet you could use the same technique
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
method #4 does it in O(N)
although method #5 could be more similar to what they want you to do, since they don't care about extra space complexity
Hi, I need to do a test with the calculation of points at the end. The test itself has already been done, but I do not know how to calculate. Now throw the code.
Hey @tulip crest!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Do not pay attention to the fact that some elements are in the Ukrainian language. Correct answers to 3 questions 1.a 2.ะฑ 3.ะฒ
Answers on the Russian layout
I hope for help, if you said something unclear, please contact.
Hi! I am a newcomer to Python. I am creating an app working with data got from remote CRM through API requests. The data returns in JSON format. I convert that into Python structures with json library, in particular it results in a list of dictionaries (a dictionary per each item). My question is what is the optimal way (timewise) to filter the data? The app uses a lot of filters which should update the outcome result constantly. Is pandas good for such a task? Any other tools? working with iteration through the list and dicts with standard Python tools seems to be a bit slow when it comes to updating the data array after any change of any filter
Afaik pandas is used for data analysis, it wouldn't be correct to use it to process your json data
You could send a sample of data and what kind of filters you want to apply to it so people can help
are the pinned posts here updated? or are there better sources for learning algorithms and data structures?
I strongly doubt that something fundamental about algorithms and data structures has changed over the last 9 months.
Although nowadays, you never know.
def test_this(param1:str, param2: str, param3:str):
print(param1)
print(param2)
print(param3)
param_1 = "This is param 1"
param_2 = "This is param 2"
param_3 = "This is param 3"
params = {"param1": param_1, "param2": param_2, "param3": param_3}
test_this(**params)
Instead of doing the above by using **params to pass in parameters as a dictionary. We can also do the below to pass in the paramters via a tuple??
def test_this(param1:str, param2: str, param3:str):
print(param1)
print(param2)
print(param3)
param_1 = "This is param 1"
param_2 = "This is param 2"
param_3 = "This is param 3"
params = (param_1, param_2, param_3)
test_this(*params)
!e
def test_this(param1:str, param2: str, param3:str):
print(param1)
print(param2)
print(param3)
param_1 = "This is param 1"
param_2 = "This is param 2"
param_3 = "This is param 3"
params = (param_1, param_2, param_3)
test_this(*params)
@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.
001 | This is param 1
002 | This is param 2
003 | This is param 3
yes, any iterable, in fact
What do you mean by any iterable?
A list, a string, a dict etc.
oh ok!!
This entire time I had been creating a dictionary to pass in multiple parameters lol. ok this is good!
well... very often named parameters are better
What does this do?
intersect(x + dx, y + dy, ax, ay + d_ay**2, False, False, True)
Yeah, I agree, but the paramters that I am passing in, I get their values few lines earlier.
i need to create an algo, looking for inspiration.. links, raw ideas plz.
say I have 5 jars, each jar has a limit of items..
some jars are full, some are not.
each item in the jars has ratings..
rating 1 chocolate type, milk, dark, white
rating 2 almonds, peanuts, cashews
ratings 3 rasberry, cream, coffee
and I would need to search all the jars and distribute the candy evenly.
Hello folks, hope everyone is having a great start to 2022.
And I'm back to DS and Algo's ๐ค
I'm currently doing 58. Merge Intervals on Leetcode
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals: return
intervals.sort()
res = []
for i in intervals:
if not res or res[-1][1] < i[0]:
res.append(i)
else:
res[-1][1] = max(res[-1][1],i[1])
return res```
This is both `O(n)` for runtime and spacetime correct?
no, intervals.sort will be at least n log n
hmm had a feeling about that
so its n log n runtime and O(n) spacetime
sounds about right
Age_Current = input("how old are you (in years):\n")
Age_Old = input("which age do you wanna live to (in years):\n")Age_months = Age_Current * 12
Age_weeks = Age_Current * 52
Age_days = Age_Current * 365
Age_hours = Age_Current * 365 * 24Age_Old_years = Age_Old - Age_Current
Age_Old_months = Age_Old *12 - Age_months
Age_Old_weeks = Age_Old * 52 - Age_weeks
Age_Old_days = Age_Old * 365 - Age_days
Age_Old_hours = Age_Old * 365 * 24 - Age_hoursprint(f"you have used ",{Age_months},"months of your life or,\n"
"you have used ",{Age_weeks},"weeks of your life or,\n"
"you have used ", {Age_days},"days of your life or,\n"
"you have used ", {Age_hours},"hours of your life.\n")print(f"you have ",{Age_Old_years},"years of your life or,\n"
"you have ", {Age_Old_months},"months of your life left or,\n"
"you have ", {Age_Old_weeks},"weeks of your life left or,\n"
"you have ", {Age_Old_days},"days of your life left or,\n"
"you have ", {Age_Old_hours},"hours of your life.\n")
how do i fix this?
this is my second day coding so use English
!e
Age_Current = input("how old are you (in years):\n")
Age_Old = input("which age do you wanna live to (in years):\n")
Age_months = Age_Current * 12
Age_weeks = Age_Current * 52
Age_days = Age_Current * 365
Age_hours = Age_Current * 365 * 24
Age_Old_years = Age_Old - Age_Current
Age_Old_months = Age_Old *12 - Age_months
Age_Old_weeks = Age_Old * 52 - Age_weeks
Age_Old_days = Age_Old * 365 - Age_days
Age_Old_hours = Age_Old * 365 * 24 - Age_hours
print(f"you have used ",{Age_months},"months of your life or,\n"
"you have used ",{Age_weeks},"weeks of your life or,\n"
"you have used ", {Age_days},"days of your life or,\n"
"you have used ", {Age_hours},"hours of your life.\n")
print(f"you have ",{Age_Old_years},"years of your life or,\n"
"you have ", {Age_Old_months},"months of your life left or,\n"
"you have ", {Age_Old_weeks},"weeks of your life left or,\n"
"you have ", {Age_Old_days},"days of your life left or,\n"
"you have ", {Age_Old_hours},"hours of your life.\n")
@gloomy wigeon :x: Your eval job has completed with return code 1.
001 | how old are you (in years):
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | EOFError: EOF when reading a line
!e
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
Age_Current = input("how old are you (in years):\n")
Age_Old = input("which age do you wanna live to (in years):\n")
Age_years = Age_Current * 1
Age_months = Age_Current * 12
Age_weeks = Age_Current * 52
Age_days = Age_Current * 365
Age_hours = Age_Current * 365 * 24
Age_Old_years = Age_Old - Age_years
Age_Old_months = Age_Old *12 - Age_months
Age_Old_weeks = Age_Old * 52 - Age_weeks
Age_Old_days = Age_Old * 365 - Age_days
Age_Old_hours = Age_Old * 365 * 24 - Age_hours
print(f"you have used ",{Age_months},"months of your life or,\n"
"you have used ",{Age_weeks},"weeks of your life or,\n"
"you have used ", {Age_days},"days of your life or,\n"
"you have used ", {Age_hours},"hours of your life.\n")
print(f"you have ",{Age_Old_years},"years of your life or,\n"
"you have ", {Age_Old_months},"months of your life left or,\n"
"you have ", {Age_Old_weeks},"weeks of your life left or,\n"
"you have ", {Age_Old_days},"days of your life left or,\n"
"you have ", {Age_Old_hours},"hours of your life.\n")
v
!e Age_Current = input("how old are you (in years):\n")
Age_Old = input("which age do you wanna live to (in years):\n")
Age_years = Age_Current * 1
Age_months = Age_Current * 12
Age_weeks = Age_Current * 52
Age_days = Age_Current * 365
Age_hours = Age_Current * 365 * 24
Age_Old_years = Age_Old - Age_years
Age_Old_months = Age_Old *12 - Age_months
Age_Old_weeks = Age_Old * 52 - Age_weeks
Age_Old_days = Age_Old * 365 - Age_days
Age_Old_hours = Age_Old * 365 * 24 - Age_hours
print(f"you have used ",{Age_months},"months of your life or,\n"
"you have used ",{Age_weeks},"weeks of your life or,\n"
"you have used ", {Age_days},"days of your life or,\n"
"you have used ", {Age_hours},"hours of your life.\n")
print(f"you have ",{Age_Old_years},"years of your life or,\n"
"you have ", {Age_Old_months},"months of your life left or,\n"
"you have ", {Age_Old_weeks},"weeks of your life left or,\n"
"you have ", {Age_Old_days},"days of your life left or,\n"
"you have ", {Age_Old_hours},"hours of your life.\n")
@fiery cosmos :x: Your eval job has completed with return code 1.
001 | how old are you (in years):
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | EOFError: EOF when reading a line
so how do we fix it
Age_Current = input("how old are you (in years):\n")
Age_Old = input("which age do you wanna live to (in years):\n")Age_years = Age_Current + str(0)
Age_months = Age_Current * 12
Age_weeks = Age_Current * 52
Age_days = Age_Current * 365
Age_hours = Age_Current * 365 * 24Age_Old_years = Age_Old - Age_years
Age_Old_months = Age_Old *12 - Age_months
Age_Old_weeks = Age_Old * 52 - Age_weeks
Age_Old_days = Age_Old * 365 - Age_days
Age_Old_hours = Age_Old * 365 * 24 - Age_hoursprint(f"you have used ",{Age_years},"years of your life or,\n"
"you have used ",{Age_months},"months of your life or,\n"
"you have used ",{Age_weeks},"weeks of your life or,\n"
"you have used ", {Age_days},"days of your life or,\n"
"you have used ", {Age_hours},"hours of your life.\n")print(f"you have ",{Age_Old_years},"years of your life or,\n"
"you have ", {Age_Old_months},"months of your life left or,\n"
"you have ", {Age_Old_weeks},"weeks of your life left or,\n"
"you have ", {Age_Old_days},"days of your life left or,\n"
"you have ", {Age_Old_hours},"hours of your life.\n")
try:
for period, coef in zip((months, weeks, days, hours), (12, 52, 365, 365 * 24)):
print(f'you have used {Age_Current * coef } {period} of your life')
where?
try this loop instead of printing 4 different lines for months, weeks, etc
!e
Age_Current = input("how old are you (in years):\n")
Age_Old = input("which age do you wanna live to (in years):\n")
for period, coef in zip((months, weeks, days, hours), (12, 52, 365, 365 * 24)):
print(f'you have used {Age_Current * coef } {period} of your life')
@gloomy wigeon :x: Your eval job has completed with return code 1.
001 | how old are you (in years):
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | EOFError: EOF when reading a line
you can use for both or change and use one loop for everything
and you have to use int() to get an int from a string. like int(input()) or later int(Age)
!e
Age_Current = int(input("how old are you (in years):\n"))
Age_Old = int(input("which age do you wanna live to (in years):\n"))
for period, coef in zip(('months', 'weeks', 'days', 'hours'), (12, 52, 365, 365 * 24)):
print(f'you have used {Age_Current * coef } {period} of your life')
@gloomy wigeon :x: Your eval job has completed with return code 1.
001 | how old are you (in years):
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | EOFError: EOF when reading a line
!e
Age_Current = int(input("how old are you (in years):\n"))
Age_Old = int(input("which age do you wanna live to (in years):\n"))
for period, coef in zip(('months', 'weeks', 'days', 'hours'), (12, 52, 365, 365 * 24)):
print(f'you have used {Age_Current * coef } {period} of your life')
@gloomy wigeon :x: Your eval job has completed with return code 1.
001 | how old are you (in years):
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | EOFError: EOF when reading a line
weird. it works in pycharm
N = int(input())
candie = 0
for i in range(1, int(N**0.5) + 1):
if N % i == 0 and i % 2 == N // i % 2:
candie += 1
print(candie)
currently only printing how many candie packet combination are possible(so output is 3 now) i want to print that packets like for 45, 3 combination are possible so, output will be {5,7,9,11,13}, {13,15,17}, {45}. how can i do that?
[
{
"id": "15880",
"code": "662621341",
"brandId": "119",
"modelYearCode": "2021",
"modelCode": "234",
"bodyCode": "base",
"complectationCode": "R5",
"packageCode": "8D234R5",
"statusCode": "RD",
"colorCode": "71700",
"trimCode": "RC0000",
"vin": "LVYPS08ADMP099980",
"mpv": "23408R50D173",
"keyNumber": null,
"inStock": "1",
"sold": "1",
"deleted": "0",
"readyForReleaseDate": "2021-12-02 16:47:34",
โฆ
},
{
"id": "15880",
"code": "662621341",
"brandId": "119",
"modelYearCode": "2021",
"modelCode": "234",
"bodyCode": "base",
"complectationCode": "R5",
"packageCode": "8D234R5",
"statusCode": "RD",
"colorCode": "71700",
"trimCode": "RC0000",
"vin": "LVYPS08ADMP099980",
"mpv": "23408R50D173",
"keyNumber": null,
"inStock": "1",
"sold": "1",
"deleted": "0",
"readyForReleaseDate": "2021-12-02 16:47:34",
โฆ
},
โฆ
] It's a list of cars. I need to be able to apply filters on engines, models, colors, ect. And it is need to be possible to apply them in combination at the same time
interesting. but there will be a lot more combinations. like 15, 15, 15; 45 x1. or there are some limitations?
The question is what tool to use. I am not sure if pandas is a good choice for a mobile app
what do you use for this app develpoment?
kivymd
you want to avoid using MDDataTable?
it's not the way of display I need
What is the best way given a unique ID input as a Constructor to identify whether or not an object with that ID already exists and if so to access that object instance? I have my own method of doing this currently but it does not seem as clean or efficient as I suspect is possible with a truly pythonic solution. Any ideas?
For reference, my current solution is to create a dictionary with the ID as the key and the object itself as the value, it grabs the object from the ID when a request is made but requires a bunch of conditionals and the method itself is less cohesive then I would like. Is there a better solution or am I stuck with this sort of dictionary storage pattern?
What's the issues with the current method?
I have hundreds of waypoints (x,y), how could I sort them to get the most efficient route ?
through all of them?
yes through all of them, Ive read about Dijkstras algorithm, but Ive only found it with one unit X (e.g. meters), so to speak , whereas my coords are X,Y(Latitude,Longitude)
look up the traveling salesman problem, you should find resources that can help
you could use a premade solver
whats a 'premade solver' ?
I guess a better way to say this is , that most samples only use vertices
this is such a common problem that there are solver APIs you can use
this leads to the question how to create a graph for this purpose , guess a simple line equation to calc the distance should be more than enough
and not have the lines crossing over
any good resources you folks recommend for bit manipulation?
I dont know how to normalize, calculate variance, or run algos on my data
because i do not understand my data, and i need help to understand it
does anyone here work with audio processing?
hi.
im new to python programming, and i was wondering if there is anyone who can help me with a problem
You might find a Digital Signal Processing Book helpful
If your application involves noise reduction read about filters and convolution topics..
Any good resources for learning two pointer technique?
these books wont help me
neither will filters
i am not trying to design a filter
I want to talk to someone who understands my data, i do not wish to understand it myself. it is far too complicated for me, i have anxiety attacks just functioning at my own level. it is not a complex application.
You may have to hire someone then
Probably lol
whats the problem?
Is it related to algorithms
Or ds
how would you make a sliding window of dimensions [1, 2] over a 2d array?
sliding window?
just a sec
a regular sliding window goes like this
a sequence 1,2,3,4 a sliding window gives the pairs 1,2 2,3 3,4
but i want a sliding window that goes over a 2d array vertical so this
0, 1, 2,
3, 4, 5,
6, 7, 9
i want the pairs
0, 3
3, 6
6, 1
1, 4
4, 7
7, 2
2, 5
5, 9
The first element of the t'th pair should be
x(t) = t // 3
y(t) = t % 3
myList[x(t)][y(t)]
and the second element, is just t+1
In [7]: a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [8]: from itertools import tee, islice
In [9]: def pairwise(iterable):
...: a, b = tee(iterable)
...: return zip(a, islice(b, 1, None))
...:
In [10]: def sliding_window_1_2(iterable):
...: for a, b in pairwise(iterable):
...: yield from zip(a, b)
...:
In [11]: list(sliding_window_1_2(a))
Out[11]: [(1, 4), (2, 5), (3, 6), (4, 7), (5, 8), (6, 9)]
nope
huh?
that's a sliding window, dunno what else you need
this doesnt match the behavior that i described
^^^
dude, I told you how
well, i'm sure you have enough information to figure it out now
wdym by that?
and ive done that
send screenshot of the pairs
I think that'd be easier for me to understand
I didn't try the code myself
2d array
1,2
3,4
i want the pair values. (these are not indexes)
1,3
3,2
2,4
aaaaand, what do you get?
this doesnt go over the boundary
that's not right
do you make sure to increment t only by one, for each new pair?
yeah, show the code actually
wait now i think you might be right but i dont know hold on lemme think.
you flip the columns and rows which is correct
alright imma rewrite it.
maybe i was just thinking about it wrong.
i got it to work but you made it seem simple
In [23]: a = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
In [24]: def sliding_window_1_2(iterable):
...: transpose = zip(*iterable)
...: flat = chain.from_iterable(transpose)
...: a, b = tee(flat)
...: return zip(a, islice(b, 1, None))
...:
In [25]: list(sliding_window_1_2(a))
Out[25]: [(0, 3), (3, 6), (6, 1), (1, 4), (4, 7), (7, 2), (2, 5), (5, 8)]
cool i implemented it your both correct. idk why i was having a issue with it
I got x and y in the wrong order, didn't I?
but glad it's working
no your completely right
ah okay
you swapped them
but i think it was becuase i was working with a larger algorithm that used this that i got confused
im embaressed on how simple it was
Hi peoples! I'm puzzling with a data structure challenge:
I want to make a system to serialize and deserialize product codes.
e.g. ENG-PUMP-CENT-SS-DN50 turns into:
- Dropdown 1: Engineering Items
- Dropdown 2: Pump
- Dropdown 3: Centrifugal Pump
- Dropdown 4: Stainless Steel
- Dropdown 5: Size DN50
Each dropdown has multiple choices, each choice can lead to a different dropdown. The system should go from code to full description and also the other way around. I wanted to try out some kind of graph representation. Good idea or bad idea?
A tree maybe?
Where each node has both the code and full description
I suppose trees are technically directed graphs too, so...
you may want to check me on this. I bassically did what you did before asking this but i think you need to divide and modulus by the max_row instead of the max_column like usually. it doesnt matter for square ones but for rectangles the math works out that way.
soemthing like
i = n // rows;
j = n % rows;
you swap them and use rows instead of columns.
You're right. The number of rows, is how elements are in a column. And, since we're scanning from the first column and down along it...
some person on twitch did it like this.
int *arrLast = NULL;
int *baseRow = arr;
int height = size / width;
int cWidth = width;
while(cWidth--)
{
int i;
for(i = 0; i < height; i++)
{
if(arrLast)
{
printf("%d, %d\n", *arrLast, *arr);
}
arrLast = arr;
arr += width;
}
arr = ++baseRow;
}
This is for a 2d indexed array though
Right, as in he's using stride right?
but thanks for helping. im embarresed that i thought this was so complicated.
glad I could help
what are algs and data-structs that i should be familiar with for interviews
check the pins
sturgling to comeup with a way to process data in 1 function, that doesnt requie an if statement to sort each classification..
classifications
priority 1, secondary
priority 1, tertiary
priority 2, secondary
priority 2, tertiary
repeated till
priority 5, septenary
print("Welcome to the Love Calculator")
name1 = input("What is your first and last name?\n")
name2 = input("What is their first and last name?\n")
love = {
"T",
"t",
"R",
"r",
"U",
"u",
"E",
"e",
"L",
"l",
"O",
"o",
"V",
"v"
}
Love_percentage = 0
named_1 = str(name1) #i tried turning them into str
named_2 = str(name2)
Lover = len(named_1+named_2[love])
Lovers = int(Lover)
Love_percentage = 100 / Lovers * 10
print(f"you are a %{Love_percentage} match with your crush")
its my 4th day coding
so please talk english
i have been getting help from here for as long as the dinosaurs have lived.
i have never gotten help from here, but i have given it quite a few times.
print("Welcome to the Love Calculator")
name1 = input("What is your first and last name?\n")
name2 = input("What is their first and last name?\n")
love = {
"T",
"t",
"R",
"r",
"U",
"u",
"E",
"e",
"L",
"l",
"O",
"o",
"V",
"v"
}
Love_percentage = 0
named_1 = str(name1) #i tried turning them into str
named_2 = str(name2)
Lover = len(named_1+named_2[love])
Lovers = int(Lover)
Love_percentage = 100 / Lovers * 10
print(f"you are a %{Love_percentage} match with your crush")
why doesn't this work?
this channel is for data structures and algorithms, please ask your question in a help channel
it is that in a way
:/
What's the fastest way to perform face recognition? I tried using face_recognition but it was too slow for my use case.
Doesn't that depend on which model you use? It's more like a #data-science-and-ml if I'm not mistaken. Also do mention to people what is face_recognition here. The origins of this function i think.
Hey, could you elaborate?
i got it sorted it out i think, just needed to create a couple of flags to sperate catagories.
could anyone provide me with an implementation of the deque class in python?
Hey I have problem with implementation of bst delete function. If I try to delete a node from left side, instead of deleting that particular node, it's deleting the entire sub tree. Same with node containing at the right side, it'll delete entire subtree.
def delete(self, root, value):
if root is None:
print("Tree is empty")
return
elif value < root.value:
root.lnode = self.delete(root.lnode, value)
elif value > root.value:
root.rnode = self.delete(root.rnode, value)
else:
if root.lnode is None:
temp = root.rnode
root = None
return temp
if root.rnode is None:
temp = root.lnode
root = None
return temp
else:
Node = root.rnode
while Node.lnode:
Node = Node.lnode
root.value = Node.value
root.rnode = self.delete(root.rnode, Node.value)
return
if name == 'main':
bst1 = BST()
l = [19,2,3,65,6,9,41,45,63,58,87,89,98]
root = Node(50)
for i in l:
bst1.insert(root,i)
bst1.postorder(root)
bst1.delete(root, 9)
print("\n")
bst1.postorder(root)
output
9 6 3 2 45 41 19 58 63 98 89 87 65 50
58 63 98 89 87 65 50 (after deletion of 9 which lies in left side of root)
Here's the code.
Any help would be amazing.
if you replace the node pointer to None all the subtree will be deleted, you can to put a child in its place
For this question, is it enough to use sorted() and check the equality to see if they're the same or do I need to iterate through one list and check with the other after both are sorted?
Check Permutation: Given two strings,write a method to decide if one is a permutation of the
other.
Is this good enough
def checkPermutation(s1, s2):
return sorted(s1) == sorted(s2)
Hello folks, currently doing 438. Find All Anagrams in a String on Leetcode
I was having trouble solving it, so I looked up the solution
I found this sliding window solution
def findAnagrams(self, s: str, p: str) -> List[int]:
start = 0
dic_pattern = collections.Counter(p)
dic_s = {}
result = []
for end in range(len(s)):
if s[end] not in dic_s:
dic_s[s[end]] = 1
else:
dic_s[s[end]] += 1
if dic_s == dic_pattern:
result.append(start)
if (end - start +1) >= len(p):
if dic_s[s[start]] > 1:
dic_s[s[start]] -= 1
else:
del dic_s[s[start]]
start += 1
return result ```
I'm having trouble understanding this part
```py
if dic_s[s[start]] > 1:
dic_s[s[start]] -= 1
else:
del dic_s[s[start]]```
Is this basically checking that we don't use the same characters again and again?
Yes, it save characters as dict with count. There it minus in every step if it left 1 it will delete dict key
use the Counter() one its easy
Hi All,
I have probably a basic query but i cant see to figure it out.
I have a dict nested in the key of a dict.
data = { '{"request_id":5300353,"token":"value".....} : "value" }
Im trying to update "request_id" value but i cannot call it since its the key of my initial dict.
( next(iter(data)) ) # 'Key1'
returns the nested value.
But i cant do anything with this then.
print(list(data.keys())[0])
also gives me the nested value, but list converts it to string so again i cant do anything.
also since its outputting the key only, i cant convert back to dict (easily)
Plus its in the original data i need to make updates so ideally dont want to export a splice of the file as a variable.
A) some dictionarys are hashable.
B) you could use ast.literal_eval or json.load to convert the dictionary like string into a dictionary. Allowing you to parse it like any other dictionary.
C) Simpler solution - just swap the pair. Let the value be the key, and the dict be the value of it.
d = {"value": {"request_id": ... } }
I loaded a string and replaced
I tried c. Invert the key/value pairing. But the dict inside it is considered a string when I load it.
See part B.
Yup. B worked.
๐
some dictionarys are hashable.
which ones?
Its possible to pack and unpack a dictionary into a hashable object. technically a hashable dict O.o
i.e. NamedTuple, or frozendict (PyPi) 
({"foo": 1},) is not hashable
I'm not sure what you mean
well, NamedTuple isn't really a dict - it doesn't support arbitrary keys
but yeah, you can use frozendict or better immutables.Map
Where do you get this weirdly shaped data from?
if you have a stringified dict as a key, you're probably doing something wrong somewhere else
d = {"foo": 1}
# packing
t = tuple(d.items()) # ( ("foo", 1), )
# unpacking
new_d = dict(t) # {"foo": 1}
well, you're stretching the definition of a dict ๐
actually, frozenset would be better here
because {"foo": 1, "bar": 2} and {"bar": 2, "foo": 1} should be equal
Yes. It will be the better option.

can I slice a numpy array by byte start and end instead of element indices?
i have no idea if you can, but i'm curious why it would be useful to
it's sorta like a linked list, but instead of each node having 1 child, it has any amount of children
how can I check is a words starts with a specific letter in context of if and else
Im using this: if string.startswith(letter): #action, will it work?
@jade oak :white_check_mark: Your eval job has completed with return code 0.
ho
oaky! thank you
some databases use something called a HAMT, which is just a really fancy tree
i think others use Btrees
no, it would just loop over the list and find the max
Headers for a request. So it's not normal python formatting and ended up not being a proper dict that I could reference which is why I was having issues.
Where does the dict being a key come in though?
Why do you need a dict?
Hey @round glacier!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
json is stricter. it may work in some cases. one common failure is that it rejects strings using single quotes, which is what Python uses in its repl of strings in dicts
In that specific case it does look like json would be okay
.
@placid geode
Possibly you can use ndarray.astype with copy set to False - not sure.
:incoming_envelope: :ok_hand: applied mute to @patent spire until <t:1641824427:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
lets say i have a list 3x3
and I want to go 1,1 -> 1,2 -> 1,3 -> 2,3 -> 3,3 -> 3,2 -> 3,1 -> 2,1
so basically cycle around 2,2 item. Any advice how to approach this?
Oh so you just want to go around the perimeter?
Hmm, what is a good way to do this? ๐ค
I guess you could have "walls" and treat it like a state machine. The state is the current position and direction. You keep moving forward, until you hit a wall, where you turn right.
So something like this:
!eval ```py
def is_wall(position):
r, c = position
return (r in (0, 4)) or (c in (0, 4))
def vadd(u, v):
return (u[0]+v[0], u[1]+v[1])
def turn_right(direction):
dr, dc = direction
return (dc, -dr)
position = (1, 1)
direction = (0, 1)
for i in range(20):
print(position, direction)
if is_wall(vadd(position, direction)):
direction = turn_right(direction)
position = vadd(position, direction)
@keen hearth :white_check_mark: Your eval job has completed with return code 0.
001 | (1, 1) (0, 1)
002 | (1, 2) (0, 1)
003 | (1, 3) (0, 1)
004 | (2, 3) (1, 0)
005 | (3, 3) (1, 0)
006 | (3, 2) (0, -1)
007 | (3, 1) (0, -1)
008 | (2, 1) (-1, 0)
009 | (1, 1) (-1, 0)
010 | (1, 2) (0, 1)
011 | (1, 3) (0, 1)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/cugocoluwa.txt?noredirect
@grave warren This probably seems like over-kill, but this approach is general enough to be extended in various ways.
Yep it is. Check out the C code for it, if you know C, it's surprisingly readable.
It's a doubly linked list. But each node in the list is actually an array that contains several items.
Yeah I'll find it for you.
It might have enough comments that you can understand it without knowing C.
Yeah essentially. It's kind of like a namedtuple in python, if you know about that.
Actually, there's two things going on there.
A struct definition, and a type definition.
They're often combined into one statement.
Yeah actually it's like a class with attributes and no methods.
I think it's worthwhile fwiw ยฏ_(ใ)_/ยฏ
It's a ubiquitous language, it's very relevant to Python, and it's also a relatively small language so doesn't take too long to learn (except maybe pointers if you find them tricky).
Yeah fair enough ๐ I'm often guilty of not managing my time well, so don't take my advice.
def combination_sum(candidates, target):
if target == 0:
return [ ]
if target < 0:
return None
for num in candidates:
remainder = target - num
remainder_result = combination_sum(remainder, candidates)
print(remainder)
print(combination_sum([1,2,3,], 6))
Traceback (most recent call last):
File "main.py", line 13, in <module>
print(combination_sum([1,2,3,], 6))
File "main.py", line 10, in combination_sum
remainder_result = combination_sum(remainder, candidates)
File "main.py", line 5, in combination_sum
if target < 0:
TypeError: '<' not supported between instances of 'list' and 'int'
idk what's going on here... it's comparing b/w list and int?
i don't get this
def combination_sum(candidates, target):
if target == 0:
return [ ]
if target < 0:
return None
for num in candidates:
remainder = target - num
remainder_result = combination_sum(candidates, remainder)
if remainder_result != None:
return [*remainder_result, num]
print(remainder)
print(combination_sum([1,2,3], 6))
@old rover Did you mean to swap the arguments?
just caught that
Yeah, looks like you figured it out.
Is it working?
I feel it might make more sense to build up the list as you recur ๐ค
yeah it's still not working
i was trying an approach i learned from freecodecamp
yeah no
didn't work
I have a project. Implementation & display of Bubble Sort algorithm using Turtle library. Do you have any ideas?
not sure if this is the right place to ask but does anyone have a fast way to write a function that takes in a 2d array of coordinates and then outputs a 3d array of the original array minus each value? So using a for loop
input = np.zeros([m, 2])
output = np.zeros([m, m, 2])
for i in range(m):
output[i, :, :] = input - input[i, :]
im looking for a way to vectorise this though
Do you have a better solution? Either faster or uses less memory, and no libraries.
def n_ranges(begin: int, end: int, n: int) -> tuple[tuple[int, int]]:
"""
Divides an inclusive range: begin..end to n smaller ranges similar in size (the difference (end - begin + 1) in the ranges returned by n_ranges(1, 100, 10) is 10 for all of them).
:param begin: the first number in the range
:type begin: int
:param end: the last number in the range
:type end: int
:param n: the number of ranges to split from the range and to return
:type n: int
:return: a tuple of smaller range tuples with similar sizes
:rtype: tuple[tuple[int, int]]
"""
ranges = []
inc: int = (end - begin + 1) // n
i: int = 0
curr_begin = begin
curr_end = begin + inc - 1
while i + 1 < n:
ranges.append((curr_begin, curr_end))
curr_begin = curr_end + 1
curr_end = curr_begin + inc - 1
i += 1
ranges.append((curr_begin, end))
return tuple(ranges)
The intention was to split an inclusive range for n threads to find all of the prime numbers in the range.
This is a homework exercise, but as I have already come up with a solution for this exercise I'm just curious how you would do this.
do you know about the GIL? ๐
I prototyped this in Python, it's for C++
ah
It will work with multiprocessing in Python, though, right?
If we're talking about a massive range like 0..1000000 (range(int(1e6) + 1))
So if I use 16 processes (I don't know what's good for this), it will be fast, right?
In one thread it did it in about 9.5 minutes in C++
what is the problem about?
that sounds really slow for primes up to 1 million. Are you using Eratosthenes' sieve?
Basically, write a function writePrimesToFile(begin, end, n) which will split begin..end to n ranges and search in n for prime numbers and write them into a file
I don't know.
def is_prime(n: int) -> bool:
if n < 2:
return False
if n == 2:
return True
if n & 1:
for i in range(3, int(n ** 0.5) + 1, 2):
if not n % i:
return False
return True
return False
that's not eratoshenes's sieve, it's the divisor checking method
I think more than this would be overkill for homework
What could I do better?
your method takes O(sqrt(n)) for each number, which is a total of O(n^(3/2)) for all primes up to n
eratosthenes' sieve takes very slightly above O(n) (something like O(n log log n)) for all primes up to n
import math
def n_ranges(begin: int, end: int, n: int) -> list[range]:
chunk_size = math.ceil((end - begin) / n)
base = range(begin, end + 1)
ranges = [base[i*chunk_size : (i+1)*chunk_size] for i in range(n)]
if (end - begin) % n:
[*first, last] = ranges
ranges = [*first, range(last.start, end)]
return ranges
``` ๐
D:\Programming\Rust\primes\target\release>primes.exe 1000000
Elapsed:0.004842067s
Head:[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Tail:[999863, 999883, 999907, 999917, 999931, 999953, 999959, 999961, 999979, 999983]
Length:78498
my Eratosthenes' sieve implementation in Rust takes around 5ms to do this, it looks like
(It's single-threaded, for that matter)
Milliseconds?
yeah
It really isn't, eratosthenes' sieve is fairly simple:
pub fn prime_sieve(n: usize) -> Vec<usize> {
if n < 2 {
vec![]
} else if n == 2 {
vec![2]
} else if n < 5 {
vec![2, 3]
} else {
let mut not_primes: Vec<bool> = vec![false; n + 1];
let mut results: Vec<usize> = vec![2, 3];
let mut end = n.integer_sqrt();
if end % 2 == 1 {
end += 1; // guarantees end being even
}
for k in (5..n + 1).step_by(6) {
for &i in &[k, k + 2] {
if !not_primes[i] {
results.push(i);
if k <= end {
for j in ((i * i)..(n + 1)).step_by(i) {
not_primes[j] = true;
}
}
}
}
}
results
}
}
(basically, every time you detect that k is a prime, you mark 2*k, 3*k up to n as not primes. Then whenever you encounter an unmarked number, it must not be a prime.
(I'm also checking 2 numbers out of every 6, which is a nonobvious optimization; a simpler idea would be to check only odd numbers)
(The reason it works is because: there are 6 possible remainders of division by 6, from 0 to 5.
- The even remainders go straight out, because then the number is even. We are left with 1,3,5.
- 3 can also be thrown out because then the number must be divisible by 3
so we can only check numbers with remainder 1 or 5 under division by 6)
Why did it take so much? I tried it in Python and it works in like 5 seconds
You must have implemented it wrong somehow, then
try also removing threading, but I doubt that's the reason
more likely you're redoing some expensive calculation for each number or something.
Let me look at my C++ code
Hey @slender sandal!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
The Python script that is supposed to copy its behavior is this https://paste.pythondiscord.com/zuwuneseto.py
Oh I didn't realize I didn't use n_ranges ๐
What's the C++ code?
the Python code looks fine
<@&831776746206265384>, here again
!pban 870500198865055785 nsfw
:ok_hand: applied purge ban to @chilly crescent permanently.
Though note that in Python, threading for this is useless
because this is a CPU-bound task, and threading is limited to one actual CPU thread
you'd need multiprocessing, which, note, has a lot of overhead
Yeah, increasing the number of threads in Python does nothing but increase the number of seconds it takes.
What object do I use to store the numbers using multiprocessing?
wdym?
with processes, you don't have shared memory: you pass messages from one process to another.
you'll have to use something like multiprocessing.Queue/Pipe
concurrently writing to a file?
make each process write to its own file, that will be 1000 times easier
I'd suggest using Pool.map
I'm all ears
it'll automate stuff like splitting for you
also that, yeah
I don't have that in C++
!docs multiprocessing.pool.Pool.map
map(func, iterable[, chunksize])```
A parallel equivalent of the [`map()`](https://docs.python.org/3/library/functions.html#map "map") built-in function (it supports only one *iterable* argument though, for multiple iterables see [`starmap()`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.starmap "multiprocessing.pool.Pool.starmap")). It blocks until the result is ready.
This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. The (approximate) size of these chunks can be specified by setting *chunksize* to a positive integer.
Note that it may cause high memory usage for very long iterables. Consider using [`imap()`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.imap "multiprocessing.pool.Pool.imap") or [`imap_unordered()`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.imap_unordered "multiprocessing.pool.Pool.imap_unordered") with explicit *chunksize* option for better efficiency.
Cool
So, what does your C++ code do?
this
Threaded
n threads
I believe order doesn't matter
I don't see how it can possible take minutes instead of Python's seconds unless it's doing something really weird, that's why I'm asking
number-crunching is something Python is really bad in, so even a naive solution in C++ should be way faster
by the way, if all your threads write to the same file one number at a time, taking a lock, that'd basically mean only one thread can ever work
I open it once
because calculating each prime will probably take less time than waiting for the lock
I don't need a clock for this
I'd instead collect all primes to a list, and only write it to the file later, or at least write in chunks
Or at least, I could wait until I have one thread with all of its primes found and then let it write all it found
That said, even this shouldn't be that slow
even a one-threaded solution should be fast
use std::time::Instant;
fn main() {
let start = Instant::now();
let v:Vec<_> = (0..1_000_000u64).filter(|&x|is_prime(x)).collect();
println!("{}", start.elapsed().as_secs_f64());
}
fn is_prime(n:u64) -> bool{
if n < 2 {
false
} else if n == 2 || n == 3 {
true
} else if n % 2 == 0 || n % 3 == 0 {
false
} else {
let end = (n as f64).sqrt() as u64;
for i in (5..end + 1).step_by(2) {
if n % i == 0 {
return false;
}
}
true
}
}
This takes 7s on a debug build and 170ms on a release one - no threading here, though this doesn't write to a file
as if it's uncommon ๐ฅด
one day I'll casually dump a wall of Rust code into pygen and ask for help because it's for a PyO3 library ๐ฅด
i must resist
I honestly don't know what I did then with the C++ code
Single-threaded takes about as much time as Python
lol, just now I was wondering why my rust solution is taking forever
turns out I typoed, wrote 0.. and was trying to find all primes up to infinity (well, to u64::MAX)
okay, there
0.193565583s to calculate the primes
1.113025647s to write to file
single-threaded Rust solution which uses the is_prime above
fn handle(max_n:u64) {
let start = Instant::now();
let v:Vec<_> = (0..max_n).filter(|&x|is_prime(x)).collect();
println!("{}s to calculate the primes", start.elapsed().as_secs_f64());
let before_dump = Instant::now();
let mut file = OpenOptions::new().write(true).truncate(true).create(true).open("primes_dump.txt").unwrap();
for (i,v) in v.into_iter().enumerate(){
if i>0{
file.write(b"\n");
}
file.write(v.to_string().as_bytes());
}
std::mem::drop(file);
println!("{}s to write to file", before_dump.elapsed().as_secs_f64());
}
wait just get nightly and do cargo bench ๐
right i'm just saying the jupyter xp in general
not slower than cargo in my experience
cool
it's the https://github.com/google/evcxr one
(which I always forget the name of. excvr? evxrc?)
now, lemme try threading
how would you thread this? just assign different threads different ranges?
My first idea would be to not think at all
and use rayon's map ๐ฅด
for 10 million without threading,
4.907431416s to calculate the primes
8.359831334999999s to write to file
rayon is so cool
Oh hey, 2.226988256s to calculate the primes using rayon
was as simple as a (0..max_n).into_par_iter().filter(...)
that's on my CPU which has, like, 2 physical cores
let me try
Good god C++ is fast
I wonder what's the right way to parallelize the writing
lemme try making proper threads
0..1000 ten threads
for such a small range the threads might be too much overhead
0..1000000
I'm reminding you my method of finding prime numbers is wacky
Validating*
that seems on the slow end still, tbh
I know
Let me try up to nine billion and with sixteen threads
I should have probably done something smarter
It's taking forever
i mean, no wonder, you have O(n^(3/2)) complexity
so 1s for 1 million implies ~853ย 814s for 9 billion
Oh these are a lot of seconds
I'm not waiting that
0..1000, 0..100000 and 0..1000000
So threading is actually better for... a lot of numbers
A single thread performed way better on 1,001 numbers
that's fairly strange, it's faster for me to use threads even for one million
It is faster for me in 1,000,001 numbers
Are you using my algorithm?
For validating primes
yes, basically it ^
So if we wanted to merge dictionary1 and dictionary2, would folowing be some of the ways to do it:
both_dictionaries = dictionary_one | dictionary_two
both_dictionaries = {**dictionary_one, **dictionary_two}
I dont know what |, except that it's a bitwise operator.
how does this approach work both_dictionaries = {**dictionary_one, **dictionary_two}, does it deconstruct both dictionaries?
If python doesn't do any magic behind the scenes then yes ๐ค
You could read about dict unions here: https://www.python.org/dev/peps/pep-0584/
hi everyone, Can someone help me on my project? I am stuck on it
Not sure if this belongs here but
Whatโs the diff between def functions and a class ?
anyone familiar with pywinauto
You have any code?
yeah
just created a matrix
can you help me solve this question further
You should store individual numbers as integers, not as strings
Also i don't really understand what it wants you to print on the second line
what language is it?
rust
can anyone suggest some resource to learn data structure and algos and kinda give roadmap
thanks buddy
After finishing that playlist, is one adequately equipped with everything they need to move onto leetcode?
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = [ ]
def dfs(i, cur, tot):
if tot == target:
res.append(cur.copy())
return
#if the total is equal to the target, append the current list to the resultant list
if i >= len(candidates) or tot>target:
return
#base case
cur.append(candidates[i])
dfs(i, cur, tot + candidates[i])
cur.pop()
dfs(i+1, cur, tot)
dfs(0, [], 0)
return res
i don't understand backtracking
actually no, it is starting to make some sense
Thanks that was helpful.
But what does it mean when the docs say:
Dict Union Is Lossy
Dict union can lose data (values may disappear); no other form of union is lossy.
Does it mean, if we have duplicate keys, then the value stored in the right dictionary will take precedence?
!e
dictionary1 = {"key1": "value1", "Key2": "value2"}
dictionary2 = {"key1": "value7"}
merged = {**dictionary1 , **dictionary2 }
print(merged)
@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.
{'key1': 'value7', 'Key2': 'value2'}
yep, unlike in a set, where all elements are preserved
I personally don't see a big need in | for dicts
Oh no I'm sorry, I think it when it says Dic Union is Lossy, it's referring to pipe |
This is an example of dict unpacking.
How are all elements preserved in a set? Doesnt set only store unique elements?
Maybe you meant a list/array?
I meant in the context of a union
A set union doesn't drop any elements
well, I don't think it's a great argument
you could technically have two different objects that hashed and eqed the same, but had different satellite data. and you'd lose that data
oh ok I see what you mean.
dictionary's key is mapped to a value. One key can only have one value. So if we have two keys that are the same then one will be dropped.
Set only stores unique values. So we dont have to worry about it dropping anything.
that was his reasoning yeah
I know I will get a lot of hate for even saying thing, but wondering if they considered using plus + operator instead.
I think that would have been a lot of work and rewrite on top of current code base they have for + operator.
+ was also an option
but the operation is more a dict union than a dict concatenation
so the | operator, which is already a set union, makes more sense IMO
it wouldn't be a lot of effort to make it the + operator
the callback would just be in different slots
Is the notion for | on a set/dictionary compared to two nums, so:
!e
merged = 24 | 3
print(merged)
@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.
27
if you imagine an integer as a bitset, it is also union
and well, or is a very similar operation to union
either it's set in the left, or in the right, or in both
it being a bit, or a set element
So pipe | used in this context is called OR from bitwise?
But pipe | used in the context of dictionary or set is called Union Operator?
it's pretty much always the bitwise or operator
but it gets overloaded for unions as well
Oh I think I see what you mean.
- operator is used for adding nums, but it gets overloaded so it can concatenate strings or lists/arrays together.
So the | or operator is like that, it gets overloaded for union?
more or less
So when we merge two dictionaries or two sets together, using dict unpacking {**d1, **d2} or union operator | both would give us the same result?
what ways are there for a graph to not have a valid mst
Source code: Lib/csv.py
The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to attempts to describe the format in a standardized way in RFC 4180. The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.
@idle pier You can read from stdin incrementally, line by line.
Then split each line.
you know about input()?
input() reads a line from standard input, or raises EOFError if there isn't any more input
Hi, im a learning python for a exam today. May I know how to sort an array with boolean values?
My current code :
has_done_homework.sort()
print(has_done_homework)```
returns `[False, False, False, True, True]`
Make a list of records. Then process that list
is this not what you want?
Are there ways to do three-way merges on rich text? Going through markdown or another markup language can lead to invalid markup even if the 3 inputs were
hello please answer, i am very desperate have been working on this for 50 hours already
sort(reverse=True)
thank you mister duck
whats an effiecient way to process 2 sets of 5 conditionals on the same data?
condition1 = priority 1-5
condition2 = position secondary-septenary
anyone good with probabilities analysis in code?
Town positions and N are given
Example:
Town positions:
(4;9); (9;5); (0;2); (7;1); (3;4)
Minimum cost:
5(4;9) - (3;4) - (9;5) | (0;2) - (7;1)
Please ping me if you can help.
Thanks in advance!
I was thinking of Kruskal's algorithm...
kruskal works here
how?
you can just generate all n^2 edges
and apply kruskal directly to find the minimum spanning tree of the graph
it will be O(n^2 log n)
N can go up to 10**5
oh
Generating all edges may not be the way...
you didn't mention that
Oops sorry...
I think this can be done in O(n log n) with prim's algorithm
hmm that sounds good
So what is the algo and how can I implement it to solve my problem?
I don't think I know how to solve this with prim's algorithm yet
but I have a O(n (log n)^2) solution using boruvka's mst algorithm
hmm...
well so about boruvka's algorithm
you start with n connected components in the graph, and all the edges in the graph are considered unused
and for each component, you find an unused edge to another component with the least weight, use it and therefore connect the two connected components into one
there's some kind of proof that after O(log n) iterations every component will be connected into one
so for this specific problem its easy to find the unused edge for each component in O(log n) so therefore it's O(n (log n)^2)
So I need to generate edges?
And use it later?
no you don't have to
So how can I "find an unused edge with the least weight" without generating unused edges?
well you can inspect the cost of the edge
min(|x_i, x_j|, |y_i - y_j|)
it is clear that for a point (x_i, y_i)
you just have to find the point with x closest to x_i
and the point with y closest to y_i
right
yes
also it must not be in the same component as point i
this can be done in O(log n) by sorting the points by x and by y
and simple binary search
key_string = {
"2" : "abc",
"3" : "def",
"4" : "ghi",
"5" : "jkl",
"6" : "mno",
"7" : "pqrs",
"8" : "tuv",
"9": "wxyz"
}
#count the number of permutations formed in total in above code
def key_comb_count(pr,u_pr,key_string):
#for storing the answers of key combinations possible
#exit condition
count = 0
if len(u_pr) == 0:
count += 1
return count
#logic
for i in u_pr: #i here refers to the key entered #say u_pr = "3" , so i = "3"
val = key_string[i] #"abc"
for i in val:
org_pr = pr #saving the above function call value of pr here
count += key_comb_count(org_pr + i ,u_pr[1:],key_string,count) #u_pr = "bc"
return count
return count
x = key_comb_count("","2",key_string)
print(x)
this is giving the permuations formed from the letters associated with keys on mobile phones
can anyone help me in getting to know the time complexity with some details
I am trying to verify a csv column depending on the value from a second column. eg column B should be 'hi' or 'hello' if the value of column A is "Python' or 'Duck'
I tried
if(df['A'].values == 'Python'or df['A'].values == 'Duck')
if(value != df['B'].apply(lambda x: 'hi' or 'hello'))
return False
else:
return True
I am new to python please
Thanks
My father is looking for a python alternative for matlab. He's been coding in matlab for decades and now trying to combine it with a python project.
He was looking into alternatives and was introduced to numpy, yet can't tell if it's reliable.
He wants to have python run on a machine that doesn't have matlab, and so he's looking for such an alternative
I agree Matlab is wonderful but numpy has perhaps a larger user base now esp in ML/AI.. More users in academia too. I have replicated computations in both and no issues but it may depend on the use case.
alright, and what about reliability? I mean, what if the creator of numpy has made a mistake that wasn't made in matlab? Matlab has many mathematical wonders especially in terms of efficiency and speed. The question is if python libraries can offer that at the very same level
its quite unlikely that numpy would have bugs, given how many users it has and how large an ecosystem depends on it
understandable
Yep used it in ML too
so in terms of efficiency and speed, is it "worthy"?
id say it should be comparable with matlab
you just have to keep in mind that you use the operations implemented in C
I have tried both
..yes
that's great to know
so numpy can actually offer all the features in matlab?
that's quite impressive
There is also octave which is closer to matlab but free but I havent tried
I'll make sure to take a look at that as well
If your father is stuck with Matlab syntax then Octave might be a better fit
syntax isn't the problem, but rather the tools
for example matlab's wonderful sort functions
MATLAB - GNU Octave Tutorial, GNU Octave is a high-level programming language like MATLAB and it is mostly compatible with MATLAB. It is also used for numerical computations.
yeah my father apparently knows octave too
alright so I think that's covered up a lot for me, my father said he'd love to try numpy then
he'll see how it performs and decide accordingly
I apparently have to go now, but thanks a lot. If you send anything further I'll come back to read here later just to confirm I haven't missed anything
Only way to know is to let him use them ...there may be edge cases where Matlab is better or Numpy ie better...Pandas can do sorting and holding data in a spreadsheet like dataframe...
Python has many libraries so if it is not in numpy there is probably another library that covers the functionality
Alright thanks
Oh my dad is also an engineer but retired and not as active as your dad lol
Well my dad is only 52 years old...
Ah ok mine significantly older
Well I'm not even 17 haha
Ah cool
Aight it was a pleasure to meet, thanks a lot for your help. Have a good day!
Im closer in age to your dad then lol
Likewise, have a good day too and good luck.
Write a python program that must accept an integer matrix of R*C and an integer โnโ as the input. Exactly one element in the given matrix is missing, which is denoted by a character โmโ. The integer โnโ represents the sum of all the integers in the column of the missing element. You must find the value of โmโ by replacing it in the given matrix and print the same (integer matrix with all R*C integers) as the output.
Note:ย Print โinvalidโ, if the boundary condition is not met.
Boundary Conditions:
2 <= R, C <= 50
1 <= matrix element value <= 1000
1 <= n <= 10^5
ย
Input Format:
The first line contains R and C separated by a space
The next R line contains the matrix elements integers separated by space(s)
The last line contains integer โnโ
Output Format:
ย The first R lines, each contains C integer values separated by space(s)
Sample Test case Input-1:
3 3
2 5 8
1 5 m
9 7 6
17
ย
Sample Test case Output-1:
2 5 8
1 5 3
9 7 6
Explanation:
Here, the missing element is present in the 3rdย column
The sum of the elements in 3rdย column is 17
So, the value of the missing element โmโ is 3 (17-(8+6))
ย
Sample Test case Input-2:
4 5
62 25 69 62 80
15 10 17 34 75
99 m 76 79 23
48 15 73 22 68
100
ย
ย
Sample Test case Output-2:
62 25 69 62 80
15 10 17 34 75
99 50 76 79 23
48 15 73 22 68 ```
solve this please
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
I have tried it bro ,but its still a problem , well if u can help it would be a big help
Thats a practice problem not my online exam problem lol ๐
Hey all I have just started learning Dynamic Programming and just want to cross check If my understanding of Dp is correct or not? Its just basically recursion + storing the repetitive stuff, right?
still funny with that behavior you expect us to just solve it for you
can some one help , i was trying to download the dependencies .
Give me the algorithm?
I don't like your attitude
"solve this please"
"not my online exam problem lol๐ "
"give me the algorithm"
Ok i guess i get my answer thanks for thehelp
Hey guys, could someone suggest good github or maybe discussion on Kaggle about most popular datasets in Kaggle? I'm practicing right now, and usually before working with dataset I check a few Kaggle notebooks to get new ideas, however I have spent already one week doing this and really run out of datasets on Kaggle with many notebooks, therefore I'm trying to find new ones. Any help is appreciated.
You'll have more luck in #data-science-and-ml
Can someone help me with probability analysis in code
DP itself is about splitting a problem into several independent smaller versions of the problem, and then only computing the problems once.
Recursion with memoization is just one way of implementing a DP. That way tends to be called the top-down version where you start with the big problem and break it apart into smaller once.
The other way is bottom-up where you compute the values directly in the order they need to be computed (so when you solve a larger problem all subproblems are already solved). The bottom-up approach can sometimes allow you to save a lot of memory because you control the order of things
E.g. for something like fibonacci the naive memoization or table approach uses O(n) memory, but you only really need the two previous elements if you do the work in the right order. In the case of fibonacci the right order is obvious, but it might be less obvious for more complex problems.
this is hardly an algo/ds problem, this is just "implement what is asked for"
Thanks man
I hope any of you guys could help me and point me in the right direction.
I have been making a cpu scheduler - priority using pandas, and I have been stuck for ages. So any help would be much appreciated.
Originally I used openpyxl to read the xlsx and create the scheduler which worked fine, until I tried to adapt it to round-robin algorithm. So I decided to try with pandas, and now I am stuck with my new code. I managed to sort the list, so that first it follows priority, and a fallback is FIFO (arrival time) as you can see in the code. But, now my simulator will not work, and the output to user is not working either (output should be similar to screenshot)
Here is the code: https://pastebin.com/4BrRUpUy
Old code that worked: https://pastebin.com/RGTsdXfH
Thanks a lot for any help, am I asking in the wrong place please tell me where to go
Kindly
Frank
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Except for collections is there any library that we generally use for ds-algo problem statements? Can anyone provide list of helpful inbuilt modules which we can use while solving ds algo problems
itertools is awesome
also functools namely for the @cache (or lru_cache) decorator that can help with dynamic programing problems
also heapq for heap stuff
not to mention math for gcds and such
hey everyone
im new to python
any ideas on how to write a nested loop
?
like my c++ habits are killing me in python lol
since its like hyper syntax heavy
ideally i want to create a nested for loop
def twoNumberSum(array, targetSum):
for i in array:
j = i + 1
for j in array:
sum = i + j
if sum == targetSum:
result = [i, j]
return result;
i created this
i want to loop through eaach element
and have the nested element starting the next element from the first loop
to store the values in the array
that match
what about this?
def twoNumberSum(array, targetSum):
for (i=0; i<len(array); i++):
for (j=i+1; j<len(array); j++):
sum = i + j
if sum == targetSum
result [i, j]
return result
that ain't python
use range to loop over actual index numbers (enumerate could work too) ```py
def twoNumberSum(array, targetSum):
for i in range(len(array)):
for j in range(i+1, len(array)):
if array[i] + array[j] == targetSum: # note how array is indexed here
return [i, j] # removed unnecessary sum and result variables
but this looks a lot like the LeetCode TwoSum problem, and this solution is not the optimal one - you may need something faster using dictionaries
Ohh... thank you so much for explaining this to me in detail, I guess I have to work a lot on DP.
Hey I noticed you are using a variable sum to store the sum, ig you might not be aware of the fact that python have a inbuilt function sum() so it can give you a error.
Also bisect
hello could i get some help
hey can somebody help me out with this question :
infix to postfix :
A * ( B + D ) / E - F - ( G + H / H)
Have you read about the shunting yard algorithm?
Hello ๐
Sure! Just ask your question, here or in a help channel.
oh sorry i thought it was general and i typed hi
No worries ๐
For anyone who has worked with networkx
import numpy as np
import networkx as nx
import pylab as plt
conn = http.client.HTTPSConnection("covid-19-data.p.rapidapi.com")
headers = {
'x-rapidapi-host': "covid-19-data.p.rapidapi.com",
'x-rapidapi-key': "#my-api-key"
}
conn.request("GET", "/country/code?code=it", headers=headers)
res = conn.getresponse()
data = res.read()
#print(data.decode("utf-8"))
graph=np.array([data]*2)
print(graph)
y=nx.graph``` okay basically im tryna make a graph from the covid 19 array which I got from an api. I made it into a 2d array but im still gettin an error
any ideas?
nvm I was makin a few errors
yeah sorry it says that its a 1d array still but i check stack over flow they said jus use the * operator and it can change but im still geting an error
here is my code for binary search algorithm
honestly i have stared at it for abt 30 mins
I am running python 3.10
heres is my result
It looks as if your search function expects the array to be sorted in ascending order. Is this correct?
return midpoint instead
okay lemme reverse the list
it works
but how did you realise it?
I think the fact that when target < val you set e to midpoint - 1.
yea?
The trick with binary search is to think in terms of an invariant, which is just a property that remains true throughout the execution of the algorithm. In your case the invariant is that any value to the right of e is greater than the target, and any value to the left of b is less than the target.
oh god, seeing binary search with inclusive on both left and right looks so weird to me, I'm so used to inclusive left, exclusive right
sorry i kinda just woke up from sleep in a data sturctures and algorithms class so please bear with me
Sometimes I prefer the symmetric version.
But usually in Python the version you describe is more natural.
okay
with inclusive exclusive, left is always has the predicate being true, and right always false, which is a nice invariant
so how do write my algorithm so that it doesnt matter the order of list
Fundamentally, a binary search only works on a sorted list.
But you could maybe add a key argument ๐ค
binary search must have a property that what you're searching goes from being false to being true (or vice versa)
and how would i apply that key argument in the algorithm
Ah yeah actually that's more general.
you're searching for the point where the switch happens
you are kinda confusing me
midpoint = ...
if predicate(midpoint):
...
else:
...
in your case the predicate is target < sequence[midpoint]
yea
what I mean is if you evaluate the predicate everywhere, it must go like
0 0 0 0 0 1 1 1 1
just one switch from 0 to 1
err...it probably should be
1 1 1 1 1 0 0 0 0
yeah, going from 1 to 0 like you do is the more natural one
Hey guys can someone refer a good book for preparing ds algo with python. Need everything at one place
(but it's just a matter of inverting the predicate, no big difference)
there
Didn't get?
search for the book you need
i am not sure if you are allowed send pdf in this channel
I am asking for the suggestions not the medium
so i shouldnt care ?
i dont understand the terminology predicate
That's fine agenda behind this question is I am unable to find a book oriented for ds algo along with the usage of important modules that we can refer while solving any problem statement
you can pick either convention, I think the one you do is the typical one (true then false)
i am not a cs student
predicate is just a function returning true or false
ohh okay
pls help
can you use binary search to find the element in a linked list
the binary search I have in my head when I write one is like
def bs(lo, hi, pred):
l = lo
r = hi
while r - l > 1:
mid = (l + r)//2
if pred(mid):
l = mid
else:
r = mid
if you have a linked list you would just do a linear search, for binary search you need to be able to compute the predicate quickly, which you can't really do with a linked list since you need to move to the element before doing anything
the predicate, some function given by the user
hmmm
ohhh okay
It's worth noting that binary search does not at all depend on that you're working on an array or similar, you could have some increasing function f(x) and you wonder when it becomes > value
If you're only interested in integer points the code is identical
ooh that's cool
Dunno if this is the right spot for this, but i made this just now:
import matplotlib.pyplot as plt
import numpy as np
num = int(input("Enter a number: "))
while num < 1:
print(f"{num} is too small. Enter a positive integer.")
num = int(input("Enter a number: "))
scoreNum = int(num)
score = 0
steps = []
valList = []
print(int(num))
def collatz():
global num, score, valList, steps
valList.append(int(num))
while num != 1:
if num % 2:
num *= 3
num += 1
else:
num /= 2
valList.append(int(num))
score += 1
if num:
score += 1
steps = [i for i in range(score)]
collatz()
print(steps)
print(valList)
plt.plot(steps, valList)
if 0 < len(valList) <= 50:
plt.xticks(np.arange(0, score + 1, 1.0))
plt.title(f"Collatz of {scoreNum}")
plt.xlabel("# of steps")
plt.ylabel("# at step X")
plt.show()
okay thats cool
i made something like it during december
is there a problem?
if there is i dont know matplotlib yet
but i made this simple program
can someone recommend Mathematics books
i'm in my first year highschool
i'm prolly gonna be here alot
def group_anagrams(list_of_strs):
res = defaultdict(list)
for s in list_of_strs:
count = [0] * 26
for c in s:
count[ord(c) - ord("a")] += 1
res[(tuple(count))].append(s)
return res.values()
print(group_anagrams["dog", "god", "sog"])
this is supposed to group anagrams together
but i'm getting a typeError
Traceback (most recent call last):
File "main.py", line 15, in <module>
print(group_anagrams["dog", "god", "sog"])
TypeError: 'function' object is not subscriptable
idk what the problem here is
You just forgot the brackets for your group_anagrams function.
This should work:
print(group_anagrams(["dog", "god", "sog"]))
Nothing is better than the internet
really? i should try this internet sometime
Yeah it has all the books you need, if you donโt find what youโre searching, try to put more details in your search
I typed something in my searchbar it asks to enable safe search
anywhy i need help
heres my attempt
the logic is a bit weird, isn't it enough to find the first position where the node data is >= the data to insert
with a special case for insertion at the end
and a special case when the list is empty
empty linked list?
yeah
so i append all values less than data in the empty list?
huh?
the weird logic to me is the one in the loop, feels like it can be done simpler
Is anyone read the book design and analysis of algorithms by Thomas H Coremen?
Here is a stab at it, though it has more cases than I prefer. IIRC there is a classic way to reduce the number lf cases, but idk how it translates to python
def insert_sorted(head, data):
new_node = Node(data)
if head == None:
return new_node
prev = None
cur = head
while cur != None:
if cur.data >= data:
if not prev:
# Before head
new_node.next = head
head = new_node
break
else:
# Between nodes
new_node.next = prev.next
prev.next = new_node
break
prev = cur
cur = cur.next
else:
# At end
prev.next = new_node
return head
decent test case
def ll_items(cur):
while cur != None:
yield cur.data
cur = cur.next
head = None
head = insert_sorted(head, 3); print(list(ll_items(head)))
head = insert_sorted(head, 1); print(list(ll_items(head)))
head = insert_sorted(head, 2); print(list(ll_items(head)))
head = insert_sorted(head, 4); print(list(ll_items(head)))
should output
[3]
[1,3]
[1,2,3]
[1,2,3,4]
hey guys i am studing Genetic Algorithems would it be possible for one of you guys to help me with one question
Discuss the different solutions to address the failure of simple crossover strategies(to solve the disadvantages) for the travelling salesman problem.
In particular:
why they are necessary
how they are applied
how they preserve the parental traits
what other possible methods are available
okay lemme have a go
Can you guys help me with something
just checking the time complexity of this code is O(n) where n is the number of elements in head?
with?
this is it
#Part 2
#Input
v1 = eval(input("Enter Mr. Veera's average speed(m/h): "))
v2 = eval(input("Enter Mr Anderson's average speed (m/h): "))
distance = eval(input("Enter the distance (m): "))
timeToCharge = eval(input("Enter number of minutes to fully charge electic bike: "))
minToCharge = eval(input("Enter number of minutes to operate before next charge: "))
minToChargeDefault = minToCharge
#Variables
hours=distance
minutes=hours*60
v1timetaken=0
v2timetaken=0
veeraD=0
andersonD=0
veeraC=0
andersonC=0
#Mr.Veera
while veeraD<distance:
#Time
v1timetaken=v1timetaken+1
#Distance
veeraD=veeraD+(1*v1)
#Mr.Anderson
while andersonD<distance :
if(minToCharge>0):
#Time
v2timetaken=v2timetaken+1
#Distance
andersonD=andersonD+(1*v2)
minToCharge = minToCharge -1
else:
v2timetaken=v2timetaken + 1 + timeToCharge
minToCharge = minToChargeDefault
#Distance comparison
for comparison in range(hours):
if(veeraC>=distance) or (andersonC>=distance):
break
veeraC=veeraC+(1v1)
andersonC=andersonC+(1v2)
print("Mr.Veera's position:", veeraC)
print("Mr.Anderson's position:",andersonC)
if v2timetaken<v1timetaken:
print("After",v2timetaken,"hour(s)","Mr.Anderson reaches finish line first")
else:
print("After",v1timetaken,"hours(s)","Mr.Veera reaches finish line first")
this my code
can u check what is wrong
what error is raised?
suggestion: you can upload python files to discord. While it may not be smart, things like underscores and ||upwards bars|| can affect if the code actually works when copied from discord.
so the examples given in the problem does not work in my code
i am trying to fix it but i am unable to do it
Hey @high pewter!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
dont worry
that means your solution is incorrect
yeah i cant figure what is the problem
are you looking for a solution or just help?
okay gimme a few i am tryna fix some of my program
the runtime is exactly proportional to where the insertion happens, but yeah, worst case O(n)
yes
thanks for your help
https://tenor.com/view/kummeli-thumbs-up-nice-well-done-approve-gif-12348671
please send your code here https://paste.pythondiscord.com/ @high pewter
i'm working on it
this the first part i already finished it
but it will give u a better understanding
Yes
okay
what's with the "using simulation" thing?
in part one you can just compute the answer directly
So the problem.is that yeah it involves math
But you don't use math at all
By using using simulation and using loops u can get it
I mean, you can. But it feels silly when the answer is pretty much right there
the smaller distance_left/vel dictates everything
I just started coding so I am not the best when it comes to this stuff
I feel like the second part kinda lacks information, we can get there faster by maybe doing a partial charge at the end. I'm assuming that's not allowed, but the task doesn't say
are you taking a physics class?
Yeah this semester
Yeah
but looking at your code you used a while loop to record timetaken why tho?
if you want to do a raw simulation it's probably a good idea to allow for a smaller time step, e.g. have some dt that dictates how long a simulation step is, rather than it being 1 as in your current code
i just tryna understand what you were tryna do
Cause it easier to my knowledge
Cause this a question our teacher assigned us and he hates us using functions we never learned in class
And gives us a 0
but the equation for time is = distance/speed
SmexyCorny I said at the top it would have made this problem a whole lot easier
But our teacher said without using math equations
So this is where loops come in
i didnt know
part 1 is just doing this I guess
while pos < goal:
pos += vel*dt
t += dt
for both scenarios
(maybe in parallel?)
they said no equations apparently
yes
but if veerson travels 25.02
good luck without any math at all ๐
Nah our teacher informed us it's okay if our answer is not decimal
i didnt know that too
the real answer is 25, I guess the extra .02 is because of the simulation time step
