#algos-and-data-structs

1 messages · Page 93 of 1

fiery cosmos
#

ill take a look @ the structure

ionic pasture
#

ok

fiery cosmos
#

thanks!

lunar jacinth
#

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

restive grotto
#

What are date structure and algorithms

flat sorrel
#

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)

brave oak
#

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

#

🥴

flat sorrel
#

!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
halcyon plankBOT
#

@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

flat sorrel
#

@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}")
flat sorrel
#

Ok I think I am done fixing bugs for the above xD

fiery cosmos
split nymph
#

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]
fallen tulip
#

do you guys have a turtle chat

astral pelican
#

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
kindred imp
split nymph
fallen tulip
#

ello

swift ether
#

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)

agile sundial
#

wait why are you using np to put multiple data types in

swift ether
#

Forget my question, you make me think jajaja I just need to turn the values into float

sand kiln
#

hello does anyone know How to write this function for this examples in the comment in one line code only?

agile sundial
#

doesn't seem that difficult

#

have you tried?

sand kiln
#

yes many times

agile sundial
#

what have you tried

sand kiln
#

my logic is if(((x*y)+z)*x:return true

#

something like that i think

agile sundial
#

isn't it supposed to return a string

kindred imp
#

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))

brave oak
#

e.g. a self-balancing binary search tree

fiery cosmos
#

nightmares

snow swift
#

heapq?

brave oak
#

you won't be able to get all the elements in sorted order in linear time

half hornet
#

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

half hornet
#

ty

#

for the help

rich cairn
#

guys can yall help me out with this error

twin edge
#

@rich cairn i guess you're missing closing parenthesis somewhere

rich cairn
#

hmm

#

what about the first error

#

the "else" one

twin edge
#

Fix that one first

rich cairn
#

finding

#

cant find it

fiery cosmos
#

@rich cairn
if
if >> elif (code):
if >> elif (code):
..
else:
code

rich cairn
#

@fiery cosmos ok

onyx mist
#

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

slim cosmos
#

hey guys is there a dedicated channel for OOP concepts?

fiery raft
#

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...

fast flicker
#

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?

agile sundial
#

codingbat has a bunch of problems that explicitly use lists

fiery cosmos
#

@fast flicker like the methods of list or problems in which lists are involved?

umbral matrix
#

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

dark sinew
#

hey guys , does anyone here uses openCV library on Pycharm mac os ?? logo_pycharm

tacit lily
#

hi i just heart that here can ask python module pandas thing and excel thing here . is it okay to ask here

snow swift
dark sinew
#

@snow swift ok thank you , i asked there too but no respond till now T-T

snow swift
#

@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

dark sinew
#

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

ashen wharf
#
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

ashen wharf
#

still doesn't work

fiery cosmos
#

whats the error

ashen wharf
#

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]))
fiery cosmos
#

well, returns the same list

ashen wharf
#

nop

fiery cosmos
#

do you want it to show [1,2,3,4,5]?

ashen wharf
#

yes it's a sort

fast flicker
fast flicker
ashen wharf
#

ew

#

i forgot the parentheses when copying it

fast flicker
#

Okay.

#

There's another problem, though.

ashen wharf
#

yes?

fast flicker
#

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.

ashen wharf
#

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
fiery cosmos
#
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 ?
ashen wharf
fast flicker
#

Just a sec.

#

Are you aware that range(4) returns [0,1,2,3]?

ashen wharf
#
for i in range(1, len(sort))
#

i gave it 5 numbers

#

it starts with 1 because i check i-1

fast flicker
#

You're only checking through i = 3.

ashen wharf
#

len(sort) = 5

#

because i inputted 5 numbers

fast flicker
#

range(0,4) => 0,1,2,3

ashen wharf
#

uh i said len(sort)

#

not len(sort)-1

fast flicker
ashen wharf
#

i changed it

fast flicker
#

So when sort = [2, 3, 4, 5, 1] and j = 0, is sort[j-1] > sort[j]?

zenith pagoda
#

In min-heap ff i will extract the 4, to which should I exchange it? to 90 ?

shrewd cradle
#

I think you bring up the last node, which is 87 in this case?

zenith pagoda
#

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.

shrewd cradle
#

Yeah I believe it's the bottom-right

outer ledge
#

is anyone available to help me with a python issue

autumn mason
#

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

brave oak
#

start, stop, and step

#

in this case, stop and step are both negative

#

so the range outputs 3, 2, 1, 0

quick tapir
#

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!

bold lake
quick tapir
#

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

burnt hamlet
#

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

quick tapir
#

I figured my question out, and even managed to make it smoother 😮

autumn mason
#

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?

agile sundial
#

you can't

fiery cosmos
#
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

agile sundial
#

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

autumn mason
#

thanks guys

autumn mason
#
    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```
agile sundial
#

what does 4[0] give

autumn mason
#

4[0]?

#

I have gotten anything like that

agile sundial
#

i know

#

it's a hypothetical question

fiery cosmos
#

@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
raven kite
#

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]

fiery cosmos
#

How big is the array

raven kite
#

not improtant

#

it doesnt have limit

#

brute force is not accepted btw xd

fiery cosmos
#

Yeah thats what i was asking size for

#

What was your time complexity?

#

N^6?

raven kite
#

n!

#

im trying better

#

im trying to find better aproach

fiery cosmos
#

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

raven kite
#

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

fiery cosmos
#

Hold up

#

Lemme switch to pc

raven kite
#

i thought about sum of big array/5 and make subs array according to it

#

but it wont be always optimal

fiery cosmos
#

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

raven kite
#

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

fiery cosmos
#

yeah I am not choosing sorted subarrays

#

I am just choosing 4 points to split by brute force

raven kite
#

oh i got it

#

brute force is possible

fiery cosmos
raven kite
#

why

#

"split" word mb

fiery cosmos
#

you need sub-array not sub-sequences

#

subarrays are like continous portions

#

i...j all included

raven kite
#

english is not my native language

#

you are right

#

i need 5 partiton of array

fiery cosmos
#

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

raven kite
#

not 1,4

#

hm

fiery cosmos
#

yes

raven kite
#

sorry for it

fiery cosmos
#

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

raven kite
#

sub sequences

#

think like its group

fiery cosmos
#

reeeeeeeee that is hard

raven kite
#

yea

#

brute force is mb only solution

fiery cosmos
#

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 ...

raven kite
#

nope

#

if there is a big element on the last

#

it will fail

#

1 ,2 ,3, 4 ,5, 15 for example

fiery cosmos
#

the only thing I can think of right now is recursive + memoization

raven kite
#

it will be minimum 16

#

but i could be 15

#

yeap

#

thanks anyway

fiery cosmos
#

and I am scared to write recursion in python

#

also how large can an element in the array be?

raven kite
#

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

fiery cosmos
#

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 .

ancient turtle
#

kill me

fiery cosmos
#

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]

raven kite
#

there is two 20

fiery cosmos
#

rip wrong input

raven kite
#

but [10,10,10] [15] must be [10,10] [10,15]

fiery cosmos
#

no it is giving wrong for [1, 2, 3, 4, 5, 15]

raven kite
#

for better solutions

fiery cosmos
#

I am really worried about the max number in the array

fiery cosmos
#
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

raven kite
#

(n^2)! > (n!)^n

#

how to proof this mathetical

wraith valve
#

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

raven kite
#

left side is bigger btw

wraith valve
#

yeah

raven kite
#

log(n^2)! for example

#

what change

wraith valve
#

left side = right side + extra terms

raven kite
#

right is nlog(n!)

wraith valve
#

n! = n * n-1 etc

#

log rules

#

changes to addition

raven kite
#

how to proof n log n bigger than logn^2+....logn

#

its obvious i see

wraith valve
#

left side expands to log(n^2) + log(n^2-1) etc

raven kite
#

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

wraith valve
#

@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

raven kite
#

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?

wraith valve
#

i was thinking the same thing

#

@raven kite

raven kite
#

so its true @wraith valve

#

i can do induction

wraith valve
#

i mean prob

#

but u gotta figure a base case

#

cuz obviously 0 doesnt work

raven kite
#

3

wraith valve
#

prob

raven kite
#

thanks @wraith valve

kindred imp
#

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

eager hamlet
#

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)

ashen wharf
#

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
drifting drum
#
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 ?
ashen wharf
#

it starts from 0

drifting drum
#

I know it starts from 0

#

are you sure you read what I wrote correctly?

ashen wharf
#

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
drifting drum
#

yeah I'm trying to trace the bug in the second loop

ashen wharf
#

thank you so much for finally helping

#

@drifting drum are you there?

drifting drum
#

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

ashen wharf
#

you mean the i?

drifting drum
#

key = sort[i], yes

ashen wharf
#

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

drifting drum
#

I'm fairly certain what I wrote works on any input, including the one in the pic

ashen wharf
#

ok

#

i was talking about my code

drifting drum
#

I did say you don't have a reference to the ith element

#

I'm not sure you understand how insertion sorts work

ashen wharf
#

i mean is it required to have a variable to store sort[i]?

drifting drum
#

yeah

ashen wharf
#

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

#

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

drifting drum
#

I've never actually done it without using the key element, let me think

ashen wharf
#
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

drifting drum
#

oh

#

I get the problem

#

it's in this line
for j in reversed(range(0, i+1)):

ashen wharf
#

yes?

drifting drum
#

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?

ashen wharf
#

it actually doesn't change anything

#

i tried it

drifting drum
#

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
ashen wharf
#

hmm

#

so all along this was the problem with the start and stops XD

#

tysm!

drifting drum
#

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
dire meadow
#

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 ?

drifting drum
dire meadow
#

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...

drifting drum
drifting drum
dire meadow
#

the problem is that i have a list of pairs of dictionaries, i needed a single dictionary.

drifting drum
#

do you want to elaborate?

dire meadow
#

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.

drifting drum
#
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}
halcyon plankBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

drifting drum
#

is that what you want?

dire meadow
#

ok, that was it, i have written a function doing just that.

drifting drum
#

yeah it's just a single line of code

#

comprehensions are nice like that

dire meadow
#

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.

drifting drum
#

it's not a reference

#

infact your values in the orginal nested dictionary are actual literal integers, not objects

dire meadow
#

how do you format code ?, in the chat i mean.

drifting drum
#

!code

halcyon plankBOT
#

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.

dire meadow
#

i guess it's the same as:

materialList = dict()
for material in materials:
    materialList[material.get('materialTypeID')] = material.get('quantity')
drifting drum
#

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

dire meadow
#

Well, i would have to declare a function, just because i'm not that clever, seems smarter to learn.

#

thanks.

agile sundial
#

wait, how are you gonna write an insertion sort without a key

dire meadow
#

@agile sundial are you asking me ?

agile sundial
#

no

raven comet
#

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

sleek tundra
#

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.

ashen wharf
#
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

tawny shore
#

@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

sleek tundra
#

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.

ashen wharf
#

can anyone help with my quicksort code above?

tawny shore
#
for key, value in mapping.items():
     #loops thru all keys+values ``` @sleek tundra
sleek tundra
#

@tawny shore Would that loop through all keys and values for all attributes of attributes of attributes etc.?

tawny shore
#

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

ashen wharf
sleek tundra
#

@tawny shore Thanks for the help! I think I've figured it out.

fiery cosmos
#

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?

cloud bough
#

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

grizzled schooner
ashen wharf
#

@cloud bough sorting algos

ashen wharf
#

yes

#

"selection sort, bubble sort, insertion sort, merge, quick sort, heap sort" are pretty much the 1st you should learn

cloud bough
fiery cosmos
#

Thanks.

#

1 last question.

#

how do i add these to a list?

#

will append work?

grizzled schooner
#

could you show your code?

fiery cosmos
#

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

lunar jacinth
#

Does anyone have some experience in huffman greedy algorithms?

#

i'm trying to implement this but im kinda stuck

lunar jacinth
#
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

bronze sail
#

what would be faster? 2d graph with connections or space partitioning?

clever solstice
#

check all value in dict, if match, return the key of the value
have anyway to do that?

agile sundial
#

have you heard of for loops?

clever solstice
#

Yep

#

but i don't know how

#

I remember I had seen but I forgot how to do

hollow isle
#
c=0
for i in dict.values():
    if i==match:
       print(dict.keys()[c])
       break
    c+=1
#

is one possible solution

clever solstice
#

I will try

agile sundial
#

how does that even work

#

what is c for

#

@hollow isle

clever solstice
#

i==match?

hollow isle
#

counter..

agile sundial
#

sure, but why

hollow isle
#

print(dict.keys()[c])

agile sundial
#

also, how does dict.keys()[c] work

hollow isle
#

isnt dict.keys() a list

#

so the c'th element of dict.keys()

agile sundial
#

nvm, i cannot read

hollow isle
#

LOL

agile sundial
#

you can also use dict.items()

hollow isle
#

there are many ways, yes.

hollow isle
clever solstice
#

the values of dict

hollow isle
#

wha-

#

i didnt understand

#

wdym

clever solstice
#

if it match to the values of dict, return the key of value

hollow isle
#

if what match

#

what is 'it'

clever solstice
#

I'll use it in @commands.command()

#

async def a(self, ctx, item)

#

item is 'it'

hollow isle
#
for i in dict.values():
    if i==item:
       print(dict.keys()[c])
       break
    c+=1```
#

must work

clever solstice
#

@hollow isle await ctx.send add after c+=1 or for?I mean indent

hollow isle
#
c=0
for i in dict.values():
    if i==item:
       await ctx.send(str(dict.keys()[c]))
       break
    c+=1```
agile sundial
#

you can skip on the count variable and the indexing if you use dict.items

hollow isle
#
    if i[0]==item:
       await ctx.send(str(i[1]))
       break```
clever solstice
#

TypeError: descriptor 'items' for 'dict' objects doesn't apply to a 'list' object

#

@hollow isle

hollow isle
#

bro replace dict with your dictionary name

#

and dont name your dictionary dict never use keywords for naming

clever solstice
#

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

hollow isle
#

you cant make a list a dictionary

#

whats the name of list

clever solstice
#

lists = dict(jdata['loadaliases'])

#

@hollow isle

hollow isle
#

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

clever solstice
clever solstice
#

my list like this [{'a':'ab', 'b':'bc'<etc>}]

clever solstice
hollow isle
#

lol wym wym, you cant

clever solstice
#

"make a list a dict"?

clever solstice
flat sorrel
#

If your list only has a single dict inside then you can get the dict using my_list[0]

clever solstice
#
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?
clever solstice
#
    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
sweet cipher
#

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)
halcyon plankBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

sweet cipher
#

In the above example the t variable is leaking into the global-namespace

#

Even when in the list-comprehension

fast birch
#

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?

trim fiber
#

@fast birch There is some tool called duplicut https://github.com/nil0x42/duplicut so maybe it is going to be helpful

GitHub

Remove duplicates from MASSIVE wordlist, without sorting it (for dictionnary-based password cracking) - nil0x42/duplicut

fiery cosmos
#

How do i get the minimum value from a dictionary?

agile sundial
#

min

fiery cosmos
#

will min work on " monthlyAvg"??

#
min(for value in dict["montlyAvg"].values())
#

does this work?

cloud bough
#

does someone have good courses for DS and Algos?

#

free preferred 😄

tough ginkgo
#

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?

fiery cosmos
#

is this homework?

#

@tough ginkgo

tough ginkgo
#

unfortunately it is and this is final task from my homework. I have to handle it.

fiery cosmos
#

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? ||

tough ginkgo
#

it can be help but I wanna ask something else. Can you give me more a little bit hint 😦

fiery cosmos
#

what part does it seem hard?

agile sundial
#

have you thought about the previous one?

tough ginkgo
#

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.

fiery cosmos
#

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

fiery cosmos
#

nvm. my prof was using another ide, no wonder i didnt get it lol

fiery cosmos
#

what is the use-case for algorithms like merge-sort when you can just use something like sort() in python?

agile sundial
#

well...sort uses a hybrid mergesort

#

so there's that

ashen wharf
#
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?
mint jewel
#

looks like insertion sort

ashen wharf
#

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...

zenith pagoda
#

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?

agile sundial
#

it means the difference must be 0

zenith pagoda
#

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);
  }
agile sundial
#

that doesn't look like python

zenith pagoda
#

oh sorry

#

let me change it

wraith valve
#

i think what ur saying is the definition of avl tree

zenith pagoda
#

@wraith valve I'm not sure. I'm not yet there on that topic

wraith valve
#

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

wide prism
#

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

wraith valve
#

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

wide prism
#

yeah, i took the question to be "why not 0? why not 2?" etc

zenith pagoda
#

@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)
lean glade
#

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]

wraith valve
#

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

zenith pagoda
lean glade
#

I think it's a max heap?

#

I don't know much, if not nothing

wraith valve
#

if it was a max heap 4 is in the wrong position

wraith valve
#

honestly idk what will happen if the difference in height was like at max 2 or 3 instead of 1

lean glade
#

So should I do binary heaps out of lists by sifting down or by sifting up?

wraith valve
#

uh for a better runtime u want to heapify down

#

starting from halfway

#

and go to the start

lean glade
#

But what I don't understand is that from what Im reading here (yes, in wikipedia), sifting down is for extraction?

wraith valve
#

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

lean glade
#

And where do I place that popped element?

wraith valve
#

oh that is gone

#

u removed it

#

like its not literally gone

lean glade
#

But when Im building the heap

wraith valve
#

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

lean glade
#

Hmm ok

#

I'll see what I can do

#

Thx

zenith pagoda
#

@wraith valve

May I ask why this is not a balanced tree?

      10
     /  \
   20    40
  /     /   
30    50     
     /
   60 
shrewd cradle
#

I don't think this is height-balanced. The right branch can be more optimized

wide prism
#

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)

zenith pagoda
zenith pagoda
shrewd cradle
#

Yeah I didn't provide the details but vt explained it well

zenith pagoda
wraith valve
#

u need to do a rotation with the tree that has 40 as a root

zenith pagoda
#

@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?

wraith valve
#

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

zenith pagoda
lunar jacinth
#

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])
wraith valve
#

ugh

#

ur tree grows so u gotta add 1

lunar jacinth
#

its only printing out 'g' for symbol, and 1 for frequency

wraith valve
#

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

zenith pagoda
wraith valve
#

we just looking at node 50

#

so it has one child to the left and none to the right

zenith pagoda
#

sorry for I'm confuse that's for my new question, isn't?

wraith valve
#

thats for the min(left, right) + 1 = height

zenith pagoda
wraith valve
#

ya u right it is max

#

typo

zenith pagoda
zenith pagoda
wraith valve
#

ur counting the heights of the subtrees

#

not the tree itself

zenith pagoda
#

I'm sorry I'm lost, may you elaborate that part?

wraith valve
#

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

zenith pagoda
#

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?

wraith valve
#

yeah

zenith pagoda
#

ok continue

wraith valve
#

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

zenith pagoda
#

cut

#

ok for example

#

for the tree with the root 20, what will be its height?

wraith valve
#

the height is 1

lean glade
#

Is this now a maxheap? [7, 3, 5, 6, 4, 2, 1]

wraith valve
#

uh no the 3 is in wrong position

lean glade
#

Should it be after the 5?

zenith pagoda
wraith valve
#

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

zenith pagoda
#

wait why 0? not 1?

wraith valve
#

what is the height of one node

zenith pagoda
wraith valve
#

yeah

#

if the tree has one node how tall is it

zenith pagoda
#

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

wraith valve
#

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

zenith pagoda
#

oh wait

wraith valve
#

there is a distinction between the height of the current tree and the height of the subtrees of the current tree

zenith pagoda
wraith valve
#

the tree left of 20 is the tree 30

zenith pagoda
#

yeah

wraith valve
#

the tree 30 has height 0

#

the tree right of 20 is no tree

zenith pagoda
#

ok I understand now

wraith valve
#

no tree has height -1 in this case

zenith pagoda
#

ok

#

wait

wraith valve
#

so to find the height of tree 20 u first need to know the height of tree 30 and no tree

zenith pagoda
#

is the same with no tree

wraith valve
#

yeah 30 has height 0

#

no tree has height -1

zenith pagoda
#

but why you said it is -1 in this case

wraith valve
#

30 is a tree

#

but the thing to the right of 20 is not a tree

#

its a NULL

zenith pagoda
#

oh ok

#

continue

wraith valve
#

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

zenith pagoda
#

ok

#

so this is the part i'm confuse

#

what is +1 for?

#

why do we need to account it?

wraith valve
#

do u know the difference between a tree and a subtree

zenith pagoda
#

no, what do you mean?

#

I'm sorry

#

yeah of course

wraith valve
#

for the tree with a root 20

#

what is one of the subtrees

zenith pagoda
#

@wraith valve

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

zenith pagoda
#

@wraith valve

wraith valve
#

if u have a tree

   20
  / 
30  
#

what are the subtrees of it

zenith pagoda
#

@wraith valve the tree with root 30 and a null tree

wraith valve
#

okay good

#

so what is the height of the tree with root 30

zenith pagoda
#

0

wraith valve
#

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

zenith pagoda
#

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?

wraith valve
#

yup

zenith pagoda
#

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?

wraith valve
#

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

zenith pagoda
#

awesome

main hedge
#

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
eager hamlet
#

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?

runic tinsel
#

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

brave oak
#

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

severe spire
#

Any book recommendations for algorithms and data structure?

viral lily
#

Data Structures and Algorithms Made Easy by Narasimha Karumanchi

vivid horizon
#

Introduction to Algorithms

#

@severe spire It's probably the best book on the subject.

fiery cosmos
#

alr can someone help

#
  1. A linear search would go one by one finding out which one is the same as the value your give it.

  2. While the binary finds it in one go.

#

is it right

keen hearth
#

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?

main hedge
pure gust
#

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?

fiery cosmos
#

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

royal holly
#

Leetcode > algoexpert

zenith zodiac
#

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

lean glade
#

Does the left child need to be bigger than the right child in a max binary heap?

fiery cosmos
#

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?

small sage
#

@smoky lion

smoky lion
#

cant zoom in far enough on my phone

small sage
#
# 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.
keen hearth
smoky lion
#

i know nothing about any kind of tree

small sage
#

well i think @keen hearth does

keen hearth
#

No prob 👍

small sage
#

anyone good with algos here? i need some help with my Q

oblique panther
#

@small sage go ahead and ask what you would ask if someone said yes.

keen hearth
#

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 😄

lean glade
#

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?

keen hearth
#

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.

small sage
#

@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

lean glade
#

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?

lean glade
#

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)```
wraith valve
#

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

lean glade
#

What would be the use of a right and left function?

#

If I can do it with whatever of both children

wraith valve
#

use those as helper functions

#

basically returns index of left and right child

#

and u basically then compare

lean glade
#

But that's just 2i+1 and 2i+2

wraith valve
#

sure

#

is ur thing 1 indexed or 0 indexed

lean glade
#

0 indexed

wraith valve
#

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

lean glade
#

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

wraith valve
#

i found it was easier to visualize recursively

trim fiber
#

@karmic quail is it related with topic of the channel?

karmic quail
#

is it? im new to discord and confused

trim fiber
#

You can always pick some free help channel

karmic quail
#

alright, i found that this python itself is a channel and it has multiple channels inside it

sweet cipher
#

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 ?

hoary bronze
#

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

blazing crest
#

@hybrid ferry

trim fiber
hoary bronze
keen hearth
#

Hey @hoary bronze 🙂 Also check out Khan Academy's algorithms course for a gentler introduction.

#

I'll find the link....

autumn timber
#

CLRS is outstanding. I’m currently taking DS at university and it is a fantastic supplement. But it is very heavy

keen hearth
#

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.

autumn timber
#

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

keen hearth
autumn timber
#

Wasn’t aware of that. Great link

keen hearth
#

Yeah, he's a good lecturer too. Super charming guy 😄

#

Although the videos are lacking in pixels... lemon_pensive

autumn timber
#

Nice. Agreed on the math heavy approach though. Im taking discrete and most of the proofs go over my head

fiery cosmos
#

the mit guy got some kind of award

keen hearth
#

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.

autumn timber
#

@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"

keen hearth
#

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.

autumn timber
#

Yep. Those khan academy folks are great. Used them a lot during the calc progression. I probably shoulda made use this semester too

lean glade
#

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

autumn snow
#

+1

wraith valve
#

nice @lean glade

wanton python
#

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!

grave glen
#

Sedgwick is a gold standard

mint jewel
#

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.

zenith pagoda
#

any tips on visualizing on understanding recursive?

wanton python
#

@mint jewel shortest path but you can skip one edge?

small sage
#

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

fiery cosmos
#

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])

odd trellis
#

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

sudden olive
#

the find function will probably be helpful

odd trellis
#

But am I thinking this correctly or am I a long shot from what I should be doing

sudden olive
#

that seems fine if you are trying to replace the char with a ":"

odd trellis
#

my problem is that if I print this it prints the string without being modified for some reason

sudden olive
#

ah yeah

#

bc strings are immutable

odd trellis
#

I could have done this print(stringNumero.replace(extraer, '')) but I lose the return -1 thing and it's not what I need

sudden olive
#

yeah if you want to do it this way

#

you'll need something like s = s[:n] + ":" + s[n+1:]

sudden olive
odd trellis
#

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?

agile sundial
#

that's a school assignment?

unborn hawk
#

Yea

#

am stuck on that

agile sundial
#

we can't write it for you

unborn hawk
#

am so sorry

agile sundial
#

np

jaunty loom
#

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?

agile sundial
#

what do you think

jaunty loom
#

O(n)

agile sundial
#

why

jaunty loom
#

cause only one for loop is present

#

is that a bad assumption?

agile sundial
#

yeah

jaunty loom
#

so how do i calculate it?

agile sundial
#

you have to look at your code

#

and understand how it works

#

what's the big O of in on lists?

jaunty loom
#

oh

#

is in o(n)?

agile sundial
#

yes

jaunty loom
#

so the code should be O(n^2) right?

agile sundial
#

yes

#

although, if you kept another_list as a set, it would be faster

jaunty loom
#

what would that change?

agile sundial
#

reduce your big O to O(n)

jaunty loom
# agile sundial 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)?

agile sundial
#

not like that

keen hearth
#

Hey, btw, you can do i in store to check if it is in the set.

#

Although store is actually a dict 😄

jaunty loom
#

wait did is in in list 0(n) but in in a set 0(1)?

agile sundial
#

yep

keen hearth
#

Sets and dicts are implemented as hash tables.

jaunty loom
#

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```
agile sundial
#

why not keep store2 as a list

jaunty loom
#

isn't sets a little faster than list?

agile sundial
#

in what way

jaunty loom
#

i guess its useless since im converting it back to a list anyway

#

thank you @agile sundial, @keen hearth for the help

fiery cosmos
#

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

agile sundial
#

yes, that's possible

lean dome
#

A Python <class 'float'> is double precision, not single precision, so you need float64, not float32

halcyon plankBOT
#

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.

barren terrace
#

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?

fiery cosmos
#

@barren terrace They probably want any 3 possible sides, so fix two of them and find the third

barren terrace
#

@fiery cosmos good point. I'll try that now. Tq!

fiery cosmos
#

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.

trim fiber
fiery cosmos
#

@trim fiber Thank you. I will look into it

lean dome
#

No, there's not, AFAIK. A Python float object is always double precision. numpy has single precision floats if you need them, I believe

hot tartan
#

is ther a way to run product without it hogging all my memory?

compact flame
#
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)

oak obsidian
#

Can you give an english description/function definition @compact flame ?

#

It is hard to know exactly what this code is doing without any documentation

deft sinew
#

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 🤦‍♂️

compact flame
# oak obsidian Can you give an english description/function definition <@!458440277548335125> ?

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.