#algos-and-data-structs
1 messages · Page 150 of 1
and then come up with some sensible scoring
it allows you to more sensibly model 2s if you want to
my suggested naive approach would score by treating 2s as zeroes and basically just sum everything up (+ a sign change in relevant scenarios)
Yes yes I think this is staring to make sense. The mod also helps me comprehend the cyclical nature too. I was way overcomplicating it to try and get the cycle effect. I'll give it a few implementations. I think I have a general idea of extrapolating it into more complex scenarios. Thank you!
Finding the right way to model things tends to simplify the problem a bunch 🙂
Indeed :) The actual use case has a lot more pieces, but this model makes it like 1000x easier to comprehend
having it constrained to only 4 options does also make the problem more annoying than if it was a real value representing the direction
because of the case where you have +-2 which you can't easily say too much about
Well the values are actually 8, with the 45 degrees incorporated. In terms of understanding, I limited it to 4 but in 8 directions, the 2 isn't as glaring of an issue
And ultimately it should be able to be extrapolated to any amount, ideally
8 feels like a nicer problem to deal with, yes
does anyone have issues running this code ?
import numpy as np
from matplotlib import pyplot as plt
arr = np.zeros(10*10).reshape(10,10)
plt.imshow(arr)
plt.show()
whenever i run it the matplotlib pyplot starts glitching out a lot whenever i put my mouse on the plot itsself
This is a jupyter notebook though
this is what i get when my mouse isnt on the plot
this is what happens when i put my mouse on it
ive been getting this with maplotlib plots for a long time rn
i have no idea if theres anything wrong with the code or with me
im not sure if this is the correct channel to ask this in , i tried with the help channels but no one responded 2 times in a row so ill try here
that code looks fine and I see none of the issues on my side
yea it looks fine, i can try to record a video of it or smth, it just glitches non stop when i put my mouse on the actual plot
fwiw we probably have very different setups
what os are you on? windows/linux/other?
you could try switching the matplotlib backend to see if that helps
import matplotlib
matplotlib.use(<some backend>)
there is a list down a bit here https://matplotlib.org/devdocs/users/explain/backends.html
though idk how many would work on windows without installing some extra dependencies
given a list A of N ints and a target K, how do you select upto 3 elements from A such that their sum is minimum, but above K
the obvious n^3 solution was good enough to pass the time limits but surely there are better ways
I mean, without thinking much O(n^2 log n) is trivial, all possible sums and look up in a sorted array
improving that to O(n^2) should also be easy enough, create sums in increasing orders, lookup the last element in decreasing order (so keep two pointers/indices, one goes strictly up, one goes strictly down
err, at least I think creating the sums in increasing order should be doable 
how big is K?
if it's not so large you can consider options that scale in K
e.g. some variation of the classic dp for the subset sum problem
alright ill look into those, thanks for the ideas
"If a = b, do not do anything, because the subarray is already sorted." -it says for the merge sort algorithm, but what if the subarry looks like this [3, 4, 5, 2, 3] here a=b will be the same but the subarray won't be sorted? - this is from andri laaksonen's book
So I am planning when finishing a theme in the textbook, solving most cses tasks (for that theme) and also finding other tasks from the same theme in my local competition, SPOJ, Usaco etc... Is that fine
hi guys can you see if my webpage works make a bookmark with the following link and go to a blocked page for it to work:converts characters into a format that can be transmitted over the Internet.
guys this was a question from daily codinng questions and can you guys help me solve this:
pls help
You could try to make a ternary search tree
Or a trie if it wants O(n)
IIRC that’s how this problem is solved
Hi Everyone, this is my solution to a program on code wars but I dont understand why Im getting it wrong. Problem: In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it. ```def alphabet_position(text):
if text == "":
return ""
alphabet: dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,
'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
result = ""
for letter in text.lower():
if letter in alphabet.keys():
result += str(alphabet[letter])
result += " "
print(result)
return result ```
You aren’t adding the non alphabet characters, and you’re adding spaces too
Converting to ord and subtracting 96 would be Easter imo.
Hi i have to find median of K numbers and everytime i find it new number will come up so I need to find the new median again (and it must be in O(log n) for operation) and i found this article that has the same question but im not sure the answer is right, so if just someone could tell me if the first answer is right. thx https://stackoverflow.com/questions/7842347/find-median-in-olog-n
sounds reasonable, yeah
A trie is the obvious solution, yeah. Especially if you want to have quick inserts.
Other fun solutions is storing things sorted is another option, if you write rarely you can just store the data sorted, some simple file formats like sstables does this to store key value pairs. If you do updates then a BBST would also work.
I guess in the end a trie is also storing things sorted, you could call it a radix sort tree, even
hi guys how would you start with this question given two lists, list_1 = [a, b, c, d, e] list_2 = [x, y, z, k] return all combination of length 4 containing elements from both lists
reduce it to the problems of picking k items from list_1 and 4-k from list_2?
I'm assuming you need to pick at least one from each list? Otherwise the question is silly
yes
i m thinking i will need all conditions of picking 3, picking 2, and pick 1
from list 1
and do the same for other list
then just append
3 from list 1, 1 from list 2
for the case of 2 from both list
will have to run combination again
how would you code this
i think i m leaning on discrete cases
write a function that loops over k and then uses itertools.combination?
what if these imports cant be used?
some recursive implementation, I guess
halp
i m not even covering all conditions even with the imports
something like this eh
yes, that's the kind of thing I meant, you can make it a generator which makes things neat and tidy
from itertools import combinations
def pick_4(list_1, list_2):
for k in range(1, 4):
for comb_1 in combinations(list_1, k):
for comb_2 in combinations(list_2, 4 - k):
yield comb_1 + comb_2
for x in pick_4([1, 2, 3, 4], [5, 6, 7]):
print(x)
itertools.combinations_with_replacement
yah..
it's not terribly hard to write these things yourself, it's just annoying and they have a bunch of edge cases
im trying to write it myself lol
not so good with recursion
trying to change this into take input as two list
e.g. here is a simple implementation on combinations
from itertools import combinations
def my_combinations(inp, k):
def pick(picked, next_valid):
if len(picked) == k:
yield tuple(picked)
return
for i in range(next_valid, len(inp)):
picked.append(inp[i])
yield from pick(picked, i + 1)
picked.pop()
return pick([], 0)
def pick_4(list_1, list_2):
for k in range(1, 4):
for comb_1 in combinations(list_1, k):
for comb_2 in combinations(list_2, 4 - k):
yield comb_1 + comb_2
def my_pick_4(list_1, list_2):
for k in range(1, 4):
for comb_1 in my_combinations(list_1, k):
for comb_2 in my_combinations(list_2, 4 - k):
yield comb_1 + comb_2
a = sorted(pick_4([1, 2, 3, 4], [5, 6, 7]))
b = sorted(my_pick_4([1, 2, 3, 4], [5, 6, 7]))
print(a == b)
I make a nested function just to make things cleaner for the caller
Changing my_combinations to allow repetitions is just a small change to that
one change to one line, I think
generator expressions, but writing them like that it pretty dumb, if you want a list you would write a list comprehension like
[some_list[i] for i in indices]
hey guys, do you know how to remove this text inside / / with / in python?````
text /WANT TO REMOVE IT/ text```
Why does leetcode say there are 2^(2n) possible sequences of ( and ) characters (some of them being invalid).
Like I know the number of possible sequences in an unsigned 8 bit number is 2^8 - 1. So it's the 2n part that confuses me.
(from https://leetcode.com/problems/generate-parentheses/solution/)
>>> import re
>>> re.sub(r"/.*/", '', ' text /WANT TO REMOVE IT/ text')
' text text'
this doesnt have to do with algorithms but i was bored
Not sure, seems like 2^n would make more sense if n is the length of the sequence
Each position is either ( or ), so that's just 2^n
I guess it's just a weird writeup... because O(2^(2n)*n) is just O(2^n) anyway I think
The statement gives you n pair of parentheses
So the length of the sequence should be 2n
👀
I don't think O(2^(2n)*n) is O(2^n) since already O(2^(2n)) is same as O(4^n) which is different (larger) than O(2^n) as they don't differ by a constant multiple
right thanks, my rusty math
if anyone has insight to the 2^2n part please let me know
since it's talking about n pairs of parens you'll have 2n characters overall. And each character has two choices ( or ), so that's 2 choices for the first char, times 2 for the 2nd char, times 2 for the 3rd char, etc up to 2^(2n)
alternatively think of ( as 0 and ) as 1 and note that a m-bit binary number can take 2^m values (m = 2n here)
ooooh I get it thank you
n is the number of pairs not the length of it
yeh
number of valid bracket would be the catalan numbers iirc
File "C:\Users\user\Desktop\python\linkedlist.py", line 39, in <module>
my_list.insert_beggining(1)
File "C:\Users\user\Desktop\python\linkedlist.py", line 11, in insert_beggining
node=Node(data, self.head)
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given```
class Node:
def __init__(self,data=None):
self.data = data
self.node = next
class Linked_list:
def __init__(self):
self.head = Node()
def insert_beggining(self,data):
node=Node(data, self.head)
self.head = node
def insert_end(self,data):
node=Node(data)
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=node
def length(self):
cur=self.head
total=0
while cur.next!=None:
total+=1
cur=cur.next
return total
def display(self):
elems = []
cur=self.head
while cur.next!=None:
cur=cur.next
elems.append(cur.data)
print(elems)
my_list = Linked_list()
my_list.insert_beggining(1)
my_list.display
on this code
can anyone help
you have no next argument in your __init__
done it
next = none\
class Node:
def __init__(self,data=None,next=None):
self.data = data
self.node = next
class Linked_list:
def __init__(self):
self.head = Node()
def insert_beggining(self,data):
node=Node(data, self.head)
self.head = node
def insert_end(self,data):
node=Node(data)
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=node
def length(self):
cur=self.head
total=0
while cur.next!=None:
total+=1
cur=cur.next
return total
def display(self):
if self.head is None:
print('this linked list is blank')
return
current = self.head
llist = ''
while current:
llist += str(current.data) + '--->'
current = current.next
print(llist)
ll = Linked_list
ll.insert_beggining(5)
ll.display()```
the insert beggining is not working\
TypeError: insert_beggining() missing 1 required positional argument: 'data'
i putted 5
????
its the classes data, and variables in classes must have self
i found it weird too but thats the way it is
got the same problem
TypeError: insert_beggining() missing 1 required positional argument: 'data'
i did what u asked
got the same problem
it must know whether it's a local value or a member of the class, python uses self to make references to class members explicit, this is especially important since python wouldn't have any clue if x = 3 meant to create a local variable or to assign to a member of the class. Unlike other langs, python has no way to tell the different types assignments apart. E.g. in C++ it's optional to use this when referring to class members, but C++ also has variable declaration syntax which makes that possible
in shory, python as designed can't distinguish between these two concepts in C++:
struct Bleh {
Bleh() {
// these two refer to the class member
// i.e. the this usage is optional
x = 0;
this->x = 0;
// this creates a new local variable
int x = 0;
}
int x;
}
Hey guys, I need a simple algorithm, that given a deck of cards (for example, user input would be - 4,2,king,9,queen) will sort it ascending values, can anyone do that for me real quick?
Hey guys, how do i make terminal usable after running python script. it's code editor and it prevents the use of this terminal
ctrl+c
okay but i wont to program working and make this terminal where it was executed usable, not to stop working code
create another tab of terminal
u can't just do two processes simultaneously on a single terminal shell
can't you run things in the background
you can
Is list.getitem O(n) or O(1)?
O(1)
Okay, thanks
Can someone help me in #help-bagel? It's somewhat related to data structs, at least the graph part
I needed a place to post this, couldn't find a better place. But I wrote a script to dynamically populated data into an excel spreadsheet from nested dictionaries and I'm pretty damn proud of it. Coding under a year.
def insert_data(nested_data):
# Iterate over dict into team str and dict
for team_key, nested_dict in nested_data.items():
# Iterate over nested dict into col str and entry data
for col_key, entry_data in nested_dict.items():
# Iterate over rows in worksheet
for i in range(1, ws_daily.max_row+1):
# iterate over cells in row
for cell_in_rows in ws_daily[i]:
# If cell in row contains team_key
if cell_in_rows.value == team_key:
# set row
row = cell_in_rows.row
# iterate over cells in row
for cell in ws_daily[row]:
# iterate over columns of each cell in row
for cell in ws_daily[cell.column]:
# If a cell in a column contains
if (cell.value == col_key):
col_let = get_column_letter(cell.column)
# convert target cell to LetterNumber string
cell_target = str(f"{col_let}{row}")
# Insert data into cell.
ws_daily[cell_target] = entry_data
return
Context, this is for automating report compilation into a single excel spreadsheet from a bunch of sources.
Mind if I give some pointers? you don't need plain return at the end, the function ends by itself. Also I'd suggest not reusing the cell as two loop variables. And you may be able to cut down on all the indents by inverting the ifs and continuing when they happen. 
Hey guys I recently read google's internship interview question this year. So given a 2d binary matrix with N lines, with each lines you can invert it if you want, find the maximum number of identical line possible
So for example
[
[0,1,1]
[1,1,0]
[1,1,1]
[0,1,1]
]
then the answer would be 3
since we can make 3 [0,1,1] or [1,1,0]
I'm thinking of using a map to store each lines then count
what does invert mean in this case?
Basicallly [::-1]
so reverse
yep
invert sounds like swapping ones with zeroes, like bit inverse
O(n^2) would be easy but that sounds horrible
Yeah I guess reverse is the better word here mb
also, why is the answer 3 in your case?
there are two groups of identical elements, no?
The third row is supposed to be different
ah
when you say n^2, isn't that just the cost of looking at all the elements in the matrix?
or, I guess n*m
n = number of lines, m = number of columns
or did you mean O(n² m)
for transparency, could you link to the thing?
My bad I was on the train without wifi
I don't have the link but I think I have screenshot
Give me a secx
Here it is
My bad the guy who took it said he wasn't allowed to ctrl P the page or screenshot
idk why the quality is so horrible tho
It looks good before I uploaded it
Open original makes it good quality again
so the invert operation could only be applied once?
and the cell changing to opposite k times in the entire matrix?
hi
I think it means you can change K columns
Or invert a column K times
row, not column
and invert in this case means flipping all 0s to 1s (and vice versa)
Yep mb I was reading a similar exercise but in column so I got it backward
And yeah it was inverted, I remembered it wrong somehow
I think grouping elements if they are related by an inversion is a good first step. After that point you can go through the groups and see what you can accomplish with your K inversions
I see... But how do we group elements together? Do we use itertools to remember indexes of the group that are related by inversion for example?
you could have as a rule that you pick as representative the version that starts with a 0, so e.g. both of these would have the representative [0,1,0]:
[1,0,1]
[0,1,0]
you can group by that representative
Good evening
Can someone explain to me how a recursive function works?, question in the help-burrito Help Channel
Gah, I missed a couple places where I reused cell. I have no idea what you mean by inverting the ifs, but it's on my TODO to look into. Thank you!
I mean instead of py if cell_in_rows.value == team_key: # bunch of indented code you can do ```py
if cell_in_rows.value != team_key:
continue
same code but not indented``` just to avoid so many indent levels
So, this?
if cell_in_rows.value != team_key:
continue
row = cell_in_rows.row
# iterate over cells in row
for cell in ws_daily[row]:
yeah
Thanks a ton, I'll play around with that and see where I can break my code and... not break it 🙂
can someone help me make a function that lets u insert some data after a certain value in a linked list
still need help with that?
no sir
hi!
I'm having trouble with some basic nparray manipulation
x_test.shape # (10000, 28, 28)
x_test[:1].shape # (1, 28, 28)
What does x_test[:1] do?
what I want is xtest[53] (which has shape (28, 28) ) but to be shape (1, 28, 28) like above
actually I just figured it out. TY!
highest_salaries = salary.sort_values(by='salary', ascending=False)
eighth_highest_salary = tenpaid.get['salary'].index[9]
eighth_player_name = tenpaid.get['name'].index[9]
print('Player:', eighth_player_name, '\nSalary:', eighth_highest_salary)
what is the issue in this code
Good morning
Can anyone explain me how can I replace every 3rd item in a list?
def mergeSort(array):
if len(array) == 1:
return array
middleIdx = len(array) // 2
leftHalf = array[:middleIdx]
rightHalf = array[middleIdx:]
return mergerSortHelper(array, mergeSort(leftHalf), mergeSort(rightHalf))
def mergerSortHelper(array, leftHalf, rightHalf):
sortedArray = [None] * (len(leftHalf) + len(rightHalf))
i = j = k = 0
while i < len(leftHalf) and j < len(rightHalf):
if leftHalf[i] <= rightHalf[j]:
sortedArray[k] = leftHalf[i]
i += 1
else:
sortedArray[k] = rightHalf[j]
j += 1
k += 1
while i < len(leftHalf):
sortedArray[k] = leftHalf[i]
i += 1
k += 1
while j < len(rightHalf):
sortedArray[k] = rightHalf[j]
j += 1
k += 1
return sortedArray
Can someone help me with this code, what I want to do is I want to access the index of elements that are being compared and swapped, I tried out many things but I failed, can someone help ? This is merge sort code btw.
what's actually wrong with the code?
it seems to work on the one list I tries throwing at it
the code could be tidied up, e.g. removing the array and not using a k and appending instead, but that's not a correctness issue
def mergeSort(array):
if len(array) == 1:
return array
middleIdx = len(array) // 2
leftHalf = array[:middleIdx]
rightHalf = array[middleIdx:]
return merge(mergeSort(leftHalf), mergeSort(rightHalf))
def merge(leftHalf, rightHalf):
sortedArray = []
i = j = 0
while i < len(leftHalf) and j < len(rightHalf):
if leftHalf[i] <= rightHalf[j]:
sortedArray.append(leftHalf[i])
i += 1
else:
sortedArray.append(rightHalf[j])
j += 1
sortedArray += leftHalf[i:]
sortedArray += rightHalf[j:]
return sortedArray
Hey @fiery cosmos!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
hi, is this the right channel to ask smth. about the pyparsing-package ?
I have a health score that decays over time, that is when a user reads the score, the initial score and a time stamp for when it was last set are read from the database, then a simple decay algorithm calculates the current score as function of the time elapsed between now and the time stamp. So far, so good that part is easy.
Intermittently the user can take certain actions that will change the score either increasing or decreasing it, or in an extreme case set it to 0. Changes to score will result in a setting of a new value in the database. Whereas the "decayed score" is calculated in real-time and the value displayed is not written to the database. This is done because the score is displayed on a public (no auth required) web-page and I only allow state changing actions for authenticated users.
Updating the score: To update the score, I would calculate the "decayed score" increment or decrement the value as needed and then save that value, with a new time stamp to the DB.
My question is, do I need to keep memory of the past score values and time stamps. Should I save the data in an array? I'm using Mongodb, so it would be JSON, array of dicts:
[{score:10, ts: 1654986544},...]
or is the last score and ts sufficient?
As I write this post I realize that the question is almost hypothetical as it really depends on whether I would have other needs for the data. So then more generally, is this a suitable method for keeping such a score are there any set patterns for this type of thing?
what's the time complexity of the in operator between strings?
substring in string
is the same as string.find(substring)?
actually i don't know
because e.g. "ssssm" in "ssssssssssssss" could take about nm
but there's no reason it would be worse than find
I think it depends on the algorithm
but I don't know how to browse the CPython source code to look for that
interesting!
this means that it's not needed to implement a KMP or Two Way by ourselves right
we can just call the Python builtin operators
How can I count the number of terns (three consecutive values) of positive and negative numbers in a list of numbers?
it would have to be spending only constant time in each iteration of the for loop for it to be O(n)
iterate through the list, keep track
So is the true answer O(n^2)?
on every iteration, twiddle-thumbs takes longer to execute
Hmmm
so squander-time is Theta((n+n^2)/2) == Theta(n^2)
which is big-O of everything bigger than it
Ahh
From the n(n+1)/2 formula right
What is that again?
just this
there's a famous story of Gauss coming up with it as a 5th grader or something
I tried this but it doesn't work```py
for i in range(len(numbers)):
if i < 0:
if numbers[i+1] < 0 and numbers[i+2] < 0:
negative_terns += 1
np
what went wrong?
Also known as Triangular numbers btw, 1, 1+2, 1+2+3, 1+2+3+4. When you draw it you can see it is about half a square (hence proportional to n^2) http://4.bp.blogspot.com/-yVAX8LG5bHE/Tb7sXx8EngI/AAAAAAAABkc/epz7p_oSPZ0/s1600/trianglenumbersintro.png 
the result is always 0. not work
what is i?
iterator
when is it less than 0?
XD
ahhhhhhhhhhhh
Ingrese una temperatura distinta de cero: -2
Ingrese una temperatura distinta de cero: 1
Ingrese una temperatura distinta de cero: 3
Ingrese una temperatura distinta de cero: -2
Ingrese una temperatura distinta de cero: -3
Ingrese una temperatura distinta de cero: -3
Ingrese una temperatura distinta de cero: -4
Ingrese una temperatura distinta de cero: 5
Ingrese una temperatura distinta de cero: 6
Ingrese una temperatura distinta de cero: -2
Ingrese una temperatura distinta de cero: -4
Ingrese una temperatura distinta de cero: 6
Ingrese una temperatura distinta de cero: -3
Ingrese una temperatura distinta de cero: -4
Ingrese una temperatura distinta de cero: -5
Ingrese una temperatura distinta de cero: 7
Ingrese una temperatura distinta de cero: 8
Ingrese una temperatura distinta de cero: -2
Traceback (most recent call last):
File "C:\Users\lucio\AppData\Roaming\JetBrains\PyCharm2021.3\scratches\scratch.py", line 21, in <module>
if valores[i+1] < 0 and valores[i+2] < 0:
IndexError: list index out of range
hmm
not good yet
for i in range(len(numbers)):
if i < 0:
if numbers[i+1] < 0 and numbers[i+2] < 0:
negative_terns += 1
Ah, the complete exercise is:
Enter 18 non-zero temperature values. You are asked to determine and report how many terns (three values in a row) of positive and how many negatives values there are.
so you'll have to look at positive numbers too
and you need numbers[i] in the first if
Is Traveling Salesman Problem Simulated Annealing = Artificial Intelligence?
what kind of question is that even? no
Does anybody know about the traveling salesman problem with restricted maximum travel distance without returning to the certain node?
Said Agent is a drone and needs to recharge at a certain point which is a moving truck.
In highschool the salesman never hit the same node twice
sorry, im a newb, i just loved that class and got excited, i have nothing to contribute
dont even know how you'd formulate a moving point into X!
crunch every single series including truck current location until it hit max, then use min distance that includes all x? The formula will be similar to a layover formula
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
my_dict = {}
for i in nums:
if i not in my_dict:
my_dict[i] = 1
else:
my_dict[i] += 1
sort_dict = sorted(my_dict.items(), key=lambda x: x[1], reverse=True)
ans = list()
for i in range(k):
ans.append(sort_dict[i][0])
return ans
#####################
Can anyone suggest me a better way to sort the dictionary using the values without using built in functions?
Above solution in for Leetcode Problem 347.
The current literature usually takes completely stochastic approach and something called Linear Integer Programming
No idea what the hell is the latter one and I didn't understand despite reading a ton of things
Some actually uses genetic algorithm where the route is the chromosome with randomly added truck-node genes
Can you spread this part more? I didn't understand. Get all possible routes until hit max (what is the max here?)
This is a combinotorial problem O(n!) actually takes giant time really
from collections import Counter
class Solution:
def topKFrequent(self, nums, k):
return [x[0] for x in Counter(nums).most_common(k)]
There is no better way to sort dictionary once you have entered the values. Maybe you will get a tiny amount of up from finding a better sort algorithm.
The percentile changes with each submission :\
@past vale I'm only just learning python, my coding isn't fluent but I think about the problem like this, you have points abcde
hmmm having trouble with the code but basically start by trying to deliver each payload and returning
then fewer stops and returning
until you have a route that allows for recharge
find each route then determine the most effective
You could keep the K values in a heap, then it’s O(n * log(k)) instead of O(n * log(n))
get routes randomly?
@past vale not randomly, organize it however you like but the way i was taught the traveling salesmen problem was that you have check every single route to find the shortest mathmatically
oh okay. Yes this is a combinatorial problem.
Meaning to find the most optimal solution it is needed to be checked for every combination
I think I can reduce the problem to, say you can meet at the nodes only. so truck can deliver items to nodes as well as the drone. It is not much easier but somewhat easier.
I was thinking about it as a truck on a set route moving a predetermined speed
don't think you could solve it with any precision in real-time
Is this kind of code allowed in the interviews ?
It's technically legal. They HAVE to hire you
It's one weird algorithms trick they don't want you to know about
Are data containers and data structures the same thing?
leetcode submissions are super variable and are not really worth trusting
like, don't trust the times and memory usage too much
they should be roughly right, but will fluctuate a lot
Not using built-in functions is not a better way to do the sorting.
fwiw Counter.most_common does use a heap
also, how tf is the top k frequent elements problem a medium problem?
it's so easy
Need help
The map contains islands named from Island 1 to island n .forvany two islands i and j you can go to island j frm i if the values i divides j.
Given the value for the last island equal to n find number of ways to reach island n from Island 1
maybe if you were to do it without builtins? idk ¯_(ツ)_/¯
the one thing that is not completely trivial to do is the heap
assuming we have dict
if you want me to implement dict in python...pls no
i mean, it's not that hard to make a dict that works
works well is a different story 🥴
it's not hard, it will just be terrible, yeah
You know how there's a way to to get the minimum element in a given range within an array in O(logn)? You know what the data structure used for that is called? I remember that it was some ___ tree.
Okay this kind of depends on interviews. This will change with each company and sometimes they will ask you to not import anything when solving the problem. But this solution has a close to top score on readability and performance, more than often, writing the actual logic instead of importing from library will score poorer and will be many lines of code. And yeah this uses the heap method.
If I was the interviewer, I would ask the person both. Their ability to workout the algorithm and test their python knowledge such as stdlib.
heap?
No it was a segment tree, thanks.
You would need a bbst like treap or splay tree
But its very slow compared to segment tree
Also theres a thing called sparse table that supports O(1) per query
if x in big_dictionary:
if y in big_dictionary[x]:
### VERSUS ###
try:
if y in big_dictionary[x]:
except:
pass
which one should i be using 
Leetcode problem ranking is just trash, thats how
is there a way to hide a value
like, let's say i have a numpy array a, i'm going to use concat, vstack, interpolate, matrix and comparison operators on this to re-arrange it into a different representation
for all of these operations i want it to take the values contained in the cells of the array, however, i also want to conserve the original index
later on, i'm going to briefly do some simple algebra on cell values and combine some of them, i'd like to conserve and attach the index's of all the original values for use in reversing them
i want to use this method to make reversing a decomposition method much more simply than deconstructing the operations to a deterministic pattern
test it out
some python principle says you should do the latter
a1 = list(a)
a1[0][0] = 3
print(a, a1)``` why are a and a1 the same?
when they shouldn't be?
do a[:] instead of list(a)
it will be the same
hmmm
oh
it just shallow copies the list
@dark aurora the elements still are the same
but the lists are different
Is there a way to change the elements without importing deepcopy
idk
you could probably do ```py
a1 = [a[0][:], a[1][:], a[2][:]]
Im guessing both list indicate to the same elements inside them but have diffrent "shells". (By shells i mean outer lists) Is that true?
yep
hey looking @ this problem here
def morgan_and_string(a: str, b: str) -> str:
a += 'z'
b += 'z'
res = ''
for _ in range(len(a) + len(b) - 2):
if a < b:
res += a[0]
a = a[1:]
else:
res += b[0]
b = b[1:]
return res
for _ in range(int(input())):
jack = input()
daniel = input()
print(morgan_and_string(jack, daniel))
isn't this code O(N^2)? why does it still run under the time limit?
I guess the worst case to try is something like strings aaa...aaab and aaa...aaac
it's quite possible that the test cases are weak
fwiw slicing is a fairly cheap linear operation, it should just be a memmove in the end
are data structures important for getting into a cybersecurity world
is anyone here cyber expert
"Let us consider the problem of calculating the number of paths in an n × n grid from the upper-left corner to the lower-right corner such that the path visits each square exactly once. For example, in a 7 × 7 grid, there are 111712 such paths"- I solved this problem in python, but it takes 30mins to calculate the result, is there any way to make it faster?
Here is the code
from copy import deepcopy
n = int(input())
pro = [[1]*(n+2)]+[[1]+[0]*n+[1] for i in range(n)]+[[1]*(n+2)]
def check2(x,y,mx):
a, b = (mx[x][y-1] ^ mx[x][y+1]), (mx[x-1][y] ^ mx[x+1][y])
return False if (mx[x][y-1], mx[x][y+1]) != (mx[x-1][y], mx[x+1][y]) and (a,b) == (0,0) else True
def baseFunc(cor, ct, mx):
pathr = 0
x, y = cor
mx[x][y] = 1
if check2(x,y,mx)==False: return 0
dirc = [(x,y+1), (x+1,y), (x-1,y), (x,y-1)] if (x,y) != (1,1) else [(x+1,y)]
if (x,y) == (n,n):
return 1 if ct==(n*n) else 0
for z in dirc:
i, j = list(z)
if mx[i][j] != 1:
pathr = pathr+baseFunc([i,j], ct+1, deepcopy(mx))
return pathr
print(baseFunc([1,1], 1, pro)*2)
:incoming_envelope: :ok_hand: applied mute to @fiery cosmos until <t:1650118584:f> (9 minutes and 59 seconds) (reason: burst rule: sent 8 messages in 10s).
Hello guys how should i merge 2 pandas dataframes in this way:
id name
1 a
2 b
3 d
id
1 e
4 g
5 f
result :
id
1 e
2 b
3 d
4 g
5 f
i guess deepcopy might be the problem.
hey so
in python
my computer dies when i recurse 10^5 times
but in c++ or java
it works just fine
is python that bloated?
There’s also no tail call optimization
Wait, Java doesn’t have that either, does it?
your "computer dies"?
Theres a max recursion depth in python btw and you have to set it higher
not so related but fun fact, the default sort implementation in Java was up until recently purely a quick sort variant, if you send the right input sequence it does not only take O(n^2) time, it also stack overflows because the implementation is recursive
yeah, python is terrible with deep recursion, you could try writing it iteratively with a stack
did that alr
Maybe its just slow
segmentation fault probably
Can i see your dfs then
(core dumped)
Hey @eager hamlet!
It looks like you tried to attach file type(s) that we do not allow (.in). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
f
considering you don't return anything in the recursion, rewriting it to be iterative would be straightforward
0xC00000FD
STATUS_STACK_OVERFLOW
true
A new guard page for the stack cannot be created.
yeah i see how it is
It runs out of memory
oh well i'll just stick to c++/java for recursion then
You can still do it in Python, but you need to use your own stack.
yeah
Aka the "iterative" (simulated recursion) method.
that's just a pain tbh
Not quite
last time i un-recursion-ed a tree dfs i needed to add flags and everything
it's not a pain in this case though, the code is almost identical
import sys
with open('planting.in') as read:
field_num = int(read.readline())
neighbors = [[] for _ in range(field_num)]
for _ in range(field_num - 1):
field1, field2 = [int(i) - 1 for i in read.readline().split()]
neighbors[field1].append(field2)
neighbors[field2].append(field1)
needed_types = [0 for _ in range(field_num)]
needed_types[0] = 1
stack = [(0, 0)]
while stack:
at, prev = stack.pop()
type_num = 1
for n in neighbors[at]:
if n == prev:
continue
while type_num in [needed_types[at], needed_types[prev]]:
type_num += 1
needed_types[n] = type_num
stack.append((n, at))
type_num += 1
print(max(needed_types), file=open('planting.out', 'w'))
hm lemme submit
Feels weird tho lmao
A recursion limit that large can seg fault on the largest case.
I didn't test it, so it's possible I typod something or made some mistake
Even a recursion of depth 1e5 shouldnt take much memory
I don't need the recursion limit since I don't use recursion, I forgot to remove it from the original code
cool, as I said in this case because you don't have return values in your dfs it's super easy to convert to iterative form
the code is almost identical
if you need to emulate return values things get less fun, but still doable
or you find some nicer way of rephrasing things to not have to do return values
The case in which you need to return stuff is not bad either, it just takes some getting use to. But there is an easy to follow pattern to convert any recursive algorithm to non-recursive.
I don't know if I've ever had to properly emulate return values when doing things iteratively
Its not always easy
most of the time there are easier ways to do it
Often you don't and it will be faster if you don't / use less memory.
Dynamic programming on tree is complicated if you want to make it iterative
500 * 100000 it’s like 50 megabytes
There is a pattern for that too, IDR the book but it gives algorithms for rewriting. Both with the full recursion stuff with return values, or not.
a typical default stack size is a few MiB iirc
seems to be 8MiB by default on my machine ulimit -s
though you can easily change it on linux
(it's considerably more annoying on windows)
8 MiB is probably way more than you need. In CPython it has a conservative limit because Python stack frames are big.
(If you are in something like C, it may also optimize it (copy vs move))
my friend wrote stuff to bootstrap recursion in python to make writing deep recursion safer in python for competitive programming https://codeforces.com/blog/entry/91490?#comment-804751
he knows way too much about how pypy behaves just from having played around with it so much 😛
For anyone that has applies quadtrees to their work. I have been looking through and testing the code below. For some reason, this algorithm is not able to insert all the points inside of it. I'm not sure why, I have tried to make several tweaks to no avail. I post te original code below
Hey @next loom!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
class Point:
"""A point located at (x,y) in 2D space.
Each Point object may be associated with a payload object.
"""
def __init__(self, x, y, payload=None):
self.x, self.y = x, y
self.payload = payload
def __repr__(self):
return '{}: {}'.format(str((self.x, self.y)), repr(self.payload))
def __str__(self):
return 'P({:.2f}, {:.2f})'.format(self.x, self.y)
def distance_to(self, other):
try:
other_x, other_y = other.x, other.y
except AttributeError:
other_x, other_y = other
return np.hypot(self.x - other_x, self.y - other_y)
"""A rectangle centred at (cx, cy) with width w and height h."""
def __init__(self, cx, cy, w, h):
self.cx, self.cy = cx, cy
self.w, self.h = w, h
self.west_edge, self.east_edge = cx - w/2, cx + w/2
self.north_edge, self.south_edge = cy - h/2, cy + h/2
def __repr__(self):
return str((self.west_edge, self.east_edge, self.north_edge,
self.south_edge))
def __str__(self):
return '({:.2f}, {:.2f}, {:.2f}, {:.2f})'.format(self.west_edge,
self.north_edge, self.east_edge, self.south_edge)
def contains(self, point):
"""Is point (a Point object or (x,y) tuple) inside this Rect?"""
try:
point_x, point_y = point.x, point.y
except AttributeError:
point_x, point_y = point
return (point_x >= self.west_edge and
point_x < self.east_edge and
point_y >= self.north_edge and
point_y < self.south_edge)
def intersects(self, other):
"""Does Rect object other interesect this Rect?"""
return not (other.west_edge > self.east_edge or
other.east_edge < self.west_edge or
other.north_edge > self.south_edge or
other.south_edge < self.north_edge)
def draw(self, ax, c='k', lw=1, **kwargs):
x1, y1 = self.west_edge, self.north_edge
x2, y2 = self.east_edge, self.south_edge
ax.plot([x1,x2,x2,x1,x1],[y1,y1,y2,y2,y1], c=c, lw=lw, **kwargs) ```
"""A class implementing a quadtree."""
def __init__(self, boundary, max_points=4, depth=0):
"""Initialize this node of the quadtree.
boundary is a Rect object defining the region from which points are
placed into this node; max_points is the maximum number of points the
node can hold before it must divide (branch into four more nodes);
depth keeps track of how deep into the quadtree this node lies.
"""
self.boundary = boundary
self.max_points = max_points
self.points = []
self.depth = depth
# A flag to indicate whether this node has divided (branched) or not.
self.divided = False
def __str__(self):
"""Return a string representation of this node, suitably formatted."""
sp = ' ' * self.depth * 2
s = str(self.boundary) + '\n'
s += sp + ', '.join(str(point) for point in self.points)
if not self.divided:
return s
return s + '\n' + '\n'.join([
sp + 'nw: ' + str(self.nw), sp + 'ne: ' + str(self.ne),
sp + 'se: ' + str(self.se), sp + 'sw: ' + str(self.sw)])
"""Divide (branch) this node by spawning four children nodes."""
cx, cy = self.boundary.cx, self.boundary.cy
w, h = self.boundary.w / 2, self.boundary.h / 2
# The boundaries of the four children nodes are "northwest",
# "northeast", "southeast" and "southwest" quadrants within the
# boundary of the current node.
self.nw = QuadTree(Rect(cx - w/2, cy - h/2, w, h),
self.max_points, self.depth + 1)
self.ne = QuadTree(Rect(cx + w/2, cy - h/2, w, h),
self.max_points, self.depth + 1)
self.se = QuadTree(Rect(cx + w/2, cy + h/2, w, h),
self.max_points, self.depth + 1)
self.sw = QuadTree(Rect(cx - w/2, cy + h/2, w, h),
self.max_points, self.depth + 1)
self.divided = True
def insert(self, point):
"""Try to insert Point point into this QuadTree."""
if not self.boundary.contains(point):
# The point does not lie inside boundary: bail.
return False
if len(self.points) < self.max_points:
# There's room for our point without dividing the QuadTree.
self.points.append(point)
return True
# No room: divide if necessary, then try the sub-quads.
if not self.divided:
self.divide()
return (self.ne.insert(point) or
self.nw.insert(point) or
self.se.insert(point) or
self.sw.insert(point))```
"""Find the points in the quadtree that lie within boundary."""
if not self.boundary.intersects(boundary):
# If the domain of this node does not intersect the search
# region, we don't need to look in it for points.
return False
# Search this node's points to see if they lie within boundary ...
for point in self.points:
if boundary.contains(point):
found_points.append(point)
# ... and if this node has children, search them too.
if self.divided:
self.nw.query(boundary, found_points)
self.ne.query(boundary, found_points)
self.se.query(boundary, found_points)
self.sw.query(boundary, found_points)
return found_points
"""Find the points in the quadtree that lie within radius of centre.
boundary is a Rect object (a square) that bounds the search circle.
There is no need to call this method directly: use query_radius.
"""
if not self.boundary.intersects(boundary):
# If the domain of this node does not intersect the search
# region, we don't need to look in it for points.
return False
# Search this node's points to see if they lie within boundary
# and also lie within a circle of given radius around the centre point.
for point in self.points:
if (boundary.contains(point) and
point.distance_to(centre) <= radius):
found_points.append(point)
# Recurse the search into this node's children.
if self.divided:
self.nw.query_circle(boundary, centre, radius, found_points)
self.ne.query_circle(boundary, centre, radius, found_points)
self.se.query_circle(boundary, centre, radius, found_points)
self.sw.query_circle(boundary, centre, radius, found_points)
return found_points ```
def query_radius(self, centre, radius, found_points):
"""Find the points in the quadtree that lie within radius of centre."""
# First find the square that bounds the search circle as a Rect object.
boundary = Rect(*centre, 2*radius, 2*radius)
return self.query_circle(boundary, centre, radius, found_points)
def __len__(self):
"""Return the number of points in the quadtree."""
npoints = len(self.points)
if self.divided:
npoints += len(self.nw)+len(self.ne)+len(self.se)+len(self.sw)
return npoints
def draw(self, ax):
"""Draw a representation of the quadtree on Matplotlib Axes ax."""
self.boundary.draw(ax)
if self.divided:
self.nw.draw(ax)
self.ne.draw(ax)
self.se.draw(ax)
self.sw.draw(ax) ```
import matplotlib.pyplot as plt
from quadtree import Point, Rect, QuadTree
from matplotlib import gridspec
DPI = 72
np.random.seed(60)
width, height = 600, 400
N = 500
coords = np.random.randn(N, 2) * height/3 + (width/2, height/2)
points = [Point(*coord) for coord in coords]
domain = Rect(width/2, height/2, width, height)
qtree = QuadTree(domain, 3)
for point in points:
qtree.insert(point)```
For any interested here is the link : https://scipython.com/blog/quadtrees-2-implementation-in-python/
The following code implements a Quadtree in Python (see the previous blog post). There are three classes: Point represents a point in two-dimensional space, with an optional "payload" (data structure associating the Point with more information, for example the identity of an object). The Rect class represents a rectangle in two-dimensional space...
is there any way to compare strings lexicographically using some form of hashing?
Hi guys appreciate any tips on how to tackle this problem. This is a max-flow problem. Thanks
i think the conditions requires a min-cut, but then the other condition is tricky
like. Disconnecting the customers from the generators involves a cut, but it doesn’t
account for the number of trips.
I dont under stand the data I', getting from scipy KD tree: ``` import numpy as np
from scipy.spatial import KDTree
pts = np.random.rand(150,3)
T1 = KDTree(pts, leafsize=20)
neighbors1= T1.query_ball_point((0.3,0.2,0.1), r=2.0)
print(neighbors1) ```
I get this[18, 48, 53, 54, 73, 83, 89, 90, 103, 127, 136, 3, 12, 47, 58, 63, 82, 95, 96, 108, 148, 4, 13, 28, 33, 34, 37, 38, 46, 50, 92, 93, 99, 138, 2, 5, 16, 24, 42, 43, 51, 65, 78, 94, 107, 113, 130, 140, 143, 146, 31, 39, 40, 57, 75, 105, 106, 116, 118, 121, 122, 145, 8, 56, 72, 74, 80, 85, 104, 110, 117, 120, 126, 1, 9, 15, 25, 26, 35, 36, 60, 61, 64, 71, 77, 98, 115, 125, 128, 129, 139, 142, 0, 44, 67, 69, 76, 87, 91, 111, 124, 147, 21, 22, 41, 52, 66, 88, 100, 101, 102, 112, 131, 11, 19, 32, 49, 59, 68, 81, 84, 109, 114, 123, 132, 133, 135, 137, 141, 6, 10, 17, 23, 29, 30, 45, 7, 14, 20, 27, 55, 62, 70, 79, 86, 97, 119, 134, 144, 149]
hello everyone I have a problem in pandas how I could do to change the data of column 2 in full knowing that I have a table of 1000 lines so I could not change for each line
I had thought of calculating the average then dividing by 10 for example for line 1: 91+100/2 =95.5 /10 = 9.55 but I know how to write it in code so that it works for the whole table
I dont know how I am to translate this array to the points around (0.3,0.2,0.1)
Does anyone know where I could find the code for some DFO (derivative-free optimization / black box) algorithms?
Local search, random search, simulated annealing etc..
you can do stuff like comparing prefixes for equality with polynomial hashes, but for lexicographical comparison you'll need to compare the strings somehow
When you iterate a set, since its unordered, should the output be random each time?
Or is my IDE bugging out?
s = {"1", 2, True}
for x in s:
print(x)```
This prints "True", "2", 1" and sometimes "2", "True", "1"
this is because the hashes of strings are randomized for every time you run the interpreter
if you looped over it multiple times in the same run of the interpreter, you should get the same ordering
although that isn't guaranteed by the language, just an implementation detail
is a parser that generates a tree an algorithm and the tree a data structure?
I am trying to take a polynomial as input and apply newton raphson method to solve it but it gives error
x = Symbol('x')
f = input("Enter a Polynomial: ")
f_prime = f.diff(x)
f = lambdify(x,f)
f_prime = lambdify(x,f_prime)
x= float(input('enter the value of x : '))
n= int(input('enter the required correct decimal places : '))
i=1
condition = True
while condition:
g=str(x)
x_n = x - (f(x)/f_prime(x))
print("i= ",i,"x= ",x,"f(x)= ",f(x))
m=str(x_n)
if m[0:n+2] == g[0:n+2]:
condition = False
else:
condition = True
x = x_n
i = i+1
print("Required root is ",x) ```
line 4, in <module>
f_prime = f.diff(x)
AttributeError: 'str' object has no attribute 'diff'
how to solve it
can anyone help me with a good machine learning course
Your input is a string, diff requires an expression. Try using sympify:
https://docs.sympy.org/latest/tutorial/basic_operations.html#converting-strings-to-sympy-expressions
thanks
Can somebody tell me how to make a store in python with the "def" command?
Late reply but how do compute those scores ?
Looks like 91+100/2 is the interval of what you define as "classroom". You continue with 95.5 /10. What is this "10". What do you want to compute?
this is why I wanted to have the values out of 10 as for the last column
for the last column the values are between 0 and 10
So in the "classroom", when we see "91-100" you want those two values right?
Then you divide by the last column?
no for the column instead of having an interval between 91-100 I wanted to have only a value that represents the interv
how do i plot contours onto an irregularly spaced grid in matplotlib?
so what i have is the array for the x values is just an array of all the latitude values, the y array is an array of all the longitude values, and the z array is the snowfall (height data for x/y)
problem is that the z array doesn't have data for every lat/long value
only some lat/long values, so it's quite uneven
(swap longitude and latitude, y array is latitude and x array is longitude)
also just a note that tricontour doesn't work for me
termfx/session.py lines 42 to 45
arguments = value.split("(")[1].split(")")[0]
arglist = arguments.split(",") if len(arguments.split(",")) > 1 else [arguments]
arguments = [int(x) if x.isdigit() else float(x) if re.match(r"^-?\d+(?:\.\d+)$", x) else self.stripper(x) for x in arglist]
func = self.functions.get(value.split("(")[0])```
def addnot2toall(lst,var):
new = []
for elem in lst:
new.append(elem + 1)
return [elem for elem in new if elem != 2]
How would this function be noted down in O?
I'm thinking O(n), but it runs two loops that aren’ nested in each other, so it seems to me this is more like O(2n)?
0(2n) or else you can try saving it and running it again @loud orbit
O(2n) is the same as O(n) since with big oh you ignore constant multiples
course you can reduce it to a single pass with a slightly different comprehension py return [elem + 1 for elem in lst if elem + 1 != 2]
Every function that is O(n) is also O(2n), and vice versa. It's not just that you ignore constant multiples, it's that what big O tells you is that there exists some constant multiple for which some condition holds
The same statement would apply equally to O(n) as O(2n), you'd simply need to choose a constant that's half or twice as large
In practice, you can just ignore constant multiples, but that's not just laziness or a shortcut or anything like that, it arises from the very nature of what big o notation is conveying
how much algos should i know before starting leetcode grind
It is possible to implement a queue such that both enqueue and dequeue have O(1) performance on average. In this case it means that most of the time enqueue and dequeue will be O(1) except in one particular circumstance where dequeue will be O(n).
Isn't this just a deque?
Or am I misunderstanding something
Yeah that's what I'm a bit confused about
It would always be O(1) in case of deque right?
you'd have to mess up really badly to dequeue in O(n) 
Yep so I guess what the exercise is saying is that, use the linked_list implementation of a Queue and then keep track of the head and tail?
¯_(ツ)_/¯
I mean
I'm currently implementing a Queue using python lists
Which is basically cheating
So they probably want me to do it differently instead
like, as a circular buffer? that's a fine way to implement a queue/deque IMO
much better for caches
Folks I have a expression I don't know how to simplify:
from sympy import *
from sympy.abc import w, x, y, z
expr = (w - x) * (x - y) + (y - z) * (z - w)
expanded = expand(expr)
back = factor(expr)
I want back to be something similar to expr. I tried factor/simplify/cancel and stuff and seems non of these works.
Anyone know what should I try?
Hello guys is there a specific channel do discuss about selenium ?
I think I found a solution check here
# Split the 'classroom' column and convert the values to integers
df[['lower', 'upper']] = df['classroom'].str.split('-', expand=True)
df.lower = df.lower.astype(int)
df.upper = df.upper.astype(int)
# Calculate the ratio `(upper+lower)/performance`.
# Other computations are also possible
df['avg'] = (df['upper'] + df['lower'])/df['performance']
This basically splits the classroom column and computes a ratio dividing with the values in the very last column I read as performance. Other numerical computations are possible, too.
I see that help channels are used for it
I need to create a recursive function that does that
But I cannot find the recursive function anyone can help me find it please?
could you provide more information if given?
f(0) == 1
f(1) == 1
f(n) == f(n-1) + f(n-1) + f(n-2)
I think that’s what it’s doing
hi, i'm really interested in learning python but i really just cant remember or figure it out. is there any help or tips anyone can give me? thank you.
Hey 👋 Have a look at our resources page if you haven't:
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Hello guys
What can I name collections.Counter()?
for example, if I did:
!e
import collections
string = "abcdefaaab"
counter = collections.Counter(string)
print(counter)
@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.
Counter({'a': 4, 'b': 2, 'c': 1, 'd': 1, 'e': 1, 'f': 1})
I usually name dict as dictionary, set as cache, not sure what to call collections.Counter(). In the above example, I just called it counter.
Hi there, anyone here using zipline? Cheers
why not name stuff after what they are used for? your counter in your example could be letter_counts
a set could be used for a cache, but could also be something else entirely
just picking a generic name isn't a good way to name instances most of the time
letter_counts works. I chose a generic name for leetcode purpose, but I agree generic name isnt a good practice.
Suggest an approach so that i can nail every dp problem
there is no single approach
finding a good dynamic programming formulation tends to require you to look at a problem from some specific angle where things work out nicely and where you can make use of the underlying structure
and this tends to be pretty different between types of problems
when you have the formulation implementing it tends to no be too hard unless you're doing dp on a graph or something
not the right channel for thia
what is the right channel?
try the general channel
ok cheers
hi everyone! iI have to pick a topic that could be the most interesting for a student led lecture- which do u think is the most interesting topic?
1 .Latent Dirichlet Allocation (Gensim)
-
Deck.gl (pydeck)
-
Sentiment Analysis (VADER)
-
K-Means & K-Medians (qualitative and quantitative)
-
K-Anonymity
-
Ward Clustering
-
Neural Networks
-
Agent-Based Modelling
-
Random Forest
-
Support Vector Machines (SVM)
k-anonymity is pretty useful and interesting, how can we release useful data while preventing re-identification of individuals the data is from
Hey all, Can I anyone tell me what's the difference between these two different chunk of code snippets -
1]
nums =[2,7,9,3,1]
prev, curr = 0, 0
for n in nums:
prev, curr = curr, max(curr, prev + n)
return curr
Output = 12
2]
nums =[2,7,9,3,1]
prev, curr = 0, 0
for n in nums:
prev = curr
curr = max(curr, prev + n)
return curr
Output = 22
Basically my problem is why can't we write prev, curr = curr, max(curr, prev + n) as
prev = curr
curr = max(curr, prev + n)
you can write it as
old_prev = prev
prev = curr
curr = max(curr, old_prev + n)
```but without the temporary copy you end up overwriting `prev` and now that data is lost
like
# prev = 123 curr = 456
prev = curr
# prev = 456 curr = 456
@astral bone , @haughty mountain Thank you for explaining it to me and clearing my doubts!!!!
What do you recommend for me to change?
Can someone explain how meet in the middle works and why?
Like if you can square root the time complexity by splitting the list in half, why don't we do that every time?
So by splitting the list in half we get two n/2 lists and then we sort them and etc...
why don't we then half those two n/2 lists thus improving the time complexity, than do that until we have just two items?
I know this may sound stupid to some but i really don't understand
i'm assuming you used a deepcopy so that you could forget all the visited blocks after performing baseFunc.
it would be better if before returning from function, you could just unmark mx[x][y] . That might work.
that would be merge sort 😛
😆
it's basically https://en.wikipedia.org/wiki/Subset_sum_problem but trying to minimize difference instead of finding an equal split/a particular sum
The subset sum problem (SSP) is a decision problem in computer science. In its most general formulation, there is a multiset
S
{\displaystyle S}
of integers and a target-sum
T
{\displaystyle T}
, and the question is to decide whether any subset of the integers s...
(nice link preview)
the dp solution I'm familiar with should solve both problems
It's a very classic knapsack like algorithm. The idea is to find which numbers are constructible, start with
reachable = [1, 0, 0, 0, ..., 0]
i.e. sum 0 is reachable using no elements
then for every possible weight w_i, looping backwards, set reachable[i + w_i] if reachable[i] is set
After going through all your numbers you know what numbers are constructible, so finding the closest to even split it trivial
Though reconstructing the solution is a tad more annoying
I guess the actual problem it resembles is the partition problem. Though it and subset sum can be easily translated into each other from what I remember
like, the second paragraph in the partition problem wiki article is exactly the problem from the textbook
an optimization version of the partition problem
I guess in general, reading up on the knapsack family of problems is probably helpful
this is a special case, and one of the easier ones
how would we trace back which weights are in each knapsack?
@haughty mountain
because I think that's part of the problem as well
one way would be storing something nicer than 0/1. like store reachable[i + w_i] = w_i if it's the first time seeing reachable[i + w_i]
then you can easily backtrack
but there can be multiple weights, how would we get those? @haughty mountain
like multiple weights make up the contents of the bag
what's the problem with multiple weights?
I just don't see how you can get the multiple weights back, so we have a reachable array which stores whether certain weights are reachable
and as you mentioned above, we would simply set it equal to w_i
but then how would we chain these to figure out what is in each bag individually
one way to get to i was from j = i - reachable[i]
one way to get to j was from k = j - reachable[j]
and so on
can confirm this approach works
the dp part is very simple
from typing import List, Optional
weights = [5,1,2,9]
reachable: List[Optional[int]] = [None]*(sum(weights) + 1)
reachable[0] = 0
for w in weights:
for i in reversed(range(len(reachable) - w)):
if reachable[i] is not None and reachable[i + w] is None:
reachable[i + w] = w
the dp logic is 4 lines, writing code to backtrack from any particular sum is like 6-7 lines of logic more
def square_mul_method(b: int, e: int, mod: int) -> typing.Generator[int, None, None]:
bc = b
steps = ['s' if n == '0' else 'sm' for n in bin(e)[3:]]
for step in steps:
if step == 's':
yield (b := (b * b) % mod)
else:
yield (b := (b * b) % mod)
yield (b := (b * bc) % mod)
args = (9832489237482759232, 1232748927398574897589349878329, 289237489789345897496283423132)
with timer('py method'):
print(pow(*args))
with timer('s-m method'):
print([*square_mul_method(*args)][-1])
👀
222240966389595545659107585232
py method -> 3.609999930631602e-05
222240966389595545659107585232
s-m method -> 5.599999985861359e-05
args = (183, 342, 3423)
2661
py method -> 1.2500000593718141e-05
2661
s-m method -> 8.400000297115184e-06
the difference decreases with increase in nums
👀 👀
ya creating a list and getting the last value was dumb
Hello there i have a class stored in a numpy array
@dataclass
class Item:
count: int
...
item_array = np.array(10, dtype=Item)
i would like to increase every item in the array, normally i would do
for c_item in item_array:
citem.count += 1
is there a better way or a vectorized way of doing this ?
thanks
you can use np.vectorize or, alternatively, add an __add__ method to your class
this works:
In [25]: @dataclasses.dataclass
...: class Item:
...: count: int = 0
...:
...: def __add__(self, val: int):
...: self.count += val
...: return self
In [26]: arr = np.array([Item(0) for _ in range(10)])
In [27]: arr += 1
In [28]: arr
Out[28]:
array([Item(count=1), Item(count=1), Item(count=1), Item(count=1),
Item(count=1), Item(count=1), Item(count=1), Item(count=1),
Item(count=1), Item(count=1)], dtype=object)
though vectorizing over objects won't necessarily be faster than pure python
Hello, I'm stuck with this problem and I can't come up with even the brute force solution, here is the problem:
'''
Test Case 1:
teamA = [1, 4, 2, 4]
teamB = [3, 5]
Output: [2, 4]
Explanation:
1. For teamB[0] = 3, we have 2 elements in teamA
(teamA[0] = 1 and teamA[2] = 2) that are <= teamB[0].
2. For teamB[1] = 5, we have 4 elements in teamA
(teamA[0] = 1, teamA[1] = 4, teamA[2] = 2, and teamA[3] = 4)
that are <= teamB[1]
###############################################################
Test Case 2:
teamA = [1, 2, 3]
teamB = [2, 4]
Output: [2, 3]
Explanation:
1. For teamB[0] = 2, we have 2 elements in teamA
(teamA[0] = 1 and teamA[1] = 2) that are <= teamB[0].
2. For teamB[1] = 4, we have 3 elements in teamA
(teamA[0] = 1, teamA[1] = 2, teamA[2] = 3)
that are <= teamB[1]
'''
def counts(teamA, teamB):
pass
print(counts([1, 2, 3], [2, 4])) # [2, 3]
# print(counts([1, 4, 2, 4], [3, 5])) # [2, 4]
# print(counts([2, 10, 5, 4, 8], [3, 1, 7, 8])) # [1, 0, 3, 4]
the actual problem statement is kinda missing, but isn't the brute force just this?
[sum(a <= b for a in teamA) for b in teamB]
and you could easily speed this up to be O(n log n + m log n) where n and m are the lengths of teamA and teamB respecively
by sorting teamA and binary searching for every element in teamB
Not with a dataclass / Python object. If you just want structured data in a numpy array and for it to be fast, that can be done.
I'm solving this recursively and I got lost on something:
https://leetcode.com/problems/palindrome-number/
class Solution:
def isPalindrome(self, x: int) -> bool:
x = str(x)
def helper(x, l, r):
if l >= r:
return True
if x[l] != x[r]:
return False
helper(x, l+1, r-1)
return helper(x, 0, len(x)-1)
This doesn't work. But when I put return helper(x, l+1, r-1) it works. Why is that?
class Solution:
def isPalindrome(self, x: int) -> bool:
x = str(x)
def helper(x, l, r):
if l >= r:
return True
if x[l] != x[r]:
return False
return helper(x, l+1, r-1)
return helper(x, 0, len(x)-1)
^This works.
it's not like helper does anything besides returning the answer
the line helper(x, l+1, r-1) can be replaced by an empty line
it's like if you had a line that says m * 10
the point of calling a function is to get the output and use it somehow
even when it's recursive
huh??
hello good people
can anyone help me out ?
I am trying to rename files with the names which i have in txt file, it does it randomly and thats okay it doesn't have to be in order or smth, the error which i ran into is that when it runs and it gets to a duplicate it stops completely and tells me it cant create an already existing file, is there a way i can tell it to not use the already used names from the txt file. heres the code
base_path = "C:/Users/B O S S/Desktop/salomee/salomeo/"
files = [base_path + file for file in os.listdir(base_path)]
with open("C:/Users/B O S S/Desktop/namessalome.txt") as f:
new_names = [base_path + name + ".jpg" for name in f.read().rstrip().split(", ")]
for old_name, new_name in zip(files, new_names):
os.rename(old_name, new_name)
Hi Everyone, I was just doing an easy leetcode and found something weird and would like to understand the reason. This is the problem link: https://leetcode.com/problems/contains-duplicate/
I have submitted two solutions which are as follows:
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: seen = set() for x in nums: if x in seen: return True seen.add(x) return False
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return len(nums) != len(set(nums))
I found that the second solution was significantly faster than the first one
But, as per my understanding, in most cases the first one will return very fast due to the duplicate finding, while the second one will always fully traverse the whole list
So, why is the second solution faster? Thanks in advance.
Because the second solution does more in C, which makes it faster on average even though it typically has to add twice as many values to the set
It adds everything to the set in C instead of in python
If you were writing the solution in a compiled language, leaving early would probably be faster on average.
exactly right
Hi
I need an algorithm to solve wordle but I don't even know where to start
Does anyone have any idea?
I know in AI we have the min-max strategy for games
the idea is to guess words that maximize the amount of information you gain
I'm currently learning DSA, and the textbook has 2 different exercises
I implemented a queue using single linked list and keep track of the head and tail node
Which I suppose is the case where both are O(1) -> Exercise 28
But I don't know what kind of implementation would have an average time complexity for queue and dequeue of O(1) but have 1 case where it's O(n)
Can someone tell me what that case and which implementation that is?
If it was implemented with a circular buffer, I think it would be enqueue that would be O(n) sometimes, not dequeue, so I wonder what the answer is too. Hopefully someone knows.
it makes no sense that dequeue would be O(n), maybe an error
Maybe they meant “enqueue and dequeue”
maybe #data-science-and-ml would be more fitting (the description there mentions "scientific Python"), this is more for computer-science and DSA
First glance at the book makes me not like it, just from reading their example of a queue. They make a queue with O(1) enqueue and O(n) dequeue (append and pop(0))
https://runestone.academy/ns/books/published/pythonds/BasicDS/ImplementingaQueueinPython.html
ew
🥴
Actually I think this situations crops up when you implement a queue using two stacks. You can always enqueue in O(1) by pushing to stack1, and to dequeue you pop from stack 2 if it's not empty, or if it is you move all of stack1 to stack2 then pop. The dequeue has worst case O(n) but on average it's O(1) since stack2 usually has stuff in it.
And I guess if your stack is a dynamic array then enqueue aka pushing is O(1) on average already 
so both enqueue and dequeue are O(1) on average
but why would you do that lol
Why do academic problems ever have contrived or unlikely situations 🤷♂️ But I bet it has been used in practice in rare situations (just maybe not in Python) 
no way. just using an array would be better in pretty much every way
well, ig if you're not thinking that could be a solution
hey i was wondering if this is an O(n) operation? i'm checking whether a character at an index is inside an substring
if s[right] not in s[left:right]:
It is O(n), worst case you have to look over all the chars in s[left:right] (though slicing is O(n) already)
got it thanks!
That's actually a thing
I see yeah that's O(n) worst case dequeue and O(1) on average
But isn't just keeping a head and tail pointer simpler and guarantee O(1) for both dequeue and enqueue?
Yeah probably, though I think it's mostly an academic exercise.
hi guys.. is there a way to save something for period of time and delete after it expires in this case :
`X = 0
Entry = close > EMA200 and X != 2
StopLoss = when price drops 3% from entery
TakeProfit = when price goes up 6% from entryif StopLoss :
X += 1
f = open("demofile3.txt", "w")
f.write(X)
f.close()`
Now how to reset the value of X to 0 after 24 hours from it being == 2
if there is a more convenient way to do please let me know !
#Nandan Bhut
#Gr 11
#ICS 3U0
#Mr veera
investment = 2500
years = 1
while (investment <= 5000):
investment = investment * (7.5/100)
years += 1
print(years)
I'm just a bit curious, if you get good at DSA can you read a solution like this and immediately understand what the answer is trying to do?
class Solution:
def removeNthFromEnd(self, head, n):
def remove(head):
if not head:
return 0, head
i, head.next = remove(head.next)
return i+1, (head, head.next)[i+1 == n]
return remove(head)[1]
It took me quite a while to even understand what the author is attempting
Especially this part (head, head.next)[i+1 == n]
that part is just silly
yeah it has less to do with DSA and more to do with writing readable python
def square_mul(base: int, exponent: int, mod: int = 0) -> int:
base_copy = base
for n in bin(exponent)[3:]:
if n == '0':
base = (base * base) % mod
else:
base = (base * base % mod) * base_copy % mod
# base = (base * base_copy) % mod
return base
Is there anything faster than this
%%timeit
square_mul(*args)
224 µs ± 4.03 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
%%timeit
pow(*args)
200 µs ± 2.87 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
is there a way i can match cpython
A perfect example of "clear is better than clever". And how not to write code.
You will find stuff like this in the wild though, but not for trivial stuff like this. The idea is turning an if-else chain into a lookup table (in this case only 1 if, and 1 else), which can be well worth it when the number of cases is large enough and you may want to dynamically add more cases.
And if your key is not just an index (enum) (and/or that index does not cover all integers between some range (e.g. you have not something like 1-4, but rather [1, 3, 4])), you can use a dict.
if x == 0:
return "foo"
elif x == 1:
return "bar"
elif x == 2:
return "baz"
# vs
lst = ["foo", "bar", "baz"]
return lst[x]
return head.next if i+1 == n else head
It could have been written like that
^ which has the advantage of being lazy evaluated 
an example of someone elses graph. they did linear regression but thats based on their data and who knows if its right. my axes and plots would look similar though
what's a better way to write this hash table?
So I have an algorithm that given a list of words calculates the best word to choose out of the list. Can anyone point me in any direction on how to improve it?
def best_guess(possible_words: List[str]) -> str:
LETTER_COUNTER = Counter(chain.from_iterable(
possible_words))
LETTER_FREQUENCY = {
character: value / sum(LETTER_COUNTER.values())
for character, value in LETTER_COUNTER.items()
}
def calculate_word_commonality(word: str) -> float:
"""
Calculates how common the letters are in a word.
"""
score = 0.0
for char in word:
score += LETTER_FREQUENCY[char]
return score / (5 - len(set(word)) + 1)
word_rankings = {}
for word in possible_words:
word_rankings[word] = calculate_word_commonality(word)
return max(word_rankings, key=word_rankings.get)
this just returns a word that has common letters in it? I'm guessing this is for something like wordle
Yes
for wordle it's more interesting to consider how much info you get from picking some particular word
I wrote a dumb solver a while back that basically did considered all combinations of words I can pick and words that could still be correct given the hints
for pick in all_possible_words_to_pick
for target in all_possible_target_words
number_of_possible_words_left(pick, target)
I decided to pick the max(num_words_left) over all targets as a score
and then I picked the word that minimizes that
it basically tries to make the worst case outcome as good as possible
If I'm understanding it well at the end of the day you picked the word that has the lowest score
right, I look at the number of words I have left to deal with in the worst case, and then I minimize that "score"
you'll end up having to implement the wordle output (green, yellow, gray), and implement code to check if a word follows the constraints you know so far
I do have a filter in place that removes words that have gray characters in them.
that can then be improved to also take greens and yellows into account
green just locks a character completely
the set of yellow characters must be part of the non-green ones in the target word
Ok then. I'll look at that as well
Hi!
I have a problem with one algorithm.
I want to get an answer which buildings should i choose among the whole T array of buildings that will contain the most people and will not intersect. The total price TotalPrice of those buildings must lower than p.
The amount of people that building can contain is given by this formula
`capacity = h * (b - a)
**We need to return an array that will contain the indexes of building that we should chose in order given in T array **
Buildings are presented like
(h, a, b ,w) where:
his a height of buildingais starting point of buildingbis ending point of buildingwis the price of the building
Example:
T = [ (2, 1, 5, 3),
(3, 7, 9, 2),
(2, 8, 11, 1) ]
p = 5
Answer: [0, 2]
One more example:
T = [(3, 3, 4, 19), (3, 11, 17, 7), (4, 8, 15, 15), (3, 1, 7, 15), (4, 12, 17, 7), (3, 1, 7, 3), (4, 8, 9, 7), (3, 11, 18, 15), (4, 20, 31, 19), (3, 17, 26, 7)]
p = 20
Answer: I not have indexes yet but the maximum capacity should be 49 capacity = 49
I need to create a select_buildings(T,p) function ( where p is a maximum price TotalPrice < p )
It's similar problem to Weighted Interval Scheduling Problem
I've already created an algorithm but it's not working for every situation... ( I modified the Weighted Interval Scheduling Problem solution )
My solution:
def select_buildings(T, p):
n = len(T)
sorted_indexes = sorted(range(n), key=lambda x: T[x][2])
maxSize = [0 for _ in range(n + 1)]
bestIndexes = [(0, 0) for _ in range(n + 1)] # (index, sumOfCost)
for i in range(1, n + 1):
currEl = T[sorted_indexes[i - 1]]
# print(f'currEl = {currEl}')
# @TODO: Implement binary search
# Searching the building that is not intersecting with currEl
# currEl.a > tmpEl.b
for j in range(i - 1, 0, - 1):
tmpEl = T[sorted_indexes[j - 1]]
if currEl[1] > tmpEl[2] and currEl[3] + bestIndexes[sorted_indexes[j - 1] + 1][1] <= p:
bestIndexes[sorted_indexes[i - 1] + 1] = (sorted_indexes[j - 1] + 1, currEl[3] + bestIndexes[sorted_indexes[j - 1] + 1][1])
break
# If there is no such a building we save the (0,currentElementCost)
if bestIndexes[sorted_indexes[i - 1] + 1] == (0,0):
bestIndexes[sorted_indexes[i - 1] + 1] = (0, currEl[3])
# print(bestIndexes)
eqItem = bestIndexes[sorted_indexes[i - 1] + 1][0]
currElSize = currEl[0] * (currEl[2] - currEl[1])
maxSize[sorted_indexes[i - 1] + 1] = max(currElSize + maxSize[eqItem], maxSize[sorted_indexes[i - 2] + 1])
# print(maxSize)
# print('--------------')
# for i in range(1, n + 1):
# print(maxSize[sorted_indexes[i - 1] + 1], end=", ")
# print('\n--------------')
print(maxSize[sorted_indexes[n - 1] + 1])
T = [(2, 1, 5, 3),
(3, 7, 9, 2),
(2, 8, 11, 1)]
p = 5
# T = [(3, 3, 4, 19), (3, 11, 17, 7), (4, 8, 15, 15), (3, 1, 7, 15), (4, 12, 17, 7), (3, 1, 7, 3), (4, 8, 9, 7), (3, 11, 18, 15), (4, 20, 31, 19), (3, 17, 26, 7)] # 49
# p = 20
print(select_buildings(T, p))
For example it's not working for such an array:
T = [(5, 3, 4, 15), (4, 1, 11, 11), (3, 1, 6, 7), (2, 1, 7, 3), (3, 4, 7, 19), (4, 15, 28, 7), (3, 1, 2, 7), (4, 7, 14, 19), (3, 8, 22, 15), (4, 13, 17, 3), (3, 12, 14, 15), (4, 23, 34, 15), (3, 20, 23, 3), (4, 13, 15, 15), (3, 8, 14, 11), (2, 23, 26, 19), (3, 16, 29, 11), (4, 27, 32, 15), (3, 28, 30, 19), (4, 19, 36, 11), (3, 18, 22, 19), (3, 33, 46, 7), (4, 28, 35, 3), (3, 25, 27, 7), (2, 30, 32, 11), (3, 23, 31, 11), (2, 32, 38, 11), (3, 29, 38, 11), (4, 22, 26, 15), (3, 35, 45, 15), (4, 24, 25, 3), (3, 33, 35, 3), (2, 30, 32, 19), (3, 31, 47, 7), (4, 34, 38, 11), (3, 43, 52, 3), (2, 34, 36, 3), (3, 35, 37, 3), (3, 36, 39, 19), (2, 25, 28, 7), (3, 44, 45, 3), (3, 41, 42, 19), (3, 60, 71, 19), (4, 35, 39, 11), (3, 48, 58, 7), (4, 51, 52, 15), (3, 38, 46, 7), (4, 43, 50, 3), (3, 50, 51, 11), (4, 41, 45, 7), (3, 50, 53, 15), (3, 37, 39, 3), (3, 52, 55, 11), (3, 43, 46, 3), (2, 56, 59, 3), (3, 55, 58, 15), (3, 44, 57, 15), (2, 69, 82, 19), (3, 68, 84, 15), (3, 63, 67, 11), (2, 70, 76, 15), (3, 75, 90, 11), (2, 60, 69, 15), (3, 69, 78, 7), (2, 64, 66, 11), (3, 69, 71, 7), (3, 70, 74, 19), (4, 51, 59, 7), (3, 62, 64, 15), (4, 67, 78, 11), (3, 62, 63, 19), (3, 75, 76, 11), (3, 70, 79, 3), (3, 71, 74, 7), (4, 80, 85, 3), (3, 73, 75, 7), (4, 70, 73, 19), (3, 69, 77, 19), (4, 62, 80, 15), (3, 87, 96, 11), (3, 90, 92, 19), (3, 83, 92, 7), (2, 86, 92, 7), (3, 77, 81, 3), (3, 84, 86, 15), (3, 71, 76, 3), (2, 88, 89, 3), (3, 87, 90, 3), (2, 86, 89, 15), (3, 103, 111, 3), (3, 88, 91, 7), (2, 95, 97, 7), (3, 96, 102, 11), (4, 97, 100, 7), (3, 98, 103, 3), (2, 93, 96, 11), (3, 92, 99, 3), (2, 95, 98, 7), (3, 96, 102, 7), (3, 105, 107, 7)]
p = 20
My code: answer = 224 ( capacity)
Correct Answer: 152 ( capacity )
sum of items isnt good hash
use multiplication:
def better_but_still_bad_hash(text: str, bucket_count: int) -> int:
result = 1
for char in text: # for x in range(len(a)) is a bad practice
result *= ord(char) + 1 # add 1 to prevent multiplication to 0 ('\0')
return result
java's set uses sum of items as the hash
jshell> Set.of(1,3,78).hashCode()
$1 ==> 82
well, sum of hashes of items
doesn't Java also make HTTP requests to calculate the hash of URLs or something 🥴
Hi! Im very new to python, im watching YT guides to learn the basics but cant figure out why this isnt working.
weight = int(input("Weight: "))
unit = input("(K)g or (L)bs: ")
if unit.upper() == "K":
converted = weight / 0.45
print("Weight in Lbs: " + str(converted))
else:
converted = weight * 0.45
print("Weight in Kgs: " + str(converted))
Uhh, is it not working?
i get the runtime error: int.lbs = (weight * 0.45)
TypeError: can't multiply sequence by non-int of type 'float'
but it works fine?
this can only mean the code you're showing us isn't the code you're actually running.
yeah
it is bad because hash(3,4) == hash(2,5)
it is a lot of collisions
well, sum of hashes of items
it is better, but i think it still has a lot of collisions
Can anyone recommend me a youtube channel from where I could learn dfs and bfs?
Having a really hard time while trying to break my own encrypting algorithm.
where is the link...
https://pastebin.com/FTAGUTp7, encrypt_txt_files() encrypts txt files like this (decrypt_txt_files() works for passing files but my stupid fucking brain cant even crack its own encrypted shit)
but really having hard time when I try to solve some very basic algo that my sick brain created, helps appreciated ofc.
Wait, so do you have a working decryption function or not?
also, looking at what you're doing - if you can't reverse it properly, it might be that your encoding is ambigous (that is, there's more than one message corresponding to one ciphertext) or at least that you can't decode it via a greedy algorithm.
Yup, looks like you have tons of codes that are prefixes of others - e.g. & gets encoded as A AAA A A A while a as A AAA. So when you see A AAA when decoding, you can't know right away whether this is an a, or part of a &
oh, or are you using an extra space between every character? that'd solve the ambiguity
let me check
my computer crashed while encrypting 15k line of text
4 gb ram gang
- No I dont have.
- I am iterating through every key first and if that list or string combination matches the exact same key it is written to deciphered. But hugely inefficient and it doesn't work at all.
3.Yes, if letter isnt equal to anything in special dictionaries or "|" it writes " "
or I can do " "
Ah, yeah, iterating here is silly. The main feature of dicts is that you can very quickly (no matter how large the dict is) look up a key in it.
Instead of iterating over the original dicts, construct the reverse dicts - mapping encoded strings to the original letters - and look up in them.
Yay, my cryptography study is going to be more various
so how will that work
like keys and values are swapped
and combination will match keys
Yup
and then you'd do
s = ""
for letter in msg:
s += letter
if s in reverse_dict:
deciphered += reverse_dict[s]
s = ""
or something like that
sure, all you need is for it to be obvious when a new char starts
By the way, I don't really see why you need separate dicts for lower and upper letters. Why not just have one?
I was very inexperienced while writing this, like 5-6 months ago and didn't touch it now
just using like it is now
trying your tips, thanks a lot matey
the issue isn't so much that there are many collisions (it should be about the same) but that collisions are easy to construct
What is the easiest solution for this?
min_gas = 20
max_gas = 40
rarity = 1 # Can be between 0% and 10%
# If rarity is 0, then the gas variable will be 40
# If rarity is 5, then the gas variable will be 30
# If rarity is 10, then the gas variable will be 20
gas = ...
uhh, max-2*rarity?
yeah that pretty much worked thanks again, stil having problems with dictionary being too ambiguous
like simply everything is decoded to E or e
if you use double-spaces to separate letters, then you can get all letters by just msg.split(" ")
then map them using the dict, and assemble into a message
yeah solved that letter problem by putting "00" in the end of it, pretty similar solution
prolly need to rewrite dict as you said
everyone is matching everyone
this script works for me
hello pips, its been a long day and I literally cant wrap my head around this, can someone help :
if any(device for device in list_of_devices):
how is this working as a condition, if device isnt specified anywhere outside of this line
hi, im making a kg to lbs converter and i cant get this to work, anyone know what wrong with?
weight = int(input("Weight: "))
unit = input("(K)g or (L)bs: ")
if unit.upper() == "K":
converted = weight / 0.45
print("Weight in Lbs: " + str(converted))
else:
converted = weight * 0.45
print("Weight in Kgs: " + str(converted))
i get the error:
int.lbs = (weight * 0.45)
TypeError: can't multiply sequence by non-int of type 'float'
the code you posted runs and works, the error you're posting seems unrelated to the code you posted
check that you're actually running the right thing
very new at pycharm, thanks 🙂
yeah now it works, man im such a potato
thanks alot algmyr
hello i have a pandas dataframe with a column that looks like this
how can i select rows within a time range
@fiery cosmos You'll probably get better responses in #data-science-and-ml
okay. thank you
i want to get into competitive programming but does anyone have any book suggestions on the basic skills needed. doesnt have to be specific to python
Hello world =), I am looking for an algo to make an icosahedron as pentagons and hexagons. There are plenty for making the icosahedron itsel which I have done but scratching my head as to how to group the triangles correctly. Thanks
!e so basically this
from collections import Counter
s = 'abdicated'
print(''.join(letter*count for letter, count in sorted(Counter(s).items(), key=lambda x: x[1], reverse=True)))
@haughty mountain :white_check_mark: Your eval job has completed with return code 0.
aaddbicte
Can someone explain why the algorithm described in the link runs in O(|V|+|E|) time? https://en.wikipedia.org/wiki/Degeneracy_(graph_theory)#Algorithms
In graph theory, a k-degenerate graph is an undirected graph in which every subgraph has a vertex of degree at most k: that is, some vertex in the subgraph touches k or fewer of the subgraph's edges. The degeneracy of a graph is the smallest value of k for which it is k-degenerate. The degeneracy of a graph is a measure of how sparse it is, and ...
guys why im having this error?
did you mean def meme_dodo(**ddd)
no i did mean meme_dodo(**ddd)
you only have one * in your code
oh i didn't see that thank you so much
why im not getting the 'key' and im only getting the value?
you used value twice in your print statement
then what im suppose to use?
no wait lol
look i used it but still the same
lol I'm confused, this is my code can you tell me where should i change things:
`def meme_dodo(**kwagrs):
print(kwagrs)
print(type(kwagrs))
meme_dodo(name='gmail', lamp='billy', animal='bird')
def meme_dodo(**kwargs):
for key, value in kwargs.items():
print("key: ",value,"\t\t", "key: ",value)
meme_dodo(name='gmail', lamp='billy', animal='bird')`
fwiw, this is the wrong channel for this. you should get a help channel, #❓|how-to-get-help
but in your print statement, you use value twice, instead of key once and value once
i = 0 x = 10 if i < x : x += 1 print(x) if i == x : break
how to ask it to restart again after the break command, other than
**if i == x : i = 0**
i want it to break stop the algo, and reset all values and start again like its the first time if that makes sense
use a loop
and break doesn't work outside a loop
!e
i = 1
x = 10
while i < x:
i += 1
print(i)
@brave hound :white_check_mark: Your eval job has completed with return code 0.
001 | 2
002 | 3
003 | 4
004 | 5
005 | 6
006 | 7
007 | 8
008 | 9
009 | 10
thanks for the reply, understood..
my main issue is that after the condition is met i want it to reset all values and restart allover again like it is the first time is that a possible thing?!
it runs good, just when it is done throw all the loops, it says nothing left to do and stops
i want it insted to reset all values to default and start all over again
i hope this makes sense
u want to restart the loop?
the whole algo, but i can't use while True:
or anything similar because i want it to take a chance to reset all appends and other varaiables
i = 1
x = 5
while i < x:
i += 1
if i == x:
i = 0
print(i)
like this?
let me write a sample code one second!
i = 0
x = 5
r = list ()
while i < x :
i += 1
r.append (i)
if i == x
r.append(x) # just as an example
print(r, i)
now what will happen it will print it will print and end the app
what i want it to do is print and end the app obviously, but i want to know if there is a way to make it relaunch it self automatically after it end, why is that because the algo has litreally 30 appends and maybe 50 diffrent loops if statments and api requests and these being live data might change
so i want it to take a chance to end and then add a peace of code that will force it restart, but with all the values being default like it has right now started, i know if i add while True :
at the begining that will do the trick but i want it to stop first and ask it to relaunch all over again if that is an option !
so to make it more simple, is there a peace of code that will allow an app to stop after its done then make it relaunch without me having to press the run botton (shift+f10) manually
is anyone worked with selenium library and proxies?
can anyone explain sorting algorithms in python and their time complexities? I know the sorting algos in python are searching, selection, duplicates, and distribution and the significance behind measuring their runtime complexity but are there other sorting algos and time complexities?
where do i go for help with my code
Merge Sort, Quick Sort = O(nlogn) Time
Selection Sort, Bubble Sort = O(n^2) Time
Insertion Sort = Average Case -> O(n^2)
Shell Sort = O(n*(log(n))^2) -> Not Sure
This YouTube playlist is great for learning Searching and Sorting Algorithms.
https://youtube.com/playlist?list=PLzgPDYo_3xunyLTJlmoH8IAUvet4-Ka0y
thanks a bunch @lament shale
guys i have a concern
i know that python is relatively slower than cpp
so is it still ok to practice dsa in python?
If I understand correctly, what you need is to add recursion to your function.
i have just checked the term definition out, i believe that'd solve the problem !
i will give it a try first thing in the morning.. thanks a lot !
let me put this as an example for your reference:
k=int(input(("Enter an integer or enter 0 to end execution: ")))
if k==0:
print("Nothing else to do")
else:
for i in range(k):
print(i)
exampleRec()```
bless you man, appreciate the help!
Question for anyone who knows both Javascript and Python. I'm trying to convert a naive bayes algorithm written in Javascript to Python. What am I missing here?
i'm missing my glasses
Hi,
If anyone comfortable with AVL Tree Left-Right rotation, Please clear my confusion. I am struggling to understand since so much time.
Let’s consider below Binary Search Tree
My teacher is saying as below:
But, my doubt is:
disbalancedNode = 30
So, disbalancedNode.rightChild = None
So; newRoot = None
But, as per my Teacher; newRoot = 20. How is that?
if you need any further information, to clear my doubt, please ask me..
Maybe I'm misunderstanding, but it seems like the arrow is saying after only the first line of the function, newRoot = 20. "After execution of this step"
you understood correctly. newRoot = 20 is after the execution of line which is pointed by arrow.
Hi if i want to do the incremental hash from one hash table to another how would i do it that each operation (Find, Insert,Delete) would take constant time ? im completely lost with it :(( any help appreciated
Are there any tricks or patterns for writing a temporarily idempotent function that returns a random value? This sounds a little oxymoronic, so let me explain the details. I have a web-app and a user action sets some random date in the database. But if the user for some reason "replays" that action I don't want to reset that date to a new one. I know that I can simply check the db and see if a value is there and then only update if it is not there. But ideally I would like to avoid the additional db request.
So really the question is, is there a way to generate a random number that is dependent on the date/time (Technically it would be random in that case) such that as long as the date is the same the random number output is the same?
it sounds like you're asking for a hash function
Pardon my ignorance but how does hashing help in this case?
if you hash the datetime you get a number that is dependent on the datetime
I see, I need to think about that for a bit.
what is the purpose of the output value being random?
if you write a function that returns the current date in a YYYYMMDD format, it will keep returning the same value throughout the day
It is to set a future date.
if you add the requesting user's ID and maybe some identifier of the operation to it, you get something that uniquely identifies a user doing some action in a given day, which can be used to remember that this specific user cannot perform the same action until we reach the next day - is this roughly what you're looking for?
Yes, exactly, I can hash the user id and the date together but then I need it to return an int within a range eg: -15 to +15 days.
I can use hashid and simply trim the last digits and round or something.
so i just made this simple code and i was wondering if this is actually a algo: ```py
def test():
n, i = random.randint(1, 100), random.randint(1, 100)
if n > i:
if (n % n) == 0:
value = str((n / 2)**2)
print('n: Resolved even number:' + value)
if (n % n) != 0:
value = (n * 3) + 1
print('n: Resolved odd number:' + value)
if n < i:
y = math.ceil(i)
if (y % y) == 0:
value = str((y / 2)**2)
print('y: Resolved even number:' + value)
if (y % y) != 0:
value = (y * 3) + 1
print('y: Resolved odd number:' + value)
test()
an algorithm is just a series of steps to solve a problem
well this code does that no? or im wrong
in a sense, all code solves some problem
whether this code solves your problem is hard for me to say because I don't know what it is
well yeah maybe its a little bit hard to understand what this is xd
just tried to do this https://github.com/karan/Projects#classic-algorithms
which one?
This doesn't do what the collatz conjecture says
whats wrong there?
collatz
no loop or recursion, you're not calculating the number of steps to bring n to 1
Because it takes many steps to bring n to 1 in some cases
suppose n = 10
10 % 2 == 0 so we return n / 2 = 5
5 % 2 == 1 so we return n * 3 + 1
16 % 2 == 0 so we return n / 2 = 8
oh
and you loop until n == 1
then ig everything is wrong?
It's not the collatz conjecture
yeah
I suggest you do it both ways
recursively and using a while loop
sure
Looking for project ideas as a beginner with python. Was thinking about something like historical data sets and seeing if python can find markers for reccesions
Am i being niave on how achievable that would be ?
It should be pretty easy with a csv or something
I'm solving this problem on leetcode
But I don't know why I'm getting infinite recursion
class Solution(object):
def floodFill(self, image, sr, sc, newColor):
rows, cols , color = len(image), len(image[0]), image[sr][sc]
def dfs(row, col, color):
if row < 0 or row >= rows or col < 0 or col >= cols:
return
current = image[row][col]
if current != color or current == newColor:
return
current = newColor
dfs(row + 1, col, color)
dfs(row - 1, col, color)
dfs(row, col + 1, color)
dfs(row, col - 1, color)
dfs(sr, sc, color)
return image
Nvm I'm stupid I was redeclaring current instead of modifying image[row][column]
@slim vault and @shut breach Here is what I came up with. I think it's ready for prime time (pardon the pun!)
---Edit deleted first pasting of code ---
Let's try the eval again.
!e
from datetime import datetime, timedelta
def set_pseudo_random_future_date(uid, delay=365, range=30):
today = datetime.utcnow()
multiplier = (((today.day + today.month) * today.year * int(uid)) % 51) / 51
delta = timedelta( delay + round(multiplier * range - 0.5 * range) )
return datetime(today.year, today.month, today.day) + delta
print(set_pseudo_random_future_date(42))
@toxic locust :white_check_mark: Your eval job has completed with return code 0.
2023-04-20 00:00:00
Hi, Anyone please clarify this. I am struggling since 3 days.
Let’s consider below Binary Search Tree
My teacher is saying as below:
But, my doubt is:
disbalancedNode = 30
So, disbalancedNode.rightChild = None
So; newRoot = None
But, as per my Teacher; newRoot = 20. How is that?
I'd guess this is talking about executing it with disbalancedNode being the 10 one. Hence the circle around that subtree.
yes, this would return None if this rotateLeft applied directly to this tree. I think the correct way is:
- applying rotateLeft to left-sub-tree, so the result would be like this:
30
/
20
/
10
- And then apply rotateRight to the tree in step 1 (above), which will return newRoot = 20, so the final result is:
20
/\
10 30
can anyone help me understand why postfix and prefix expressions are so important in algos or data structures
like I am studying it because huge portion of my midterm will be from them, but cant find motivation behind it, from start why they even exist
I mean,this algo
postfix and prefix notation is super easy to work with compared to infix
but isnt infix much much readable compared to polished notations
expressions like a*b + c*d has awkward precedence rules
readable to who?
human yes
machine no
oh
well..
thank you, but still huge weirdness why this is huge part of my data structures course :/
it would make more sense if you were writing a parser
yeah probably
they are just bashing us to teach how computers or compilers work, most of the things
is this normal by the way, like is the main purpose of computer sciences curriculum is this?
it feels a bit weird for a data structures course
other than maybe as an application of stacks or something
we are learning it under stacks yeah
nvm will not judge any kind of nonsense thing going on this course lol
there are more classical examples where a stack is useful, e.g. if I give you an expression like ([]{[])}, is this a "valid" bracket sequence? i.e. does every start have a corresponding end, and are things properly nestes
in this case it's not valid because we encounter an ) when we expect a closing }
I guess there are parallels between this and parsing prefix expressions
yeah I have that example on book too, but never seen professor mentioning it
its algo is literally too easy when you understand this 9 step algo
I need to continue to learn it someway... thx for making it at least more senseful @haughty mountain
fwiw postfix being easier to deal with is a pretty big reason why lisp like languages were common in early computing
Should you know the Brute Force approach for every question?
Or can you just jump to Optimized solution if you find Brute Force hard to explain/implement?
in an interview setting (which is what I assume you're asking about), I would at least mention the brute force solution
Yeah, I meant in an interview setting.
And are you expected to implement Brute Force solution?
I can mostly figure out Brute Force solutions, but there are always question that are hard to implement.
I am trying to make something akin to a convolution algorithm akin to what openCv uses to blur images and what not. I'm confused how to create a "stride" process for my kernel matrix to move around the 2D array I wish to use my kernel on. right now I have an algortihm that only works if the kernel and the 2D array are the same size, please see here: ``` import numpy as np
k=np.array([[1,2,3,4,5],[6,7,8,9,2],[3,4,5,8,12],[4,6,23,14,5],[13,6,3,4,6]])
w=np.array([[1,1,1],[0,0,1],[1,0,1]])
def wash(rc,w):
acc = 0
for i in range(len(rc)):
for j in range(len(rc[0])):
for m in range(len(w)):
for n in range(len(w[0])):
if i==m and j==n:
acc+=(rc[i,j] * w[m,n])
print(acc)
rc = np.array([[2,3,4],[3,5,2],[0,9,8]])
wash(rc,w) ```
if there's a better solution, often no
ok thank you!!
why would you implement something where you know a better solution?
sometimes brute force can be improved upon to make it better, but otherwise writing a brute force solution is just a waste of time
I dont know that's why I asked.
I dont know what the leetcode style coding interview would look like, so I wondered if the interviewer could be like, "ok forget the optimized approach. Can you implement a brute force instead", or "Optimized approach looks good and we still have plenty of time. Can you implement Brute force now".
the latter for sure no
can't imagine a situation where the interviewer would ask for a worse solution after you finish a better one
if you hear the former you're probably either doing quite badly, or the interviewer wants something simple first to then ask for improvements on
ok I see.
Hello every one
The maximum number of subdivisions (100) has been achieved.
If increasing the limit yields no improvement it is advised to analyze
the integrand in order to determine the difficulties. If the position of a
local difficulty can be determined (singularity, discontinuity) one will
probably gain from splitting up the interval and calling the integrator
on the subranges. Perhaps a special-purpose integrator should be used.
can someone explain to me
and what should I do
Hey guys! This can be a rather stupid question, but I'm struggling to understand 1 thing:
suppose we have a binary search algorithm:
def binarysearch:
low = 0
high = len(list) - 1
while low <= high:
middle = low + (high - low) // 2
if numbers[middle] == number_to_find:
return middle
elif numbers[middle] < number_to_find:
low = middle + 1
else:
high = middle - 1
return -1
Why do we add 1 to low and subtract 1 from high?
low and high represent the first and last indices at which the element can potentially occur
if the element is greater than the middle, the first index it can occur at is middle + 1
likewise if its smaller, the last index it can occur at is middle - 1
fwiw this is a consequence of doing inclusive, inclusive indexing. If you do inclusive, exclusive (like how range(l, r) works) things become so much nicer
hmmm, you mean, that we do it because lists in python starts from 0 and not from 1?
e.g. searching for the first integer where cond(x) is True
l = 0 # assume cond(0) == False
r = n # assume cond(n) == True
while r - l > 1:
mid = l + (r - l)//2
if cond(mid):
r = mid
else:
l = mid
# now, l and r are next to each other and are the last False value and first True value respectively
yeah
having l and r different sides of the False->True transition makes things quite nice
and the if check and assignment is pretty obvious, if cond(mid) is true we should move r to mid, because r is on the True side of the transition
cond in your case would check some value at an index in a list, but the technique is a lot more general
yeah I see
it's like a template
you can apply that binary search "template" to wide range of problems
just change that condition
yeah seems good
I like to point this out because I see a lot of people assuming that binary search is something you do on arrays, while in reality it's very general
right
thanks for making things a lil bit clearer for me!
having a tough time to implement algorithms in python
np
sometimes I feel like I understand how it works, and I can explain it on paper...
but when it comes to python.. ehh.. My brain goes absolute blank
"practice makes perfect"
I agree. Thanks for help!
in the beginning you'll struggle a bit with even simple algos, then you get used to the simple stuff and start being able to use those as building blocks for other algorithm
and so on
I like to think about data structures and algorithms as useful tools in your toolbox for solving algorithmic problems
binary search is a very useful tool to have, it's useful in a lot of places
ha ha yes I'am struggling even with simple ones, for instance binary search. I've started reading a book "Grokking Algorithms" and I faced that problem again.. I understand how it works, I can explain it on paper, but implementing binary search in python.... :/
I'm just preparing for a code interview. I guess there are still some jobs which doesn't really require knowledge of algorithms...
guys how can i write
if a list is descending:
do something (e.g. <=)
elif a list is not descending:
do the exact opposite (e.g. >=)
with just one if-statement?
the clue ive been given is by doing:
if a list is descending and [something] or if a list is not descending and [again something]:
do something
does know how to switch from using the nltk to spacy
hey, i have a question about merge sort
def merge_sort(array):
if len(array) > 1:
midpoint = int(len(array) / 2)
left_array = array[:midpoint]
right_array = array[midpoint:]
#recursive call on left and right side
merge_sort(left_array)
merge_sort(right_array)
#merge step, compare the left most element of one array to the left most of the other
leftpointer = 0
rightpointer = 0
mergedpointer = 0
while leftpointer < len(left_array) and rightpointer < len(right_array): #check if both left and right have values in it
if left_array[leftpointer] < right_array[rightpointer]:
array[mergedpointer] = left_array[leftpointer]
leftpointer += 1
else:
array[mergedpointer] = right_array[rightpointer]
rightpointer += 1
mergedpointer += 1 #increment the position of the merged pointer we do this for both cases
#once we have ran out of elements in either one of the sublists, we can add the remaining elements to the array
while (leftpointer < len(left_array)):
array[mergedpointer] = left_array[leftpointer]
leftpointer += 1
mergedpointer +=1
while (rightpointer < len(right_array)):
array[mergedpointer] = right_array[rightpointer]
rightpointer +=1
mergedpointer += 1
array = [5,23,1,2,45,6,4,2,1,5,6,1,3,4,6,3,2,1,3,4,5,6,3,2]
merge_sort(array)
print(array)```