#algos-and-data-structs

1 messages · Page 98 of 1

rich ridge
#
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
def maxDepth(node):
    if node is None:
        return 0
    else:
        return max(maxDepth(node.left),maxDepth(node.right)) + 1

root = Node(5)
root.left = Node(6)
root.right = Node(7)
root.left.left = Node(8)
root.left.right = Node(9)
print("Height of tree is %d" %(maxDepth(root)))
#

How do we calculate ht of binary tree when there is no incremental counting in above program ??

fiery cosmos
#

Hey can someone help me with a deepdream neural network? I have my own dataset I want to train it with

vocal gorge
floral crane
#

Can someone please explain the qiucksort to me

north zealot
#

Hey @next storm, please do not post random memes in the server

north zealot
#

!mute @next storm 5h Posting a meme just after a mod ask you not to isn't the way to go. Please re-read over our #rules.

halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied mute to @next storm until 2021-02-02 16:09 (4 hours and 59 minutes).

wispy hare
#

you can directly ask

wispy hare
eager hamlet
#

given a list of points and another point, how would i efficiently check whether the manhattan distance between any of them and the other point is less than or equal to n?

#

(ping 2 reply thx)

buoyant badger
eager hamlet
#

you just ask your questoin lol

buoyant badger
#

lol

eager hamlet
#

ok uh

#

ok so i found out

#

i found a better problem to solve that would solve my problem

#

given a grid of points labelled either A or B, is there a way to calculate the closest B point to each A point (through manhattan distance)?

buoyant prawn
#

Guys any good course to learn algos and data structure ?

buoyant badger
#

how do i get all permutations of [-,+,*]

#

idk how to work with 3

wicked coyote
#

just brute force ig?

#

srry could u elaborate on the question?

#

I need more info to provide a good answer

lean dome
#

!e ```py
import itertools
print(list(itertools.permutations("-+*")))

halcyon plankBOT
#

@lean dome :white_check_mark: Your eval job has completed with return code 0.

[('-', '+', '*'), ('-', '*', '+'), ('+', '-', '*'), ('+', '*', '-'), ('*', '-', '+'), ('*', '+', '-')]
buoyant badger
#

i kinda cant use that i need to use recursion

#

since i need to find all expression that give that target

#

nums = [1, 2, 3] and target = 6 → 2 (expressions: 1 + 2 + 3, 1 * 2 * 3) *example

vocal gorge
# buoyant badger i kinda cant use that i need to use recursion

To get all permutations of n things, separate out the first thing (we'll call it A), and get all permutations of the remaining n-1 things. Then, for each such permutation, generate n new permutations, corresponding to the n different places you can insert A in.

#

For example, for 1,2,3. All permutations of 2,3 are [2,3], [3,2]. Insert 1 into 3 possible positions in each:

[2,3] -> [1,2,3], [2,1,3], [2,3,1]
[3,2] -> [1,3,2], [3,1,2], [3,2,1]

So you get 6 permutations of 1,2,3, as you should.

#

That's your recursive algorithm.

fiery cosmos
fiery cosmos
#

hey guys! how would i go about implementing a sorting algorithm for example quicksort in a way that i can store its state and resume sorting later? or should i just use a sorting algo without recursion? i looked into external sorting but its not exactly what im looking for

flat sorrel
#

Not entirely sure what you mean but perhaps create a wrapper class around a list that overrides mutator methods so that they "pause" the algorithm somehow?

balmy oak
#

@fiery cosmos Perhaps you can do that with generators

fiery cosmos
#

thx ill look into that

stable pecan
#

it is possible

brazen imp
#

guys could anyone help me in exam

#

it will be start in 3mins

#

dm me

#

if u want to help

lucid whale
wicked coyote
#

Could you solve this my first making the black edge 0 and the red edge 1. Then you solve it but make it so u start with either 0 or 1 in the node. Then after that u add .5 to every single node that way black edge becomes 1 and red edge becomes 2. But how would you prove / disprove the fact that u could solve red edge 1 and black edge 0 with starting 0 or 1 in initial node?

vocal gorge
#

Just a tree? There's also the term p-ary tree for trees with p children per node.

subtle hearth
#

basically, just think about moving only on the x or y direction but not both at the same time, how would you get somewhere without using diagonal (sloped) paths

#

Like you would in Manhattan

#

Is this aoc?

eager hamlet
#

no

#

it's usaco

rustic hatch
#

hi, could someone help me determine the complexity of an algorithm?

subtle hearth
eager hamlet
#

5

subtle hearth
#

right and same with (0, -5)

eager hamlet
#

uh yeah

subtle hearth
#

now (1, -5) is 6 away from (0, 0) because you also have to go down 1

#

right 5, down 1

#

so just check the distance from each point to every other point

#

and pair the distance with the coordinate in some data structure like a list of tuples or soemthing

vocal gorge
eager hamlet
#

yeah

#

just pure linear

#

max a mil points so

subtle hearth
#

Ahh that may take a while with my naive method haha

vocal gorge
#

no idea, I'd want to know too. There are spacial subdivision algoritmhs for that, but I don't know an implementation

#

by the way, the good way to calculate the naive way would be with the holy grail: scipy.spatial.distance.cdist

#

then do argmin to find the closest B for each A.

subtle hearth
#

Ohh that's handy, what do you mean by argmin?

vocal gorge
#

np.argmin

subtle hearth
#

ahhh

vocal gorge
#

can do things like "for each row, get the index of the lowest column in that row"

subtle hearth
#

I think I need to understand np arrays better to get what you are talking about

vocal gorge
#

the ith row in the array returned by cdist will be the distances from As[i] to each of the Bs.

#

so to find the closest B-point, you need the minimum in the row. But not the minimum's value, but its index - hence, argmin and not min.

subtle hearth
#

Euclidean Algorithm to find the GCD of two numbers: Voila py def euclidean_algorithm(nums): if all(nums): greater = max(nums) smaller = min(nums) remainder = greater % smaller if remainder == 0: return smaller else: return euclidean_algorithm((smaller, remainder)) else: return max(nums) numbers = 0, 5465465654654654 print(euclidean_algorithm(numbers)) slaps hood

agile sundial
#

nums is a tuple, you don't need to unpack it into a list

#

or unpack it into max

subtle hearth
#

Can I just put nums into all() like ```py
all(nums)

#

Niiice

agile sundial
#

yep, nums is a tuple

subtle hearth
#

fixed

#

thanks!

fair latch
#

how much python should you know before jumping into data structures/algo problems?

crimson wave
#

can i get any fake profile detection projects

fiery cosmos
#

Any YouTube playlist for Graphs, Binary Tree and advanced data structures!!

feral flint
#

ע

keen hearth
#

Studying algorithms goes hand-in-hand with learning Python, as python has some useful data-structures built-in.

#

set and dict are hash-tables; list is a dynamic-array; sorted implements a hybrid of merge-sort and insertion-sort (called Tim-sort)

green cobalt
#

will u help me with 0(1) space complexity?
what it is

#

??

trim fiber
#

For example if you are iterating through array it's not O(1) because different arrays have different number of elements

keen hearth
#

This is also known as an in-place algorithm.

#

Another example: take the problem of reversing a list. You could create a new list, and insert the elements into that list in reversed order; this would not be in-place. Or, you could work from the outside in, swapping corresponding pairs of elements; this would be in-place.

#
def reverse(arr):
    new_arr = []
    i = len(arr) - 1
    while i >= 0:
        new_arr.append(arr[i])
        i -= 1
    return new_arr

def in_place_reverse(arr):
    i, j = 0, len(arr) - 1
    while i < j:
        arr[i], arr[j] = arr[j], arr[i]
        i += 1
        j -= 1
worthy rivet
steady arch
#

hmm ill try solving it

#

and maybe helping u out

#

but im in tenth grade so im not sure whether ill be able to

#

but ill try

#

just gimme some time

#

ooh the first problem i think i can see is that u didnt unpack the list containing the input('').split() that u used

#

to take the n and k integers

#

as input

raw bridge
#

does iterative solutions have better space complexity than recursive ones on an average scale?

mint jewel
#

generally yes

#

but it is not a hard rule

raw bridge
#

ah

ruby swan
worthy rivet
fair latch
keen hearth
# fair latch So right now I'm taking an intro to Python course. Yes, I'm learning about abstr...

Python probably isn't the best language to practice implementing data structures, as it's so high-level. Perhaps something like Java or C++ would be better suited.

Implementing can help you to really understand a data-structure, but it's also important to know when to use it. Practicing programming problems on sites like leetcode or hackerrank can help with this. You don't need to know a lot of python for the easy/medium problems, and it's ok to attempt a problem and look at model solutions if you aren't able to solve it.

fair latch
#

My dilemma is that I know a little about a few different programming languages: Java, Python, & JavaScript. My favorite is Java and would love to learn DS using Java, but I'm also a Data Science/SWE student, and the language that makes the most sense to make my "native" language is Python. I have tried some of the easy problems on Leetcode, and struggled a lot, so that's why I'm going back to build my Python knowledge before attempting any problems.

maiden hornet
#

Binary Tree Question given an array POSTORDER[n] and PREORDER[n] and variable i, j ... how can i determine if i is a parent of j using the 2 arrays?

flint mason
#

wheres a good place to start.

modest pecan
#

When i have a JSON Like this:

my_dictionary = {
    "key 1": "Value 1",
    "key 2": "Value 2",
    "decimal": 100,
    "boolean": False,
    "list": [1, 2, 3],
    "dict": {
        "child key 1": "value 1",
        "child key 2": "value 2"
    }
}

How can i get the value from child key 1?

fresh moss
#

my_dictionary[“dict”][“child key 1”]

#

Or my_dictionary.get(“dict”, {}).get(“child key 1”) if you want to be safe

rough osprey
#

not completely safe:

d = {'key': None}
d.get('key', {}).get('some')
halcyon plankBOT
#

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

fiery cosmos
#

hey guys

re.match(r"[0-9][0-9]okt$|[0-9][0-9]maj$|[0-9][0-9]febr$", "adsf18majadsf")

returns None but i want it to match on 2 numbers followed by a "febr" or a "maj" or an "okt"
how could i achieve this? thanks in advance :)

fiery cosmos
#

i know im pretty new to regex

brave oak
#

can you explain

#

the multiple $s

fiery cosmos
#

i've solved it since then

#

but thanks :)

brave oak
#

yw

#

lmk if you need explanations

fiery cosmos
#

thanks :)

final egret
#

really simply question ... I don't know how to use a function within a class...

class Solution:
def combinationSum(self, candidates, target):
self.res = []
self.candidates = candidates
self.backtrack([],self.target,0) #start at 0th index
return self.res
def backtrack(self,path,target,idx):
if target == 0:
self.res.append(path)
return
if target <0:
return
for x in range(idx,len(self.candidates)):
self.backtrack(path + [self.candidates[x]], target - [self.candidates[x]])
target - [self.candidates[x]]

#

why doesn't doing

Solution(candidates,target) ... how can i run the function combinationSum in this class?

spring grove
#

in order to run functions inside of a class you first have to create an instance of that class and then use the function.

autumn whale
#

you need to declare a constructor for the class

spring grove
#

^and that

#

try looking at using __init__ as a constructor

#

what is it youre trying to do @final egret ?

compact cloud
#

yo are there people that can help with competitve programming questions?

#
subtle hearth
#
Generated 10,000,002 points of y=sqrt(1**2 + x**2)
Quadrants copied, new points: 40,000,008 points of y=sqrt(1**2 + x**2)
true pi........ 3.141592653589793
as generated... 3.141592653580496
corrected...... 3.14159265358
``` How could I make this more accurate? https://pastebin.com/VXiZEPc8
vocal gorge
#

(it's not the current value to full float precision, but I wasn't able to improve it)

subtle hearth
vocal gorge
#
from decimal import Decimal as D
import decimal
decimal.getcontext().prec=28
def pi_est_dec(N):
    step = D(2)/(N-1)
    stepsq = step**2
    total = D(0)
    cur_x = D(-1)+step
    last_y = 0
    for i in range(1,N):
        cur_y = (1-cur_x**2).sqrt()
        total += ((cur_y-last_y)**2 + stepsq).sqrt()
        last_y = cur_y
        cur_x += step
    return total
print(pi_est_dec(1000000))
print("3.1415926535897932384626433832795029") # true 35 digits from wolfram

Output:

3.141592652756257066384470676
3.1415926535897932384626433832795029
#

This takes around 10 seconds already. So Decimals can achieve higher accuracy than floats... but for that you still need to have enough points.

#

And decimals are far slower, so it's hard to get that many points.

subtle hearth
#

Hmm yeah doesn't seem to be that effective... I can get that accuracy but it only takes 2-3 seconds for 1 mil iterations. What exactly does decimal do? Guessing it's for use with currency and very small important numbers

#

Oh does it store the decimal as an int or soemthing?

vocal gorge
# subtle hearth Hmm yeah doesn't seem to be that effective... I can get that accuracy but it onl...

Python floats are the same as numpy's float64, and the same that's called "double"s in other languages - 64bit floating-point numbers. They are implemented in hardware, that's what modern CPUs are build to work with. If you need more precision than that, the only way is to implement such numbers in software. That's what the decimal library does. Of course, doing in software what's usually done in hardware is way, way slower.

#

In general, that's what's is known as "arbitrary-precision arithmetic". It's when you implement your own numbers in software so that you can get as much precision as you need.

subtle hearth
#

Rocket science, Finance, and finding the value of pi, thx arbitrary precision arithmetic!

vocal gorge
#

yeah, another use of decimals is that they aren't floats

#

like, they are fixed-point and not floating-point

#

in anything money-related you want fixed-point numbers, everywhere - not for precision, just for the lack of loss of precision in intermediate calculations

#

you don't want 10 cent + 10 cent +... + 10 cent (10 times) to be equal to 0.999999999 dollars.

subtle hearth
#

Right or like when ur trying to do the Pythagorean theorem 10,000,00 times haha

fiery cosmos
#

hello

#

oh

copper arrow
#

Hey its been a while

lyric bramble
#

Given an array of size n, find the majority element. The majority element is the element that appears more than floor(n/2) times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example :

Input : [2, 1, 2]
Return : 2 which occurs 2 times which is greater than 3/2.

#

what could be the best time complexity for this

vocal gorge
#

Time complexity? O(n), pretty clearly, as it's achievable and I don't think it's possible to do less.
(to achieve, make a Counter, then pick the element with the most appearances)

main flower
#

Yeah, O(n) seems the best the best

#

Altough, you are probably going to use a hash table for a counter

#

So you should watch out for hash collisions

#

cuz then it could be O(n^2)

vocal gorge
#

Does anyone actually expect hash collision problems in real applications? I got the impression that they only really happen (in large amounts) when you manually design a hash function that's very bad.

main flower
#

Well, I'm not sure, but they can happen so It's better to watch out

#

Another thing would be to just sort the array

#

In O(nlogn)

#

And then just acces mid+1-th element

#

I mean, for arrays with even number of elements acces n/2-th element while for arrays with odd num of elements access n/2+1-th element

soft sequoia
#

I have a test, the questions will be based on algorithm, data structure such,,, how should I prepare for it??? Any help is appreciated thank you :)

tame wigeon
#

Use geekforgeeks website if it consists pseudo code or any implementation.

#

Hackerrank.com is also good for a long run I don't recommend it for a test though

undone ingot
#

How can I define a function where you don’t have to put all arguments when you execute it?

soft sequoia
#

@tame wigeon thank you!

lucid olive
#

ay u know any good resources to learn data structures and algos for beginners

#

preferably free

rustic portal
#

I'm doing coding challange and I think my issues is not undertanding how to apply algo's to solutions, is there a good website or video to increase my undertanding?

bleak tapir
eager hamlet
uneven jungle
#

@rustic portal go check this book: Data Structures and Algorithms in Python, Michael T. Goodrich. It exists in pdf version., it's really great.

floral crane
#

What is quicksory

agile sundial
#

quicksort?

fiery cosmos
#

hi

#

I try to use variable and definitions external to the file, but can't find a way to do it.

#

example:
test1.py:

def a():
    return 1;

test2.py:

def b():
    result = b.test;
    result = 1 + a();
    return result

main.py:

import test1, test2
client = "test";
print(b());
#

I know you can but I have no idea how.

spring grove
#

if the file is in the same directory you can use:

from test1 import a
from test2 import b
print(b())

if you use your method then:

import test1
import test2
print(test2.b())
#

@fiery cosmos

fair plover
#

This is kind of a more general quesstion but should you include floor/ceilings in timee complexity?

#

Like if an algorithm has floor(n) times, should it be O(n) or O(floor(n))

fiery cosmos
#

@spring grove thk

#

what can i do if i need to use a variable from the running file?

#

test.py:

def a():
    print(client)

run.py:

import test
client = "hi"
a()
#

since it tells me that client is not defined.

spring grove
#

You should probably just make your function return that variable

fiery cosmos
#

yes, but the variable is not defined.

spring grove
#

@fiery cosmos or make your function take a parameter

def a(thing_i_want_to_print):
  print(thing_i_want_to_print)

then
import test
test.a('hi')
#

@fiery cosmos if you dont want to use either of those mthods, make your variable global and pass it to the next file

#

its better practice to use either of the first 2

fiery cosmos
#

yes

rich cairn
#

hey guys idk if this is the right channel

#

couldnt find a channel for matplotlib.pyplot

#

so im asking here, how do i solve this?

rich cairn
#
y=np.array([2,3,4,5,6,7])
plt.scatter(x,y,color='red')
plt.show()```
#

this is it?

vocal gorge
#

How exactly do you expect someone to answer the question "how do I solve this", without having given any details on, well, what you're trying to do?

vocal gorge
flat sorrel
#

Btw you could always just run your code to verify that it's correct

rich cairn
fiery cosmos
#

can someone convert .py to exe for me

coral loom
#

When defining dictionaries in Python, how would I store the first element of every grouped tuple list just as a dictionary key?

mint jewel
#

what do you want as the values?

coral loom
#

At the moment when I create my dictionary using a for-loop over the list of tuples, I get the following output (which still includes tuples):

#

You can see, there's a comma separating each name-value pairs but within each **name ** you might have noticed there's additional ** two element **enclosed with a pair of parenthesis (a tuple otherwise known as)

mint jewel
#

well, you would do ```py
{first: value for fist, *rest in some_list_of_tuples}

coral loom
#

Wait what? Hold on, let me show you how I currently done my dictionary...

mint jewel
#

ah

coral loom
#

named_entities is the list with tuples

#

ne_dict is the Named Entity dictionary

mint jewel
#

so the second elements are entirely irrelevant here?

coral loom
#

For my purpose in this particular count_entity_freq_dict function, yes it is irrelevant

mint jewel
#

on an unrelated note, I would suggest pprint so that the output is more readable

from collections import Counter
from pprint import pprint
pprint(dict(Counter(i[0] for i in named_entities)))
#

use Counter to count things

coral loom
#

So what I've done with my for-loop, you can easily do it with 1 liner? 😯

mint jewel
#

ye, counting things is so common that there is a helper class for it

coral loom
#

I can easily store this as a variable: dict(Counter(i[0] for i in named_entities)) right? And then pass the reference to pprint ( ) ...?

mint jewel
#

yes

coral loom
pure marlin
#

Hi guys I have problem with updating my JSON file.

for file in os.listdir("./python_files"):
    if file.endswith(".xlsx"):
        df = pd.read_excel(os.path.join("./python_files", file)) 
        CRD_Array = df.iloc[:,1].values
        column_length = len(CRD_Array)
        row_iterator = 0
        for single_CRD in CRD_Array: 
                    if os.path.isfile(f'output/{single_CRD}.json'):
                        with open(f"output/{single_CRD}.json", "r+") as json_file:
                            parsed_file = json.load(json_file)                     
                            parsed_file['body-{}'.format(file)]=[]
                            parsed_file['body-{}'.format(file)].append({
                              'Total Employees':  '{}'.format(filed_handler(df,row_iterator,'5A'))})
                            json.dump(parsed_file, json_file)```
#

When file is found I want to add new array to it

#

At this moment file isn't updated with new array

compact otter
#

Hey guys. I'm using weight of evidence to bin my continuous variables. Now that i have all weights, I want to replace my values by there WoE based on the bin they fall into. Is is possible to do this without using 10 if loops?

flat sorrel
#

If your bins are named then bins would instead be a list of strings and replacements a dictionary

lavish flame
#

Hi I wanted to get started with Data structures and algo I am okay with lists dictionaries tuples arrays..is there any other pre-requisite before I start with it. It would be great if u could suggest a few sites where I can start as well

latent wasp
#

Hi,

I am looking to convert an integer from an integer to the following string:

Say we have a variable that holds the integer 240555
I want to convert it to the following string: "$240.6K"

How would I do that?

lavish flame
#

s="$"+str(round(float(num/1000),1))+"K", this will convert to K alsways

#

*always

latent wasp
#

hmm

#

let me see

latent wasp
#

wow it works!

#

thanks a lot @lavish flame

fiery cosmos
#

heyyy

jovial hill
#

Hi there, I would like to store a list of strings and I would like to add another string to the list only if the string is not present in the list. So for example if I have a list with ['the','blue'] and i want to add 'red' to the list, it will check if 'red' is present in the list. Since, it is not present in this case, it will add 'red' to the list. I would like to know if lists work best for this?

spring grove
#

hi @jovial hill maybe look at sets

#

you dont need to check if the item already exists, as duplicate entries cannot exist in a set

jovial hill
#

Aha, cheers 😋

spring grove
hallow vortex
#

Hi guys, hope you are doing well. I was solving this LC, but I don't understand this solution. Could you please explain how this works?

zealous junco
#

can anyone help to convert this code to javascript

#

class Solution:
def solve(self, n):
temp = str(n)
ans = float('-inf')
for i in range(len(temp) + 1):
cand = temp[:i] + '5' + temp[i:]
if i == 0 and temp[0] == '-':
continue
ans = max(ans, int(cand))
return ans
ob = Solution()
print(ob.solve(268))

teal lake
#

Hi

#

need helo

#

help

#

I need the function to add plurals

#

I had to create 2 lists becuase I couldnt figure it out

jovial hill
clear urchin
#

Hi !
I just want to know if there is a solution for this :

a = 4
type(a) #It return "int"
hex(a) #But hex(a) return "0x4" and i want that return "0x04"
lavish flame
clear urchin
#

Thank you @lavish flame

lavish flame
#

np I also learned something new!

jovial hill
#

I am crawling a website and I don't want to visit the same link more than once. To do this I would like to store the links_yet_to_visit in a queue and all the links either in the queue or have already been visited in a set. Each url will have its corresponding parameters and whether its a post or get request. How would I store the values in the queue and set. so each url with be something like:
[url1:{name1:value, name2:value}, post] [url2:{name1:value}, get] [url3:{name1:value, name2:value, name3:value, name4:value}, post]

#

I've gone for the following:
urls = {url1, url2, url3} left_to_visit = deque([[url1, {name1:value, name2:value}, post], [url2, {name1:value}, get] ]) visited_urls = [[url3, {name1:value, name2:value, name3:value, name4:value}, post ]]

So when I find a url, I check if its present in urls, if it isn't I append to urls and I append to left_to_visit. When I visit a url, I pop it from left_to_visit and store it in visted_urls

fiery cosmos
#

Hello, I need help with a python program. The goal of the program is to give a match list (to make a tournament) according to the number of teams. Except I don't have a clue how to do it, could you help me?

clear urchin
fiery cosmos
clear urchin
#

so you want to show something like : l[1] vs l[2] ?

fiery cosmos
#

yeah

clear urchin
#

so u can use something like this @fiery cosmos i think :

I guess every "equipe" is affected to a number.
Ex: Equipe 1 is affected to number 1, etc....

import random

opposant1 = 0
opposant2 = 0
for n in range(Match-1): #You will print as much many times as necessary
    while (opposant1 == opposant2):
        """
        you don't want that a team face himself lol.
        So you will run "random.randint(a,b)" until opposant1 and 2 are different.
        """
        opposant1 = l[random.randint(a,b)] #You define the minimum 'a' and maximum 'b' amount of teams.
        opposant2 = l[random.randint(a,b)]
    del opposant1 #You want to suppress teams that got a game.
    del opposant2
    print(opposant1+"vs"+opposant2) #Finally, you print the game.   
#

I'm not sure that it will work perfectly but i think that's the idea and i didn't think if we can dodge the utilization of the "while" loop. So it's not an optimized python script.

agile sundial
#

pretty sure that will not work

#

although, i'm not sure what you mean by "make a tournament", could you clarify? @fiery cosmos

fiery cosmos
#

@agile sundial for sure , the program serves after entering a number, to know all possible matches between them? (as an example if in a tournament there are 14 people) the program gives us the list for everyone to face everyone like this with 4 teams

agile sundial
#

i see

agile sundial
#

uh

gloomy harbor
#

anyone know how to work this out?

vocal gorge
#

well, that if is O(1), so just consider how many iterations is being done.

clear urchin
agile sundial
#

maybe

#

in this case he doesn't care about the space though

vocal gorge
#

"iteration" just means "one execution of a loop".

clear urchin
#

i'm so n00b XD

gloomy harbor
#

so what is the time complexity then im still lost sorry

#

just O(1)?

vocal gorge
#

Uhh, no?

#
for i in range(n):
    some_operation_that_takes_constant_time(i)
#

what'd be the time complexity here?

gloomy harbor
#

erm im not sure tbh sorry

vocal gorge
#

How many times is some_operation_that_takes_constant_time called?

gloomy harbor
#

is O(n) i think

#

thats all I have to answer

#

in that ss

lean glade
vocal gorge
#

I think combinations accepts iterators as well as lists.

lean glade
#

Yeah ik

#

There, changed it for your liking

vocal gorge
#

also, that's technically only the first round of a tournament 😉

#

...but nevermind, the rest of the lines are not exactly important

lean glade
#

And also idk if the teacher wanted tillmister to do the whole process of selecting the different pairs for the matches

pure terrace
#

How can I define a method that accepts a variable number of paramaters? For instance, i have the following:

await self.add(member, action)

But on some occasions I want to add another variable:

await self.add(member, action, number)
#

and use number whenever is provided

lean glade
#

def func(*args):

#

Or you can use keyword arguments

pure terrace
lean glade
#

Yep, def func(member, action, number = None)

pure terrace
odd hill
#

Hello! im getting this error

#

ERROR::CTag::init::Given souptag is not a bs4.element.Tag instance.

#

Why dosent it work?:)

#

i already pip installed everything

fossil topaz
#

Hey, I have a question about an exams questions about bubble sort. It's more CS in general than Python-specific but I couldn't solve it right anyway.

This exercise (sorry for the Greek) wants me to "print" the array for every iteration of the bubble sort.

The original array A is [55, 34, 5, 2, 2, 1]

#

For some reason, 1 which is at [-1], is being swapped to [0]

#

Can someone explain why that happens

#
def bubble_sort(arr):
    N = len(arr)
    for i in range(N):
        for j in range(N - 1, 0, -1):
            if arr[j] < arr[j - 1]:
                arr[j-1], arr[j] = arr[j], arr[j-1]

bubble_sort([55, 34, 5, 2, 2, 1])
agile sundial
#

it's swapping the min to the left instead of the max to the right

fossil topaz
#

yes that's what I thought

#

but the textbook actually gave me this code snippet

agile sundial
#

and?

fossil topaz
#

how should I do it

agile sundial
#

do what

fossil topaz
#

how should I implement a python function that would modify the array according to the needs of the exercise

#

sorry for the lack of clarity in my questions

agile sundial
#

that snippet already does what you need

fossil topaz
#

yes it gives the same result but the process is different

#

The exercise requires the first iteration to be [1, 55, 34, 5, 2, 2]

#

The textbook snippet does this: [55, 34, 5, 2, 1, 2]

agile sundial
#

i don't think so

#

maybe you're printing on every iteration of the inner loop instead of the outer loop

fossil topaz
#

No, I am not printing, I am using PythonTutor

#

It just visualises the executions

agile sundial
#

i see

#

the instructions say to print on each iteration

#

but you're looking at the result of each iteration of the inner loop

fossil topaz
#

so I need to print the iterations on the outer loop?

agile sundial
#

i think so

fossil topaz
#

yes you were right, a few frames ahead it actually shows the right thing

#

thank you

dim cypress
jovial tartan
#

this might be an extremely stupid question but

#

when you have a function that includes a binary search (complexity is O(logN)) as well as a loop with complexity O(N) , then the complexity of the whole function is O(logN + N) = O(N)

#

at that point, why would we optimize the search if the function time is going to be linear anyways?

#

wouldn't linear search make it O(N + N) = O(N)? which is the same time complexity?

#

I realize that it will be faster to use binary search but I'm confused about the notational differences

storm owl
#

big O notation does not denote runtime, it is just a general overview of how complex a algorithm is, so you are right in that using binary search would not change the complexity, but realistically it is useful to apply when possible.

jovial tartan
#

ok, thank you

#

that clears it up

half lotus
#

It also goes the other way

#

Sometimes an algorithm with a better big-o complexity may be slower in practice

#

Perhaps it has poor performance for very small inputs, for example

coral loom
#

Just a quick question, can you access a class instance attribute/variable from an external Python script?

lavish flame
trim fiber
lavish flame
trim fiber
#

!rule 5

halcyon plankBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.

trim fiber
#
for medicine in s:
  if medicine not in d:
    d[medicine] = 0
  d[medicine] += 1
#

You also should use better names for your variables because it's really hard to remember all of s, d, i, j and so on

trim fiber
lavish flame
#

I wanna know how to distinguis between 2 letters with the same frequency

#

distinguish

trim fiber
#
medicines = list("ABCDE")
freqs = {medicine: 0 for medicine in medicines}
string = input()
for medicine in string:
  freqs[medicine] += 1
lavish flame
#

okay...yea but the final value of freqs is gonna be the same right

trim fiber
#

Then for input "ABAAACEBDAE" you got {'A': 5, 'B': 2, 'C': 1, 'D': 1, 'E': 2} so you can sort dict pairs by value by using sorted(freqs.items(), key=lambda item: item[1], reverse=True)

lavish flame
#

so this is going to give someting like A B E C D or A E B C D like on what basis will it sort if the frequencies are the same

trim fiber
#

If freqs are same then it will use original order as far as I know

#

Result is [('A', 5), ('B', 2), ('E', 2), ('C', 1), ('D', 1)]

lavish flame
#

okay thanks lemme try and get back to you in a min

#

thanks a lot! it worked!

coral loom
trim fiber
trim fiber
coral loom
#

@trim fiber Well, I don't really think I need to create any threads in my application as it doesn't require heavily extensive tasks that need to processed

trim fiber
jovial hill
coral loom
meager chasm
#

ParseError: bad input on line 3

pure parrot
#

true should be True, no?

meager chasm
#

still no ):

#

ParseError: bad input on line 3

agile sundial
#

you shouldn't need to declare it global

#

just remove that part

meager chasm
#

NameError: name 'true' is not defined on line 3

agile sundial
#

true should be True, no?

meager chasm
#

i changed it

#

plzzz

agile sundial
#

is that the right link

meager chasm
#

ya

agile sundial
#

it seems to be the exact same as the one earlier

meager chasm
#

bcz i changed it beck to the global

agile sundial
#

sorry, i don't understand

meager chasm
#

me too

agile sundial
#

what did you change

meager chasm
#

as the link

#

what in the link in the code

agile sundial
#

did you change what i told you to change

meager chasm
#

ya

#

i deleted this

#

still no

#

so i bring the global brck

heavy cloak
#

Why is it returning a syntax error

halcyon plankBOT
#
float.is_integer()```
Return `True` if the float instance is finite with integral value, and `False` otherwise:

```py
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
heavy cloak
#

THANK YOU SO MUCH

#

UR INSANE @mystic basin

#

uh melio one more wuick question

#

alg = lambda x: True if (x ** 1/2).is_integer() == True else False

#

uh is that the proper way too use it?

#

its returning false

#

returns false when i sqeare root perfect squars

#

oh

#

why dont i have to specific if it is true or not

#

still dont work

#

16

#

and 25

#

they both got perfect squares

#

4 and 5

#

what

#

idk what thiws trickery is

#

but it just started working for me

#

idk my python IDE is sus

#

i mean

#

ill use visual studio from now on 😄

#

or something online

#

yeah

#

idk why its weird on mme sometimes

#

whaa

#

i used biger numbers

#

like

#

121

#

and

#

it retunred false on 121

#

for some odd reason

#

ok dude now its returning true

#

dont mind this

#

its pycharm 🙂

#

lmao

fiery cosmos
#

bruh

heavy cloak
#

I see

#

thanks Melio-

shy gate
#

Is there a way to generalize a root finding algorithm to solve generalized equations?

#

Basically i have some expensive function to calculate in a hot path of code: ```python
def f(x: int) -> float:

stuff happens here


I want to find a value for

f(x) < N
f(x+1) > N```

Basically the largest integer to meet the criterion.

#

right now I'm using a basic bisection method, but I was curious if i could steal from root finding and use a secant/interpolation/combination method? Or if this particular problem has a specific name for me to look up the literature on

chrome ermine
#

This might be a dumb question. I have a list of hardware crash data for anytime a piece of HW crashes.

Example:
[dsp crash] Pmd.34938249324 e ent=12 pmasdaaa cf4
[dsp crash] Pmd.34933449324 ee nt=12 pmasdaaa cx

Using difflib, i can match them but running into a problem where i'm trying to build a dict that has say the first crash text and the count anytime it sees a match thats ~90% the same.

thoughts?

warm solstice
#

How do I go about solving this kind problem f program? The problematic part is figuring out the amount of days it takes to update "the servers" pretty confusing

trim fiber
trim fiber
# coral loom <@!690641855045697653> So the point I made earlier on is not possible other than...

Maybe there is but I don't know it. If you have two Python threads inside Python process you have Python which can communicate data from one thread to another. From another hand if you have two processes in your OS (can by Python programs or whatever) you can communicate data from one to another by using OS built-in methods (like FIFOs). There is a problem because you should write some kind of encoder/decoder that encodes your Python data into binary to transfer it through OS methods and you need to have decoder on the other side to decode binary into Python objects for example.
The easiest case is to spawn new Python thread inside script and use Python objects to communicate those threads.

jovial hill
rose kraken
#

anyone coder here dm me

coral loom
#

We can use deepcopy to copy variable's content, if it's to copy the nested items inside an object, right? i.e. a dictionary with a list of string names and integer values

#

I'm trying to define/rename an instance attribute in a Child class and copy over the content from a dict object declared in a Parent class --- but no values actually gets stored/shown (even when I instantiate a Child class instance member)

#
from copy import deepcopy
class Child(Parent):
    def __init__(self):
        super().__init__()
            self.dict = deepcopy(self.parentDict)
#

@wild urchin I think I've got a problem when I deepcopy data found in the original dict object onto a new variable object - no values gets stored on it

wild urchin
#

The code above doesn't include what the Parent class looks like

#

I'd suggest doing so in a help channel, rather than in this topical discussion channel.

crimson jacinth
#

@vocal gorge after thinking about it more I realized I’m not really interested in the entire table but just the frequency of values

#

From that problem in help-chlorine

#

so for example, “how many values are 2000 in the table” etc

#

so I’m thinking to create a dictionary with the keys as values and increment each access

vocal gorge
#

the problem is that you're building the table by incrementing elements multiple times

#

so you can't easily transfer that into another form, I don't think

crimson jacinth
#

I see

frank harbor
#

how do you do the python typing for discord, is it ``?

glossy breach
#

Three "`"

zenith pagoda
#

Hi, can someone help me to visualize or understand the sentence below.

lean glade
#

And the array would have a size of 128 million

zenith pagoda
#

@lean glade is bit vector is an array of arrays of int32s?

vocal gorge
#

well, they might want a vector of int32s. A vector being a dynamic array.

prisma sedge
#

i just started to write a code for a simple binary tree and i have an attribute error. can someone help? i'm new

#

class Node(object):
def init(self,value):
self.value = value
self.left = None
self.right = None

class BinaryTree(object):
def init(self,root):
self.root = Node(root)

def print_tree(self, traversal_type):
    if traversal_type == "preorder":
        return self.preorder_print(tree.root, "")
     else:
        print("Traversal type " + str(traversal_type) + " is not supported.")
        return False

def preorder_print(self, start, traversal):
   
    if start:
        traversal += (str(start.value) + "-")
        traversal = self.preorder_print(start.left, traversal)
        traversal = self.preorder_print(start.right, traversal)
    return traversal
zenith pagoda
crimson jacinth
#

So this isn't a python question per se, but I have an array with 4 billion elements, and I have to iterate over all that, and increment each [x,y] for a given function. Some [x,y] will never be accessed, but others may be accessed multiple times.

#

what are some ways i can speed up this traversal? RAM isn't an issue

#

i will likely implement this in C as well.

vocal gorge
#

Isn't it the same task you did earlier, which could be vectorized with .add.at?

#

oh, in C, I see. Yeah, then I don't have any advice besides "write the loop in a sideeffects-free way and hope for the compiler to optimize it right, preferably with vectorization".

in C, I see
...pun not intended.

crimson jacinth
#

@vocal gorge well I actually ended up doing it in C and surprisingly it finished in 2 minutes but in Python the loop ran for several hours

vocal gorge
#

that's very possible if the Python one was just a loop too

crimson jacinth
#

What do you mean?

#

The function is pretty simple, just takes a lot of memory, it should take the same time in Python I’d imagine

#

But it did not

trim fiber
crimson jacinth
#

but like, orders of magnitude slower?

trim fiber
#

I created simple functions in C and Python to calculate entropy and as far as I remember C code executes about more than 3 times faster

crimson jacinth
#

i see

#

possibly something to do with the data types

trim fiber
#

I think that creating Python objects is overwhelming

#

In C you can use simple types like int or char[], Python needs to create huge structures under the hood

agile sundial
#

that's part of it, yeah

vernal stirrup
#

i have an np array t = [3,2,4,2,4,NaN,NaN] and i have an array tisNaN = [False,False,False,False,False,True,True] (from np.isnan(t) and i want to delete the nan values out of t

#

how do i do it?

fiery cosmos
#

hi guys, Im not sure if this is the right channel but I want ´how can I create a list out of copy pasted text? I basically want a programm in which one copy pastes their insta followers and their insta following and I then want the programm to check who follows you but not them, who you follow but they dont back..... If i copy paste my followers, after every follower it says "profile picture", so I would like the list replace "profile picture" with a comma. Im very new so maybe there is an easy function to do this, but I have been googling for a while and didnt quite get what Im looking for....

shy gate
#

would be much easier to just authenticate a user and log in and pull that information instead of having to copy and paste it yourself

fiery cosmos
#

but for me as a programmer API are far out of reach tbh

#

can I like replace "profile picture" with "," and then its a list?

#

i was trying this, I put it together from a few forums

#

s = input("Copy paste your followers here")
s = re.sub("profile picture" , "," , s)
f.seek(0)
f.write(text)
f.truncate(0)
print(s)

dense rain
#

what does python do?

fiery cosmos
#

but it tells me "re" is not defined

pure terrace
#

Hello how can I delete one event object from the following dict:
my_dict = { user_id: { event_id: {'name': event, 'time': time} } }

#

del my_dict[user_id][event_id]

trim fiber
lavish violet
#

Can i speak?

sudden kernel
#

genuinely lost

#

Note that another sample input can be 14 X X X X 18 X 16 X and output can be ```
14 16 18
14 16 18
14 16 18

violet bramble
#

Hey anyone know how to solve sudoku in python using the ac3 constrain satisfaction algorithm

pale prism
# sudden kernel how would I do this:

do this on paper first. if you have two numbers from one line, how do you calculate the third? check with some simple values and then with letters: if you name the elements in the line a b c, how do you find value of b when you have a and c?
work from there - do the maths, try coding what you found out. that will cover some points
analyse what to do if you have more x's - e.g in your example with 6 x's, are there more solutions? 😉 how do you know when there are more solutions? (answer: ||that's the only solution there - we have a system of 6 independent linear equations, and we have 6 variables; more solutions are possible for "at least 7 x's" case which is for more points||)

clever stratus
#

Let's say I have a set, setA={dog, cat, mouse}, I would like to create a data structure with the strings in Set A, so it would make:

dog = {}
cat = {}
mouse = {}

is that possible?

#

*name the data structures with the strings in SetA

pale prism
main flower
#

why would u do that tho

clever stratus
#

actually I can just create a class lol..

#

just realized that

#

I have a list of email addresses with data associated with them, so I wanted to create a set named after each unique email address

unreal rain
#

I'm wondering how search data structures like a trie works in the real world. Is the whole trie stored in memory or is this search / storage capability on the database level?

grim dove
#

Hi, someone could help me create this function that would allow me to do that ? Thx x)

code = r"""
int a = 5;
foo2(16, 255);
...
"""

code = function(code) 

print(code)
Output:
int a = 0x5;
foo2(0xA, 0xFF);
...
vernal stirrup
#

or do you want the function to format the string?

grim dove
#

yes the function 😂

vernal stirrup
#

use string.split(";") and work it togeteher with "\n" in between?

#

can you explain the purpose of the method?

#

why you want a function like that

grim dove
#

no 😂
I want a function to convert decimal to hexadecimal in a string

vernal stirrup
#

oh i havent seen the difference

#

i am lost sorry

#

that explains a lot i am really sorry

grim dove
#

ah too bad, I hope someone else will have the solution 😅

robust trellis
#

def check_int_and_convert(s): if s[0] in ('-', '+'): if s[1:].isdigit(): return s[0]+hex(int(s[1:])) elif s.isdigit(): return hex(int(s)) else: return s

trim fiber
pure terrace
#

Hello I'm trying to convert an object that contains a nested dict into a dictionary itself:

def to_dict(self) -> dict:
        data = {
            "notifications": self.notifications
        }
        return data

new_not = Notification()
new_not.notifications['users'][_id] = {}
new_not.to_dict()

#

I feel like I might be doing sth wrong

trim fiber
keen hearth
noble vector
#

Hey guys, reading Algorithms in a nutshell, do I just sit with the complexity or should I focus on a prerequisite that I didn't know I needed?

#

I get the data structures part but the notations of the algorithms is just convoluted for me

eager hamlet
icy crane
#

@eager hamlet thanks.…..

noble vector
noble vector
#

The definitions were in the next chapter lol

fair prairie
vocal gorge
#

Basically, if there exists some constant C such that, for all sufficiently large n, T(n) <= C F(n), then T(n) is O(F(n)).

#

For example, T(n) would be O(n^2) if T(n) <= C n^2 for some C and for all sufficiently large n.

fair prairie
#

@vocal gorge 🤔 its soo confusing

vocal gorge
#

some examples:

  1. 1 - exp(-n) is O(1)
  2. 5 n^3 - 10 n^2 + 5n - 120 is O(n^3)
  3. 3log(10n) + 10n is O(n)
  4. 100000 n^1000 exp(-n) is O(1)
fiery cosmos
#

how can I spread (disperse) a set of numbers from n1 to n2 with an exact distance of each other ? Example, dx = 5 n1 = 1 and n2 = 3, so answer is 1, 1.5 , 2, 2.5 , 3

#

i am trying to figure out what formula to use in order to find that answer.

vocal gorge
#

(of course, you can also just realise the distance must be (n2-n1)/(dx-1), because there are dx-1 increases between the first and the last point).

fiery cosmos
#

not sure if my english is very good at explaining what i mean

#

apologies

vocal gorge
#

...because (3-1)/(5-1) = 0.5?

fiery cosmos
#

oh oh okay damn. that was easy

#

is that formula linked with something a bit more general ?

vocal gorge
#

alternatively, we have a general linear function a n + b. Requirements:
1)f(0) = 1, meaning b = 1.
2)f(4) = 3, meaning 4 a + b = 3, therefore a = 0.5

fiery cosmos
#

oh okay i get it now

#

many thanks @vocal gorge !

vocal gorge
#

And in general, the formula is f(n) = n_1 + (n2-n1)/(dx-1) * n - the formula for a line drawn through points (0,n1) and (dx-1,n2)

fiery cosmos
#

also this exercise has to do with Riemann sum

vocal gorge
#

I can't read Greek(?), so I don't know what you mean.

eager hamlet
#

http://www.usaco.org/index.php?page=viewproblem2&cpid=765
so uh i'm working on this problem, and i know that it involves bfs
but how do i do this in linear or linearithmic time
because for each state i also have to keep track of the pies given so i don't accidnetally give 2 of the same pies for the same state

queen ruin
#

what's the dunder that executes on object creation

#

before init

trim fiber
queen ruin
#

ahh yes thank you, google sucks at showing these results

edgy haven
#

Are there any good books to learn algorithms that have examples in python

gilded turtle
#

guys i need help in minimax algorithm

#

I am trying to make a tic tac toe Ai using minimax

halcyon plankBOT
#

Hey @gilded turtle!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

gilded turtle
#

it keeps throwing an error

#

Traceback (most recent call last):
File "D:\Coding\Projects\Unbeaten_X&O\main.py", line 172, in <module>
minimax(Board, 6, True)
File "D:\Coding\Projects\Unbeaten_X&O\main.py", line 156, in minimax
e_val = minimax(bo, depth-1, False)
File "D:\Coding\Projects\Unbeaten_X&O\main.py", line 164, in minimax
e_val = minimax(bo, depth-1, True)
File "D:\Coding\Projects\Unbeaten_X&O\main.py", line 156, in minimax
e_val = minimax(bo, depth-1, False)
File "D:\Coding\Projects\Unbeaten_X&O\main.py", line 162, in minimax
index = Board.index('-')
ValueError: '-' is not in list

coral loom
#

Just a fairly quick question, what are the different ways to do "getters" and "setters" in Python, let's say for a variable named myList of the datatype, list, initialised normally in a class constructor?

flat sorrel
#
class MyClass:
    def __init__(self, lst):
        self.my_list = lst

    @property
    def my_list(self):  # getter
        return self._my_list

    @my_list.setter
    def my_list(self, value):  # setter
        self._my_list = value
stable pecan
#
class MyProperty:
    def __set__(self, instance, value):
          instance.__dict__[self.name] = value

    def __get__(self, instance, owner):
          if instance is None:
              return self
          
          return instance.__dict__[self.name]

    def __set_name__(self, owner, name):
          self.name = name

class MyClass:
    my_list = MyProperty()
    def __init__(self, lst):
        my_list = lst
heady plaza
#

Huuu anyone to explain me this error plz...
Traceback (most recent call last): File "compiler.py", line 7, in sol = solve(expr) File "/usr/local/lib/py/dist-packages/sympy/solvers/solvers.py", line 1162, in solve solution = _solve(f[0], *symbols, **flags) File "/usr/local/lib/py/dist-packages/sympy/solvers/solvers.py", line 1444, in _solve soln = _solve(m, symbol, **flags) File "/usr/local/lib/py/dist-packages/sympy/solvers/solvers.py", line 1498, in _solve f_num, sol = solve_linear(f, symbols=symbols) File "/usr/local/lib/py/dist-packages/sympy/solvers/solvers.py", line 2072, in solve_linear eq = lhs - rhs TypeError: unsupported operand type(s) for -: 'Tuple' and 'int'

#

Ooo

#

I just understood

coral loom
fiery cosmos
fiery cosmos
#

where you didn't want to...

heady plaza
#

Thhhhx

#

U awesome !!

stable pecan
drowsy bolt
#

hey how do i use excel cell value as input for driver.get(cellValue) to vist that url in cell. I have already imported the cell value and workbookwith openpyxl

tame minnow
#

Hi! I am making a project regarding graph theory in python.
Is there a algorithm to split a minimum spanning tree into many paths? (Path is basically a line with 2 ends only) attached are 2 images which might be helpful.
I couldn’t find any answers on google.

grizzled dragon
#

This is an interesting problem!

#

Are you trying to turn the connectogram @ the top, into something like what you display at the bottom? Do you know what sort of constraints, or additional rules ?

tame minnow
#

Yeah

#

The only rule is that the line can only have 2 ends, no branches

grizzled dragon
#

Exhaustive search of all possibilities?

#

non overlapping? overlapping?

tame minnow
#

Overlap is fine

#

I think the search could be limited at some point, and the time complexity will be very high as the nodes increase

grizzled dragon
#

yes, of course, as well as the degree of each node

#

how are you representing the top image?

tame minnow
#

I have a nxn distance/adjacency matrix

grizzled dragon
#

NxN with 1's and 0's denoting connection?

tame minnow
#

Nxn for weight, in this case it’s the pixel distance

grizzled dragon
#

what is the weight needed?

tame minnow
#

Btw it is a complete graph, all the nodes have a weight to every other node

grizzled dragon
#

yeah, but I don't think you need to weight each node to answer the question you posted at the very top

tame minnow
#

Oh yeah

grizzled dragon
#

It's easier to visualize a way forward if you cast the graph in a different representation, e.g. not the adjacency matrix which I think you're using

#

because, to code this, you have to know where to go once you're at a given node.

#

you also have to store the paths somewhere

#

Try the adjacency list.

tame minnow
#

Is there other ways to represent a tree?

grizzled dragon
#

I've done a similar problem to this one, but using adjacency lists. The code was messy AF, but it worked always

#

In graph theory and computer science, an adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a vertex in the graph. This is one of several commonly used representations of graphs for use in computer programs.

tame minnow
#

Oh so something like a dictionary?

grizzled dragon
#

yeah, like a dictionary. I am not sure if this is efficient but it will at least help you visualize a programming solution

#

it is harder to do visualize what is going on with the adjacency matrix representation

#

"An implementation suggested by Guido van Rossum uses a hash table to associate each vertex in a graph with an array of adjacent vertices. In this representation, a vertex may be represented by any hashable object. There is no explicit representation of edges as objects"

#

Guido van Rossum, Mr Python Inventor himself

#

So, to find your paths, you have to figure out some way of coding through all the permutations that the dictionary / hash table produces. There are additional problems that arise when you try to avoid repeating paths, not going around in circles, etc.

tame minnow
#

Do I basically connect each end to another end?

grizzled dragon
#

the structure of the graph will obviously be encoded in the adjacency list. What your code needs to do is simply inspect this structure aided by the how it is encoded.

#

like the A-B-C triangle in the preview

#

a={b,c}

#

b={c,a}

#

c={a,b}

upper tartan
#

(Sorry if there’s a better channel for this.)

Are there any PEP guidelines (or other principles) on whether you should make your class subscriptable or not?

grizzled dragon
#

if you start in a, you notice that there are 2 directions: b & c. Then your code will have to explore each separately, with the first path a-b, and the next a-c.

#

etc.

tame minnow
#

Ah I see, I’ll try to implement this

#

Do you think it will be good to start at a node more at the center?

grizzled dragon
#

I don't think it matters.

#

this should work regardless of the starting point

tame minnow
#

Cool

#

Thanks for the help 🙏

grizzled dragon
#

btw, as I said, I did this in the past, but with a constraint of 2 edges.

#

and it was a nightmare scenario of nested loops and gotos

#

(C++, not python)

tame minnow
#

Do you think I can have a look?

grizzled dragon
#

tbh, it would take you less time to sort it out on your own than it would to figure out my spaghetti

tame minnow
#

lol

#

Ok I’ll try first

grizzled dragon
#

“Do or do not. There is no try.”

tame minnow
#

😂

half gazelle
#
words = ['book', 'pencil', 'pen', 'note book', 'sharpener', 'rubber'] 
def arraySearch(array, search):
    return True
print(arraySearch(words, 'note book') if 'Vrai' else 'Faux')
print(arraySearch(words, 'dog') if 'Vrai' else 'Faux')```
#

help me understand?

#

algo termaire ?

tame minnow
#

arraysearch doesn’t seem complete

half gazelle
#

okay !!thanks

#
words = ['book', 'pencil', 'pen', 'notebook', 'sharpener', 'rubber']

def arraySearch(array, search):
    for i in range(len(words)):
        if words[i] == (array, search):
            print(arraySearch(words, 'note book') if 'VRAI' else 'FAUX')
        elif words[i] != (array, search):
            print(arraySearch(words, 'dogs') if 'VRAI' else 'FAUX')

    return True```
#

like this

tame minnow
#

What’s your question?

#

Also you could just use if item in array: ...

half gazelle
#

my teacher gave me the first code but didn't give us any instructions, I'm looking for a way to understand, I just know that it has something to do with a sorting algo!?

#

thank you for these precisions

tame minnow
#

What’s vrai and faux?

jovial hill
#

Hi, I have two variables but I want them to have difference reference ids:
self.x = aep[1] self.y = aep[1] self.x[key] = 'test' self.y[key] = 'test2' print(self.x) #prints key with value test2 print(self.y)#prints key with value test2

How can avoid this and have both variables to have different references so self.y prints test2 and self.x prints test

vocal gorge
jovial hill
#

oh sorry

#

but thanks anyways

vocal gorge
#

Yup, that's pretty much it. In Python, all assignments are by reference - a copy is never made without explicitly doing so.
(really, most other languages are the same - only primitive types are passed by value, a big object like Map would never get implicitly copied. In Python, there also aren't such primitive types).

jovial hill
#

Thanks a lot!👍

solar musk
#

hello, so i want to create a basic search mechanism in my website but i have trouble making out the logic for it. so the idea is that a user searches something using the search bar right? so i want to show records from database related to quries that user has searched number of times. but i still want to take into the account the time factor. for example: if user searched for oranges 7 times but that was a month back. and the user searches for apples 6 times but it was just a week back. the latest search should have more priority right? what kind of algorithm i should use here? im sure there's already an algorithm for this which exists. any intresting read that you can point me to would be great?

dusk quest
#

hey i created this

halcyon plankBOT
#

Hey @dusk quest!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

dusk quest
#

omg why

#

can anyone dm me if u are good at python and help me out with a code

vocal gorge
dusk quest
#

noo it still shows

#

spam and stuff

vocal gorge
#

or use a pasting service (see below)
@dusk quest

halcyon plankBOT
#

Hey @dusk quest!

It looks like you tried to attach file type(s) that we do not allow (). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .flac, .afdesign, .m4a, .csv.

Feel free to ask in #community-meta if you think this is a mistake.

dusk quest
#

;-;

vocal gorge
#

...why don't you read the bot's message?

#

Or this one, at least:

#

!paste

halcyon plankBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

lost osprey
#

milfs

full stream
#

Would webscraping somewhat fit here?

fiery cosmos
#

hi, I was reading an algo & ds book and I just had a question.

so, arrays store elements contiguous in memory. arrays (unlike linked lists) can have random access, so you can read the 5th index (which is O(1) compared to reading the 5th index of a linked list where you traverse the elements before it, making it O(n)). So, linked lists have sequential access.

So my question is, when using python (for example) using lists, is that saved in RAM as it's random access?

vocal gorge
#

A vector is a dynamic array - it's an array that gets resized when it starts running out of space. So yeah, it's O(1) random access. Not sure what you mean by saved memory - access complexity and memory usage aren't related in an obvious way (though linked lists are terrible in both, and in general - it's a data structure that everyone gets taught, but is rather rarely used).

fiery cosmos
#

i see, thank you very much for the explanation! I think I just confused lists being "random access" and made a link with RAM "random access memory" and thought there was a link. i must say, this algo stuff is pretty interesting so far 🙂

#

also it probably doesn't help that python is a high level language so we cant handle our own memory and understand it, there might be a bit of obfuscation there

vocal gorge
#

Yup, that's pretty true. It's a bit harder to learn DSes in Python than in compiled languages, because implementing them manually in Python is not very useful (any implementation you can make in pure Python will often be literally orders of magnitudes slower than the C-based implementations of the standard library). You still need to know DSA to know when to use the right data structures, though, so it's by no means useless even for Python.

#

and yeah, being far removed from handling memory makes it harder to understand too

quasi basalt
#

can someone help with sklearn here

main flower
#

Well, It's probably connected to machine Learning or data science so you should probably ask in #data-science-and-ml

#

But I don't know your question so idk

vernal stirrup
#

i want to create a boxplot via pandasDataFrame.boxplot(column="dataColumnName", by="seperatingColumnName") but the data in the "dataColumnName" is a list and only the last value of the list should be used. Is there an efficient and clean solution for my problem?

rancid patio
#

How can i get the last date by symbol in this dict of tuples

 ('2020-12-02', 'FB'): -5025,
 ('2020-12-04', 'FB'): 1950,
 ('2020-12-01', 'AAPL'): 15000}````
sullen summit
#

is this the sort of thing you're going for?

rancid patio
#

[{'FB':'2020-12-04'}, {'AAPL':'2020-12-01'}]

#

im looking for something to the sorts of

    from x
    group by sym```
sullen summit
#

oh you want them sorted?

rancid patio
#

i just need the last date for each sym

sullen summit
#

sorry, I'm not sure I understand. You're saying you want to pass the function a symbol, and then have it return the last date in the dictionary associated with that symbol?

#

so here, you would pass it 'FB' and it would return '2020-12-04'?

rancid patio
#

I wouldnt be passing in a symbol. I just need to for each symbol, in this case there is only two FB and AAPL, return me the latest available date

sullen summit
#

should it return that in another dictionary?

rancid patio
#

yeah thats perfectly fine

sullen summit
#

try this and see if it does what you want:

from dateutil.parser import parse
my_dict = {('2020-12-01', 'FB'): 2000,
 ('2020-12-02', 'FB'): -5025,
 ('2020-12-04', 'FB'): 1950,
 ('2020-12-01', 'AAPL'): 15000,
 ('2021-12-01','test'): 0000}


symbol_dict = {}

def create_symbol_dict():
    for key, value in my_dict.items():
        if key[1] not in symbol_dict.keys():
            symbol_dict[key[1]] = key[0]
        

def update_symbol_dict_dates():
    for key, value in my_dict.items():
        if parse(key[0]) > parse(symbol_dict[key[1]]):
            symbol_dict[key[1]] = key[0]

create_symbol_dict()
update_symbol_dict_dates()
print(symbol_dict)
rancid patio
#

yeah this is great!

sullen summit
rancid patio
#

great,yeah i understand. The only thing i was thinking was a will probably want to use a set for the tickers

#

instead of a function

sullen summit
#

yeah, it might be cleaner that way

ember locust
#

hey guys, anyone know Java and can help me go thru each problem on the codility quiz website so I can be prepared for a job interview soon?

flat sorrel
ember locust
#

could you link me to java server plz?

#

i'm totally new here

ember locust
#

thx buddy

flat sorrel
#

np

trim fiber
#

@fiery cosmos How about call help(fxcmpy.fxcmpy)?

#

Your welcome

#

I don't know why there are 10, 20, 30 and so on but when you set for example log level to warn (30) you get logs from error too because 40 > 30 (so you get all log levels above choosen)

#

Your welcome!

half gazelle
#
names = ['Tamata', 'Nicolas', 'Marie-Claude', 'Oriane', 'Florian', 'Yvanne', 'Jordan', 'Joyce', 'Julien', 'Clément', 'Jeremy', 'Daren', 'Mikaele']
def arraySort(myArray):
  # code here ...
print(arraySort(names))```
#

I have to sort all the names in alphabetical order, I have to use the sort by insertion, which could make me rotate the code in all directions but no result.

#

without using .sorted

trim fiber
half gazelle
#
names = ['Tamata', 'Nicolas', 'Marie-Claude', 'Oriane', 'Florian', 'Yvanne', 'Jordan', 'Joyce', 'Julien', 'Clément', 'Jeremy', 'Daren', 'Mikaele']
alphabet=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']

def arraySort(myArray):
    for i in myArray:
        if i in alphabet:
            return myArray

        
print(arraySort(names))
trim fiber
#

Secondly - I cannot write the algorithm instead of you because it breaks rules

#

!rule 5

halcyon plankBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.

trim fiber
#

Show your minimal effort please

half gazelle
#

I understand but I'm just looking for a way out.

trim fiber
#

Take a look at pseudocode here: https://en.wikipedia.org/wiki/Insertion_sort

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. However, insertion sort provides several advantages:

Simple implementation: Jon Bentley shows a three-line C version, and...

half gazelle
#

thx

trim fiber
#

You can come here when you will have a problem with some part for implementation

half gazelle
#

okay thx

mint jewel
#

(get_data,) is a tuple, but (get_data) is just get_data

#

(value) can't be a tuple, since it would break parentheses for math

#

add_callbacks expects some iterable of callbacks

#

but (5 + 6) * 8 is 88, not a tuple.

#

in order to create a tuple with a single element in it, you need a comma

#

(5 + 6,) * 8 is (11, 11, 11, 11, 11, 11, 11, 11)

#

it is not great, but there is real way around it

#

you could also just do [get_data] and avoid this whole issue

coral loom
#

I don't suppose anybody can help me out with something? So I'm creating a pandas **dataframe **from a dictionary, which is populated with mixed **entities **as keys (that includes names of country/people/object etc) and the **occurrences **of that particular entity is stored as the corresponding **value **... Here's how I'm making a dataframe from the dictionary key-value pair items... ```py
def convert_dict_into_dataframe(self):
df = pd.DataFrame.from_dict(self.myDict, columns = ['Entities', 'Frequency'])
return (df.head())

#

Are there any ways to simply check which elements in a df column i.e. Entities, is contained (recognised as a country) in a list of predefined country list object let's say called countryList...? And then with this, be able to extract those identified elements, "countries", and add it to a new column in the **dataframe **table where it just contains data fields of countries.. is this something which can be done?

zenith pagoda
#

May I ask what is the time complexity when an integer x keeps on divided by 10? Is it O(log(x))?

Let say x = 123 and

while x > 0:
  # Some if-block going on here
  x = x // 10
trim fiber
#

However... It depends on number of digits... So number of digits can be calculated by log_10(x) so...

zenith pagoda
#

Additionally, so that's a question with a solution. And the solution says

There are roughly log⁡_10(x) digits in x.

What do they mean by that?

trim fiber
#

Ya... So you are right

#

It's O(log(x))

#

Sorry for mistake

zenith pagoda
trim fiber
#

So you want to find such n that y^n = x

#

Am I correct?

#

So if you want to find n then n = log_y(x)

zenith pagoda
#

Oh yeah, math. I forgot that.

trim fiber
#

Ya, math. Queen of the science

zenith pagoda
#

Thanks for reminding me.

trim fiber
#

Your welcome!

runic moss
#

🔥

wise bronze
#

Hi, how can i make a thread to when i input a word this for loop restarts

while True:
    downloadFiles()
    for remaining in range(10, 0, -1):
        sys.stdout.write("\r")
        sys.stdout.write("{:2d} seconds remaining.".format(remaining)) 
        sys.stdout.flush()
        time.sleep(1)

    sys.stdout.write("\rComplete!            \n")
#

This for is a timer countdown

scarlet gate
heavy cloak
#
translate = lambda x:(ord(i).split() for i in x)
<generator object <lambda>.<locals>.<genexpr> at 0x00000249AF5EC890>
#

thats hte output

#

why is it not returning the unicode of the letters in the string in a list

wise bronze
scarlet gate
#

but you are clearing the output before sleep

#

which clears the output and waits for a sec and then show the output and clears it immediately and so on

kindred coyote
#

So here i have two programs that output the same thing. ```py
m = int(input())
n = int(input())
brushes = input()
stroke = []

colors = [['B' for _ in range(n)] for _ in range(m)]
for i in range(int(brushes)):
g = input().split(' ')
if stroke.count(g) == 1:
stroke.remove(g)
else:
stroke.append(g)
def changeColumn(num,colors,index):
if num == 0:
return colors
colors[num-1][index] = 'G' if colors[num-1][index] == 'B' else 'B'
num -= 1
changeColumn(num,colors,index)

def countGold(c,options,i):
if options == []:
s = 0
for l in c:
s += l.count("G")
print(s)
return
area = options[i][0]
times = int(options[i][1]) - 1
if area == "R":
c[times] = list(''.join(c[times]).replace("G","A").replace("B","G").replace("A","B"))
elif area == "C":
changeColumn(m,c,times)

options.remove(options[i])
countGold(c,options,i)

countGold(colors,stroke,0)

#

and and ```py
c = int(input())
rows = int(input())
brush = int(input())
strokes = []
tc = []
for i in range(c):
tc.append('B' * rows)
for i in range(brush):
strokes.append(input().split(' '))

for i in range(brush):
if strokes[i][0] == 'R':
new_str = ''
for char in tc[int(strokes[i][1]) - 1]:
if char == 'B':
new_char = 'G'
elif char == 'G':
new_char = 'B'
new_str += new_char
tc[int(strokes[i][1]) -1] = new_str
elif strokes[i][0] == 'C':
new_str = ''
for j in range(c):
if tc[j][0] == 'B':
old_char = list(tc[j])
pos = strokes[i][1]
old_char[int(pos)-1] = 'G'
tc[j] = (''.join(old_char))
elif tc[j][0] == 'G':
old_char = list(tc[j])
pos = strokes[i][1]
old_char[int(pos)-1] = 'B'
tc[j] = ''.join(old_char)

s = ''
for t in tc:
s += t

print(s.count('G'))

#

i was wondering which one is more efficient

fiery cosmos
#

Hello guys !
Does someone can help me on an implementation of the IDA* algorithm with Manhattan heuristic ?
Question here : https://stackoverflow.com/questions/66264958/how-can-i-implement-ida-algorithm-in-pyhton-for-15-puzzle-problem

lean ice
#

im trying to write a function that takes in a 2D list and if there's any duplicate values, merges the sublists:
[[1,2,3],[1,4,5],[6,7,8],[1,9,10],[12,3,4]] -> [[1,2,3,4,5,9,10,12], [6,7,8]]

def merge(lst: list) -> list:
    next_value = 1
    all_items = []
    for sub in lst: # group all items to check for dupes
        all_items += sub
    merged = False
    while len(set(all_items)) != len(all_items): # check if dupes
        for sub in lst: 
            for item in sub:
                for _sub in lst: # iterate through each sublists items and check if they are in any other sublist
                    if item in _sub and (sub != _sub or id(sub) != id(_sub)): # ids have to be checked in case 2 sublists have the same values
                        print(f"before: {lst}")
                        sub_index = lst.index(sub) # get sublist index
                        sub += _sub # merge the two sublists together
                        lst[sub_index] = list(set(sub)) # remove the dupe
                        lst.remove(_sub) # remove the merged sublsit
                        merged = True # set flag
                        print(f"after: {lst}")
                    else:
                        pass
                else: # once the sublists are exhausted, skip checking the other values in the sublist
                    if merged: merged = False; break
        
        for sub in lst:
            all_items += sub
    return lst```
#

I'm not quite sure where im going wrong and if there's a better solution for it (im assuming there's something in itertools but im not familiar with it)

zenith pagoda
#

Hi, what is the time complexity of the code below? My initial thought is O(n) but I realize the min() function could affect the runtime but I'm not sure.

# strs = ["foo", "bar", "foobar", "barfoo"]
min_len = 0
for word in strs:
  min_len = min(min_len, len(word))
agile sundial
#

the min function does affect it

void kettle
#

Hey guys, does anyone know how to compare words from a list to words from a txt file? My purpose is to compare a sentence to a grammar and perform a leftmost derivation operation.

#

If anyone is familiar with how to implement left most derivations that'll help too

zenith pagoda
agile sundial
#

well, what do you think?

#

@zenith pagoda

zenith pagoda
#

still O(n) because min() time complexity is O(1).

#

is that correct?

agile sundial
#

think about what operations min does

zenith pagoda
#

min compares two number only. We can do it in this form too:

if min_len < len(word):
  return min_len
else:
  return len(word)

And that is O(1)

agile sundial
#

ah shit I can't read

#

yeah it's O(n) my bad

raven bison
raw zealot
#

Hey,
I am an intermediate python programmer , but I only have experience of python
What's the best time for me to start learning algo and data structures

flat sorrel
hollow lichen
#

Guys can anyone help me with this error

flat sorrel
#

You're already using TensorFlow 2

#

If you're using the latest version I think you can import feature_column directly from tf

fringe thistle
#

TensorFlow Material?

flat sorrel
#

I don't really see TensorFlow being used outside of the machine learning field

hollow lichen
#

Ok thnx 😀

void kettle
pure terrace
#
class Pool:

    def __init__(self):
        pass

    def to_dict(self) -> dict:
        data = {
            "_id": self._id,
            "choices": self.choices,
        }
        return data
my_new_pool = Pool()      
my_new_pool._id = 1
key = "1"
my_new_pool.choices = {}
my_new_pool['choices'][key] = 'value'
print(my_new_pool['choices'][key])
```It doesn't give me its value
trim fiber
#

Try my_new_pool.to_dict()["choices"]

pure terrace
#

Roger that, I will try that thank you

kindred coyote
#

Let's say I have this problem: Input Specification: First Line: contains an integer, M (1 < M < 1 000 000) Next M lines: contains two integers For example: ```py

5
1 2
3 4
5 6
7 8
9 10
I know you can do this using this:py
m = input()
for i in range(m):
numbers = input()

agile sundial
#

how would you be able to reduce the complexity

vocal gorge
#

Time complexity? Definitely not, how'd you read numbers without reading them?

agile sundial
#

you have to read every integer, and to read it, you have to look at them

kindred coyote
#

also I have another questions

vocal gorge
#

also, you're missing a cast to int

kindred coyote
#

So i have this problem: ```
Problem Description
A new and upcoming artist has a unique way to create checkered patterns. The idea is to
use an M-by-N canvas which is initially entirely black. Then the artist repeatedly chooses
a row or column and runs their magic brush along the row or column. The brush changes
the colour of each cell in the row or column from black to gold or gold to black.
Given the artist’s choices, your job is to determine how much gold appears in the pattern
determined by these choices.

Input Specification
The first line of input will be a positive integer M. The second line of input will be a positive
integer N. The third line of input will be a positive integer K. The remaining input will be
K lines giving the choices made by the artist. Each of these lines will either be R followed
by a single space and then an integer which is a row number, or C followed by a single space
and then an integer which is a column number. Rows are numbered top down from 1 to M.
Columns are numbered left to right from 1 to N.

Output Specification
Output one non-negative integer which is equal to the number of cells that are gold in the
pattern determined by the artist’s choices.

#

And I have two pieces of code, but idk which one is more efficient

kindred coyote
#

I have a questions

#

So on the first line of input are two numbers, N and M
The next M lines contain 3 numbers, X Y and Z
How would I generate an array in which the GCD (Greatest Common Divisor) of arr[(X-1)] and arr[(Y-1)] are equal to Z. Note that this array must fall true of all of the different M lines. For example: ```py
2 2 #2 is N, 2 is M
1 2 2 # X is 1, Y is 2, Z is 2
2 2 6 # X is 2, Y is 2, X is 6

[4,6] #The GCD of arr[X-1] (4) and arr[Y-1] (6) is 2 (Line 1)
#The GCD of arr[X-1] (6) and arr[Y-1] (6) is 6 (Line 2)

cobalt forum
#

pls see

#

if y'all could help

sand kiln
#

do anyone knows what go to spaces?

fierce mantle
#

what does that comment say?

willow meteor
#

hi all; what's the best way of storing info in this format, but if i want to be able to search efficiently with both the name or detail?

#

sorry for my quick whiteboard sketch

#

should i make 2 copies of the json, 1 for name and other for detail?

#

1 name can have multiple details and 1 detail can have multiple names

glossy breach
#

If the resulting array does not fit the criterias then it's probably impossible 🤔

trim fiber
#

What you did and what is the problem?

rancid patio
#

has anyone seen this problem before
Consider an array, a, of n distinct positive integers where the elements are sorted in ascending order. We want to find all the subsequences of a consisting of exactly m elements. For example, given array a = [1, 2, 3, 4], the subsequences consisting of m = 3 elements are {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, and {2, 3, 4}. Once we have all of the m-element subsequences, we find the value of globalMaximum using the following pseudocode

#
for each subsequence, s, consisting of m elements {
    currentMinimum = 1018
    for each (x, y) pair of elements in subsequence s {
        absoluteDifference = abs(x - y)
        if absoluteDifference < currentMinimum {
            currentMinimum = absoluteDifference
        }
    }
    
    if currentMinimum > globalMaximum {
        globalMaximum = currentMinimum
    }
}```
#

i am not fully understanding the concept of global maximum

#

based on the example outputs provided

idle ferry
halcyon plankBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.

trim fiber
rancid patio
#

which is what i believed, not sure why this is the result though

After the iteration on subsequence {1, 2, 3}, the value of globalMaximum is 1.
After the iteration on subsequence {1, 2, 4}, the value of globalMaximum is 1.
After the iteration on subsequence {1, 3, 4}, the value of globalMaximum is 1.
After the iteration on subsequence {2, 3, 4}, the value of globalMaximum is 1.
Thus, the function returns 1 as the answer.```
trim fiber
#

Oh, I am wrong

#

We are calculating currentMinimum so globalMaximum is the biggest of the smallest absolute difference between two elements

rancid patio
#
The subsequences of array a = [1, 2, 3, 4] consisting of m = 2 elements are {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, and {3, 4}.
After the iteration on the subsequence {1, 2}, the value of globalMaximum is 1.
After the iteration on the subsequence {1, 3}, the value of globalMaximum is 2.
After the iteration on the subsequence {1, 4}, the value of globalMaximum is 3.
After the iteration on the subsequence {2, 3}, the value of globalMaximum is 3.
After the iteration on the subsequence {2, 4}, the value of globalMaximum is 3.
After the iteration on the subsequence {3, 4}, the value of globalMaximum is 3.
Thus, the function returns 3 as the answer.```
#

here is another example

#

last one

The subsequences of array a = [1, 2, 4, 5, 8] consisting of m = 3 elements are {1, 2, 4}, {1, 2, 5}, {1, 2, 8}, {1, 4, 5}, {1, 4, 8}, {1, 5, 8}, {2, 4, 5}, {2, 4, 8}, {2, 5, 8}, and {4, 5, 8}.
After the iteration on the subsequence {1, 2, 4}, the value of globalMaximum is 1.
After the iteration on the subsequence {1, 2, 5}, the value of globalMaximum is 1.
After the iteration on the subsequence {1, 2, 8}, the value of globalMaximum is 1.
After the iteration on the subsequence {1, 4, 5}, the value of globalMaximum is 1.
After the iteration on the subsequence {1, 4, 8}, the value of globalMaximum is 3.
After the iteration on the subsequence {1, 5, 8}, the value of globalMaximum is 3.
After the iteration on the subsequence {2, 4, 5}, the value of globalMaximum is 3.
After the iteration on the subsequence {2, 4, 8}, the value of globalMaximum is 3.
After the iteration on the subsequence {2, 5, 8}, the value of globalMaximum is 3.
After the iteration on the subsequence {4, 5, 8}, the value of globalMaximum is 3.
Thus, the function returns 3 as the answer.```
trim fiber
rancid patio
#

sub sequence as in (1,2), (2,3) -> (1,2,3)?

trim fiber
night pewter
#

hi y'all. I'm in search of deeper knowledge. by accident I wrote a condition which gets really good results, but it's obviously bogus, so I want understand what it actaully does. I know when accessing a panda dataframe viadataframe.loc[] "Logical Operators in Pandas are &, | and ~, and parentheses (...) " are important. And that you are actually generating a series which then gets used as an index.
This is the code I'm talking about:

        dataframe.loc[
            (
                (dataframe['ha_marubozu']) &
                (dataframe['smooth_ha_green']) & 
                (False) &  # WHAT DOES THIS DO?
                (dataframe['smooth_ha_green'].shift(2) != True) | 
                (dataframe['smooth_ha_green'].shift(3) != True) &                 
                (dataframe['volume'] > 0)  
            ),
            'buy'] = 1

Does (False) & just flip a column (before or after?). If I delete (False) & I actually get different results

rancid patio
#

@trim fiber thanks for the help

trim fiber
night pewter
night pewter
#

Ok, to answer my own question. Basically what it does, it negates everything that comes before (False) &. It' like I just deleted:

    (dataframe['ha_marubozu']) &
    (dataframe['smooth_ha_green']) & 
rancid patio
#

@trim fiber in example 2, are we comparing the differences between ([1,2) and (2,4) and since 2-1 < 4-2 the global maximum is 1

#

then do that for each ele

trim fiber
#

About which one are you talking?

rancid patio
#

yes that was the one i was referring to

#

really any example

trim fiber
# rancid patio really any example

Before first iteration we have globalMaximum = 0.
Then from subsequence {1, 2, 4} we get localMinimum = 1 then localMinimum > globalMaximum so globalMaximum = 1
Later next sequences {1, 2, 5}, {1, 2, 8} and {1, 4, 5} gives us localMinimum = 1 so we don't update globalMaximum.
In each other sequences we get:

  • {1, 4, 8} gives 3 because 4 - 1 is less than 8 - 4 so globalMaximum is now 3;
  • {1, 5, 8} gives 3 too;
  • {2, 4, 5} gives 1 but 1 is less than current globalMaximum;
  • {2, 4, 8} gives 1 too;
  • {2, 5, 8} gives 3 so don't update because it's equal to globalMaximum;
  • {4, 5, 8} gives 1 again.
rancid patio
#

@trim fiber thanks so much

rancid patio
#

last question @trim fiber why does - {2, 4, 5} gives 1 but 1 is less than current globalMaximum; give 1, looking at the example it is returning After the iteration on the subsequence {2, 4, 5}, the value of globalMaximum is 3

fiery cosmos
#

help idk whats wrong with my while loop

#

while phcid == True do:

#

phcid is a var

#

boolean

vocal gorge
#

do is wrong.

fiery cosmos
#

OH

#

sorry i forgot its not lua...

vocal gorge
#

Also, it'd fit more in a help channel or general 🙂

fiery cosmos
#

okay

#

where can i share my code?

vocal gorge
#

in a help channel, ideally

#

!paste if it's big

halcyon plankBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

fiery cosmos
#

okay

vocal gorge
fiery cosmos
#

thank you

drowsy minnow
#

Does anyone have experience with Trie's? Attempting to convert this kinda brute force method into a trie instead. I was told it would be more efficient but I'm having a hard time understanding the concept entirely. If you get what I'm talking about, let me know and I'll show ya the whole algo question.

#
def removeDuplicates(str):
    return "".join(set(str))
def numKeypadSolutions(wordlist,keypads):
    a=[]
    for x in wordlist:
        x=removeDuplicates(x)
    for x in keypads:
        flag=True
        count=0
        for y in wordlist:
            if(x[0] not in y):
                continue
            for z in y:
                if(z not in x):
                    flag=False
                    break
            if(flag):
                count+=1
        a.append(count)
    return a
  
wordlist=['APPLE','PLEAS','PLEASE']
keypads=['AELWXYZ','AELPXYZ','AELPSXY','SAELPRT','XAEBKSY']
a=numKeypadSolutions(wordlist,keypads)
print(a)
keen hearth
#

Hey @small sage Do you still need help with your problem? Just reading up on that algorithm.

small sage
#

yes

#

i do

#

can u?

#

@keen hearth

#

I need help with Union Find

keen hearth
#

Alright 😄

#

So, it's the algorithm to union two sets in a disjoint set data structure that you need help with?

glossy breach
#

What's your problem with Union Find?

oblique echo
#

Hello algorithms experts, I have 2 questions about the following algorithm. What is the specific type of algorithm used in the sort() method, and how can I tell the complexity in Big O notation?

class Algorithm:
    """
    A class to represent an algorithm.

    ...
    Attributes
    ----------
    
    Methods
    -------
    sort()
        outputs a sorted list of integers

    """

    def sort(self, data, length): #(data, n):
        """ Outputs a sorted list of integers
        Parameters
        ----------
        data : list
            a collection of integers as a list

        length : integer
            an integer value representing the len() of the data list
        """
        
        if length == 1:
            print(data)
            return
        
        for i in range(length):
            self.sort(data, length - 1)
            if length % 2 == 0:
                data[i], data[length - 1] = data[length - 1], data[i]
            else:
                data[0], data[length - 1] = data[length - 1], data[0]
agile sundial
#

that sounds like a test question?

oblique echo
#

The test was to use it (it swaps numbers around so 1 2 becomes 2 1) and say what the Big O is. I just want to know what it is and how to even try to find the Big O

#

Just looking for some general guidance, not an answer

agile sundial
#

is it a test question?

oblique echo
#

It's part of a homework assignment to say what the complexity is in Big O.

agile sundial
#

ok, what do you think it is

oblique echo
#

It seems like quadratic time because it takes really long to run when I put in a lot of inputs

agile sundial
#

why isn't it cubic then

oblique echo
#

good point

#

can it have 2? because it would be constant if length was 1

agile sundial
#

it can't have two time complexities

#

and time complexity is based on how it changes, so it's not just about when the length is 1

oblique echo
#

understood, thank you

dreamy arrow
#

time complexity here you have (n) iterations for the first loop then for each time in that n you have to call the recursion which decrease size by 1 each time so it will call itself n times as well until it reaches the base case at length =1
so Time Complexity = n*n *(Condition)
Condition = O(1) Because its assignment

#

nn1 = n^2

#

nn1

#

nn1=n^2

vocal gorge
severe geyser
#

Funny thing, i'm also learning about the BigO notation atm

vocal gorge
#

This recurrent equation is solved by approximately n!. So factorial complexity, if I didn't mess anything up.

#

way higher than O(n^2). @dreamy arrow

severe geyser
#

alright

vocal gorge
#

here's a plot of computation time vs the list's length

#

Same plot with logarithmic y axis. As you can see, time appears to be exponential with the list's length, but you can also see a slight curve upwards compared to the straight line approximation (orange line) - factorial complexity indeed.

fast timber
#

j

noble leaf
#

can I plz get help i dont understand this question based on the essay Look Away by Siri Hustvedt?
Hustvedt recounts a story about her daughter, Sophie’s, experience on the subway and the way in which a fellow passenger ‘broke the code’ of the “pretend-it-isn’t-happening law.” In doing so, Hustvedt argues, the man gave Sophie “a feeling of ordinary human solidarity.” Explain what she means by this and why she feels it’s so important.

vocal gorge
#

...how is that related to algorithms and data structures, or even programming at all?

agile sundial
#

use gpt3, duh @vocal gorge

vocal gorge
agile sundial
#

that's still an algorithm though

rancid patio
#

is there a way to dynamically use the len of a tuple to use in a for loop

#

for example if the length of the tuple == 2 then -> for x,y in tuple: and if the tuple len==3 then -> for x,y,z in tuple"

agile sundial
#

wait for pattern matching in 3.10 i guess lol

proven creek
#
# sum_integers_args.py
def my_sum(*args):
    result = 0
    # Iterating over the Python args tuple
    for x in args:
        result += x
    return result

print(my_sum(1, 2, 3))
agile sundial
#

i don't see how that's useful here

proven creek
#

then i'm probably misunderstanding something

#

lol

rancid patio
#

this is what im doing

#
n = 2
x =list(combinations( [1,2,3,4], n))
gloabl = 0
local_min = 0
n = 2
for a, b in x:
    lm = findMinDiff((a,b),n)
    if lm > local_min:
        local_min= lm
local_min```
#

so n will obviously change, up the the length of the list

proven creek
#

mhm, and if you have a helper function which takes *args

#

you can deal with the varying amount of iterables

#

@agile sundial making me feel crazy but i'm pretty sure i'm making sense

lean dome
#

I think you are, too.

proven creek
proven creek
lean dome
#

But that's overcomplicating it, I think

proven creek
#

ah, fair enough

rancid patio
#
    # Initialize difference as infinite 
    diff = 10**20
      
    # Find the min diff by comparing difference 
    # of all possible pairs in given array 
    for i in range(n-1): 
        for j in range(i+1,n): 
            if abs(arr[i]-arr[j]) < diff: 
                diff = abs(arr[i] - arr[j]) 
  
    # Return min diff 
    return diff```
lean dome
#

You can just do:

for t in x:
    lm = findMinDiff(t, n)
    ...
agile sundial
#

yeah, ^