def __init__(self, data):
self.data = data
self.left = None
self.right = None
def maxDepth(node):
if node is None:
return 0
else:
return max(maxDepth(node.left),maxDepth(node.right)) + 1
root = Node(5)
root.left = Node(6)
root.right = Node(7)
root.left.left = Node(8)
root.left.right = Node(9)
print("Height of tree is %d" %(maxDepth(root)))
#algos-and-data-structs
1 messages · Page 98 of 1
How do we calculate ht of binary tree when there is no incremental counting in above program ??
answer is 3
Hey can someone help me with a deepdream neural network? I have my own dataset I want to train it with
There it is:
return max(maxDepth(node.left),maxDepth(node.right)) + 1
Can someone please explain the qiucksort to me
Hey @next storm, please do not post random memes in the server
!mute @next storm 5h Posting a meme just after a mod ask you not to isn't the way to go. Please re-read over our #rules.
:incoming_envelope: :ok_hand: applied mute to @next storm until 2021-02-02 16:09 (4 hours and 59 minutes).
you can directly ask
by the way define your class Node as:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right```
it gives you the ability to create a tree like this `tree = Node(5, Node(6, Node(8), Node(9)), Node(7))` for example
given a list of points and another point, how would i efficiently check whether the manhattan distance between any of them and the other point is less than or equal to n?
(ping 2 reply thx)
how do i ask directly ?
you just ask your questoin lol
lol
ok uh
ok so i found out
i found a better problem to solve that would solve my problem
given a grid of points labelled either A or B, is there a way to calculate the closest B point to each A point (through manhattan distance)?
Guys any good course to learn algos and data structure ?
just brute force ig?
srry could u elaborate on the question?
I need more info to provide a good answer
check out itertools.permutations.
!e ```py
import itertools
print(list(itertools.permutations("-+*")))
@lean dome :white_check_mark: Your eval job has completed with return code 0.
[('-', '+', '*'), ('-', '*', '+'), ('+', '-', '*'), ('+', '*', '-'), ('*', '-', '+'), ('*', '+', '-')]
i kinda cant use that i need to use recursion
since i need to find all expression that give that target
nums = [1, 2, 3] and target = 6 → 2 (expressions: 1 + 2 + 3, 1 * 2 * 3) *example
To get all permutations of n things, separate out the first thing (we'll call it A), and get all permutations of the remaining n-1 things. Then, for each such permutation, generate n new permutations, corresponding to the n different places you can insert A in.
For example, for 1,2,3. All permutations of 2,3 are [2,3], [3,2]. Insert 1 into 3 possible positions in each:
[2,3] -> [1,2,3], [2,1,3], [2,3,1]
[3,2] -> [1,3,2], [3,1,2], [3,2,1]
So you get 6 permutations of 1,2,3, as you should.
That's your recursive algorithm.
Take Developer Ecosystem Survey by JetBrains
https://t.co/S8US6FsJAQ?amp=1
hey guys! how would i go about implementing a sorting algorithm for example quicksort in a way that i can store its state and resume sorting later? or should i just use a sorting algo without recursion? i looked into external sorting but its not exactly what im looking for
Not entirely sure what you mean but perhaps create a wrapper class around a list that overrides mutator methods so that they "pause" the algorithm somehow?
@fiery cosmos Perhaps you can do that with generators
thx ill look into that
it is possible
guys could anyone help me in exam
it will be start in 3mins
dm me
if u want to help

Could you solve this my first making the black edge 0 and the red edge 1. Then you solve it but make it so u start with either 0 or 1 in the node. Then after that u add .5 to every single node that way black edge becomes 1 and red edge becomes 2. But how would you prove / disprove the fact that u could solve red edge 1 and black edge 0 with starting 0 or 1 in initial node?
Just a tree? There's also the term p-ary tree for trees with p children per node.
the non-euclidean distance is what you want to google
basically, just think about moving only on the x or y direction but not both at the same time, how would you get somewhere without using diagonal (sloped) paths
Like you would in Manhattan
Is this aoc?
what is the distance from (0, 5) on a graph to (0, 0) on a graph?
5
right and same with (0, -5)
uh yeah
now (1, -5) is 6 away from (0, 0) because you also have to go down 1
right 5, down 1
so just check the distance from each point to every other point
and pair the distance with the coordinate in some data structure like a list of tuples or soemthing
You mean, like, in less than O(n*m)?
Ahh that may take a while with my naive method haha
no idea, I'd want to know too. There are spacial subdivision algoritmhs for that, but I don't know an implementation
by the way, the good way to calculate the naive way would be with the holy grail: scipy.spatial.distance.cdist
https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist
for example,
dists = cdist(As,Bs,"cityblock")
for cityblock distance
then do argmin to find the closest B for each A.
Ohh that's handy, what do you mean by argmin?
np.argmin
ahhh
can do things like "for each row, get the index of the lowest column in that row"
I think I need to understand np arrays better to get what you are talking about
the ith row in the array returned by cdist will be the distances from As[i] to each of the Bs.
so to find the closest B-point, you need the minimum in the row. But not the minimum's value, but its index - hence, argmin and not min.
Euclidean Algorithm to find the GCD of two numbers: Voila py def euclidean_algorithm(nums): if all(nums): greater = max(nums) smaller = min(nums) remainder = greater % smaller if remainder == 0: return smaller else: return euclidean_algorithm((smaller, remainder)) else: return max(nums) numbers = 0, 5465465654654654 print(euclidean_algorithm(numbers)) slaps hood
yep, nums is a tuple
how much python should you know before jumping into data structures/algo problems?
can i get any fake profile detection projects
Any YouTube playlist for Graphs, Binary Tree and advanced data structures!!
ע
I mean, really you can study algorithms without knowing any programming language. But it can be helpful to be able to implement the algorithm yourself.
Studying algorithms goes hand-in-hand with learning Python, as python has some useful data-structures built-in.
set and dict are hash-tables; list is a dynamic-array; sorted implements a hybrid of merge-sort and insertion-sort (called Tim-sort)
O(1) is when you always do finite number of steps for every input
For example if you are iterating through array it's not O(1) because different arrays have different number of elements
It's where the additional memory required by an algorithm to run does not depend on the size of the input.
This is also known as an in-place algorithm.
Check out the table of sorting algorithms here. Ones with 1 in the "Memory" column are in-place: https://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms
Another example: take the problem of reversing a list. You could create a new list, and insert the elements into that list in reversed order; this would not be in-place. Or, you could work from the outside in, swapping corresponding pairs of elements; this would be in-place.
def reverse(arr):
new_arr = []
i = len(arr) - 1
while i >= 0:
new_arr.append(arr[i])
i -= 1
return new_arr
def in_place_reverse(arr):
i, j = 0, len(arr) - 1
while i < j:
arr[i], arr[j] = arr[j], arr[i]
i += 1
j -= 1
hello everyone,I'm new to this server and in my first year of b tech...i am stuck in a problem can anyone point out my mistake in it.it would be really helpful🥺 .....question link:https://www.codechef.com/problems/INTRVS
hmm ill try solving it
and maybe helping u out
but im in tenth grade so im not sure whether ill be able to
but ill try
just gimme some time
ooh the first problem i think i can see is that u didnt unpack the list containing the input('').split() that u used
to take the n and k integers
as input
does iterative solutions have better space complexity than recursive ones on an average scale?
ah
Bot should be displayed if he has solve the problems in "at most one second each". In your code you check for at most 'K' seconds.
thank you...i found that....ps too silly though
So right now I'm taking an intro to Python course. Yes, I'm learning about abstract data types/structures - but not quite implementing anything. I'm learning a lot, but I feel like I want to jump into DS/Algos already and I'm wasting time. At the same time, I feel like I don't know enough about python to understand the implementation of data structures.
Python probably isn't the best language to practice implementing data structures, as it's so high-level. Perhaps something like Java or C++ would be better suited.
Implementing can help you to really understand a data-structure, but it's also important to know when to use it. Practicing programming problems on sites like leetcode or hackerrank can help with this. You don't need to know a lot of python for the easy/medium problems, and it's ok to attempt a problem and look at model solutions if you aren't able to solve it.
My dilemma is that I know a little about a few different programming languages: Java, Python, & JavaScript. My favorite is Java and would love to learn DS using Java, but I'm also a Data Science/SWE student, and the language that makes the most sense to make my "native" language is Python. I have tried some of the easy problems on Leetcode, and struggled a lot, so that's why I'm going back to build my Python knowledge before attempting any problems.
Binary Tree Question given an array POSTORDER[n] and PREORDER[n] and variable i, j ... how can i determine if i is a parent of j using the 2 arrays?
wheres a good place to start.
When i have a JSON Like this:
my_dictionary = {
"key 1": "Value 1",
"key 2": "Value 2",
"decimal": 100,
"boolean": False,
"list": [1, 2, 3],
"dict": {
"child key 1": "value 1",
"child key 2": "value 2"
}
}
How can i get the value from child key 1?
my_dictionary[“dict”][“child key 1”]
Or my_dictionary.get(“dict”, {}).get(“child key 1”) if you want to be safe
not completely safe:
d = {'key': None}
d.get('key', {}).get('some')
You are not allowed to use that command here. Please use the #bot-commands channel instead.
hey guys
re.match(r"[0-9][0-9]okt$|[0-9][0-9]maj$|[0-9][0-9]febr$", "adsf18majadsf")
returns None but i want it to match on 2 numbers followed by a "febr" or a "maj" or an "okt"
how could i achieve this? thanks in advance :)
🥴
r'\d{2}(febr|maj|okt)'
i know im pretty new to regex
thanks :)
really simply question ... I don't know how to use a function within a class...
class Solution:
def combinationSum(self, candidates, target):
self.res = []
self.candidates = candidates
self.backtrack([],self.target,0) #start at 0th index
return self.res
def backtrack(self,path,target,idx):
if target == 0:
self.res.append(path)
return
if target <0:
return
for x in range(idx,len(self.candidates)):
self.backtrack(path + [self.candidates[x]], target - [self.candidates[x]])
target - [self.candidates[x]]
why doesn't doing
Solution(candidates,target) ... how can i run the function combinationSum in this class?
in order to run functions inside of a class you first have to create an instance of that class and then use the function.
you need to declare a constructor for the class
^and that
try looking at using __init__ as a constructor
what is it youre trying to do @final egret ?
yo are there people that can help with competitve programming questions?
DMOJ: Modern Online Judge
Jo is a blogger, specializing in the critique of restaurants. Today, she wants to visit all the Vietnamese Pho restaurants in the Waterloo area, in order to determine which one is the best.
Generated 10,000,002 points of y=sqrt(1**2 + x**2)
Quadrants copied, new points: 40,000,008 points of y=sqrt(1**2 + x**2)
true pi........ 3.141592653589793
as generated... 3.141592653580496
corrected...... 3.14159265358
``` How could I make this more accurate? https://pastebin.com/VXiZEPc8
Pastebin
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.
y=sqrt(1**2 + x**2)
Presumably, you mean-🙂
And I don't think you can get more accuracy than that using floats. You'd have to switch to Decimal.
(it's not the current value to full float precision, but I wasn't able to improve it)
Ahh typo! Ok, maybe I will look more into an advanced way to do it then!
looks like there's a problem with using decimals
from decimal import Decimal as D
import decimal
decimal.getcontext().prec=28
def pi_est_dec(N):
step = D(2)/(N-1)
stepsq = step**2
total = D(0)
cur_x = D(-1)+step
last_y = 0
for i in range(1,N):
cur_y = (1-cur_x**2).sqrt()
total += ((cur_y-last_y)**2 + stepsq).sqrt()
last_y = cur_y
cur_x += step
return total
print(pi_est_dec(1000000))
print("3.1415926535897932384626433832795029") # true 35 digits from wolfram
Output:
3.141592652756257066384470676
3.1415926535897932384626433832795029
This takes around 10 seconds already. So Decimals can achieve higher accuracy than floats... but for that you still need to have enough points.
And decimals are far slower, so it's hard to get that many points.
Hmm yeah doesn't seem to be that effective... I can get that accuracy but it only takes 2-3 seconds for 1 mil iterations. What exactly does decimal do? Guessing it's for use with currency and very small important numbers
Oh does it store the decimal as an int or soemthing?
Python floats are the same as numpy's float64, and the same that's called "double"s in other languages - 64bit floating-point numbers. They are implemented in hardware, that's what modern CPUs are build to work with. If you need more precision than that, the only way is to implement such numbers in software. That's what the decimal library does. Of course, doing in software what's usually done in hardware is way, way slower.
In general, that's what's is known as "arbitrary-precision arithmetic". It's when you implement your own numbers in software so that you can get as much precision as you need.
Rocket science, Finance, and finding the value of pi, thx arbitrary precision arithmetic!
yeah, another use of decimals is that they aren't floats
like, they are fixed-point and not floating-point
in anything money-related you want fixed-point numbers, everywhere - not for precision, just for the lack of loss of precision in intermediate calculations
you don't want 10 cent + 10 cent +... + 10 cent (10 times) to be equal to 0.999999999 dollars.
Right or like when ur trying to do the Pythagorean theorem 10,000,00 times haha
Hey its been a while
Given an array of size n, find the majority element. The majority element is the element that appears more than floor(n/2) times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example :
Input : [2, 1, 2]
Return : 2 which occurs 2 times which is greater than 3/2.
what could be the best time complexity for this
Time complexity? O(n), pretty clearly, as it's achievable and I don't think it's possible to do less.
(to achieve, make a Counter, then pick the element with the most appearances)
Yeah, O(n) seems the best the best
Altough, you are probably going to use a hash table for a counter
So you should watch out for hash collisions
cuz then it could be O(n^2)
Does anyone actually expect hash collision problems in real applications? I got the impression that they only really happen (in large amounts) when you manually design a hash function that's very bad.
Well, I'm not sure, but they can happen so It's better to watch out
Another thing would be to just sort the array
In O(nlogn)
And then just acces mid+1-th element
I mean, for arrays with even number of elements acces n/2-th element while for arrays with odd num of elements access n/2+1-th element
I have a test, the questions will be based on algorithm, data structure such,,, how should I prepare for it??? Any help is appreciated thank you :)
Try your best to solve as many questions as you can related to the materials, preferably on your own. Try to learn the pattern then apply it to questions on the test.
Use geekforgeeks website if it consists pseudo code or any implementation.
Hackerrank.com is also good for a long run I don't recommend it for a test though
How can I define a function where you don’t have to put all arguments when you execute it?
@tame wigeon thank you!
ay u know any good resources to learn data structures and algos for beginners
preferably free
I'm doing coding challange and I think my issues is not undertanding how to apply algo's to solutions, is there a good website or video to increase my undertanding?
@undone ingot
https://book.pythontips.com/en/latest/args_and_kwargs.html
also wrong channel, ask in #python-discussion if simple stuff
idk, the only thing i can suggest is just grind problems
@rustic portal go check this book: Data Structures and Algorithms in Python, Michael T. Goodrich. It exists in pdf version., it's really great.
What is quicksory
quicksort?
hi
I try to use variable and definitions external to the file, but can't find a way to do it.
I know you can but I have no idea how.
if the file is in the same directory you can use:
from test1 import a
from test2 import b
print(b())
if you use your method then:
import test1
import test2
print(test2.b())
@fiery cosmos
This is kind of a more general quesstion but should you include floor/ceilings in timee complexity?
Like if an algorithm has floor(n) times, should it be O(n) or O(floor(n))
@spring grove thk
what can i do if i need to use a variable from the running file?
since it tells me that client is not defined.
You should probably just make your function return that variable
yes, but the variable is not defined.
@fiery cosmos or make your function take a parameter
def a(thing_i_want_to_print):
print(thing_i_want_to_print)
then
import test
test.a('hi')
@fiery cosmos if you dont want to use either of those mthods, make your variable global and pass it to the next file
its better practice to use either of the first 2
yes
hey guys idk if this is the right channel
couldnt find a channel for matplotlib.pyplot
so im asking here, how do i solve this?
How exactly do you expect someone to answer the question "how do I solve this", without having given any details on, well, what you're trying to do?
there isn't one, but a help channel(#❓|how-to-get-help) would do
Since matplotlib is commonly used in data science projects, asking in #data-science-and-ml would be appropriate.
Btw you could always just run your code to verify that it's correct
epic thanks
yes lol i got it later, nvm me.
can someone convert .py to exe for me
When defining dictionaries in Python, how would I store the first element of every grouped tuple list just as a dictionary key?
what do you want as the values?
At the moment when I create my dictionary using a for-loop over the list of tuples, I get the following output (which still includes tuples):
You can see, there's a comma separating each name-value pairs but within each **name ** you might have noticed there's additional ** two element **enclosed with a pair of parenthesis (a tuple otherwise known as)
well, you would do ```py
{first: value for fist, *rest in some_list_of_tuples}
Wait what? Hold on, let me show you how I currently done my dictionary...
ah
so the second elements are entirely irrelevant here?
For my purpose in this particular count_entity_freq_dict function, yes it is irrelevant
on an unrelated note, I would suggest pprint so that the output is more readable
from collections import Counter
from pprint import pprint
pprint(dict(Counter(i[0] for i in named_entities)))
use Counter to count things
So what I've done with my for-loop, you can easily do it with 1 liner? 😯
ye, counting things is so common that there is a helper class for it
I can easily store this as a variable: dict(Counter(i[0] for i in named_entities)) right? And then pass the reference to pprint ( ) ...?
yes
Thanks for your help lakmatiol 🙂
Hi guys I have problem with updating my JSON file.
for file in os.listdir("./python_files"):
if file.endswith(".xlsx"):
df = pd.read_excel(os.path.join("./python_files", file))
CRD_Array = df.iloc[:,1].values
column_length = len(CRD_Array)
row_iterator = 0
for single_CRD in CRD_Array:
if os.path.isfile(f'output/{single_CRD}.json'):
with open(f"output/{single_CRD}.json", "r+") as json_file:
parsed_file = json.load(json_file)
parsed_file['body-{}'.format(file)]=[]
parsed_file['body-{}'.format(file)].append({
'Total Employees': '{}'.format(filed_handler(df,row_iterator,'5A'))})
json.dump(parsed_file, json_file)```
When file is found I want to add new array to it
At this moment file isn't updated with new array
Hey guys. I'm using weight of evidence to bin my continuous variables. Now that i have all weights, I want to replace my values by there WoE based on the bin they fall into. Is is possible to do this without using 10 if loops?
values = [] # Your values
bins = [] # Populate this such that bins[i] is the bin index for values[i]
replacements = [] # Populate this such that replacement[i] is the replacement value for bin index i
for i, bin in enumerate(bins):
values[i] = replacements[bin]
If your bins are named then bins would instead be a list of strings and replacements a dictionary
Hi I wanted to get started with Data structures and algo I am okay with lists dictionaries tuples arrays..is there any other pre-requisite before I start with it. It would be great if u could suggest a few sites where I can start as well
Hi,
I am looking to convert an integer from an integer to the following string:
Say we have a variable that holds the integer 240555
I want to convert it to the following string: "$240.6K"
How would I do that?
heyyy
Hi there, I would like to store a list of strings and I would like to add another string to the list only if the string is not present in the list. So for example if I have a list with ['the','blue'] and i want to add 'red' to the list, it will check if 'red' is present in the list. Since, it is not present in this case, it will add 'red' to the list. I would like to know if lists work best for this?
hi @jovial hill maybe look at sets
you dont need to check if the item already exists, as duplicate entries cannot exist in a set
Aha, cheers 😋
@jovial hill here 🙂 https://www.w3schools.com/python/python_sets.asp
Hi guys, hope you are doing well. I was solving this LC, but I don't understand this solution. Could you please explain how this works?
it is LC 137 and its link is here: https://leetcode.com/problems/single-number-ii/
can anyone help to convert this code to javascript
class Solution:
def solve(self, n):
temp = str(n)
ans = float('-inf')
for i in range(len(temp) + 1):
cand = temp[:i] + '5' + temp[i:]
if i == 0 and temp[0] == '-':
continue
ans = max(ans, int(cand))
return ans
ob = Solution()
print(ob.solve(268))
Hi
need helo
help
I need the function to add plurals
I had to create 2 lists becuase I couldnt figure it out
Hi !
I just want to know if there is a solution for this :
a = 4
type(a) #It return "int"
hex(a) #But hex(a) return "0x4" and i want that return "0x04"
Thank you @lavish flame
np I also learned something new!
I am crawling a website and I don't want to visit the same link more than once. To do this I would like to store the links_yet_to_visit in a queue and all the links either in the queue or have already been visited in a set. Each url will have its corresponding parameters and whether its a post or get request. How would I store the values in the queue and set. so each url with be something like:
[url1:{name1:value, name2:value}, post] [url2:{name1:value}, get] [url3:{name1:value, name2:value, name3:value, name4:value}, post]
I've gone for the following:
urls = {url1, url2, url3} left_to_visit = deque([[url1, {name1:value, name2:value}, post], [url2, {name1:value}, get] ]) visited_urls = [[url3, {name1:value, name2:value, name3:value, name4:value}, post ]]
So when I find a url, I check if its present in urls, if it isn't I append to urls and I append to left_to_visit. When I visit a url, I pop it from left_to_visit and store it in visted_urls
Hello, I need help with a python program. The goal of the program is to give a match list (to make a tournament) according to the number of teams. Except I don't have a clue how to do it, could you help me?
Bonjour,
first, if u want to specify all teams, you should find a way to initialize them with variables or list...
i don't need to specify them just number , i use a list
so you want to show something like : l[1] vs l[2] ?
yeah
so u can use something like this @fiery cosmos i think :
I guess every "equipe" is affected to a number.
Ex: Equipe 1 is affected to number 1, etc....
import random
opposant1 = 0
opposant2 = 0
for n in range(Match-1): #You will print as much many times as necessary
while (opposant1 == opposant2):
"""
you don't want that a team face himself lol.
So you will run "random.randint(a,b)" until opposant1 and 2 are different.
"""
opposant1 = l[random.randint(a,b)] #You define the minimum 'a' and maximum 'b' amount of teams.
opposant2 = l[random.randint(a,b)]
del opposant1 #You want to suppress teams that got a game.
del opposant2
print(opposant1+"vs"+opposant2) #Finally, you print the game.
I'm not sure that it will work perfectly but i think that's the idea and i didn't think if we can dodge the utilization of the "while" loop. So it's not an optimized python script.
pretty sure that will not work
although, i'm not sure what you mean by "make a tournament", could you clarify? @fiery cosmos
@agile sundial for sure , the program serves after entering a number, to know all possible matches between them? (as an example if in a tournament there are 14 people) the program gives us the list for everyone to face everyone like this with 4 teams
i see
uh
well, that if is O(1), so just consider how many iterations is being done.
iterations or operations ? i think time complexity is about operations no ?
iterations is about space complexity ?
Uhh, "iterations is about space complexity" is a very weird statement (how are iterations related to memory?), but also, here each iteration is a single operation, so you just need the number of iterations.
"iteration" just means "one execution of a loop".
my bad about space complexity HAHAH
i'm so n00b XD
Uhh, no?
for i in range(n):
some_operation_that_takes_constant_time(i)
what'd be the time complexity here?
erm im not sure tbh sorry
How many times is some_operation_that_takes_constant_time called?
You can solve that by just doing:```python
import itertools
x = int(input("Amount of teams: "))
matches = itertools.combinations([i for i in range(1, x+1)], 2)
for match in matches:
print("/".join((str(i) for i in match)))```
I think combinations accepts iterators as well as lists.
also, that's technically only the first round of a tournament 😉
...but nevermind, the rest of the lines are not exactly important
And also idk if the teacher wanted tillmister to do the whole process of selecting the different pairs for the matches
How can I define a method that accepts a variable number of paramaters? For instance, i have the following:
await self.add(member, action)
But on some occasions I want to add another variable:
await self.add(member, action, number)
and use number whenever is provided
I can also set a default value so that whenever is different to the default value is because there is value provided
Yep, def func(member, action, number = None)
exactly, ty very much
Hello! im getting this error
ERROR::CTag::init::Given souptag is not a bs4.element.Tag instance.
DEFAULT_LINK_ATTR_NAME ="href"
ODDSCHECKER_HOME = "https://www.oddschecker.com/"
Why dosent it work?:)
i already pip installed everything
Hey, I have a question about an exams questions about bubble sort. It's more CS in general than Python-specific but I couldn't solve it right anyway.
This exercise (sorry for the Greek) wants me to "print" the array for every iteration of the bubble sort.
The original array A is [55, 34, 5, 2, 2, 1]
But the given solutions for this are very strange
For some reason, 1 which is at [-1], is being swapped to [0]
Can someone explain why that happens
def bubble_sort(arr):
N = len(arr)
for i in range(N):
for j in range(N - 1, 0, -1):
if arr[j] < arr[j - 1]:
arr[j-1], arr[j] = arr[j], arr[j-1]
bubble_sort([55, 34, 5, 2, 2, 1])
it's swapping the min to the left instead of the max to the right
and?
how should I do it
do what
how should I implement a python function that would modify the array according to the needs of the exercise
sorry for the lack of clarity in my questions
that snippet already does what you need
yes it gives the same result but the process is different
The exercise requires the first iteration to be [1, 55, 34, 5, 2, 2]
The textbook snippet does this: [55, 34, 5, 2, 1, 2]
i don't think so
maybe you're printing on every iteration of the inner loop instead of the outer loop
i see
the instructions say to print on each iteration
but you're looking at the result of each iteration of the inner loop
so I need to print the iterations on the outer loop?
i think so
yes you were right, a few frames ahead it actually shows the right thing
thank you
is anyone familiar with the Max^n (similar to minimax but for n players instead of 2)? I've been trying to implement the shallow pruning version of it for 2 days now using this paper:
https://www.cc.gatech.edu/~thad/6601-gradAI-fall2015/Korf_Multi-player-Alpha-beta-Pruning.pdf (specifically top of page 5)
but it's not working 
this might be an extremely stupid question but
when you have a function that includes a binary search (complexity is O(logN)) as well as a loop with complexity O(N) , then the complexity of the whole function is O(logN + N) = O(N)
at that point, why would we optimize the search if the function time is going to be linear anyways?
wouldn't linear search make it O(N + N) = O(N)? which is the same time complexity?
I realize that it will be faster to use binary search but I'm confused about the notational differences
big O notation does not denote runtime, it is just a general overview of how complex a algorithm is, so you are right in that using binary search would not change the complexity, but realistically it is useful to apply when possible.
It also goes the other way
Sometimes an algorithm with a better big-o complexity may be slower in practice
Perhaps it has poor performance for very small inputs, for example
Just a quick question, can you access a class instance attribute/variable from an external Python script?
can someone please help me with this question
What are you mean? Do you have two scripts that are running simultaneously?
this is code I have written it doesnt work for the letters with same frequency
What exactly do you need? If you want complete solution it breaks rule 5
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.
Why do you have nested for loops?
for medicine in s:
if medicine not in d:
d[medicine] = 0
d[medicine] += 1
You also should use better names for your variables because it's really hard to remember all of s, d, i, j and so on
You also can prepare d dict earlier using
for medicine in medicines:
d[medicine] = 0
I wanna know how to distinguis between 2 letters with the same frequency
distinguish
You should update your first loop as far as I understand
medicines = list("ABCDE")
freqs = {medicine: 0 for medicine in medicines}
string = input()
for medicine in string:
freqs[medicine] += 1
okay...yea but the final value of freqs is gonna be the same right
Then for input "ABAAACEBDAE" you got {'A': 5, 'B': 2, 'C': 1, 'D': 1, 'E': 2} so you can sort dict pairs by value by using sorted(freqs.items(), key=lambda item: item[1], reverse=True)
so this is going to give someting like A B E C D or A E B C D like on what basis will it sort if the frequencies are the same
If freqs are same then it will use original order as far as I know
Result is [('A', 5), ('B', 2), ('E', 2), ('C', 1), ('D', 1)]
Yeah I do.. I'm making a Flask webapp that so far has the main application in app.py and another script which has a class with all its attributes and instance methods defined inside of it.. there isn't a way to access an instantiated object's class variable externally from app.py, is there?
Your welcome!
Can you spawn this script as a Python thread?
@trim fiber Well, I don't really think I need to create any threads in my application as it doesn't require heavily extensive tasks that need to processed
Then if you want to communicate two processes you can use FIFO or something similar but if you want to easily manipulate object from other script the best solution is to use threads
Are you aware of any youtube tutorials that explain threads in detail?
@trim fiber So the point I made earlier on is not possible other than making threads? There's no way to access a variable in class from another Python script?
true should be True, no?
NameError: name 'true' is not defined on line 3
true should be True, no?
is that the right link
ya
it seems to be the exact same as the one earlier
bcz i changed it beck to the global
sorry, i don't understand
me too
what did you change
.
as the link
what in the link in the code
did you change what i told you to change
float.is_integer()```
Return `True` if the float instance is finite with integral value, and `False` otherwise:
```py
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
THANK YOU SO MUCH
UR INSANE @mystic basin
uh melio one more wuick question
alg = lambda x: True if (x ** 1/2).is_integer() == True else False
uh is that the proper way too use it?
its returning false
returns false when i sqeare root perfect squars
oh
why dont i have to specific if it is true or not
still dont work
16
and 25
they both got perfect squares
4 and 5
what
idk what thiws trickery is
but it just started working for me
idk my python IDE is sus
i mean
ill use visual studio from now on 😄
or something online
yeah
idk why its weird on mme sometimes
whaa
i used biger numbers
like
121
and
it retunred false on 121
for some odd reason
ok dude now its returning true
dont mind this
its pycharm 🙂
lmao
bruh
Is there a way to generalize a root finding algorithm to solve generalized equations?
Basically i have some expensive function to calculate in a hot path of code: ```python
def f(x: int) -> float:
stuff happens here
I want to find a value for
f(x) < N
f(x+1) > N```
Basically the largest integer to meet the criterion.
right now I'm using a basic bisection method, but I was curious if i could steal from root finding and use a secant/interpolation/combination method? Or if this particular problem has a specific name for me to look up the literature on
This might be a dumb question. I have a list of hardware crash data for anytime a piece of HW crashes.
Example:
[dsp crash] Pmd.34938249324 e ent=12 pmasdaaa cf4
[dsp crash] Pmd.34933449324 ee nt=12 pmasdaaa cx
Using difflib, i can match them but running into a problem where i'm trying to build a dict that has say the first crash text and the count anytime it sees a match thats ~90% the same.
thoughts?
How do I go about solving this kind problem f program? The problematic part is figuring out the amount of days it takes to update "the servers" pretty confusing
I don't like videos as a form of learning but everything depends on you - if you like then use it 🙂
However remember that at some experience level there are no more video tutorials anymore 😦
Maybe there is but I don't know it. If you have two Python threads inside Python process you have Python which can communicate data from one thread to another. From another hand if you have two processes in your OS (can by Python programs or whatever) you can communicate data from one to another by using OS built-in methods (like FIFOs). There is a problem because you should write some kind of encoder/decoder that encodes your Python data into binary to transfer it through OS methods and you need to have decoder on the other side to decode binary into Python objects for example.
The easiest case is to spawn new Python thread inside script and use Python objects to communicate those threads.
I don’t mind reading aswell, but I can pick up concepts with videos quicker especially watching them x2
anyone coder here dm me
I'm not sure if I should do that in my application just yet as I've got few functionalities that I've need to implement
We can use deepcopy to copy variable's content, if it's to copy the nested items inside an object, right? i.e. a dictionary with a list of string names and integer values
I'm trying to define/rename an instance attribute in a Child class and copy over the content from a dict object declared in a Parent class --- but no values actually gets stored/shown (even when I instantiate a Child class instance member)
from copy import deepcopy
class Child(Parent):
def __init__(self):
super().__init__()
self.dict = deepcopy(self.parentDict)
@wild urchin I think I've got a problem when I deepcopy data found in the original dict object onto a new variable object - no values gets stored on it
Can you post a minimal code snippet that shows this issue you're having?
The code above doesn't include what the Parent class looks like
I'd suggest doing so in a help channel, rather than in this topical discussion channel.
I'm on #help-chili
@vocal gorge after thinking about it more I realized I’m not really interested in the entire table but just the frequency of values
From that problem in help-chlorine
so for example, “how many values are 2000 in the table” etc
so I’m thinking to create a dictionary with the keys as values and increment each access
the problem is that you're building the table by incrementing elements multiple times
so you can't easily transfer that into another form, I don't think
I see
how do you do the python typing for discord, is it ``?
Hi, can someone help me to visualize or understand the sentence below.
I guess the array would contain int32s, and each int, when converted to binary, would contain 32 ones and zeros, which would represent true or false, respectively
And the array would have a size of 128 million
@lean glade is bit vector is an array of arrays of int32s?
Uhh, no? Just an array of int32s.
well, they might want a vector of int32s. A vector being a dynamic array.
i just started to write a code for a simple binary tree and i have an attribute error. can someone help? i'm new
class Node(object):
def init(self,value):
self.value = value
self.left = None
self.right = None
class BinaryTree(object):
def init(self,root):
self.root = Node(root)
def print_tree(self, traversal_type):
if traversal_type == "preorder":
return self.preorder_print(tree.root, "")
else:
print("Traversal type " + str(traversal_type) + " is not supported.")
return False
def preorder_print(self, start, traversal):
if start:
traversal += (str(start.value) + "-")
traversal = self.preorder_print(start.left, traversal)
traversal = self.preorder_print(start.right, traversal)
return traversal
thanks
So this isn't a python question per se, but I have an array with 4 billion elements, and I have to iterate over all that, and increment each [x,y] for a given function. Some [x,y] will never be accessed, but others may be accessed multiple times.
what are some ways i can speed up this traversal? RAM isn't an issue
i will likely implement this in C as well.
Isn't it the same task you did earlier, which could be vectorized with .add.at?
oh, in C, I see. Yeah, then I don't have any advice besides "write the loop in a sideeffects-free way and hope for the compiler to optimize it right, preferably with vectorization".
in C, I see
...pun not intended.
@vocal gorge well I actually ended up doing it in C and surprisingly it finished in 2 minutes but in Python the loop ran for several hours
that's very possible if the Python one was just a loop too
What do you mean?
The function is pretty simple, just takes a lot of memory, it should take the same time in Python I’d imagine
But it did not
Python is slower than C even when you do a simple loop
but like, orders of magnitude slower?
I created simple functions in C and Python to calculate entropy and as far as I remember C code executes about more than 3 times faster
I think that creating Python objects is overwhelming
In C you can use simple types like int or char[], Python needs to create huge structures under the hood
that's part of it, yeah
i have an np array t = [3,2,4,2,4,NaN,NaN] and i have an array tisNaN = [False,False,False,False,False,True,True] (from np.isnan(t) and i want to delete the nan values out of t
how do i do it?
hi guys, Im not sure if this is the right channel but I want ´how can I create a list out of copy pasted text? I basically want a programm in which one copy pastes their insta followers and their insta following and I then want the programm to check who follows you but not them, who you follow but they dont back..... If i copy paste my followers, after every follower it says "profile picture", so I would like the list replace "profile picture" with a comma. Im very new so maybe there is an easy function to do this, but I have been googling for a while and didnt quite get what Im looking for....
I'd actually look into using the instagram API or a third party instagram api
would be much easier to just authenticate a user and log in and pull that information instead of having to copy and paste it yourself
but for me as a programmer API are far out of reach tbh
can I like replace "profile picture" with "," and then its a list?
i was trying this, I put it together from a few forums
s = input("Copy paste your followers here")
s = re.sub("profile picture" , "," , s)
f.seek(0)
f.write(text)
f.truncate(0)
print(s)
what does python do?
but it tells me "re" is not defined
Hello how can I delete one event object from the following dict:
my_dict = { user_id: { event_id: {'name': event, 'time': time} } }
del my_dict[user_id][event_id]
Right, here you are
Can i speak?
how would I do this:
genuinely lost
Note that another sample input can be 14 X X X X 18 X 16 X and output can be ```
14 16 18
14 16 18
14 16 18
Hey anyone know how to solve sudoku in python using the ac3 constrain satisfaction algorithm
do this on paper first. if you have two numbers from one line, how do you calculate the third? check with some simple values and then with letters: if you name the elements in the line a b c, how do you find value of b when you have a and c?
work from there - do the maths, try coding what you found out. that will cover some points
analyse what to do if you have more x's - e.g in your example with 6 x's, are there more solutions? 😉 how do you know when there are more solutions? (answer: ||that's the only solution there - we have a system of 6 independent linear equations, and we have 6 variables; more solutions are possible for "at least 7 x's" case which is for more points||)
Let's say I have a set, setA={dog, cat, mouse}, I would like to create a data structure with the strings in Set A, so it would make:
dog = {}
cat = {}
mouse = {}
is that possible?
*name the data structures with the strings in SetA
the easiest thing would be to just do a dictionary with those as keys. then you'd be able to do my_dict["dog"] to access the dog's structure
because if you name them from a set, how are you gonna use them in your code? with dict, you can access those structures by their string name
why would u do that tho
actually I can just create a class lol..
just realized that
I have a list of email addresses with data associated with them, so I wanted to create a set named after each unique email address
I'm wondering how search data structures like a trie works in the real world. Is the whole trie stored in memory or is this search / storage capability on the database level?
Hi, someone could help me create this function that would allow me to do that ? Thx x)
code = r"""
int a = 5;
foo2(16, 255);
...
"""
code = function(code)
print(code)
Output:
int a = 0x5;
foo2(0xA, 0xFF);
...
print(code)```
or do you want the function to format the string?
yes the function 😂
use string.split(";") and work it togeteher with "\n" in between?
can you explain the purpose of the method?
why you want a function like that
no 😂
I want a function to convert decimal to hexadecimal in a string
oh i havent seen the difference
i am lost sorry
that explains a lot i am really sorry
ah too bad, I hope someone else will have the solution 😅
def check_int_and_convert(s): if s[0] in ('-', '+'): if s[1:].isdigit(): return s[0]+hex(int(s[1:])) elif s.isdigit(): return hex(int(s)) else: return s
You can use exec but I recommend to use strings from set as keys in some dict
names = {"bat", "cat", "dog"}
struct = {name: {} for name in names}
Hello I'm trying to convert an object that contains a nested dict into a dictionary itself:
def to_dict(self) -> dict:
data = {
"notifications": self.notifications
}
return data
new_not = Notification()
new_not.notifications['users'][_id] = {}
new_not.to_dict()
I feel like I might be doing sth wrong
What is the problem?
You should consider using copy.deepcopy
I fixed
Hey 😄 It probably depends on the application, to be honest.
Hey guys, reading Algorithms in a nutshell, do I just sit with the complexity or should I focus on a prerequisite that I didn't know I needed?
I get the data structures part but the notations of the algorithms is just convoluted for me
if you just mean complexity notation, it isn't that hard to understand
http://www.usaco.org/index.php?page=viewproblem2&cpid=765
so uh i'm working on this problem, and i know that it involves bfs
but how do i do this in linear or linearithmic time
because for each state i also have to keep track of the pies given
maybe #databases would be better
@eager hamlet thanks.…..
I mean sure, I guess to read more will do
The definitions were in the next chapter lol
how to read these stuff
This is the definition of the O-notation.
Basically, if there exists some constant C such that, for all sufficiently large n, T(n) <= C F(n), then T(n) is O(F(n)).
For example, T(n) would be O(n^2) if T(n) <= C n^2 for some C and for all sufficiently large n.
@vocal gorge 🤔 its soo confusing
some examples:
1 - exp(-n)is O(1)5 n^3 - 10 n^2 + 5n - 120is O(n^3)3log(10n) + 10nis O(n)100000 n^1000 exp(-n)is O(1)
how can I spread (disperse) a set of numbers from n1 to n2 with an exact distance of each other ? Example, dx = 5 n1 = 1 and n2 = 3, so answer is 1, 1.5 , 2, 2.5 , 3
i am trying to figure out what formula to use in order to find that answer.
Well, one simple way to find it is to note that the formula must be linear, so it has the form f(n) = a * n + b. The coefficients a and b can be found by requiring f(0) = n1, f(dx-1) = n2
(of course, you can also just realise the distance must be (n2-n1)/(dx-1), because there are dx-1 increases between the first and the last point).
I understand this part, but still not too sure on how to find the 0,5 gap that seperates 1 to 3 in a dx=5 manner
not sure if my english is very good at explaining what i mean
apologies
...because (3-1)/(5-1) = 0.5?
oh oh okay damn. that was easy
is that formula linked with something a bit more general ?
alternatively, we have a general linear function a n + b. Requirements:
1)f(0) = 1, meaning b = 1.
2)f(4) = 3, meaning 4 a + b = 3, therefore a = 0.5
And in general, the formula is f(n) = n_1 + (n2-n1)/(dx-1) * n - the formula for a line drawn through points (0,n1) and (dx-1,n2)
I can't read Greek(?), so I don't know what you mean.
http://www.usaco.org/index.php?page=viewproblem2&cpid=765
so uh i'm working on this problem, and i know that it involves bfs
but how do i do this in linear or linearithmic time
because for each state i also have to keep track of the pies given so i don't accidnetally give 2 of the same pies for the same state
Are you asking about __new__?
ahh yes thank you, google sucks at showing these results
Are there any good books to learn algorithms that have examples in python
Grokking Algorithms
guys i need help in minimax algorithm
I am trying to make a tic tac toe Ai using minimax
Hey @gilded turtle!
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:
it keeps throwing an error
Traceback (most recent call last):
File "D:\Coding\Projects\Unbeaten_X&O\main.py", line 172, in <module>
minimax(Board, 6, True)
File "D:\Coding\Projects\Unbeaten_X&O\main.py", line 156, in minimax
e_val = minimax(bo, depth-1, False)
File "D:\Coding\Projects\Unbeaten_X&O\main.py", line 164, in minimax
e_val = minimax(bo, depth-1, True)
File "D:\Coding\Projects\Unbeaten_X&O\main.py", line 156, in minimax
e_val = minimax(bo, depth-1, False)
File "D:\Coding\Projects\Unbeaten_X&O\main.py", line 162, in minimax
index = Board.index('-')
ValueError: '-' is not in list
Just a fairly quick question, what are the different ways to do "getters" and "setters" in Python, let's say for a variable named myList of the datatype, list, initialised normally in a class constructor?
class MyClass:
def __init__(self, lst):
self.my_list = lst
@property
def my_list(self): # getter
return self._my_list
@my_list.setter
def my_list(self, value): # setter
self._my_list = value
class MyProperty:
def __set__(self, instance, value):
instance.__dict__[self.name] = value
def __get__(self, instance, owner):
if instance is None:
return self
return instance.__dict__[self.name]
def __set_name__(self, owner, name):
self.name = name
class MyClass:
my_list = MyProperty()
def __init__(self, lst):
my_list = lst
Huuu anyone to explain me this error plz...
Traceback (most recent call last): File "compiler.py", line 7, in sol = solve(expr) File "/usr/local/lib/py/dist-packages/sympy/solvers/solvers.py", line 1162, in solve solution = _solve(f[0], *symbols, **flags) File "/usr/local/lib/py/dist-packages/sympy/solvers/solvers.py", line 1444, in _solve soln = _solve(m, symbol, **flags) File "/usr/local/lib/py/dist-packages/sympy/solvers/solvers.py", line 1498, in _solve f_num, sol = solve_linear(f, symbols=symbols) File "/usr/local/lib/py/dist-packages/sympy/solvers/solvers.py", line 2072, in solve_linear eq = lhs - rhs TypeError: unsupported operand type(s) for -: 'Tuple' and 'int'
Ooo
I just understood
Could you talk through explaining how this works internally, if you don't mind @stable pecan ? @flat sorrel approach is fairly the simple way... easily understood 👍 😀
You tried to subtract an integer from a tuple 🙂
Sometime happens if you put somewhere a comma... 🙂
where you didn't want to...
i would read the descriptor how-to in the python docs: https://docs.python.org/3/howto/descriptor.html
this is the order of attribute lookup python uses
hey how do i use excel cell value as input for driver.get(cellValue) to vist that url in cell. I have already imported the cell value and workbookwith openpyxl
Hi! I am making a project regarding graph theory in python.
Is there a algorithm to split a minimum spanning tree into many paths? (Path is basically a line with 2 ends only) attached are 2 images which might be helpful.
I couldn’t find any answers on google.
This is an interesting problem!
Are you trying to turn the connectogram @ the top, into something like what you display at the bottom? Do you know what sort of constraints, or additional rules ?
Overlap is fine
I think the search could be limited at some point, and the time complexity will be very high as the nodes increase
yes, of course, as well as the degree of each node
how are you representing the top image?
I have a nxn distance/adjacency matrix
NxN with 1's and 0's denoting connection?
Nxn for weight, in this case it’s the pixel distance
what is the weight needed?
Btw it is a complete graph, all the nodes have a weight to every other node
yeah, but I don't think you need to weight each node to answer the question you posted at the very top
Oh yeah
It's easier to visualize a way forward if you cast the graph in a different representation, e.g. not the adjacency matrix which I think you're using
because, to code this, you have to know where to go once you're at a given node.
you also have to store the paths somewhere
Try the adjacency list.
I was thinking of a array eg 1,3,5 connects 1 to 3 to 5
Is there other ways to represent a tree?
I've done a similar problem to this one, but using adjacency lists. The code was messy AF, but it worked always
Oh so something like a dictionary?
yeah, like a dictionary. I am not sure if this is efficient but it will at least help you visualize a programming solution
it is harder to do visualize what is going on with the adjacency matrix representation
"An implementation suggested by Guido van Rossum uses a hash table to associate each vertex in a graph with an array of adjacent vertices. In this representation, a vertex may be represented by any hashable object. There is no explicit representation of edges as objects"
Guido van Rossum, Mr Python Inventor himself
So, to find your paths, you have to figure out some way of coding through all the permutations that the dictionary / hash table produces. There are additional problems that arise when you try to avoid repeating paths, not going around in circles, etc.
Do I basically connect each end to another end?
the structure of the graph will obviously be encoded in the adjacency list. What your code needs to do is simply inspect this structure aided by the how it is encoded.
like the A-B-C triangle in the preview
a={b,c}
b={c,a}
c={a,b}
(Sorry if there’s a better channel for this.)
Are there any PEP guidelines (or other principles) on whether you should make your class subscriptable or not?
if you start in a, you notice that there are 2 directions: b & c. Then your code will have to explore each separately, with the first path a-b, and the next a-c.
etc.
Ah I see, I’ll try to implement this
Do you think it will be good to start at a node more at the center?
btw, as I said, I did this in the past, but with a constraint of 2 edges.
and it was a nightmare scenario of nested loops and gotos
(C++, not python)
Do you think I can have a look?
tbh, it would take you less time to sort it out on your own than it would to figure out my spaghetti
“Do or do not. There is no try.”
😂
words = ['book', 'pencil', 'pen', 'note book', 'sharpener', 'rubber']
def arraySearch(array, search):
return True
print(arraySearch(words, 'note book') if 'Vrai' else 'Faux')
print(arraySearch(words, 'dog') if 'Vrai' else 'Faux')```
help me understand?
algo termaire ?
arraysearch doesn’t seem complete
okay !!thanks
words = ['book', 'pencil', 'pen', 'notebook', 'sharpener', 'rubber']
def arraySearch(array, search):
for i in range(len(words)):
if words[i] == (array, search):
print(arraySearch(words, 'note book') if 'VRAI' else 'FAUX')
elif words[i] != (array, search):
print(arraySearch(words, 'dogs') if 'VRAI' else 'FAUX')
return True```
like this
my teacher gave me the first code but didn't give us any instructions, I'm looking for a way to understand, I just know that it has something to do with a sorting algo!?
thank you for these precisions
What’s vrai and faux?
Hi, I have two variables but I want them to have difference reference ids:
self.x = aep[1] self.y = aep[1] self.x[key] = 'test' self.y[key] = 'test2' print(self.x) #prints key with value test2 print(self.y)#prints key with value test2
How can avoid this and have both variables to have different references so self.y prints test2 and self.x prints test
You need to make a copy of aep[1], rather than have two references to the same object. Use self.y = aep[1].copy() (or the deepcopy library if this is a nested object you need to fully copy).
(also, it's more of a question for a help channel or #python-discussion)
oh sorry
but thanks anyways
Yup, that's pretty much it. In Python, all assignments are by reference - a copy is never made without explicitly doing so.
(really, most other languages are the same - only primitive types are passed by value, a big object like Map would never get implicitly copied. In Python, there also aren't such primitive types).
Thanks a lot!👍
hello, so i want to create a basic search mechanism in my website but i have trouble making out the logic for it. so the idea is that a user searches something using the search bar right? so i want to show records from database related to quries that user has searched number of times. but i still want to take into the account the time factor. for example: if user searched for oranges 7 times but that was a month back. and the user searches for apples 6 times but it was just a week back. the latest search should have more priority right? what kind of algorithm i should use here? im sure there's already an algorithm for this which exists. any intresting read that you can point me to would be great?
hey i created this
Hey @dusk quest!
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:
why don't you post it in a help channel instead? #❓|how-to-get-help
or use a pasting service (see below)
@dusk quest
Hey @dusk quest!
It looks like you tried to attach file type(s) that we do not allow (). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .flac, .afdesign, .m4a, .csv.
Feel free to ask in #community-meta if you think this is a mistake.
;-;
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.
milfs
Would webscraping somewhat fit here?
hi, I was reading an algo & ds book and I just had a question.
so, arrays store elements contiguous in memory. arrays (unlike linked lists) can have random access, so you can read the 5th index (which is O(1) compared to reading the 5th index of a linked list where you traverse the elements before it, making it O(n)). So, linked lists have sequential access.
So my question is, when using python (for example) using lists, is that saved in RAM as it's random access?
Python lists are, under the hood, vectors of pointers to PyObjects (which is the class of all Python objects, ultimately).
A vector is a dynamic array - it's an array that gets resized when it starts running out of space. So yeah, it's O(1) random access. Not sure what you mean by saved memory - access complexity and memory usage aren't related in an obvious way (though linked lists are terrible in both, and in general - it's a data structure that everyone gets taught, but is rather rarely used).
i see, thank you very much for the explanation! I think I just confused lists being "random access" and made a link with RAM "random access memory" and thought there was a link. i must say, this algo stuff is pretty interesting so far 🙂
also it probably doesn't help that python is a high level language so we cant handle our own memory and understand it, there might be a bit of obfuscation there
Yup, that's pretty true. It's a bit harder to learn DSes in Python than in compiled languages, because implementing them manually in Python is not very useful (any implementation you can make in pure Python will often be literally orders of magnitudes slower than the C-based implementations of the standard library). You still need to know DSA to know when to use the right data structures, though, so it's by no means useless even for Python.
and yeah, being far removed from handling memory makes it harder to understand too
can someone help with sklearn here
Well, It's probably connected to machine Learning or data science so you should probably ask in #data-science-and-ml
But I don't know your question so idk
i want to create a boxplot via pandasDataFrame.boxplot(column="dataColumnName", by="seperatingColumnName") but the data in the "dataColumnName" is a list and only the last value of the list should be used. Is there an efficient and clean solution for my problem?
How can i get the last date by symbol in this dict of tuples
('2020-12-02', 'FB'): -5025,
('2020-12-04', 'FB'): 1950,
('2020-12-01', 'AAPL'): 15000}````
from dateutil.parser import parse
my_dict = {('2020-12-01', 'FB'): 2000,
('2020-12-02', 'FB'): -5025,
('2020-12-04', 'FB'): 1950,
('2020-12-01', 'AAPL'): 15000,
('2021-12-01','test'): 0000}
most_recent_date = '1900-01-01'
symbol = None
for key, value in my_dict.items():
if parse(key[0]) > parse(most_recent_date):
most_recent_date = key[0]
symbol = key[1]
print(symbol)
is this the sort of thing you're going for?
[{'FB':'2020-12-04'}, {'AAPL':'2020-12-01'}]
im looking for something to the sorts of
from x
group by sym```
oh you want them sorted?
i just need the last date for each sym
sorry, I'm not sure I understand. You're saying you want to pass the function a symbol, and then have it return the last date in the dictionary associated with that symbol?
so here, you would pass it 'FB' and it would return '2020-12-04'?
I wouldnt be passing in a symbol. I just need to for each symbol, in this case there is only two FB and AAPL, return me the latest available date
should it return that in another dictionary?
yeah thats perfectly fine
try this and see if it does what you want:
from dateutil.parser import parse
my_dict = {('2020-12-01', 'FB'): 2000,
('2020-12-02', 'FB'): -5025,
('2020-12-04', 'FB'): 1950,
('2020-12-01', 'AAPL'): 15000,
('2021-12-01','test'): 0000}
symbol_dict = {}
def create_symbol_dict():
for key, value in my_dict.items():
if key[1] not in symbol_dict.keys():
symbol_dict[key[1]] = key[0]
def update_symbol_dict_dates():
for key, value in my_dict.items():
if parse(key[0]) > parse(symbol_dict[key[1]]):
symbol_dict[key[1]] = key[0]
create_symbol_dict()
update_symbol_dict_dates()
print(symbol_dict)
yeah this is great!
you know how it works? if you have any questions on what I did, let me know
great,yeah i understand. The only thing i was thinking was a will probably want to use a set for the tickers
instead of a function
yeah, it might be cleaner that way
hey guys, anyone know Java and can help me go thru each problem on the codility quiz website so I can be prepared for a job interview soon?
Sorry, this is a Python server so we won't offer help on Java outside of the off-topic channels (and even so, you might want to visit the Java server instead)
thx buddy
np
@fiery cosmos How about call help(fxcmpy.fxcmpy)?
Your welcome
This library uses logging under the hood, here is the source code: https://github.com/chaipat-ncm/fxcmpy/blob/master/fxcmpy/fxcmpy.py#L121-L126
I don't know why there are 10, 20, 30 and so on but when you set for example log level to warn (30) you get logs from error too because 40 > 30 (so you get all log levels above choosen)
Your welcome!
names = ['Tamata', 'Nicolas', 'Marie-Claude', 'Oriane', 'Florian', 'Yvanne', 'Jordan', 'Joyce', 'Julien', 'Clément', 'Jeremy', 'Daren', 'Mikaele']
def arraySort(myArray):
# code here ...
print(arraySort(names))```
I have to sort all the names in alphabetical order, I have to use the sort by insertion, which could make me rotate the code in all directions but no result.
without using .sorted
What is the problem? Where is your algorithm?
names = ['Tamata', 'Nicolas', 'Marie-Claude', 'Oriane', 'Florian', 'Yvanne', 'Jordan', 'Joyce', 'Julien', 'Clément', 'Jeremy', 'Daren', 'Mikaele']
alphabet=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
def arraySort(myArray):
for i in myArray:
if i in alphabet:
return myArray
print(arraySort(names))
First of all you can use list(string.ascii_letters) to create array of letters
Secondly - I cannot write the algorithm instead of you because it breaks rules
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.
Show your minimal effort please
I understand but I'm just looking for a way out.
Take a look at pseudocode here: https://en.wikipedia.org/wiki/Insertion_sort
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. However, insertion sort provides several advantages:
Simple implementation: Jon Bentley shows a three-line C version, and...
thx
You can come here when you will have a problem with some part for implementation
okay thx
(get_data,) is a tuple, but (get_data) is just get_data
(value) can't be a tuple, since it would break parentheses for math
add_callbacks expects some iterable of callbacks
but (5 + 6) * 8 is 88, not a tuple.
in order to create a tuple with a single element in it, you need a comma
(5 + 6,) * 8 is (11, 11, 11, 11, 11, 11, 11, 11)
it is not great, but there is real way around it
you could also just do [get_data] and avoid this whole issue
I don't suppose anybody can help me out with something? So I'm creating a pandas **dataframe **from a dictionary, which is populated with mixed **entities **as keys (that includes names of country/people/object etc) and the **occurrences **of that particular entity is stored as the corresponding **value **... Here's how I'm making a dataframe from the dictionary key-value pair items... ```py
def convert_dict_into_dataframe(self):
df = pd.DataFrame.from_dict(self.myDict, columns = ['Entities', 'Frequency'])
return (df.head())
Are there any ways to simply check which elements in a df column i.e. Entities, is contained (recognised as a country) in a list of predefined country list object let's say called countryList...? And then with this, be able to extract those identified elements, "countries", and add it to a new column in the **dataframe **table where it just contains data fields of countries.. is this something which can be done?
May I ask what is the time complexity when an integer x keeps on divided by 10? Is it O(log(x))?
Let say x = 123 and
while x > 0:
# Some if-block going on here
x = x // 10
I think it's rather O(n)
However... It depends on number of digits... So number of digits can be calculated by log_10(x) so...
Additionally, so that's a question with a solution. And the solution says
There are roughly log_10(x) digits in x.
What do they mean by that?
What do you mean by it can be calculated by log_10(x) ?
When you want to know number of digits of some number x in base of y you count how many multiplications of y are in x
So you want to find such n that y^n = x
Am I correct?
So if you want to find n then n = log_y(x)
Oh yeah, math. I forgot that.
Ya, math. Queen of the science
Thanks for reminding me.
Your welcome!
🔥
Hi, how can i make a thread to when i input a word this for loop restarts
while True:
downloadFiles()
for remaining in range(10, 0, -1):
sys.stdout.write("\r")
sys.stdout.write("{:2d} seconds remaining.".format(remaining))
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\rComplete! \n")
This for is a timer countdown
I have a doubt in your code can I ask?
translate = lambda x:(ord(i).split() for i in x)
<generator object <lambda>.<locals>.<genexpr> at 0x00000249AF5EC890>
thats hte output
why is it not returning the unicode of the letters in the string in a list
yes
you are clearing the output right
but you are clearing the output before sleep
which clears the output and waits for a sec and then show the output and clears it immediately and so on
So here i have two programs that output the same thing. ```py
m = int(input())
n = int(input())
brushes = input()
stroke = []
colors = [['B' for _ in range(n)] for _ in range(m)]
for i in range(int(brushes)):
g = input().split(' ')
if stroke.count(g) == 1:
stroke.remove(g)
else:
stroke.append(g)
def changeColumn(num,colors,index):
if num == 0:
return colors
colors[num-1][index] = 'G' if colors[num-1][index] == 'B' else 'B'
num -= 1
changeColumn(num,colors,index)
def countGold(c,options,i):
if options == []:
s = 0
for l in c:
s += l.count("G")
print(s)
return
area = options[i][0]
times = int(options[i][1]) - 1
if area == "R":
c[times] = list(''.join(c[times]).replace("G","A").replace("B","G").replace("A","B"))
elif area == "C":
changeColumn(m,c,times)
options.remove(options[i])
countGold(c,options,i)
countGold(colors,stroke,0)
and and ```py
c = int(input())
rows = int(input())
brush = int(input())
strokes = []
tc = []
for i in range(c):
tc.append('B' * rows)
for i in range(brush):
strokes.append(input().split(' '))
for i in range(brush):
if strokes[i][0] == 'R':
new_str = ''
for char in tc[int(strokes[i][1]) - 1]:
if char == 'B':
new_char = 'G'
elif char == 'G':
new_char = 'B'
new_str += new_char
tc[int(strokes[i][1]) -1] = new_str
elif strokes[i][0] == 'C':
new_str = ''
for j in range(c):
if tc[j][0] == 'B':
old_char = list(tc[j])
pos = strokes[i][1]
old_char[int(pos)-1] = 'G'
tc[j] = (''.join(old_char))
elif tc[j][0] == 'G':
old_char = list(tc[j])
pos = strokes[i][1]
old_char[int(pos)-1] = 'B'
tc[j] = ''.join(old_char)
s = ''
for t in tc:
s += t
print(s.count('G'))
i was wondering which one is more efficient
Hello guys !
Does someone can help me on an implementation of the IDA* algorithm with Manhattan heuristic ?
Question here : https://stackoverflow.com/questions/66264958/how-can-i-implement-ida-algorithm-in-pyhton-for-15-puzzle-problem
im trying to write a function that takes in a 2D list and if there's any duplicate values, merges the sublists:
[[1,2,3],[1,4,5],[6,7,8],[1,9,10],[12,3,4]] -> [[1,2,3,4,5,9,10,12], [6,7,8]]
def merge(lst: list) -> list:
next_value = 1
all_items = []
for sub in lst: # group all items to check for dupes
all_items += sub
merged = False
while len(set(all_items)) != len(all_items): # check if dupes
for sub in lst:
for item in sub:
for _sub in lst: # iterate through each sublists items and check if they are in any other sublist
if item in _sub and (sub != _sub or id(sub) != id(_sub)): # ids have to be checked in case 2 sublists have the same values
print(f"before: {lst}")
sub_index = lst.index(sub) # get sublist index
sub += _sub # merge the two sublists together
lst[sub_index] = list(set(sub)) # remove the dupe
lst.remove(_sub) # remove the merged sublsit
merged = True # set flag
print(f"after: {lst}")
else:
pass
else: # once the sublists are exhausted, skip checking the other values in the sublist
if merged: merged = False; break
for sub in lst:
all_items += sub
return lst```
I'm not quite sure where im going wrong and if there's a better solution for it (im assuming there's something in itertools but im not familiar with it)
Hi, what is the time complexity of the code below? My initial thought is O(n) but I realize the min() function could affect the runtime but I'm not sure.
# strs = ["foo", "bar", "foobar", "barfoo"]
min_len = 0
for word in strs:
min_len = min(min_len, len(word))
the min function does affect it
Hey guys, does anyone know how to compare words from a list to words from a txt file? My purpose is to compare a sentence to a grammar and perform a leftmost derivation operation.
If anyone is familiar with how to implement left most derivations that'll help too
then what should be the time complexity of it?
think about what operations min does
min compares two number only. We can do it in this form too:
if min_len < len(word):
return min_len
else:
return len(word)
And that is O(1)
I would read the words in from the text file into a list then compare the two lists. Do you know the syntax for file io in python?
Hey,
I am an intermediate python programmer , but I only have experience of python
What's the best time for me to start learning algo and data structures
Once you are comfortable with OOP
Guys can anyone help me with this error
You're already using TensorFlow 2
If you're using the latest version I think you can import feature_column directly from tf
Btw, if you're dealing with machine learning, you should ask in #data-science-and-ml
TensorFlow Material?
I don't really see TensorFlow being used outside of the machine learning field
Ok thnx 😀
Ohk
I don't but I can look online
Thank you for your help tho man
class Pool:
def __init__(self):
pass
def to_dict(self) -> dict:
data = {
"_id": self._id,
"choices": self.choices,
}
return data
my_new_pool = Pool()
my_new_pool._id = 1
key = "1"
my_new_pool.choices = {}
my_new_pool['choices'][key] = 'value'
print(my_new_pool['choices'][key])
```It doesn't give me its value
my_new_pool.choices is not my_new_pool["choices"]
Try my_new_pool.to_dict()["choices"]
Roger that, I will try that thank you
Let's say I have this problem: Input Specification: First Line: contains an integer, M (1 < M < 1 000 000) Next M lines: contains two integers For example: ```py
5
1 2
3 4
5 6
7 8
9 10
I know you can do this using this:py
m = input()
for i in range(m):
numbers = input()
how would you be able to reduce the complexity
Time complexity? Definitely not, how'd you read numbers without reading them?
you have to read every integer, and to read it, you have to look at them
also I have another questions
also, you're missing a cast to int
So i have this problem: ```
Problem Description
A new and upcoming artist has a unique way to create checkered patterns. The idea is to
use an M-by-N canvas which is initially entirely black. Then the artist repeatedly chooses
a row or column and runs their magic brush along the row or column. The brush changes
the colour of each cell in the row or column from black to gold or gold to black.
Given the artist’s choices, your job is to determine how much gold appears in the pattern
determined by these choices.
Input Specification
The first line of input will be a positive integer M. The second line of input will be a positive
integer N. The third line of input will be a positive integer K. The remaining input will be
K lines giving the choices made by the artist. Each of these lines will either be R followed
by a single space and then an integer which is a row number, or C followed by a single space
and then an integer which is a column number. Rows are numbered top down from 1 to M.
Columns are numbered left to right from 1 to N.
Output Specification
Output one non-negative integer which is equal to the number of cells that are gold in the
pattern determined by the artist’s choices.
And I have two pieces of code, but idk which one is more efficient
I have a questions
So on the first line of input are two numbers, N and M
The next M lines contain 3 numbers, X Y and Z
How would I generate an array in which the GCD (Greatest Common Divisor) of arr[(X-1)] and arr[(Y-1)] are equal to Z. Note that this array must fall true of all of the different M lines. For example: ```py
2 2 #2 is N, 2 is M
1 2 2 # X is 1, Y is 2, Z is 2
2 2 6 # X is 2, Y is 2, X is 6
[4,6] #The GCD of arr[X-1] (4) and arr[Y-1] (6) is 2 (Line 1)
#The GCD of arr[X-1] (6) and arr[Y-1] (6) is 6 (Line 2)
pls see
if y'all could help
what does that comment say?
hi all; what's the best way of storing info in this format, but if i want to be able to search efficiently with both the name or detail?
sorry for my quick whiteboard sketch
should i make 2 copies of the json, 1 for name and other for detail?
1 name can have multiple details and 1 detail can have multiple names
I'm not sure but I think you can try this greedy algorithm:
For each i from 1 -> n, arr[i - 1] is LCM of all Z in lines which X or Y equals to i + 1.
If the resulting array does not fit the criterias then it's probably impossible 🤔
What you did and what is the problem?
has anyone seen this problem before
Consider an array, a, of n distinct positive integers where the elements are sorted in ascending order. We want to find all the subsequences of a consisting of exactly m elements. For example, given array a = [1, 2, 3, 4], the subsequences consisting of m = 3 elements are {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, and {2, 3, 4}. Once we have all of the m-element subsequences, we find the value of globalMaximum using the following pseudocode
for each subsequence, s, consisting of m elements {
currentMinimum = 1018
for each (x, y) pair of elements in subsequence s {
absoluteDifference = abs(x - y)
if absoluteDifference < currentMinimum {
currentMinimum = absoluteDifference
}
}
if currentMinimum > globalMaximum {
globalMaximum = currentMinimum
}
}```
i am not fully understanding the concept of global maximum
based on the example outputs provided
writing a programm for this exercice it's words guessing game
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.
As far as I understand globalMaximum is the biggest difference between two elements in all considered subsequences
which is what i believed, not sure why this is the result though
After the iteration on subsequence {1, 2, 3}, the value of globalMaximum is 1.
After the iteration on subsequence {1, 2, 4}, the value of globalMaximum is 1.
After the iteration on subsequence {1, 3, 4}, the value of globalMaximum is 1.
After the iteration on subsequence {2, 3, 4}, the value of globalMaximum is 1.
Thus, the function returns 1 as the answer.```
Oh, I am wrong
We are calculating currentMinimum so globalMaximum is the biggest of the smallest absolute difference between two elements
The subsequences of array a = [1, 2, 3, 4] consisting of m = 2 elements are {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, and {3, 4}.
After the iteration on the subsequence {1, 2}, the value of globalMaximum is 1.
After the iteration on the subsequence {1, 3}, the value of globalMaximum is 2.
After the iteration on the subsequence {1, 4}, the value of globalMaximum is 3.
After the iteration on the subsequence {2, 3}, the value of globalMaximum is 3.
After the iteration on the subsequence {2, 4}, the value of globalMaximum is 3.
After the iteration on the subsequence {3, 4}, the value of globalMaximum is 3.
Thus, the function returns 3 as the answer.```
here is another example
last one
The subsequences of array a = [1, 2, 4, 5, 8] consisting of m = 3 elements are {1, 2, 4}, {1, 2, 5}, {1, 2, 8}, {1, 4, 5}, {1, 4, 8}, {1, 5, 8}, {2, 4, 5}, {2, 4, 8}, {2, 5, 8}, and {4, 5, 8}.
After the iteration on the subsequence {1, 2, 4}, the value of globalMaximum is 1.
After the iteration on the subsequence {1, 2, 5}, the value of globalMaximum is 1.
After the iteration on the subsequence {1, 2, 8}, the value of globalMaximum is 1.
After the iteration on the subsequence {1, 4, 5}, the value of globalMaximum is 1.
After the iteration on the subsequence {1, 4, 8}, the value of globalMaximum is 3.
After the iteration on the subsequence {1, 5, 8}, the value of globalMaximum is 3.
After the iteration on the subsequence {2, 4, 5}, the value of globalMaximum is 3.
After the iteration on the subsequence {2, 4, 8}, the value of globalMaximum is 3.
After the iteration on the subsequence {2, 5, 8}, the value of globalMaximum is 3.
After the iteration on the subsequence {4, 5, 8}, the value of globalMaximum is 3.
Thus, the function returns 3 as the answer.```
Updated my message above, check it
sub sequence as in (1,2), (2,3) -> (1,2,3)?
No, it's like (1, 2, 3) with m = 2 then (1, 2), (2, 3), (1, 3) so every possible combination
https://www.wolframalpha.com/input/?i=n+choose+k
hi y'all. I'm in search of deeper knowledge. by accident I wrote a condition which gets really good results, but it's obviously bogus, so I want understand what it actaully does. I know when accessing a panda dataframe viadataframe.loc[] "Logical Operators in Pandas are &, | and ~, and parentheses (...) " are important. And that you are actually generating a series which then gets used as an index.
This is the code I'm talking about:
dataframe.loc[
(
(dataframe['ha_marubozu']) &
(dataframe['smooth_ha_green']) &
(False) & # WHAT DOES THIS DO?
(dataframe['smooth_ha_green'].shift(2) != True) |
(dataframe['smooth_ha_green'].shift(3) != True) &
(dataframe['volume'] > 0)
),
'buy'] = 1
Does (False) & just flip a column (before or after?). If I delete (False) & I actually get different results
@trim fiber thanks for the help
Your welcome
I suspect it may have something to do with the bitwise |
Ok, to answer my own question. Basically what it does, it negates everything that comes before (False) &. It' like I just deleted:
(dataframe['ha_marubozu']) &
(dataframe['smooth_ha_green']) &
@trim fiber in example 2, are we comparing the differences between ([1,2) and (2,4) and since 2-1 < 4-2 the global maximum is 1
then do that for each ele
About which one are you talking?
This one?
Before first iteration we have globalMaximum = 0.
Then from subsequence {1, 2, 4} we get localMinimum = 1 then localMinimum > globalMaximum so globalMaximum = 1
Later next sequences {1, 2, 5}, {1, 2, 8} and {1, 4, 5} gives us localMinimum = 1 so we don't update globalMaximum.
In each other sequences we get:
{1, 4, 8}gives3because4 - 1is less than8 - 4soglobalMaximumis now3;{1, 5, 8}gives3too;{2, 4, 5}gives1but1is less than currentglobalMaximum;{2, 4, 8}gives1too;{2, 5, 8}gives3so don't update because it's equal toglobalMaximum;{4, 5, 8}gives1again.
@trim fiber thanks so much
last question @trim fiber why does - {2, 4, 5} gives 1 but 1 is less than current globalMaximum; give 1, looking at the example it is returning After the iteration on the subsequence {2, 4, 5}, the value of globalMaximum is 3
help idk whats wrong with my while loop
while phcid == True do:
phcid is a var
boolean
do is wrong.
Also, it'd fit more in a help channel or general 🙂
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.
okay
(see #❓|how-to-get-help if you don't know how the channels work)
thank you
Does anyone have experience with Trie's? Attempting to convert this kinda brute force method into a trie instead. I was told it would be more efficient but I'm having a hard time understanding the concept entirely. If you get what I'm talking about, let me know and I'll show ya the whole algo question.
def removeDuplicates(str):
return "".join(set(str))
def numKeypadSolutions(wordlist,keypads):
a=[]
for x in wordlist:
x=removeDuplicates(x)
for x in keypads:
flag=True
count=0
for y in wordlist:
if(x[0] not in y):
continue
for z in y:
if(z not in x):
flag=False
break
if(flag):
count+=1
a.append(count)
return a
wordlist=['APPLE','PLEAS','PLEASE']
keypads=['AELWXYZ','AELPXYZ','AELPSXY','SAELPRT','XAEBKSY']
a=numKeypadSolutions(wordlist,keypads)
print(a)
Hey @small sage Do you still need help with your problem? Just reading up on that algorithm.
Alright 😄
So, it's the algorithm to union two sets in a disjoint set data structure that you need help with?
What's your problem with Union Find?
Hello algorithms experts, I have 2 questions about the following algorithm. What is the specific type of algorithm used in the sort() method, and how can I tell the complexity in Big O notation?
class Algorithm:
"""
A class to represent an algorithm.
...
Attributes
----------
Methods
-------
sort()
outputs a sorted list of integers
"""
def sort(self, data, length): #(data, n):
""" Outputs a sorted list of integers
Parameters
----------
data : list
a collection of integers as a list
length : integer
an integer value representing the len() of the data list
"""
if length == 1:
print(data)
return
for i in range(length):
self.sort(data, length - 1)
if length % 2 == 0:
data[i], data[length - 1] = data[length - 1], data[i]
else:
data[0], data[length - 1] = data[length - 1], data[0]
that sounds like a test question?
The test was to use it (it swaps numbers around so 1 2 becomes 2 1) and say what the Big O is. I just want to know what it is and how to even try to find the Big O
Just looking for some general guidance, not an answer
is it a test question?
It's part of a homework assignment to say what the complexity is in Big O.
ok, what do you think it is
It seems like quadratic time because it takes really long to run when I put in a lot of inputs
why isn't it cubic then
it can't have two time complexities
and time complexity is based on how it changes, so it's not just about when the length is 1
understood, thank you
time complexity here you have (n) iterations for the first loop then for each time in that n you have to call the recursion which decrease size by 1 each time so it will call itself n times as well until it reaches the base case at length =1
so Time Complexity = n*n *(Condition)
Condition = O(1) Because its assignment
nn1 = n^2
nn1
nn1=n^2
sort of an n-length list calls, n times, sort of an n-1-length list, and also does n O(1) operations.
So the recurrent equation for T(n) is:
T(n) = n T(n-1) + n
and T(1) is around n operations (it's a print)
Funny thing, i'm also learning about the BigO notation atm
This recurrent equation is solved by approximately n!. So factorial complexity, if I didn't mess anything up.
way higher than O(n^2). @dreamy arrow
alright
here's a plot of computation time vs the list's length
Same plot with logarithmic y axis. As you can see, time appears to be exponential with the list's length, but you can also see a slight curve upwards compared to the straight line approximation (orange line) - factorial complexity indeed.
j
can I plz get help i dont understand this question based on the essay Look Away by Siri Hustvedt?
Hustvedt recounts a story about her daughter, Sophie’s, experience on the subway and the way in which a fellow passenger ‘broke the code’ of the “pretend-it-isn’t-happening law.” In doing so, Hustvedt argues, the man gave Sophie “a feeling of ordinary human solidarity.” Explain what she means by this and why she feels it’s so important.
...how is that related to algorithms and data structures, or even programming at all?
use gpt3, duh @vocal gorge
But that's #data-science-and-ml 😉
that's still an algorithm though
is there a way to dynamically use the len of a tuple to use in a for loop
for example if the length of the tuple == 2 then -> for x,y in tuple: and if the tuple len==3 then -> for x,y,z in tuple"
wait for pattern matching in 3.10 i guess lol
Pretty sure a similar thing can be solved if you look into *args and **kwargs @rancid patio https://realpython.com/python-kwargs-and-args/
# sum_integers_args.py
def my_sum(*args):
result = 0
# Iterating over the Python args tuple
for x in args:
result += x
return result
print(my_sum(1, 2, 3))
i don't see how that's useful here
this is what im doing
n = 2
x =list(combinations( [1,2,3,4], n))
gloabl = 0
local_min = 0
n = 2
for a, b in x:
lm = findMinDiff((a,b),n)
if lm > local_min:
local_min= lm
local_min```
so n will obviously change, up the the length of the list
mhm, and if you have a helper function which takes *args
you can deal with the varying amount of iterables
@agile sundial making me feel crazy but i'm pretty sure i'm making sense
I think you are, too.
🙏
*args right?
But that's overcomplicating it, I think
ah, fair enough
# Initialize difference as infinite
diff = 10**20
# Find the min diff by comparing difference
# of all possible pairs in given array
for i in range(n-1):
for j in range(i+1,n):
if abs(arr[i]-arr[j]) < diff:
diff = abs(arr[i] - arr[j])
# Return min diff
return diff```
You can just do:
for t in x:
lm = findMinDiff(t, n)
...
yeah, ^