#algos-and-data-structs
1 messages · Page 93 of 1
ok
thanks!
can someone help me understand how to utilize my vertex and graph function
for undirected graphs?
ive been stuck for quite a while and opened like 4 help channels with no responses
What are date structure and algorithms
Well the idea is that the nodes would eventually reach an equilibrium where the nodes are more or less distanced according to the input subgraph. Btw this is just a random thought so I may be totally off xD
You construct the final (dense) graph according to the distance matrix
The number of dimensions you use should be consistent with the spatial constraints in the context that the graph represents.
It might also be worth considering nodes that have leftover degrees of freedom in their coordinates (due to not having enough connections)
that is a very physics answer
that I do not have the background to appreciate
I have solved the problem in a much poorer way
but thank you for your input
I gotta say though
what you suggested sounds MEGA cool
I wouldn’t even know how to start doing that
🥴
!e
import numpy as np
from scipy.spatial.distance import cdist
n_points = 10 # No. of nodes
n_dims = 2 # No. of spatial dimensions
n_iter = 500 # No. of iterations
damp_factor = 0.5 # Reduce velocity by this proportion per iteration
accel_factor = 0.01 # Ratio of force to mass (learning rate)
# Original distance matrix
dummy_coords = np.random.rand(n_points, n_dims) * 10
target = cdist(dummy_coords, dummy_coords)
print(f"Target:\n{target}")
# Simulate the input
prune_ratio = 0.2
idx = np.ravel_multi_index(np.tril_indices(n_points, k=-1), target.shape)
to_prune = np.random.choice(idx, size=int(prune_ratio * len(idx)), replace=False)
pruned_target = target.copy()
pruned_target[np.unravel_index(to_prune, target.shape)] = np.nan
pruned_target = (pruned_target + pruned_target.T) / 2
print(f"Pruned:\n{pruned_target}")
# Set up initial state
box_size = np.ptp(target) / np.sqrt(n_dims)
coords = np.random.rand(n_points, n_dims) * box_size
velocities = np.zeros_like(coords)
for n in range(1, n_iter + 1):
print(f"[Iteration {n}]")
# Shape: (n_points, n_points, n_dims)
deltas = coords[np.newaxis] - coords[:, np.newaxis]
# Shape: (n_points, n_points, 1)
dists = np.linalg.norm(deltas, axis=-1, keepdims=True)
diffs = np.nan_to_num(dists - pruned_target[..., np.newaxis]) # Ignore the pruned connections
errors = np.abs(diffs)
print(f"Train Error: {errors.sum() / 2}")
# Shape: (n_points, n_points, n_dims)
unit_vects = np.divide(deltas, dists, out=np.zeros_like(deltas), where=dists!=0)
accels = -np.sign(diffs) * errors * unit_vects # a = F / m where F = k * error
# Shape: (n_points, n_dims)
new_velocities = velocities * (1 - damp_factor) + accels.sum(axis=0) * accel_factor
# Update state
coords += (velocities + new_velocities) / 2
velocities = new_velocities
@flat sorrel :white_check_mark: Your eval job has completed with return code 0.
001 | Target:
002 | [[ 0. 8.55590774 8.34378067 7.30506343 9.69365725 7.79709852
003 | 6.2691179 4.87532748 4.17133523 2.8336265 ]
004 | [ 8.55590774 0. 1.22205037 2.58555024 1.88326539 5.67348333
005 | 6.44558182 3.89974462 5.50053533 9.0027916 ]
006 | [ 8.34378067 1.22205037 0. 1.53364889 3.06785746 6.63951194
007 | 7.18117649 3.48767616 4.84587458 8.41150492]
008 | [ 7.30506343 2.58555024 1.53364889 0. 4.46539201 7.18684936
009 | 7.34988324 2.48494214 3.48275978 7.03677166]
010 | [ 9.69365725 1.88326539 3.06785746 4.46539201 0. 4.9934119
011 | 6.24456377 5.42575124 7.14252204 10.52683554]
... (truncated - too many lines)
Full output: too long to upload
@brave oak
The larger n_points gets, the smaller accel_factor needs to be to avoid divergence
A smaller prune_ratio also demands smaller accel_factor from what I have tried
For evaluation (I ran out of characters 😦 )
# Evaluate
deltas = coords[np.newaxis] - coords[:, np.newaxis]
dists = np.linalg.norm(deltas, axis=-1)
print(f"Result:\n{dists}")
diffs = dists - target
errors = np.abs(diffs)
print(f"Test Error: {errors.sum() / 2}")
Ok I think I am done fixing bugs for the above xD
I found this line of code online for creating a hangman game I just wanted to understand it a little better if someone could explain pls
indices = [i for i, letter in enumurate(word) if letter == guess]
do you guys have a turtle chat
Hi, I have two programs in my hand and I can't tell why one of them is working significantly faster than the other one. Can someone help?
Here's the slower one:
from collections import Counter
for _ in range(int(input())):
n=int(input())
w=list(map(int,input().split()))
c,ans=Counter(w),0
for i in range(2,2*n+1):
cur=0
for j in range(1,(i//2)+1):
ad=min(c[i-j],c[j]) if i-j!=j else c[j]//2
cur+=ad
ans=max(ans,cur)
print(ans)
And here's the faster one:
from collections import defaultdict, Counter
for i in range(int(input())):
n = int(input())
a = input()
a = a.split()
a = list(map(int, a))
C = Counter(a)
sum = defaultdict(int)
for p in C:
for q in C:
if p <= q:
sum[p + q] += min(C[p], C[q]) if p != q else C[p] // 2
print(max(sum.values()))
Here's a sample testcase:
5
5
1 2 3 4 5
8
6 6 6 6 6 6 8 8
8
1 2 2 1 2 1 1 2
3
1 3 3
6
1 1 3 4 2 2
basically its looping through letter in the word, building a list of indices of the letters guessed that are in the word
indices = []
for i, letter in enumerate(word):
if letter == guess:
indices.append(i)```
Yeah! I figured that out, thank you so much tho still
ello
Hello, I have one, probably, silly question here. I'm trying to divide two numpy arrays that are updated in real-time, and some of the values of them might be None. It's there a pythonic way to deal with this issue?
Thanks in advance
For example: array([5759.5, 3425, None, 10.8, 11.2, 39.13], dtype=object) / array([1231, 3212, 1243, 42.3, None, 39.13], dtype=object)
wait why are you using np to put multiple data types in
Forget my question, you make me think jajaja I just need to turn the values into float
hello does anyone know How to write this function for this examples in the comment in one line code only?
yes many times
what have you tried
isn't it supposed to return a string
Hoping someone can assist with this.
I am given a Class called Order, which is made up of ( id, symbol, quantity, price, side, timestamp), I want to store this order in an orderbook which is a list (not my choice) and when i store it in the orderbook, the list needs to be sorted by price and then timestamp.
There are two lists a buy list and a sell list
Is there an elegant way of inserting into the list the order so its ordered from insertion thats quicker than just append and sort
my_list.append(order)
my_list.sort(key=lambda k: (k.price, k.timestamp))```
can i use this
bisect.insort_right(my_list, (order.price, order.timestamp, order))
you want a different data structure that inherently maintains an internal ordering
e.g. a self-balancing binary search tree
nightmares
heapq?
not fully ordered
you won't be able to get all the elements in sorted order in linear time
if age>=18
print('test1')
elif age>=13
print('test2')
else
print('test3')
can anybody help me with this cuz the app I used for programming said that the syntax is invalid
you need colons.
@rich cairn i guess you're missing closing parenthesis somewhere
Fix that one first
@rich cairn
if
if >> elif (code):
if >> elif (code):
..
else:
code
@fiery cosmos ok
Hey guys. Probably simple solution but when I looped through this dictionary to minus the level from the capacity to create a 'fuel needed' it gave all these recurring values? simplest way to fix this inaccuracy?
Would rounding it to 2 decimal places make any further inaccuracies?
Looking through after trying that, it seems that rounding to 2 decimal places was fine
hey guys is there a dedicated channel for OOP concepts?
does anyone know what is the max row count for parsing a csv with DictReader?
I have 1.4 million but when I do list(reader), len(list) I get approx 900k rows...
So I’m realizing some of my into-level CS students need more work on Python lists. Anyone have suggestions for some interesting problems that lend themselves to solutions using lists?
codingbat has a bunch of problems that explicitly use lists
@fast flicker like the methods of list or problems in which lists are involved?
Hey guys, I'm Brazilian and I need help, with some codes, I specifically need help to put codes on the Cozmo robot, but I really didn't understand how to do this, nor how to use the robot's SDK properly ....
the code I intend to use on it is the voice control
hey guys , does anyone here uses openCV library on Pycharm mac os ?? 
hi i just heart that here can ask python module pandas thing and excel thing here . is it okay to ask here
@dark sinew @tacit lily that seems more suited for #data-science-and-ml
@umbral matrix doesn't quite seem like the right channel; maybe get a help channel #❓|how-to-get-help
@snow swift ok thank you , i asked there too but no respond till now T-T
@dark sinew it'll also be better if you ask about your specific problem
since plenty of people know opencv
but noone can answer your question if you dont post it
so basically Pycharm can't get access to my mac's camera
for privacy reasons
i added some code on the pycharm Info.plist , it does work but when i close the app and reopen it it quits unexpectedly
so i have to edit the Info.plist every time
def insertionSort(l):
for i in range(0, len(l)):
if l[i-1] > l[i]:
for j in reversed(range(0, i)):
if l[j-1] > l[j]:
l[j-1], l[j] = l[j], l[j-1]
else:
break
return l```
why does it not work
range(0, len(l)-1)
still doesn't work
whats the error
no error
but it doesn't sort
def insertionSort(l):
sort = l
for i in range(0, len(sort)-1):
if sort[i-1] > sort[i]:
for j in reversed(range(0, i)):
if sort[j-1] > sort[j]:
sort[j-1], sort[j] = sort[j], sort[j-1]
else:
break
return sort
print(insertionSort([5, 4, 3, 2, 1]))
well, returns the same list
nop
do you want it to show [1,2,3,4,5]?
yes it's a sort
Problems that involve lists. I think they’ve got a handle on the basic methods, but I want to get them using them to solve real-world problems.
Well, the first thing I notice is that the syntax on your function call is wrong.
yes?
Well, first maybe try adding a print statement to print sort after each loop. See if you can figure it out.
[4, 3, 5, 2, 1]
[3, 4, 5, 2, 1]```
That's what it does.
ok
for some reason it doesn't check the last element
def insertionSort(l):
sort = l
for i in range(1, len(sort)):
print(sort[i-1], sort[i])
if sort[i-1] > sort[i]:
for j in reversed(range(0, i)):
if sort[j-1] > sort[j]:
sort[j-1], sort[j] = sort[j], sort[j-1]
else:
break
print(sort)
return sort
class Tree(object):
def __init__(self, entry, left=None, right=None):
self.entry = entry
self.left = left
self.right = right
def insert(item, tree):
if (item < tree.entry):
if (tree.left != None):
insert(item, tree.left)
else:
tree.left = Tree(item)
else:
if (tree.right != None):
insert(item, tree.right)
else:
tree.right = Tree(item)
t = Tree(5, Tree(1, None, Tree(4)), Tree(7, Tree(6), Tree(8)))
insert(2, t)
print(t)
```So im trying understand binary search trees a bit better , when I use insert(2, t) is there a way to see the new updated tree ?
@fast flicker
for i in range(1, len(sort))
i gave it 5 numbers
it starts with 1 because i check i-1
You're only checking through i = 3.
range(0,4) => 0,1,2,3
I copied and pasted right from here.
So when sort = [2, 3, 4, 5, 1] and j = 0, is sort[j-1] > sort[j]?
I think you bring up the last node, which is 87 in this case?
On the book CTCI it said that i swap it with last element in the heap which is the bottom most and right most. But the book illustration is quite confusing that's why I want to verify it.
Yeah I believe it's the bottom-right
is anyone available to help me with a python issue
ammm
guys
I need python experts
print(list(data[i] for i in range(len(data) - 1, -1, -1)))```
how does this function work? like I see the output, I just can't understand how it works in details
it gives as an output ['d', 'l', 'o', 'g'] but I would appreciate if someone could explain those -1,-1,-1 in the end
like the first one subtracts the length of the string, but the others do I can't comprehend
range takes 3 arguments
start, stop, and step
in this case, stop and step are both negative
so the range outputs 3, 2, 1, 0
Hey! I can't figure out this math in my head so wondering if you guys could help me. Pretty much, I'm trying to calculate the rotation angle for a jump animation.
It gets three input variables; jumpLength, jumpAngle and jump. jumpLength says how many frames the jump animation should last, jumpAngle is what angle should be rotated from 0 (so for a 150* total angle, this would be 75* to say 75* down and 75* up from 0) and jump is what frame we're currently on.
By default, I want the angle to be 0, but must fall down to negative jumpAngle (e.g: -75) for a quater of the jumpLength. Then, when in the jump cycle, it will go up for half the frames (from -75 to 75) then back down for the last quater (75 to 0) where the process repeats.
https://repl.it/@CameronJohnston/Flappy-Bird Here's my current best attempt [34:], but I realize the math is completely wrong but I've already got a headache trying to figure it out
If anyone could give me a good pointer, that would be great!
y dont u use https://en.wikipedia.org/wiki/Rotation_matrix
In linear algebra, a rotation matrix is a transformation matrix that is used to perform a rotation in Euclidean space. For example, using the convention below, the matrix
R
=
[
cos
θ...
I'll have a look
Uh yeh I'm not smart enough to understand any of that sadly lol, but from what I an tell this is just for calculating the position of pixels after a rotation which isn't what I'm looking for since pygame handles that for me
Implemented a defaultlist :D https://github.com/Honno/coinflip/blob/da55d7ad8678cc76235bd4e190141d24d48d7c8c/src/coinflip/_randtests/common/collections.py#L123
Basically a glorifed wrapper of the defaultdict, as obviously it deals with a lot of the problems very well. I really wanted slices to be supported, and to first assume the slice range is for an infinitely-sized list as opposed to constrained by the "length" (highest defaultdict key) of the list
Guys to assing certain type to argument is it suffciient to write
def reverse(self,x:int):?
if not how can I make x type int?
you can't
def reverse(self, x):
x = int(x)
...
Not sure why you would want to do that though
The users of the function should be passing in the correct types
you can use static type checkers to emulate a statically typed language
something like mypy
you can't guarantee what type you get with vanilla python though
thanks guys
def reverse(self, x):
self.x = x
return self.x[::-1]```
guys can somebody tell me why is it when paste integers into the method ```reverse```
I am getting ```TypeError: 'int' object is not subscriptable```
what does 4[0] give
@autumn mason I think you want to take a number and reverse it
so there are two ways
Approach 1
def reverse(x):
return int(str(x)[::-1])
Approach 2
def reverse(x):
rev = 0
while x:
rem = x % 10
rev = rev*10 + rem
x //= 10
return rev
i have an array of integers, i need to split this to five sub array. And max sum between this arrays must be minimum. For example [10,10,20,30,30,10,20,15,10] to [10,10,10] [30] [30] [20 10] [ 20 15] max sum is 35 [20 15]
How big is the array
its N
not improtant
it doesnt have limit
brute force is not accepted btw xd
brute force currenlty
n!
im trying better
im trying to find better aproach
N factorial?
You can do n^6 by runnin 5 for loops and then other for loop to get the sums
i, j, k, l, m, n are the split indices
so 0..i
i..j
j..k
k..l
Aand l.. N
Oops 4 are enough
but you are thinking like i need split array according the their sorting
no
i can choose one from start one from mid for one sub array
my aim is minimizing the max sum of sub array
i thought about sum of big array/5 and make subs array according to it
but it wont be always optimal
okay
so we have an array and we need to make 4 points to split the array into 5 subarrays
so we don't know which 4 points we are needed to split since we can't modify the array
and
we dont need 4 splits
because we are not making sub arrays according to their sorting
we can choose from anything from any place
its not sorted subarrays
its jsut 5 sub arrays
yeah I am not choosing sorted subarrays
I am just choosing 4 points to split by brute force
also this explanation seems to be wrong
you need sub-array not sub-sequences
subarrays are like continous portions
i...j all included
okay a sub array is like there are no break between start and end
[1, 2, 3, 4]
[2, 3] is a subarray
[2, 4] is not
yes
sorry for it
in your example the grouping doesnt seem correct
it doesn't obey subarrays
so is it sub-array or sub-sequences?
cause the whole algorithm gets changed for both
reeeeeeeee that is hard
brute force won't pass
it would be like 5^n solution lol
does this element belong to first part or second part or so on ...
nope
if there is a big element on the last
it will fail
1 ,2 ,3, 4 ,5, 15 for example
the only thing I can think of right now is recursive + memoization
and I am scared to write recursion in python
also how large can an element in the array be?
no limit
i dont need to test code btw
i need just implement it
after pseudocode
but only brute force is coming to my idea
okay I might try to code it
I feel like you could you some backtracking here
backtracking will be too slow
yeah yeah
I thought of a binary search solution
ig that should work
O(N*log(sum(array))
but if N is like 10^9 then rip
For binary search minimum sum can be 1 and the maximum sum can be the sum of all the elements.
Maintain a count of sub – arrays, include all possible elements in sub array until their sum is less than the max sum. After, if the count is less than or equal to 5, then sum is achievable .
kill me
sorry, im bad at explaining stuff 😦
@raven kite for this [10,10,20,30,30,10,20,15,10]
my code found 30
[30] [30] [10,10,10] [15] [20,10]
there is two 20
rip wrong input
its still good soluiton
but [10,10,10] [15] must be [10,10] [10,15]
no it is giving wrong for [1, 2, 3, 4, 5, 15]
for better solutions
I am really worried about the max number in the array
import numpy as np
n = int(input("matrix dimension: "))
matrice = np.zeros(n, n)
matrix dimension: 3
Traceback (most recent call last):
File "myfile.py", line 7, in <module>
matrice = np.zeros(n, n)
TypeError: Cannot interpret '3' as a data type```
why tho?
the second argument takes data type
what?
import numpy as np
d = np.zeros((2,3))
>>> d
[[ 0. 0. 0.]
[ 0. 0. 0.]]
matrix = np.zeros((n,n), dtype=int)
should work
yeah
oh, i did it wrong
sorry
i think if u take log of both sides to expand the factorial @raven kite
u will find that the left side has the same terms as the right side plus extra terms
left side is bigger btw
yeah
left side = right side + extra terms
right is nlog(n!)
left side expands to log(n^2) + log(n^2-1) etc
there is at least n time
hmm
its right
but i feel like im adding some comments to it
but thanks
probably its only way
@raven kite is there like a range of n that it is valid for
cuz if n = 0
both sides equal 1
and ur inequality isnt true
its growth rat
so small numbers are not important
mb i can do induction after converting thme log base
@wraith valve
can it be valid?
3
prob
thanks @wraith valve
aghhh, do class projects just get uglier and ugler as you ammend code to bandaid something else 😄
I am sure this is why version1.0 of software sucks
https://codeforces.com/contest/831/my
ok so rn i have a n^3 sol
which times out
and even when i redid it in java
it still times out
for the same test case so
any help? (ping plz)
why does this insertionsort not work
def insertionSort(sort):
for i in range(0, len(sort)):
if sort[i-1] > sort[i]:
for j in reversed(range(0, i)):
if sort[j-1] > sort[j]:
sort[j-1], sort[j] = sort[j], sort[j-1]
else:
break
return sort
for i in range(0, len(sort)):
if sort[i-1] > sort[i]:
``` that part is gonna compare the -1th (last) element with the 1st element of the list(in the first iteration), is that what you really wanna do? Or should`i` start from 1 ?
it starts from 0
it won't compare the last and the 1st element
oh wait
ok i'm dumb but how do i fix it
i literally made a working insertionsort a week ago
i made it start from 1
modified it
def insertionSort(l):
for i in range(1, len(l)-1):
if l[i-1] > l[i]:
for j in reversed(range(0, i+1)):
if l[j-1] > l[j]:
l[j-1], l[j] = l[j], l[j-1]
else:
break
return l
``` @drifting drum
yeah I'm trying to trace the bug in the second loop
yeah
so I slightly modified your code
def insertionSort(sort):
for i in range(1, len(sort)):
key = sort[i]
j = i - 1
while(j >= 0):
if sort[j] > key:
sort[j+1] = sort[j]
else:
break
j -= 1
sort[j+1] = key
the problem with the earlier one I think is that I don't see you hold a reference to the ith element, ie the key
you mean the i?
key = sort[i], yes
well, it actually seems to work right now, except
for some reason it seems to mix up the last few elements
i didn't change the code since
I'm fairly certain what I wrote works on any input, including the one in the pic
I did say you don't have a reference to the ith element
I'm not sure you understand how insertion sorts work
i mean is it required to have a variable to store sort[i]?
yeah
actually for the rest of the code where the displaced element moves back, i just swapped the elements
it doesn't need to keep track which one is the key since it either swaps and then continues or breaks
this demo shows the list and then which index has been swapped
it does everything right but doesn't check the last element
i do not know why
@drifting drum oof, sorry for another ping
if i'm totally wrong then i'll use your code
I've never actually done it without using the key element, let me think
vector<int> insertionSort(vector<int> list) {
int temp;
for(int i = 1; i < list.size(); i++) {
if(list[i] < list[i-1]) {
for(int j = i; j > 0; j--) {
if(list[j] < list[j-1]) {
temp = list[j];
list[j] = list[j-1];
list[j-1] = temp;
} else {
break;
}
}
}
}
return list;
}
this is my cpp code, idk if you understand or not, but it works well and similarly without a key
yes?
That should really be
for j in reversed(range(1, i+1)):
Since you wanna exclude the 0
could you check if that solves it?
one sec lemme get to my screen
def insertionSort(sort):
for i in range(0, len(sort)):
for j in reversed(range(1, i+1)):
if sort[j-1] > sort[j]:
sort[j-1], sort[j] = sort[j], sort[j-1]
else:
break
return sort
This has one less check
if you really want to stick to your original code
def insertionSort(sort):
for i in range(0, len(sort)):
if sort[i-1] > sort[i]:
for j in reversed(range(1, i+1)):
if sort[j-1] > sort[j]:
sort[j-1], sort[j] = sort[j], sort[j-1]
else:
break
return sort
I have a YAML file, with different materials, when i read it with pyYMML i get a list of list of dicts, i have problems querying this data, i'm quite new to python, but i managed to get it to work, but i'm sure there is a better way, is this the right place to ask ?
Maybe not, a help channel seems better suited for that
ok, i kinda figured it out, i needed this to be converted to this:
<class 'list'>
[{'materialTypeID': 34, 'quantity': 566667}, {'materialTypeID': 35, 'quantity': 133333}, {'materialTypeID': 36, 'quantity': 37778}, {'materialTypeID': 37, 'quantity': 10667}, {'materialTypeID': 38, 'quantity': 2889}, {'materialTypeID': 39, 'quantity': 1312}, {'materialTypeID': 40, 'quantity': 412}]
<class 'dict'>
{34: 566667, 35: 133333, 36: 37778, 37: 10667, 38: 2889, 39: 1312, 40: 412}
No way to do it but to write a function i guess.
My problem was, how do i lookup a material...
well you could just iterate through the list and update your dictionary, perhaps neatly using some comprehensions
not sure what you mean
the problem is that i have a list of pairs of dictionaries, i needed a single dictionary.
do you want to elaborate?
I had i list of:
{keyA:valueA}, {keyB:valueB}
i needed a list of
{valueA:valueB}
I need it bacause i have no clue as how to lookup valueB from valueA in the other format.
your_list = [{'materialTypeID': 34, 'quantity': 566667}, {'materialTypeID': 35, 'quantity': 133333}, {'materialTypeID': 36, 'quantity': 37778}, {'materialTypeID': 37, 'quantity': 10667}, {'materialTypeID': 38, 'quantity': 2889}, {'materialTypeID': 39, 'quantity': 1312}, {'materialTypeID': 40, 'quantity': 412}]
your_dict = {item['materialTypeID']:item['quantity'] for item in your_list}
You are not allowed to use that command here. Please use the #bot-commands channel instead.
is that what you want?
ok, that was it, i have written a function doing just that.
just tested, same result, now is this new dict a copy or a reference to the original data.
I will go read more about comprehensions, before i ask more.
it's not a reference
infact your values in the orginal nested dictionary are actual literal integers, not objects
how do you format code ?, in the chat i mean.
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
i guess it's the same as:
materialList = dict()
for material in materials:
materialList[material.get('materialTypeID')] = material.get('quantity')
yes, it's the same
the idea was the write that in a compact form, which was why we used a comprehension
but then again that's upto you
Well, i would have to declare a function, just because i'm not that clever, seems smarter to learn.
thanks.
wait, how are you gonna write an insertion sort without a key
@agile sundial are you asking me ?
no
I’m trying to make a program that requires authorisation of a username to use (usernames have been imported from an external file called usernames.txt but whenever I put something in it says access denied for each line in the file despite that I’m putting in the correct username
Not sure if this is the right channel, but is there any way I can easily iterate through all attributes of an object, and all attributes of all the attributes, and all of the attributes of those etc? I'm trying to convert nested dictionaries into an object with attributes, and there doesn't seem to be an easy way.
def partition(low, high, l):
i = low - 1
pivot = (low-high) // 2
for j in range(low, high):
if l[j] <= pivot:
i += 1
l[i], l[j] = l[j], l[i]
l[high], l[i+1] = l[i+1], l[high]
return i+1
def quickSort(l, low=None, high=None):
if len(l) == 1:
return l
if not low and not high:
low = 0
high = len(l)-1
if low < high:
part_idx = partition(low, high, l)
l = quickSort(l, low, part_idx-1) + quickSort(l, part_idx+1, high)
return l```
can anyone help
the quicksort isn't sorting properly
@sleek tundra py class attrDict: def __init__(self, mapping): self.__dict__ = mapping
Then loop through the dictionary recursively and replace all dicts (including the top level one) with instances that class ^
That will let you make dictionaries accessible thru attributes
That's the issue I have, I can't loop through the dictionary, since there are nested dictionaries inside it.
I've found a module munch which might be what I need though, I'm looking into it right now.
can anyone help with my quicksort code above?
for key, value in mapping.items():
#loops thru all keys+values ``` @sleek tundra
@tawny shore Would that loop through all keys and values for all attributes of attributes of attributes etc.?
Well no, you'd need to run it recursively
Basically use isinstance to check if the value is a dictionary, then run the func on it
I can sketch up what the function would look like roughly if you want @sleek tundra
i'm trying to make this work #algos-and-data-structs message
@tawny shore Thanks for the help! I think I've figured it out.
num = "53,34.4,56.8,43.8,16.9,9.6,4.7,5.8,23.5,48.2,66.6,97.6"
How do i make it a list without changing anything?
can someone recommend me algorithms to learn? like the most common used ones. I am completely new to this, i only know OF linked lists and binary trees
you can use string.split() to split a string into a list. num.split(“,”) would split your string anywhere there’s a comma
@cloud bough sorting algos
yes
"selection sort, bubble sort, insertion sort, merge, quick sort, heap sort" are pretty much the 1st you should learn
awesome, ill get to learning then. thanks
could you show your code?
import json
with open("climate.json", 'r') as f:
data = json.load(f)
bis = []
sum = 0
total = 0
n = -1
hello = ""
cello = ""
climate = ["high", "low", "dryDays", "snowDays", "rainfall"]
city = input("Enter the city")
if city == "0"
for id in range(0, 105):
if data[id]["city"] == city:
city_copy = data[id]["monthlyAvg"]
while n <= 10:
n += 1
for record in climate:
nis = data[id]["monthlyAvg"][n][record]
hello = nis + sum
h = bis.append(hello)
print(bis)
break
its basically extracting data from a json file with nested dictionaries
i got it to work thanks
Does anyone have some experience in huffman greedy algorithms?
i'm trying to implement this but im kinda stuck
import heapq
import collections
def huff(my_freq_data):
merged_lists = []
heaps = []
for i, my_lst in enumerate(my_freq_data):
if my_lst:
heaps.append((my_lst[0], i, 0))
heapify(heaps)
im trying to create something like this
can someone lmk if im on the right track?
does that have to be a dictionary or is a list fine?
its called the huffman greedy algorithm
what would be faster? 2d graph with connections or space partitioning?
check all value in dict, if match, return the key of the value
have anyway to do that?
have you heard of for loops?
c=0
for i in dict.values():
if i==match:
print(dict.keys()[c])
break
c+=1
is one possible solution
I will try
i==match?
counter..
sure, but why
print(dict.keys()[c])
also, how does dict.keys()[c] work
nvm, i cannot read
LOL
you can also use dict.items()
there are many ways, yes.
where match is the matching word you wanna match with
the values of dict
if it match to the values of dict, return the key of value
@hollow isle await ctx.send add after c+=1 or for?I mean indent
c=0
for i in dict.values():
if i==item:
await ctx.send(str(dict.keys()[c]))
break
c+=1```
you can skip on the count variable and the indexing if you use dict.items
if i[0]==item:
await ctx.send(str(i[1]))
break```
TypeError: descriptor 'items' for 'dict' objects doesn't apply to a 'list' object
@hollow isle
bro replace dict with your dictionary name
and dont name your dictionary dict never use keywords for naming
why It become list?
[{'a': 'bc', 'c': 'h', 't': 'u'}]
it is list?
When I want py dict(thatlist)
It sendValueError: dictionary update sequence element #0 has length 13; 2 is required
@hollow isle
i dont understand lol
guys i need help
i wanna convert a dictionary
to markdown table
here's the dict i have
{'Airline Rank': 'Captain', 'Base Airport': 'OMDB', 'IVAO VID': '43', 'VATSIM CID': 'Not Provided', 'Pilot Origin ': '![United Arab Emirates] (AE)', 'Total Pay ': '138,285 /-', 'Status': ' Active '}
can you convert this using python to something to a markdown table
i saw the tomark library but that's makes the keys as headings and values as values, however i want it like
+--------------------------+
|Airline Rank | Captain |
| Base Airport| OMDB |
like that
can someone help
also I import a dict from json, and it become list, how make it conver to dict?
learn the json library https://docs.python.org/3/library/json.html
my list like this [{'a':'ab', 'b':'bc'<etc>}]
wym
lol wym wym, you cant
"make a list a dict"?
wym you cant
If your list only has a single dict inside then you can get the dict using my_list[0]
async def load(self, ctx, extension):
lists = jdata['loadaliases'][0]
for i in lists.items():
if i[0] == extension:
b = i[1]
self.bot.load_extension(f'cmds.{extension}')
await ctx.send(f'load **{extension}**')
break```
Why it don't send anything?
async def load(self, ctx, extension):
lists = jdata['loadaliases'][0]
for i in lists.items():
print(1)
if i[0] == extension:
print(2)
b = i[1]
for a in lists.keys():
print(3)
if a == extension:
print(4)
self.bot.load_extension(f'cmds.{extension}')
print('a')
await ctx.send(f'load **{extension}**')
else:
self.bot.load_extension(f'cmds.{b}')
print('ab')
await ctx.send(f'load **{b}**')
break```Why it doesn't work? @hollow isle
Walrus operator variable leaking is fine for global use, but even when the walrus operator variable in the list comprehensions also leaking to globals is acceptable?
Should we not report it as a bug for it
>>> [(t:=(t[1], sum(t)) if i else (0,1))[0] for i in range(20)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
>>> t
(4181, 6765)
You are not allowed to use that command here. Please use the #bot-commands channel instead.
In the above example the t variable is leaking into the global-namespace
Even when in the list-comprehension
Hello ! I have a huge XML file with the following structure:
<?xml version="1.0" encoding="UTF-8"?>
<!-- (...definition of elements and entities...) -->
<JMdict>
<entry>
<ent_seq>1000000</ent_seq>
<r_ele>
<reb>ヽ</reb>
</r_ele>
<sense>
<pos>&unc;</pos>
<xref>一の字点</xref>
<gloss g_type="expl">repetition mark in katakana</gloss>
</sense>
<sense>
<gloss xml:lang="dut">hitotsuten 一つ点: teken dat herhaling van het voorafgaande katakana-schriftteken aangeeft</gloss>
</sense>
</entry>
<!-- (...5 million lines...) -->
</JMdict>
It's a multilingual Japanese dictionary. It's 104Mo. How can I perform binary search in the dictionary's entries without loading all of it in memory?
@fast birch There is some tool called duplicut https://github.com/nil0x42/duplicut so maybe it is going to be helpful
How do i get the minimum value from a dictionary?
min
i wanna get the minimum value from the monthly dict.
will min work on " monthlyAvg"??
min(for value in dict["montlyAvg"].values())
does this work?
Hey guys I have a task about Python Alg. This task is from my school. I was tried so many ways to solve this problem but I couldn't make it. That task so important for me. Could anyone help me pls?
unfortunately it is and this is final task from my homework. I have to handle it.
maybe I can give you a hint
|| count the number of distinct number of characters using ___ and then subtract this from the total length. Think why? ||
it can be help but I wanna ask something else. Can you give me more a little bit hint 😦
what part does it seem hard?
have you thought about the previous one?
I was working on 3 task before fourth. This tasks tired me of. Now I can't even think. Normally, it seems not hard to me. But unfortunately I can't anything about that because I am so tired now and I have to deliver tomorrow morning. For that reason I written here to get help. Sorry guys I did not want to bother anyone.
guys what is this window called?
a text box inside a canvas?
idk I am not good at gui stuff
well my prof didnt teach us gui. so im kinda lost lol
i could maybe do some research if i knew what it is
nvm. my prof was using another ide, no wonder i didnt get it lol
what is the use-case for algorithms like merge-sort when you can just use something like sort() in python?
def sort(l):
res = [min(l), max(l)]
l.remove(min(l))
l.remove(max(l))
for i in l:
for interval in range(len(res)-1):
if res[interval+1] > i > res[interval]:
res.insert(interval+1, i)
break
return res
```does this algorithm match any existing one?
looks like insertion sort
yeah it's similar
the only thing is that i'm not iterating in the result list, as doing that along with using insert might be a problem...
Why it is said that for a binary tree to be balance is that the difference between the left and right subtrees should not be more than 1? Why 1? Is there any meaning behing the number 1?
it means the difference must be 0
i'm sorry but could you please elaborate it?
let me share this code from CTCI
public static int getHeight(TreeNode root) {
if (root == null) {
return -1;
}
return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}
public static boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
int heightDiff = getHeight(root.left) - getHeight(root.right);
if (Math.abs(heightDiff) > 1) {
return false;
}
else {
return isBalanced(root.left) && isBalanced(root.right);
}
that doesn't look like python
i think what ur saying is the definition of avl tree
@wraith valve I'm not sure. I'm not yet there on that topic
like the difference in height between 2 subtrees cannot be greater than 1
thats just definition
like u can also choose another definition which is what red black uses
not sure, but i guess allowing the gap to be one allows some flexibility as to the number of nodes that can be in the tree
eg if you required the depths to be the exactly the same you could not balance a tree with two nodes, or with 4 if you wanted to fill every level other than the last
maybe someone can say with more authority
btw wikipedia has
A balanced binary tree is a binary tree structure in which the left and right subtrees of every node differ in height by no more than 1.[22] One may also consider binary trees where no leaf is much farther away from the root than any other leaf. (Different balancing schemes allow different definitions of "much farther".[23])
so i'm thinking the right way to go is a bit dependent on the context at hand
i think the difference of no more than 1 asserts the log n runtime
not sure about a different size tho like 2 or 3
yeah, i took the question to be "why not 0? why not 2?" etc
@agile sundial
this is the python equivalent
def get_height(root):
if root is None:
return -1
return max(get_height(root.left), get_height(root.right)) + 1
def is_balanced(root):
if root is None:
return True
height_diff = get_height(root.left) - get_height(root.right)
if abs(height_diff) > 1:
return False
else:
return is_balanced(root.left) and is_balanced(root.right)
Does this array have the form of a binary heap? Just to trying to understand what Im doing. [4, 6, 7, 3, 5, 2, 1]
i think simple is doing balanced trees
oh wait ur not talking about simple
@lean glade assuming ur doing a min heap the 3 5 children of 6 doesnt seem to work
I think you're right about this
if it was a max heap 4 is in the wrong position
thank you for citing this
honestly idk what will happen if the difference in height was like at max 2 or 3 instead of 1
So should I do binary heaps out of lists by sifting down or by sifting up?
uh for a better runtime u want to heapify down
starting from halfway
and go to the start
But what I don't understand is that from what Im reading here (yes, in wikipedia), sifting down is for extraction?
and with regard to difference in heights i think u just need a limit on how much the difference can be. you cant have too big of a difference so i guess they just chose 1
@lean glade so if u want to remove for a priority queue
u pop the first
and u replace that with the last element
and u heap down the first element
And where do I place that popped element?
But when Im building the heap
but like its not part of the structure anymore
if u want to build a heap from a list
u start from index n/2 and u go to index 0 assuming u have an 0 index heap
and for each element u heapify down for the better runtime
@wraith valve
May I ask why this is not a balanced tree?
10
/ \
20 40
/ /
30 50
/
60
I don't think this is height-balanced. The right branch can be more optimized
oops i'm taking that back
A balanced binary tree is a binary tree structure in which the left and right subtrees of every node differ in height by no more than 1
eg the node labeled 40 has a subtree of height 2 and and one of height 0, so
(sorry, i misread the def before making the comment preceding this one)
is it the same to what @wide prism is saying?
oh ok I think I understand now, so let's say if there's another node on the right of 40 then it will be balance? right? because that will make a difference of 1 against the left side of 40 ?
Yeah I didn't provide the details but vt explained it well
yeah but still thank you
u need to do a rotation with the tree that has 40 as a root
@wraith valve no I mean if I will create a new tree with the same with that but with a node on the right of 40 will that be a balanced tree?
if u insert sth to the right of 40 it should
cuz 40's left subtree has a height of 1
and 40's right subtree has a height of 0
and then u check 10 who's left subtree has height of 1 and whos right subtree has a height of 2
@wraith valve Thanks,
last question, may I ask why in this code why they add 1 after getting the max between the root.left and root.right ?
return max(get_height(root.left), get_height(root.right)) + 1
does anyone know why my program isnt working correctly?
import heapq
import collections
def helper_func(k):
return len(k[-1]), k
def huff(my_freq_data):
heaps = []
for sym, freq in my_freq_data.items():
heaps.append([freq, [sym, '']])
heapq.heapify(heaps)
while len(heaps) > 1:
l = heapq.heappop(heaps)
h = heapq.heappop(heaps)
for i, k in enumerate(l):
if i != 0:
k[1] = f"0{k[1]}"
for i, k in enumerate(h):
if i != 0:
k[1] = f"1{k[1]}"
heapq.heappush(heaps, [l[0] + h[0]] + l[1:] + h[1:])
return sorted(heapq.heappop(heaps)[1:], key=helper_func, reverse=False)
if __name__ == '__main__':
string = "this is an example for huffman encoding"
my_freq_data = collections.defaultdict(int)
for sym in string:
my_freq_data[sym] = my_freq_data[sym] + 1
dummy = huff(my_freq_data)
print("Symbol".ljust(10) + "Weight".ljust(10) + "Huffman Code")
for k in dummy:
print(k[0].ljust(10) + str(my_freq_data[k[0]]).ljust(10) + k[1])
its only printing out 'g' for symbol, and 1 for frequency
like if u take the node 50
its left has height 0 and the right has a height -1 assuming no node is represented as -1 height
but the node itself is one taller than it's tallest subtree so u add 1 to get the node's height
which in the case of 50 is 0 + 1 = 1 which matches the pic
@wraith valve I'm sorry is that you answer here? or still about adding a node on the right of 40 ?
sorry for I'm confuse that's for my new question, isn't?
thats for the min(left, right) + 1 = height
oh ok but why min()? I think it should be max()
ok so with this diagram isn't it when we take the node 50 the height on the left will be 1 and right is 0?
but you said here the height will be 0 and the right will be -1
I'm sorry I'm lost, may you elaborate that part?
like when u find the height of the tree
u find the maximum height of the subtrees
and to find the height of the subtrees u ignore the node itself and look at the child nodes
and u count the height of the child nodes
let me cut you on that part
on the diagram, you mean I will ignore the 10 and look on the child of it on both left and right?
yeah
ok continue
u find the height of the tree that has root 20
and u find the height of the tree that has root 40
those two are subtree heights
and now to find the height of the tree that has root 10
u find the max of the height of the tree that has root 20 and the tree that has root 40
and then u add 1
the height is 1
Is this now a maxheap? [7, 3, 5, 6, 4, 2, 1]
uh no the 3 is in wrong position
Should it be after the 5?
that height consider both left and right of 20, isn't?
yeah
the height of the tree left of 20 is 0 and the height of the tree right of 20 is -1 bc there is no tree
wait why 0? not 1?
what is the height of one node
you mean a tree with one node?
what I understand is that it is 0 because if that tree has a child that will make it's height 1
I'm not sure
yup if a tree has a child it is height one
so the height of the subtree 30 is 0
so the height of the subtree 20 is 1
oh wait
there is a distinction between the height of the current tree and the height of the subtrees of the current tree
I'm lost with you wording here
the tree left of 20 is the tree 30
yeah
ok I understand now
no tree has height -1 in this case
so to find the height of tree 20 u first need to know the height of tree 30 and no tree
you said here
is the same with no tree
but why you said it is -1 in this case
so since 30 has height 0 and the NULL has height -1
the height of 20 would be the max of those two + 1
so max(0, -1) = 0
0 + 1 = 1
so height of 20 is 1
ok
so this is the part i'm confuse
what is +1 for?
why do we need to account it?
do u know the difference between a tree and a subtree
what is one or which one? if which one then the tree with the root 30
@wraith valve
i mean the tree with root 20 in ur example
a bin tree has two subtrees
what is one of the subtrees of the tree with root 20 in ur case
I'm confuse with your wording here I'm sorry
@wraith valve
@wraith valve the tree with root 30 and a null tree
0
good
so to find the height of the tree 20
u need to know the height of the tree 30
since 20 has one more edge to it, it's height is 1 greater than the height of 30
which is where the +1 comes from
oh
wait
I quite understand it now but I need to a proper wording to remember it
so +1 is needed to account for the height of current node as being parent of two subtrees?
yup
which is the same when we need to find the height of tree with root 10 (the entire tree). We neglect the node 10 itself for the moment but rather focus on its subtrees (on left and right)?
is that right?
yeah
once u found the subtrees
u can then use the max value of the subtrees then u add 1 to account for the extra edge
awesome
How can I extract all "metrics" from a JSON that looks like:
{ comments: [
comment: "blahblah"
metric: "metrics"
replies: [
reply1: {
comment: "blahblah"
metric: "metrics"
replies: [
reply1: {
comment: "blahblah"
metric: "metrics"}
reply2: {
comment: "blahblah"
metric: "metrics"}
]
}
reply2: {
comment: "blahblah"
metric: "metrics"
replies: []
}
]}
I have no idea how deep the rabbit hole goes (meaning I have no way of knowing if there is one reply to a given comment or 20). Right now I've been saying:
try:
for comment in JSONofabitch['comments']['comment']:
getMetrics(comment['metrics'])
try:
for reply in comment['replies']
getMetrics(reply['metrics'])
...
Except as KeyError:
continue
Except as KeyError:
continue
so uh
how the frick do i do this
i'm guessing there's maybe an O(1) way to do each of these?
i mean an O(1) way to apply an operation on a row?
like you use O(n) time to make O(n) steps
so that's kinda O(1) per row
idk it's confusing
I did the "insane" one, technically a different kata
yeah, can't pass this one
How can I extract all "metrics" from a JSON that looks like:
{ comments: [ comment: "blahblah" metric: "metrics" replies: [ reply1: { comment: "blahblah" metric: "metrics" replies: [ reply1: { comment: "blahblah" metric: "metrics"} reply2: { comment: "blahblah" metric: "metrics"} ] } reply2: { comment: "blahblah" metric: "metrics" replies: [] } ]}I have no idea how deep the rabbit hole goes (meaning I have no way of knowing if there is one reply to a given comment or 20). Right now I've been saying:
try: for comment in JSONofabitch['comments']['comment']: getMetrics(comment['metrics']) try: for reply in comment['replies'] getMetrics(reply['metrics']) ... Except as KeyError: continue Except as KeyError: continue
@main hedge recursion would be good
Any book recommendations for algorithms and data structure?
Data Structures and Algorithms Made Easy by Narasimha Karumanchi
Introduction to Algorithms
@severe spire It's probably the best book on the subject.
alr can someone help
-
A linear search would go one by one finding out which one is the same as the value your give it.
-
While the binary finds it in one go.
is it right
You're right about linear search, but a binary search works by repeatedly ruling out half of the remaining options.
Is this a graded test?
Honestly, I forgot that python functions can call themselves. Thanks for the tip.
not sure if this is the right channel, but I'm basically looking for some help with something I'm trying to do with game screenshots.
Want to determine the native resolution of a game, even though its streamed at a higher resolution, if that makes sense.
talking about cloud gaming services here.
those work in a way where the game is 1080p for example, but streamed at 4k (no real upscaling in the game, the stream is upscaled)
I have found a way to do this by hand, but its pretty tedious...
so I'm trying to automate it.
right now I've used PIL to do this, but that just reads the resolutions of the file, which isn't what I'm looking for.
anyone an idea how I could do this?
i have a text file. and inside it there’s like
test1
test2
test3
if i look for a string in the text file it finds it. but say i look for t. it also finds it and lets it through. is there a way i can match case
so it only accepts the ones that are in there
such as test3 and not just 3
Leetcode > algoexpert
I want to do a list of n numbers that the user types, I want the result as another list which has the same numbers from lowest to highest, only using for (comparing i and i+1 as numbers), while, and functions.
For example, I type n as 5, it will request me 5 numbers, I type 6, 8, 2, 5, 1
I get a result of a list which has numbers as following: 1 2 5 6 8
Does the left child need to be bigger than the right child in a max binary heap?
Hello folks. I need to find the coordinates of the intersections of one segment with several others (<10) on the same line. It looks like "interval trees" could be of use, does anybody have experience with them? Could you point out some decent resources to learn about their implementation?
cant zoom in far enough on my phone
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not cloned or original:
return
if original == target: return cloned
self.getTargetCopy(original.left,cloned.left,target)
self.getTargetCopy(original.right,cloned.right,target)
code ^
question:
Given two binary trees original and cloned and given a reference to a node target in the original tree.
The cloned tree is a copy of the original tree.
Return a reference to the same node in the cloned tree.
Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.
Follow up: Solve the problem if repeated values on the tree are allowed.
example:
Input: tree = [7,4,3,null,null,6,19], target = 3
Output: 3
Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.
Nope, only the relative size between parent and child matter in a heap, not between siblings.
i know nothing about any kind of tree
well i think @keen hearth does
Thanks!
No prob 👍
anyone good with algos here? i need some help with my Q
@small sage go ahead and ask what you would ask if someone said yes.
Hey @small sage I suppose your only option is to search for the target node, and remember the steps required to get to that node from the root.
Then follow the same steps in the cloned tree to find the right node.
If the nodes had a parent attribute it would be much easier 😄
I've been trying to understand how to make a list into a heap, and I found that sifting down through the list is the best option. And from what I understood, it said that I don't need to sift down the entire list, instead I can sift down all nodes which have children, in reverse order, and the last node with children can be found by doing (len(list)//2)-1. Is what I said correct?
Yes that sounds right @lean glade
Might need to check the calculation, one sec...
Yeah so, for each two nodes you add to the tree, you make it so that one more node has a child.
For a tree with zero or one nodes there are zero nodes with children. For a two node there is one node with a child. So for an n node tree, there are n//2 nodes with children, the last of which has index n//2 - 1.
Proof by induction 😄
And yes, if you use sift down nodes in reverse order I believe the heapification is O(n), where n is the number of nodes.
@oblique panther
@keen hearth yep thats what i did actually
here is my code:
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not cloned or original:
return
if original == target: return cloned
self.getTargetCopy(original.left,cloned.left,target)
self.getTargetCopy(original.right,cloned.right,target)
i fuckign got it
i forgot the keyword RETURN
LMAO
oh and also
shouldve said return this or this
not just return line one and return line two
thanks guys
I wonder why is that
And for the sifting down, I just swap the current node with the root node for each node? Or do I insert it at the top?
I got to do this using down sifts, but there's something missing, and I really don't know what:
def heapify_down(lis):
last_parent=len(lis)//2-1
for ind,t in enumerate(list(reversed(lis[:last_parent+1]))):
ind=last_parent-ind
while (2*ind+1 and 2*ind+2)<=len(lis) and lis[ind]<(lis[2*ind+1] or lis[2*ind+2]):
if lis[ind]<lis[2*ind+1]:
lis[ind],lis[2*ind+1]=lis[2*ind+1],lis[ind]
ind=2*ind+1
elif lis[ind]<lis[2*ind+2]:
lis[ind],lis[2*ind+2]=lis[2*ind+2],lis[ind]
ind=2*ind+2
print(lis)```
i think it might be easier to do it recursively
it might also help if u make a function that returns the left child and another function that returns the right child
@lean glade
What would be the use of a right and left function?
If I can do it with whatever of both children
use those as helper functions
basically returns index of left and right child
and u basically then compare
But that's just 2i+1 and 2i+2
0 indexed
okay
well it might be sth to do with ur while loop
hence y i said if u made it recursive it might be easier
Yeah, tomorrow I'll implement it recursively
I just wanted to do it with a while loop to help me understand down sifts and all that shit
i found it was easier to visualize recursively
@karmic quail is it related with topic of the channel?
is it? im new to discord and confused
I think not 🙂 It rather #tools-and-devops in my opinion
You can always pick some free help channel
alright, i found that this python itself is a channel and it has multiple channels inside it
Microdict on PyPi showing huge gain interms of space,time. I think it's better to implement it in standards track of Python, though the API is somewhat difficult to use. Did anybody seen yet microdict ?
hey how r u guys , i hope u all okay . I want to start algos and data structures. And im completely beginner , so can you guys help me about it (where can i start , how can i start)? can you guys offer me any source ? (video ,book)
or advices , or anything that would help
@hybrid ferry
Introduction to Algorithms by Cormen, Rivest and others
thx you so much
Hey @hoary bronze 🙂 Also check out Khan Academy's algorithms course for a gentler introduction.
I'll find the link....
CLRS is outstanding. I’m currently taking DS at university and it is a fantastic supplement. But it is very heavy
CLRS is a really good undergraduate algorithms textbook. But I'd recommend it as your second introduction to algorithms as you might find it easier to digest if you already have some familiarity with the topic.
It's a fairly mathy book.
Having a structured series like ^ or Princeton’s free coursera course is the move. Then supplement understanding with books like CLRS or skienna, or videos I.e Abdul bari, backtobackswe, hackerrank
Video lectures to accompany CLRS from one of the authors: https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-algorithms-sma-5503-fall-2005/
Wasn’t aware of that. Great link
Yeah, he's a good lecturer too. Super charming guy 😄
Although the videos are lacking in pixels... 
Nice. Agreed on the math heavy approach though. Im taking discrete and most of the proofs go over my head
the mit guy got some kind of award
Yeah, understanding mathematical proofs is a skill that takes effort to learn. Although it's worthwhile as the techniques make it easier to reason about the correctness of your programs. For example, yesterday in this channel I did an informal proof by induction to check the correctness of an algorithm.
@autumn timber You should check out the Art of Problem Solving book series. They're really meant to be for precocious kids doing maths competitions, but they're actually not bad as a supplement for undergraduates. The Intermediate Counting and Probability is particularly relevant to discrete math.
@keen hearth thats great, thats just what I need. I just picked up a copy of how to solve it to read over winter break, I'll add those books. I have one more semester of discrete.
It's the intuition that I'm lacking. In part because I took 10 years off from school/math, and while I did fine in high shool, I didn't particularly care, so I didn't cultivate a "math brain"
Oh, the Polya book? That's a classic 😄
Don't worry, I didn't really develop a love of learning and maths until after I left school.
Mostly by watching Khan Academy videos.
Yep. Those khan academy folks are great. Used them a lot during the calc progression. I probably shoulda made use this semester too
Hey @wraith valve, I found out why it wasn't working, it was because I wasn't swapping the node with it's biggest child
And yeah, the sift down method is way more optimal
Im so happy now
+1
nice @lean glade
I might be biased as a student, but Algorithms by K Wayne and R Sedgwick is preety good
There's a free coursera course too!
Sedgwick is a gold standard
What's a smart algorithm for find shortest path but you can break a single wall. My idea with bfs where you keep track in the queue whether a wall was already broken on this path or not ended up too slow.
any tips on visualizing on understanding recursive?
@mint jewel shortest path but you can skip one edge?
so im doing this question
and im stuck because heres my code:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
visited = []
output = 0
def deepestLeavesSum(self, root: TreeNode) -> int:
if root not in self.visited:
self.visited.append(root)
if root.left is not None:
return self.deepestLeavesSum(root.left)
if root.right is not None:
return self.deepestLeavesSum(root.right)
else:
current = root
for i in self.visited:
current = self.visited.pop()
if current.left is None and current.right is None:
self.output = self.output + current.val
return self.output
the output i get is:
i dont get why because it technically should be recording
can someone help
okay traverse the tree and if you hit a node store its value in a dictionary where height of the node is the key
now return the sum(dict[max_height])
can anyone give me a little help with an exercise? I need to convert an int to a str in order to read each digit an extract one number passed.
if that digit to extract is not in the number then return -1
I have this ugly thing that I tried
the find function will probably be helpful
But am I thinking this correctly or am I a long shot from what I should be doing
that seems fine if you are trying to replace the char with a ":"
my problem is that if I print this it prints the string without being modified for some reason
I could have done this print(stringNumero.replace(extraer, '')) but I lose the return -1 thing and it's not what I need
yeah if you want to do it this way
you'll need something like s = s[:n] + ":" + s[n+1:]
if you want to do it this way w/ -1:
if c not in s:
print(-1)
else:
print(s.replace(c, ":"))
ok got it, thanks
One more thing, I don't know if we are going to be allowed to use .replace
Any work around for that?
that's a school assignment?
we can't write it for you
also, this isn't really the right chat, check out #❓|how-to-get-help
am so sorry
np
what is the big O of py class solutions(): def find_duplicate(lst): answer = [] another_list = [] for ind in lst: if ind in another_list: answer.append(ind) another_list.append(ind) return answer?
what do you think
O(n)
why
yeah
so how do i calculate it?
you have to look at your code
and understand how it works
what's the big O of in on lists?
yes
so the code should be O(n^2) right?
what would that change?
reduce your big O to O(n)
like this py class solutions(): def find_duplicate(lst): store = {} store2 = set() for i in lst: try: if store[i]: store2.add(i) except KeyError: store.__setitem__(i, True) return list(store2)?
not like that
Hey, btw, you can do i in store to check if it is in the set.
Although store is actually a dict 😄
wait did is in in list 0(n) but in in a set 0(1)?
yep
Sets and dicts are implemented as hash tables.
so how about this
class solutions():
def find_duplicate(lst):
store = set()
store2 = []
for i in lst:
if i in store:
store2.append(i)
store.add(i)
return store2```
why not keep store2 as a list
isn't sets a little faster than list?
in what way
i guess its useless since im converting it back to a list anyway
thank you @agile sundial, @keen hearth for the help
excuse me guys, im a university student and i wanna ask all of u python developers. i have a task from my university to make a list. what inside the list is integer that i input. and the input textbox won't stop until i write 0 number. is that possible?. many thx btw
yes, that's possible
A Python <class 'float'> is double precision, not single precision, so you need float64, not float32
Hey @fiery cosmos!
It looks like you tried to attach file type(s) that we do not allow (.pdf). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .flac, .afdesign, .m4a, .csv.
Feel free to ask in #community-meta if you think this is a mistake.
hello! So i was given this question to solve:
Given that the area of a triangle is N .
Output three sides of the triangle.
Sample input: N = 7
Sample output:
3.5
4
5.315
From what I can see, this is basically just "Heron's Formula", which is √s(s-a)(s-b)(s-c) in reverse, but I'm not exactly sure how to reverse the formula. Considering there are 3 unknown variables ie a, b and c, isn't it impossible to solve?
@barren terrace They probably want any 3 possible sides, so fix two of them and find the third
@fiery cosmos good point. I'll try that now. Tq!
Hello. I have a question. I've built a web parser to find a bunch of web urls/links. In what format should I save the parsed links? Should I just plain append them to a .txt file and put a comma in between? The goal is to use them in another function and be ressource-friendly. I should mention that all of the parsed links have the exact same length (36) and formatting. Only the last 6 chars differ.
You can save one url per one line - it's easy to read this file and recover results
@trim fiber Thank you. I will look into it
No, there's not, AFAIK. A Python float object is always double precision. numpy has single precision floats if you need them, I believe
is ther a way to run product without it hogging all my memory?
def swp_cs(out):
t_out = copy.deepcopy(out)
for t, c, cswp in zip(t_out, c_s, c_swps):
for e in t_out[tk]:
e_s = e['s']
if e_s:
e['s'] = e_s.replace(c, cswp)
return t_out
This works fine, but is there an algorithm I can leverage for this kind of logic? I'm trying to practice my Python algorithms intuition. Maybe something like a transform if? (Please tag me if you reply)
Can you give an english description/function definition @compact flame ?
It is hard to know exactly what this code is doing without any documentation
i made a search algorithm but don't know if i can improve the speed
algorithm goes from the database and checks the values of names, every time it matches one in the database the counter is increased by 1 (for that key-value pair) and the item name with the highest counter appears first.
Example
user enters a list of words: jacket, black, lego
data =
[{"name": "Black Card Nvidia", "price":...}, {"name": "Green Jacket Nintendo", "price":...}, {"name": "Black Jacket Lego", "price":...},{...}]
counter for item index 0 is 1 (matching word(s): black),
counter for item index 1 is 1 (matching word(s): jacket),
counter for item index 2 is 3 (matching word(s): black, jacket, lego) thus index 2 appears at top.
EXAMPLE ENDS HERE
EDIT: Did I accidentally reinvented the wheel for a basic search algorithm 🤦♂️
The function takes a dictionary, and returns a transformed copy of it.
The dictionary has the following structure:
{
'A': [ {'a': 'someText1', 's': 'text_to_modify'}, ...],
'B': [ {'a': 'someText2', 's': 'text_to_modify'}, ...], ...
}
The transformation: Every s key must be accessed and if its value text_to_modify exists, replace a given word in it such as: e['s'] = e['s'].replace(current_old_word, current_new_word).
current_new_word and current_old_word come from known lists of strings which are zip-iterated through along with the dictionary.