#algos-and-data-structs

1 messages · Page 81 of 1

obtuse jungle
#

ye

split obsidian
#

is there an easy / intuitive way to learn ds/algo? I have a vague understanding of how they work, but probably couldn't code from scratch in an interview. i.e. I can use heapq, but don't know how to efficiently implement heapq. Or even linked lists tbh. When in python do you actually use a linked list?

obtuse jungle
#

also sometimes the interview is about your thinking process and not about your a structure knowledge, so when it turns out you actually remember how to do stuff, they just skip past it

#

ah well, linked lists first - very rarely

#

actually im not sure python needs linked lists

split obsidian
#

If you care about efficiency, doesn't the generator expression give you the same thing for memory/cpu?

obtuse jungle
#

let's take a looksee at ye olde timecomplexity site...

split obsidian
#

but it shows up in interview q, so I think I have to learn it anyways

obtuse jungle
#

oh yeah okay

#

python linked lists

#

when you want to split and merge really big lists

#

a lot

#

since in python concatenating lists requires a new list

#

being copied from the two other ones

#

that being said

#

generally speaking python can be kinda wacky with coding interview questions

#

if you ignore the python part and just say generally when you would use a linked list

#

then you have some more applications

#

but most of those applications are very specific

split obsidian
#

is there an easy / intuitive resource for learning ds/algo and their implementations?

obtuse jungle
#

i guess a programming book/textbook(?)

#

depending on definitions and personal opinions on ease and intuition

#

i mostly learned this stuff in my algos class i guess, but i'm not sure how helpful that might be

split obsidian
#

any recommendations?

obtuse jungle
#

you want something specific tailored towards coding interviews or like

#

a general textbook

split obsidian
#

mostly 1, but maybe 2 for reference material

obtuse jungle
#

cracking the coding interview is pretty popular i think?

#

though you might want to ask around

#

i havent read any so i dont have much of an opinion

split obsidian
#

ok, thanks

amber loom
#

i found that it helps a lot

fiery cosmos
#

does anyone have experience with WSL, does it use window's low level system calls

#

rather than linux's

#

I think WSL 1 uses a transition layer, but WSL 2 ships with a linux kernel

fiery cosmos
#

it's amazing

#

but very limiting

fiery cosmos
#

what is cs mainly about??

jovial creek
#

hey can someone explain why I am getting two different results?

test = list(board[box_num][space_num])
hold = board[box_num][space_num].pop()
backup.append(dict(board))
test2 = list(board[box_num][space_num])
backup[len(backup)-1][box_num][space_num] = list(board[box_num][space_num])
board[box_num][space_num] = []
board[box_num][space_num].append(hold)
print("CHOOSING : {} / {} / {} - {} FROM {}.{}".format(hold,test,test2,backup[len(backup)-1][box_num][space_num],box_num,space_num))

The output that I am getting is
CHOOSING : 7 / [2, 7] / [2] - [7] FROM 1.6
but it should say
CHOOSING : 7 / [2, 7] / [2] - [2] FROM 1.6

since backup[len(backup)-1][box_num][space_num] is assigned the same thing test2 is

#

im not sure why python is making a pointer to the variable, and how can I break that

#

even when setting
backup[len(backup)-1][box_num][space_num] = test2, it still gives the wrong output

#

please feel free to ping me, Ill be free all day!

jovial creek
#

Okay, so I fixed the problem, and i'm not happy with the solution that I had and was wondering if theres a better way. My solution was I assumed that since there is a lot of nesting of arrays inside of arrays that somewhere it was just making one a pointer so I would "manually" append the board into the backup by going through a nested for loop. This works really; however, I don't like the solution and believe that there is a far simpler one that I am missing. If anyone knows of one, please let me know! The code is finished, and its a simple sudoku solver, for solving more advance boards I decided to go about a deep first search method (because I hate breath first search algorithms with python, and doing the Big O math it was quicker to use a deep first due to how the board will fill out), which is why I needed a backup board

jovial creek
#

small video of it in action*

amber loom
#

@jovial creek try python's builtin list.copy() method?

jovial creek
#

well the structure is a dictionary with a number key and a dictionary value, and inside that dictionary is a number key with a list value. I think due to the nesting it was making a pointer to the second dictionary

#

Backup[Board{# : Box{# : Guess[#]}}] was the structor I wanted

#

@amber loom

#

i know the structor is weird but it makes all the checks worlds easier cause everything can be in terms of 3's and from there is just modules and divisions to group everything

amber loom
#

personally, i would use a 9x9 nested array

#

and use modulo to access

jovial creek
#

true, and most logic could be used in the same way it was, I just like dictionaries for some reason I've come to learn

#

idk it mentally helps me keep up even though I just use the key as a place holder for the index

amber loom
#

what algorithm are you using to solve it

#

backtracking?

jovial creek
#
def row_check(board,box_num,space_num):
    if len(board[box_num][space_num]) == 1:
        return board[box_num][space_num]
    
    box_row = int(box_num / 3) * 3
    guess_space = int(space_num / 3) * 3
    my_list = list(board[box_num][space_num])
    
    for i in range(3):
        for x in range(3):
            guess = board[box_row+i][guess_space+x]
            if (len(guess) == 1) and (guess[0] in my_list):
                my_list.remove(guess[0])
                
    return my_list

theres 4 others, and when I post it on my git after I comment it all i can ping ya a link, but the idea is just this

#

it could work with a nested arrays since I practically treated my dict like an array in this case

main vortex
#

Anyone knows any algorithm that calculates the link relevance of each vertex of a tripartite graph?

tiny anchor
#

Hi, I'm a relatively new programmer and I wanted your guys' thoughts on this little coin flipping game I made: from random import randint
#coin flip
heads = 0
tails = 0
total = heads + tails
while True:
coin = input('To flip a coin, enter in an amount of times to flip it: ')
coin = int(coin)
#looping through all values of coin
while coin > 0:
coin = coin - 1
for n in range(1):
value = randint(1,2)
print(value)
if value == 1:
heads = heads + 1
if value == 2:
tails = tails + 1
total = heads + tails
req = input('Type done to end or any other key to continue: ')
if req == 'done':
print('wrapping up...')
break
else:
print("Heads: ", heads, "Tails: ", tails, "Total: ", total)
continue
print("Heads: ", heads, "Tails: ", tails, "Total: ", total)
if heads > tails:
print("Heads is more likely to happen.")
print('Heads won for', float(heads/(heads + tails)*100),'% of the time.')
elif tails > heads:
print('Tails is more likely to happen.')
print('Tails won for', float(tails/(heads + tails)*100),'% of the time.')
else:
print('Both are equal.')

amber loom
#

@tiny anchor very nice, but you can make your code a little bit more consise.

#

for example for the flips, you can do this:

#
  r = randint(1,2)
  if r == 1:
    heads += 1
  else:
    tails += 1```
#

and instead of counting the total each time, you can do it at the end of the program.

#

also, in the future, you can wrap your code in a codeblock with ``` around it

fiery cosmos
#

Hello

jovial creek
#

@tiny anchor you’re doing good, just know that For value in range(1): is the same as not having a for loop also for making a string it’s a popular practice to use the format method which would look something like this : print ( “Heads won for {}/{} = {}%”.format( heads, total, 100*heads/total))

jovial creek
amber loom
#

nice

obtuse jungle
#

@jovial creek this is just a broad suggestion if you're interested in alternative means of sudoku solvers

#

but you could look into storing a lookup table from (index) to (relevant_other_indexes)

#

and simply precomputing that at some point

jovial creek
#

@obtuse jungle I like the feedback, just a little confused. To my understanding the only way to lower the big O notation would be to make the for loop have a terminating condition instead of a fixed end

#

could you provide an example please, id love to use your method too!

tiny anchor
#

@jovial creek thanks for the feedback :)

#

also does anyone have an idea as to how i can make th process of flipping a coin faster if the user enters in a large request?

jovial creek
#

@tiny anchor

for i in range(input_number_from_user):
  heads = heads+1 if (random.randint(0,1) == 1) else heads
tails = input_number_from_user - heads
#

something like this would be what to look into the key thing limit the amount of variables that you use, but with your big O notation being just O, I wouldn't worry about speed

#

one important thing to take away from the small bit of code that I wrote is that we are only changing one variable and assigning the opposite of it to tails @tiny anchor

This is an important concept because a very common mistake is people try to place varibles about when they aren't really needed. For a small project it doesnt matter but for a bigger project it does. Also note that you have to define above heads as 0 and still get an input, that code is just for your flipping process

#

But yeah, always try to keep it simple!

obtuse jungle
#

@jovial creek ah, right

#

i'm not really referring to like, runtime speedups

#

since sudoku solvers technically all run in constant time

#

since board size is constant

#

unless you measure board complexity, which is a little bit more of a tricky thing

tiny anchor
#

@jovial creek alright I'll post an optimised result for ya asap :)

obtuse jungle
#

i was referring more to uh, code simplicity

#

and

#

@tiny anchor you could look into getrandbits

#

which is blisteringly fast in the specific use case of (powers of 2), aka exactly useful for a seires of boolean values

#

and @jovial creek that being said, a lookup table will probably let you squeeze out some performance improvements

#

even if they would be dominated by other things in the case of an arbitrary sudoku-esque problem size

jovial creek
#

Ooooooh so you’re saying that if there was a board it previously solved that matched to just paste that?

obtuse jungle
#

hm

#

i wonder if it would work if i put in a medium-sized code snippet

#

eh ill put it in a replit just to be safe

jovial creek
#

Okay! Looking forward to it!

obtuse jungle
#

@jovial creek

#

i tried to comment gen_connecteds to make it more legible, but lmk if it's confusing

#

the lookup table is really just a nested list comprehension dressed up as a function

jovial creek
#

Ah okay yeah I see what ya mean. Idk I feel like that would take up a lot of size, but yes I do agree that would be nice

obtuse jungle
#

you'd be surprised

#

's all generators

#

and consider this

#

do you care about size?

jovial creek
#

Huh interesting

obtuse jungle
#

the total memory usage is almost negligible

#

in the worst case

jovial creek
#

Lmao, well on my 8GB computer yes haha

obtuse jungle
#

it's like, a total of 81*81 ints

#

which is like 52 kilobytes

#

i dont think you're going to hurt too much for 52 KB

#

or well like 81*81*9 maybe, 450 KB

#

even with super worst cases

#

the generators oughta negate most of that

#

with a brief check, it consumes around 266 KB of memory after the strings/python have been loaded in

#

or well, allocates

jovial creek
#

Haha I guess, hrmm idk still feel like the performance time that I’m getting with what I posted is 0-2 seconds (2 being for some of the really expert boards) and I’ll take that delay over the size! I do appreciate the feedback though!

obtuse jungle
#

ah aye, but you should check the runtime of that code

jovial creek
#

Haha I have no doubts that what you provided is faster 😄

obtuse jungle
#

0.0067s baybee

#

though with a fairly simple board

#

and general disclaimer that runtimes across systems are basically non-comparable yadda yadda

#

keep in mind that when it really boils down to it

#

python is pretty slow

#

or well, regular ol python

#

and in a problem of limited size, oftentimes the "dominated" big o factors actually are what matter

#

your constant time object accesses, control flow changes, and other forms of overhead

#

esp. things like copying lists, etc

#

or well, that's my 2 cents at least

jovial creek
#

Haha thank you a lot for your feed back, I will be looking into something like this for other projects!

obtuse jungle
#

👍

brave oxide
#

I have a question, when consider the efficiency of an algorithm is n^n have an exponential behaviour or something else?

#

because whenever I see a definition of exponential behaviour, it is say something along the line of 'constant raised to the power of an input size'

exotic hatch
#

n^n = exp(ln(n^n)) = exp^(nln(n)))

#

you may be able to hone in on a more specific complexity class but exponential isn't wrong

foggy oxide
#

Can someone do my schoolwork python coding for me it's a small amount

exotic hatch
#

lol

#

no

#

But I'm sure people would be happy to help you

foggy oxide
#

Do anybody who would ?

exotic hatch
foggy oxide
#

/help

jovial creek
#

@foggy oxide hey mate, if you cheating at coding then maybe you need to take a step back. I know most schools dont have coding as a manditory course, so try to ask yourself what made you want to code in the first place and attempt to rekindle that flame

foggy oxide
#

I dont understand it, I dont understand the type of python I'm supposed to be doing and my teacher wont help me

jovial creek
#

well whats the assignment and we can work it through in baby steps

foggy oxide
#

I'm on this website called CMU US Acedamy I'm supposed to be making a land scape with shapes and it's not working

jovial creek
#

are you using turtle?

foggy oxide
#

Idk I'm really new at this stuff can just send a picture of it?

jovial creek
#

sure drop a pic here

foggy oxide
#

Srry I have a Samsung

jovial creek
#

oh mate, you got this. You already can make a cloud and bush so just make a green box to put on the on the screen and change the background from black to blue

foggy oxide
#

no I need to make it night I just cant get the moon right

jovial creek
#

the moon looks great to me

foggy oxide
#

Yeah I think it dose to hut it has to be exactly right

fickle seal
#

If tony knows fun I choose stark

fiery cosmos
#

@foggy oxide which I could do that

#

I’ll work on learning

foggy oxide
#

@fiery cosmos wym

fiery cosmos
#

The whole design

frail valve
#

computer science --- how to define

fiery cosmos
#

Hello people, I am trying to traverse a BST using BFS.

#

I have implemented the BST with code from stackoverflow, but I need help implemented the BFS portion.

#
class Node:
    def __init__(self, val):
        self.l_child = None
        self.r_child = None
        self.data = val

def binary_insert(root, node):
    if root is None:
        root = node
    else:
        if root.data > node.data:
            if root.l_child is None:
                root.l_child = node
            else:
                binary_insert(root.l_child, node)
        else:
            if root.r_child is None:
                root.r_child = node
            else:
                binary_insert(root.r_child, node)

def complete_binary_tree(arr):
    r = Node(arr[0])
    for i in range(1,len(arr)): 
        binary_insert(r,Node(arr[i]))

complete_binary_tree([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
jovial creek
#

@fiery cosmos I can help you but to make sure you’re not script kittying I won’t write any direct code. You can see that each node is a class and we know that for a Breath First Search we want to check for the nodes that are all directly related to our current state. This means 0 checks 1 and 2, then 1 check 3 and 4, then 2 check 5 and 6 and so on and so on. So all this being said let’s just first start with a tree of 3 nodes. We check the root and then left node and right node, while don’t ya code up that and we’ll make more

frail valve
#

i had adversion to CLASS -- maybe i need to learn how to use ,, or why to use

midnight mantle
#

Hi, im doing some course work for my computer GCSE ive got a problem with my if statement in the function Screen

#

def menu():
    print("--------------------------------")
    print("[1] Enter cinema screen size")
    print("[2] Enter seating information")
    print("[3] Calculate profit")
    print("[4] Clear data")
    print("[0] Quit")
    print("--------------------------------")

def screen():
    screen.size = str(input("Enter the screen size you want to model [SM/ST/Xl]: "))
    print(screen.size)
    if screen.size == ("sm") or ("SM"):
        print("Screen size chosen: Small")
        print("Max Capacity:       120")
        print("Min Premium Seats:  10")
    elif screen.size == ("st") or ("ST"):
        print("Screen size chosen: Standard")
        print("Max Capacity:       150")
        print("Min Premium Seats:  20")
    elif screen.size == ("xl") or ("XL"):
        print("Screen size chosen: Large")
        print("Max Capacity:       200")
        print("Min Premium Seats:  30")
    else:
        print("Not an option")
    




menu()
option = int(input("Enter your choice: "))

while  option != 0:
    if option == 1:
        screen()
        pass
    elif option == 2:
        print(screen.size)
        pass
    elif option == 3:
        print("3")
        pass
    elif option == 4:
        print("4")
        pass
    else:
        print("Invalid option.")

    print()
    menu()
    option = int(input("Enter your choice: "))

print("Goodbye")```
#

when i enter xl it outputs the code for small

#

and the same for standard

topaz pulsar
#

when using an if statement like this screen.size == ("sm") or ("SM") it evaluatse each side seperately, if will evaluesate what is on the left of the or and then what is on tthe right before comparing those boolean values @midnight mantle

midnight mantle
#

i don't complely follow

topaz pulsar
#

so as python evaluates an expression, python if my_value == x or y is done in these stages my_value == x (boolean result), or y so if the value of y in this example is tre then the condition will always be True

#
>>> value = 0
>>> if value == 0 or 1:
    print(f"Always runs")
else:
    print("Unreachable code")

    
Always runs
>>> value = 2
>>> if value == 0 or 1:
    print(f"Always runs")
else:
    print("Unreachable code")

    
Always runs```
midnight mantle
#

so how would i fix this

topaz pulsar
#

I can't give an exact answer because its GCSE work but you need to find another way of comparing the input to the desired values

midnight mantle
#

ok thanks for the help

humble lichen
#

Does anyone know a good algorithm to go through a maze with a person (you can only move to adjacent cells to find out what is there) and locate all the unknown barriers?

#

So a way to find out where all the crosses are in this maze when "walking" through it

spring mirage
#

if you want to expore a maze there are several usefull algorithms such as tremaux's algorithm

#

i didnt quite get your question tho. so if you want to find a path i'd suggest a* algorithm or Dijkstra's algorithm

fiery cosmos
#

You could use greedy dfs

#

If u know where the ending spot is

tardy venture
#

where can i ask linux related python questions

jovial creek
#

DFS would be the easiest to code but BFS I think would be the better algorithm

gusty grove
#

Hm? They are pretty much the same right?

finite summit
#

Hey, does anybody know a good computer science course for beginners?

jovial creek
#

@finite summit SoloLearn

finite summit
#

@jovial creek Thanks'.

jovial creek
#

Np

clever stratus
#

Hi all, I am wondering if anyone can answer htis question. If I pass an object into a function, does python use the existing object or does it create a copy of that object and I have to return it? Does this question make sense?

mint jewel
#

Python never implicitly copies. It will be the same object, so any changes you make on it will persist. Do note that redirecting the argument name does not change the source name, as no objects are changed. So

def f(a):
   a = 4
   return a
b = 6
print(b)
print(f(b))
print (b)

prints
6
4
6

clever stratus
#

Thanks lakmatiol, you explained that perfectly - I understand now. You're the best!

brave oxide
#

I am having trouble understanding selection sort algorithm, anyone can help?

#

Just a step of it

#

How can you know what is the smallest number

#

?

past flare
#
def encrypt(n, key):
    if not isinstance(n, int):
        raise TypeError("The value to encrypt must be an integer")

    DELTA = 0xff ^ key
    cipher = n ^ key
    cipher += DELTA

    cipher = ((cipher-1)*cipher) // 2

    return cipher

def decrypt(v, key):
    if not isinstance(v, int):
        raise TypeError("The value to decrypt must be an integer")

    DELTA = 0xff ^ key

    v = (2*v) // v-1
    v -= DELTA
    v ^= key

    return v
#

could someone say what's wrong with the decrypt function?

#

@brave oxide you want to sort a list of numbers?

brave oxide
#

@past flare Yes I do,but with insertion algorithm

past flare
#

okay

brave oxide
#

I know how insertion works, but what I don't understand is the step where you determine what is the smallest number

mint jewel
#

Selection or insertion sort?

past flare
#
def order(array):
    sort_array = []
    while array:
        minimum = array[0]
        for num in array:
            if num < minimum:
                minimum = num
        sort_array.append(num)
        array.remove(num)

    array = sort_array
    
    return array
#

@brave oxide

#

So we took the first number of the array in a variable called minimum, and then we start a for loop, if a number is smaller than the minimum, then this number will become the minimum

brave oxide
#

@mint jewel aren't they the same?

mint jewel
#

No

past flare
#

isn't that what you needed ?

mint jewel
#

Selection sort goes through the unsorted part, keeping track of the index and value of the minimum, then moves it to the end of the sorted part

#

Insertion sort searches backwards through the sorted part, placing the first unsorted element into it such that it remains sorted

brave oxide
#

@past flare So take a number and compare it with every number in the list if we found a smaller number we set that to the minimum

past flare
#

yup exactly

brave oxide
#

@mint jewel I see

#

Thank you @mint jewel @past flare for helping me

lavish prawn
#

@everyone anybody know how i can write html in a python file?

mint jewel
#

pyxl, though generally you use a templating engine

#

also, pinging everyone is generally bad form

lavish prawn
#

what do you mean @mint jewel

tepid vessel
#

Hey! So I'm stuck on my hw assignment, and I was wondering if anybody would be able to help me with it?

Now we can write a function lap(edges) to compute the Laplacian matrix of the graph specified by edges. We can assume the graph is connected and there are no isolated edges, so all of the node indices appear at least once in the edge list and there are no indices missing between zero and the highest node index.

Theres a little bit more background though. I would have to upload the PDF

#

its in python btw

#

or I could upload the jupyter notebook file

exotic hatch
#

Sure ill take a look

tardy venture
#

if i use external lib in python to make a program and make a exe using pyinstaller will the exe work on a system that doesnt has python installed

mint jewel
#

With pyinstaller yes afaik

tardy venture
#

it has smtplib

rugged quartz
#

how do I calculate the space complexity of a program?

#

ping me when you answer

quasi oracle
#

@rugged quartz that's a really general question, but it depends on what resources you're using in the program. If for example you have a list with a length linearly dependent on the size of your input n, then your program requires at least O(n) space

rugged quartz
#

what about o(n*2)?

quasi oracle
#

You mean O(n^2)?

rugged quartz
#

yes

quasi oracle
#

If you have n numbers, and you make a list of n lists, with n numbers each, you would get an n^2 matrix of numbers

#

So it would take O(n^2) space

fiery cosmos
#

has anyone connected to sql developer using cx oracle/ oracle instant client from python?

rugged quartz
#

@quasi oracle thank you 🙂

jovial creek
#

@fiery cosmos like in terms of just editing a .db file? Cause python has an SQLite3 lib that works wonders

fiery cosmos
#

does that use the oracle client? @jovial creek

jovial creek
#

I don’t believe so, but what’s the goal?

fiery cosmos
#

i need to connect to an oracle database that has 16 million rows so that i can build data science models

#

i cant export more than 1million rows to a csv

#

do you have advice?

jovial creek
#

Oh yikes, hrmmmmm... honestly I’d recommend webscrapping it as a all else fails solution. Websrape and make it into a CSV

fiery cosmos
#

i just need to extract the data from the sql query into python for pandas

#

would sql lite not work?

jovial creek
#

Idk if you can connect to a file that isn’t local

fiery cosmos
#

i'll look it up . thanks. oracle instant client lets you connect to a file but im having installation trouble with that

jovial creek
#

Ah yeah oracle I’m never to happy with using PandaSweat sorry I couldn’t get ya a better answer

fiery cosmos
#

wait doesnt sqllite work for oracle?

#

nvm lmao

#

damn

wild bronze
#

you should never send a kill signal always first terminate the app to allow it a chance to cleanup does it apply to programs that aren't handling any signals?

#

"hello world" program for example

lean dome
#

no; if the program doesn't handle signals then both SIGTERM and SIGKILL will kill it. You should always prefer to send SIGTERM first though because it's the correct thing to do regardless of the program's implementation details.

#

the difference between them is that SIGTERM allows the program to clean up and SIGKILL doesn't. Getting into the habit of sending the "exit immediately without cleanup" signal without first trying the "cleanup and then exit" signal is only going to bite you by having you eventually kill a program that leaves a lock file on disk, or that fails to commit to a database or flush its files and so loses your most recent work, etc

wild bronze
#

if a string gets stored in a buffer to get flushed and the app goes into infinite loop. Is the program expected to flush before exiting when it receives a SIGTERM(without any signal handling)

#

or abort immediately

lean dome
#

if the program receives a SIGTERM and doesn't have a SIGTERM handler, the default action is to die immediately, assuming we're talking about Unix. So, buffers won't be flushed.

wild bronze
#

okay I got it

#

thank you

lean dome
fiery cosmos
#

I wasn't really sure where I could ask for help, so I figured this channel might be most relevant to my issue.

I uploaded a project to my github using VSCode, but I accidently uploaded it to the wrong branch and I have no idea how to fix it.

https://github.com/tscheer100/Spam-Sec-Check
vs
https://github.com/tscheer100/Spam-Sec-Check/tree/orrigin

#

btw I also misspelled origin.

lean dome
#

I know how to fix that from the command line, but I don't know how to fix it from VS Code.

fiery cosmos
#

@lean dome well VSCode uses powershell

lean dome
#

is the name of the branch in your local repos origin, and you just pushed it to the wrong name?

#

wait, no - is the name of the branch in your local repo master, and you incorrectly pushed it to orgin as orrigin ?

#

basically, what does

git branch
git remote -v

show

fiery cosmos
lean dome
#

you did 0v instead of -v

fiery cosmos
#

derp

#

as you can tell, I have no idea how to use git.,

lean dome
#

OK - and how about

git diff --name-only master orrigin
fiery cosmos
lean dome
#

ok. then let's just:

git branch -d orrigin
git push origin :orrigin
git push
#

those 3 commands should delete your local orrigin branch, delete the orrigin branch from github, and push your master branch (the branch you're currently on) to github. Let me know if any of them fail.

fiery cosmos
lean dome
#

you didn't run my last command at all there.
git push

fiery cosmos
#

mmm hold up let me try again

lean dome
#

run that, then:

git push --set-upstream origin master
fiery cosmos
lean dome
#

ok. thought that might happen. Last one:
git push --set-upstream origin master -f

fiery cosmos
#

thank you so much. i'll be sure to watch a video on git tutorial

#

you were a lot of help.

lean dome
#

👍

whole siren
#

i am trying to test my AI model and i have an error

#
import numpy as np

model = tf.keras.models.load_model('trained_model')
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()




prediction = model.predict(x_test)
np.set_printoptions(surpress=True)

print(y_test[0])
print(prediction[0])
#

AttributeError: '_UserObject' object has no attribute 'add_slot'

#

anyone has any idea? this is my first AI project, it just predicts a written number

fiery cosmos
#

hey guys im really new to python can anybody help me out?

lean dome
#

!resources

halcyon plankBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

lean dome
#

@fiery cosmos ^

fiery cosmos
#

thanks man

fiery cosmos
lean dome
#

what's in the git log, @fiery cosmos ?

fiery cosmos
#
error: 'full/' does not have a commit checked out
fatal: adding files failed
> git ls-files --stage -- C:\Users\Turtle\OneDrive\Documents\VSCodeProjects\email_clog\spam.py
> git cat-file -s 63b8f33341fc8770df5a48bbb63020f7ac6fe38a
> git show :spam.py
> git status -z -u
> git symbolic-ref --short HEAD
> git rev-parse master
> git rev-parse --symbolic-full-name master@{u}
> git rev-list --left-right master...refs/remotes/origin/master
> git for-each-ref --format %(refname) %(objectname) --sort -committerdate
> git remote --verbose
> git config --get commit.template
> git add -A -- .
error: 'full/' does not have a commit checked out
fatal: adding files failed
> git add -A -- .
error: 'full/' does not have a commit checked out
fatal: adding files failed
#

I don't ever remember even adding "full"

lean dome
#

I have no idea what that is...

fiery cosmos
#

thats the log.

lean dome
#

yeah, I mean - I have no idea what that error message might mean.

fiery cosmos
#

I think what happened was

#

I tried to do a "full" commit but literally wrote the word full somewhere and f'd everyhing up

lean dome
#

is there a full/ directory in the repo?

fiery cosmos
#

I'm going to be honest I have no idea.

#

oop. yes.

#

so should I just manually delete it?

#

@lean dome I guess I can just delete it.. hopefully I don't f things up some more

#

that worked. thank you again

fiery cosmos
#

Guys can you help me with a thing

#

How do i make an operating system withpython?

#

I mean using pythkn

#

Python

stark bridge
#

How do i make an operating system withpython?
@fiery cosmos you can't.

fiery cosmos
#

Y not

#

Then what steps to be followed?

mortal musk
#

You probably can make OS with any programming language, but why?

stable pecan
#

there's a python-based os already

jovial creek
#

@fiery cosmos when you say OS, do you actually mean an OS like Ubuntu, Windows, Macintosh? Or are you trying to make a shell, which is the kernel mode of the OS

#

Cause that’s are 2 really big difference and I see them get misused a lot by newer programmers

stark bridge
#

a shell is not "the kernel mode of the OS".

#

but you're right, there is a big difference between a shell and an operating system.

fiery cosmos
#

Im assuming were making a list that contains ints

stable pecan
#

nums.sort()

fiery cosmos
#

and what does -> mean?

quasi oracle
#

That's the return type of the function

#

It returns an integer

#

In Java it would be public int singleNumber(...

fiery cosmos
#

I have a crew of 5 programmers so we decided to make a light os like android but in bash

#

What would be our steps to be taken?

marble tree
fossil elk
#

!rule 5

halcyon plankBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious/inappropriate or be for graded coursework/exams.

fiery cosmos
#

hey everyone, im working on my computer science project. its a website for helping primary school students learn maths. im at a road block on my server for it. can anybody help? the server is in python

frigid quail
#

go ahead and ask your problem so someone could take a look and see

fiery cosmos
#

its not a problem like my code doesnt work or something im just not sure how to go about making the next section of my project

#

i have a database with all teacher and user accounts

#

i need to store also classrooms but im not sure how

#

should i make a new db file with the classrooms? if so how do i link it with the first dbfile

exotic hatch
#

Just add a new table to that database which consists of 2 columns, a primary key from teachers and a primary key from students

#

Maybe a third column if you want to give classroom some sort of pseudokey unique identifier

nocturne linden
#

there's a python-based os already
@stable pecan really? can u link it

#

I have a crew of 5 programmers so we decided to make a light os like android but in bash
@fiery cosmos that sounds even harder than a python-based os

#

Are you sure you know what you're doing?

#

Writing a full OS with an HWE will be quite difficult, especially for relatively unexperienced programmers

#

should i make a new db file with the classrooms? if so how do i link it with the first dbfile
@fiery cosmos what database are you using?

#

Is it a relational database?

fiery cosmos
#

Im using json

nocturne linden
#

ah ok

#

as a side note, I would recommend looking into MongoDB in the future

fiery cosmos
#

Okay

nocturne linden
#

or any other NoSQL database

fiery cosmos
#

Thanks

nocturne linden
#

ok so can u share your json structure?

fiery cosmos
#

Yeah but sorry im away from my laptop right now

#

Im on my phone

nocturne linden
#

ok, post it here and ping me

#

I most likely won't be able to help but somebody else likely will

fiery cosmos
#

When i can i will do, thanks alot

nocturne linden
#

👍

nocturne linden
#

dang

#

well it still uses the Linux kernel and HWE, but its still cool

sudden sinew
#

@tardy drift This channel (and this server) is not for dumping random reddit links, please don't do this

south slate
#

I know homework questions aren't allowed but I really can't solve this^^

#

I came at the conclusion that big O efficiency of the code is O(n^2) because the outer loop will execute n times and in worst case the inner while loop should execute (n-1)/2 times

#

But I don't know for sure.

last blaze
#

I think it might be n log n. The inner loop is doubling each time

summer reef
#

Well, to me, the relevant parts of the script are :

For I (n -> 0) :
  While 1 :
    c *= 2 # c=2p+1 but later, p=c
    if (c >= I) :
      break
    if (arbitrary) :
      break

In all cases, the outer (for) loop runs O(n) times.
In the best case, the inner (while) loop runs O(1) time (thanks to the if (arbitrary), A being arbitrary), so the whole algorithm is O(n).
In the worst case, the second if doesn't help, we have to rely on the first one to break the loop. As I=O(n), we have to run O(lb(n)) times to get big enough, so the overall complexity is O(nlog(n)).

(I'm a student as well, so I'm not to be trusted on this, but this is what I would have answered.)

south slate
#

I don't understand what "if(arbitrary)" means. Can you clarify?

#

Also,the last conditional can also break the loop. So should we not consider that case as well?

summer reef
#

Well, there are three "ifs" :

  • if c >= I : break (1)
  • if c !=I and A[c] < A[c+1] : c+=1 (2)
  • if x >= A[c] : break (3)
    In my shortening, I ommited the second one, because it takes O(1) to run and really changes nothing (can't break the loop)
    The first one, well, it has to do with the lb(n)
    The third one is an arbitrary condition, because it depends solely on the input (A), as x=A[i] : you're comparing A[i] and A[c], wich can be taken arbitrary, as it's an input of the algorithm : the end-user can tweak this condition at will, and so do we : in best-case complexity, we take the comparison as always true, because it helps break the loop, whereas in worst-case complexity, we take the comparison as always false, because we don't "want" the loop to be broken (searching for the worst case)
brave oxide
#

Why is Bubble sort is considered less efficient than insertion sort and selection sort, even though they have the same running time complexity?

tribal pendant
#

You'd have to look at average complexity

bronze gazelle
#

Time complexity only speaks to how the running time behaves as the number of inputs increase. Two things can have the same time complexity and have drastically different runtimes

tribal pendant
#

Also you can have the same complexity and still being x time slower, as long as x is a constant

#

Ela phrased that better

#

Afaik quicksort is the most extreme example of distortion between worst case complexity and average one

south slate
#

Well, there are three "ifs" :

  • if c >= I : break (1)
  • if c !=I and A[c] < A[c+1] : c+=1 (2)
  • if x >= A[c] : break (3)
    In my shortening, I ommited the second one, because it takes O(1) to run and really changes nothing (can't break the loop)
    The first one, well, it has to do with the lb(n)
    The third one is an arbitrary condition, because it depends solely on the input (A), as x=A[i] : you're comparing A[i] and A[c], wich can be taken arbitrary, as it's an input of the algorithm : the end-user can tweak this condition at will, and so do we : in best-case complexity, we take the comparison as always true, because it helps break the loop, whereas in worst-case complexity, we take the comparison as always false, because we don't "want" the loop to be broken (searching for the worst case)
    @summer reef got it for good. Thanks.
clever stratus
#

I have a bunch of strings with dates and times in it, is it possible to sort that info with a built in function? Or would I have to manually write a sorter

For example if I have
[('6/15/2020 2:17:32 PM'), ('6/15/2020 5:01:29 PM'),('6/15/2020 8:34:09 AM')]

I would want:
[('6/15/2020 8:34:09 AM'), ('6/15/2020 2:17:32 PM'), ('6/15/2020 5:01:29 PM')]

clever stratus
#

`import datetime
d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007']

sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))`

#

I'm having trouble understanding what "key=lambda x: datetime.datetime.strptime(x, '%m-%Y')" does. I know that key=lambda x: tells the program to iterate the array, but what exactly is the text after the : telling it to do?

frank vessel
#

Anyone here understands the theory of pushdown automatas?

lean dome
#

@frank vessel a bit rusty, but yes.

primal dock
#

` n, m = map(int, input().split())
adj = [[] for i in range(n)]

for i in range(m):
u, v = map(int, input().split())
adj[u-1].append(v)
stack = [1]
path = []

while stack or (len(path) != n):
# print(path)
visiting = stack.pop() - 1
for i in adj[visiting]:
if i not in set(path):
stack.append(i)
# check if vertex if leaf or has children that have already been visited
if len(set(adj[i-1]) & set(path)) == len(adj[i-1]) or len(adj[i-1]) == 0:
path.append(i)
# if we run into a dead end but there's still exploration left to do
if len(path) != n and len(stack) == 0:
for j in range(n):
if j+1 not in set(path):
stack.append(j+1)
break
# checking if the parent vertex has children that have already been visited
if visiting+1 not in path and len(set(adj[visiting]) & set(path)) == len(adj[visiting]):
path.append(visiting+1)
path = path[::-1]

for k in path:
print(k, end=' ') `

#

I'm trying to do a topological sort for a DAG

#

But it's too slow, so does anyone know of some optimizations that I can make

#

All vertices are integers and if a graph for example has n vertices then the vertices are numbered from 1 to n

lean dome
#

you seem to keep making new sets over and over again - seems like you should just keep sets around and reuse them instead. Moreover, if j+1 not in set(path): is strictly slower than ```
if j+1 not in path:

summer reef
#

I'm having trouble understanding what "key=lambda x: datetime.datetime.strptime(x, '%m-%Y')" does. I know that key=lambda x: tells the program to iterate the array, but what exactly is the text after the : telling it to do?
@clever stratus
sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))
When you write this, you're sorting using a custom sorting criteria (key) ; key must be (in general) a function to be called on each element of the array, and the sorting choices (i.e. is A<B ?) will be turned into is key(A)<key(B) ?.
Now, you don't seem to get lambda functions : they're just a quicker way to write functions, instead of writing def key(x) : return value, you write key = lambda x : value (you can take as many parameters as you want, of course).
So, in your example, you're sorting strings according to the date they represent (if you assume the format is correct).

jolly jewel
fiery cosmos
#

Semi colon idk

tribal pendant
#

@jolly jewel You need to split each line in two, where there is : (there is a function that does that) and then calculate the average river flow. What have you tried, and where are you stuck?

paper iron
#

Hello there, can someone help me understand why C.f(n) should upper bound T(n)?

exotic hatch
#

to test if T is O(f), pick the biggest number you can think of

#

let's say 1,000,000,000

#

and plug it in both functions

#

and if T(1,000,000,000) < f(1,000,000,000) that's a good sign T is O(f)

#

the intuition is that if one function 'grows' faster than another, no matter if at some point the slower one is higher, at some point as they grow to infinity the 'faster' growing function will always overtake the 'slower' one

#

another way

#

graph both functions and zoom way out

#

You'll see the faster growing one eventually look like a straight line up and the slower growing one will look almost like a flat line

#

if you know calculus

#

T is O(f) if the limit as n goes to infinity of T(n)/f(n) goes to zero

#

@paper iron

paper iron
#

@exotic hatch makes sense, thanks for the info!

exotic hatch
#

👍

summer reef
#

T is O(f) if the limit as n goes to infinity of T(n)/f(n) goes to zero
Aren't you mixing big-Oh and small-Oh notations ?
T is o(f) if the limit as n goes to infinity of T(n)/f(n) goes to zero
as opposed to
T is O(f) if the limit as n goes to infinity of T(n)/f(n) goes to a nonzero constant

exotic hatch
#

ya

#

technically T is o(f) implies T is O(f) and here's why ^

fiery cosmos
#

cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

#

I get this with openCV

#

`import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

img = cv2.imread('sachin.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
`

split garden
#

is there a more efficient (in time) method of telling if a dir has file/subfolder than os.listdir(d)?

#

I don't need the items just if it's not empty

torn scarab
#

from the documentation for os.listdir:

The scandir() function returns directory entries along with file attribute information, giving better performance for many common use cases.
so I would use that along with is_dir

#

!pep 471

halcyon plankBOT
#
**PEP 471 - os.scandir() function -- a better and faster directory iterator**
Status

Final

Python-Version

3.5

Created

30-May-2014

Type

Standards Track

split garden
#

I'm aware of scandir, however scandir is actually slower due to the complexity of the objects it returns

torn scarab
#

did you benchmark it?

split garden
#

sec

#

weird

#

maybe I was doing somethign wrong

#

thanks

torn scarab
#

np, sometimes if you do additional checks within scandir or listdir, the complexity of the check may be the bottleneck instead

split garden
#
import os, time
class Timer:
    def __init__(self, time_function = time.perf_counter):
        self.time_function = time_function
        self.timer_epoch = self.time_function()
        self.timers = {}

    def add(self, name: str):
        self.timers[name] = self.time_function()

    def get(self, name: str):
        return self.time_function() - self.timers[name]

    def elapsed(self):
        return self.time_function() - self.timer_epoch

    def print_difference(self, t0: int, t1: int):
        td = t1 - t0
        print(f"Took {td}")

timer = Timer()
timer.add("listdir")
os.listdir(os.path.expanduser('~'))
print("listdir", timer.get("listdir"))
timer.add("scandir")
os.scandir(os.path.expanduser('~'))
print("scandir", timer.get("scandir"))

for anyone interested

#

I'll do some more testing and see if certain folders do different things

high shore
#

lo

placid sun
#

Hello, does anybody is familiar with Hoare's logic ?

exotic hatch
#

I've done some Hoare proofs before

#

@placid sun what's the question

fiery cosmos
#

just looked up hoares logic O.O

exotic hatch
#

ping me when you get back im going on an errand run

placid sun
#

@exotic hatch I have a school exercise where I have to prove the rules of Hoare's logic

#

But the rules are based on the axiom

#

And i don't really know how to do it x (

#

after googling there is just examples using the relus

#

rules *

exotic hatch
#

Prove the rules as theorems?...

#

Seems impossible

balmy siren
#

Hey guys, anyone can share some good resources to learn Graph DS ?

foggy abyss
#

Hey guys! I'm needing some help. I'd like to do a command that works like this:

ME: .command
(Bot starts timer)
BOT: Hey there! You have 30 seconds to chose between 'a', 'b' or 'c'.
ME: .choose b
(Cancel timer)
BOT: You choose 'b'.

#

I'm aware of the use of threading, but I'm clueless how to make the second command (.choose on the example) to cancel the timer set on the first command (.command)

loud trail
#

you dont even need threading

#

asyncio is perfect for this

#

with asyncio.sleep or asyncio.wait_for(..., timeout=)

foggy abyss
#

ok! I'll give a look on that! Thx!!

fiery cosmos
#

can anyone say me how can i learn algorithms of python?

#

thanks in advance

torn scarab
fiery cosmos
#

thank you!

torn scarab
#

just in case you missed it, at the top there's also a link to a youtube channel where there are playlists covering each chapter in the text, if you're looking for visual/aural content

fiery cosmos
#

^+1 for the book @torn scarab recommended, there are also some really good language agnostic resources. when I was learning, I really liked Grokking Algorithms by Aditya Bhargava; not sure about the price as I bought the polish translation of the book. if you're willing to pay it's a really nice resource providing gentle introduction to the topic, yet it'll make your further learning a lot easier, and being honest I don't think you need any other book or course unless you are willing to do any algorithm heavy job; just get your hands dirty solving a couple of problems on sites like hackerrank or leetcode

visual mulch
#

hello sir I am a new learner of python so can you please help me learning it

#

I want to master python

fiery cosmos
#

This whole community is made to help each other at learning so of course you can feel free to ask any questions you have and I'm sure someone is going to help you

visual mulch
#

ok thank you sir

fiery cosmos
#

If you need any pointers on where to start, as far as I know there's this page:

#

!resources

halcyon plankBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

visual mulch
#

ok thank you sir

#

sir I know the basic commands such as print loops etc

fiery cosmos
#

Instead of reading books you might like to just build some stuff then. A common direction for newcomers is web development as it's fairly easy to learn and lets you build something useful pretty quick

visual mulch
#

sir I'm a 13 year old child and does'nt have any experience of python so how

fiery cosmos
#

There's a ton of stuff to learn at first but don't get overwhelmed, it's hard for everything

#

If you want to do so, I really recommend you learn Flask first, but that's just my personal opinion - it's pretty simple framework, so it lets you focus on understanding the concepts without complicating it all learning the framework-specific mechanics

#

Oh and by the way in the future I think talks like this belong more to the #python-discussion room. It's good to use the proper place as not only you reach people with more expertise in the topic, but also other users don't get notified on the topics they are uninterested

loud trail
#

@restive vale maybe Pendulum

summer reef
#

well, Python's time.strftime will do the job as well, I think, as long as you know the input date's format

zinc birch
#

Hello,
I'm just learning about Hash functions, tables, and hash mapping, After some learning the site I'm learning from said that a "Much like an image that has been shrunk to a lower resolution, the output of a hash function contains less data than the input. Because of this hashing is not a reversible process. With just a hash value it is impossible to know for sure the key that was plugged into the hashing function."
But why wouldn't you just make the hash function save the number of times divided and then combine that with the mod function and boom a reversible hash function.... I believe I'm missing something since it's not so complex...

topaz pulsar
#

@zinc birch sometimes you don't want a hash function to b reversible, it isn't supposed to be a form of compression as much as a form of encryption, often passwords can be encrypted with strong hashing so that they can't be decryptrd (kepping your password secure) and when it comes time to compare a password that is entered to the one saved, it can just copare the hash of the password that is entered and see if they are the same value, this way nobody can (easily) find out your password while still being able to compare it to another value

zinc birch
#

So it's just because that's the use of it?

#

People don't want hash functions to be reversible?

topaz pulsar
#

hashing algorithms can also be used to validate if a file is corrupt, for example using md5 sums, you can see if the md5 sum of a file you download matches the md5 sum of what the file is supposed to be as a quick test to see if a file is corrupt

#

that is one of the reasons, but I don't know if the method you mentioned will work anyways, otherwise it would probably be used for compression quite frequently but I may be wrong there

zinc birch
#

Thank you

mint jewel
#

say you have a 64 byte result from your hash function. And say you pass in a whole lot of 128 byte strings. The thing is, there is no way to map every 128 byte string into 64 bytes, because there just is not enough space in 64 bytes

zinc birch
#

But you don't need to map everything

#

You need to map the steps to get everything

#

for example if after hashing you MOD the result, then you also save the integer of how many times you need to multiply back

mint jewel
#

Doesn't really help, how you store the information does not matter, you just cannot store every 128 byte string (meaning 0-255 128 times) in fewer than 128 bytes

tribal pendant
#

unless there is some kind redundancy/repetition/pattern

#

which is usually not the case after using a hash function

mint jewel
#

Yeah, if you do not need to be able to store every 128byte string, you can obviously use fewer bytes

onyx root
#

@zinc birch knowing the modulus, and how many times it was applied, you cannot reverse it. I have a number x between 1..100. x % 10 == 9. What is x? You can't know.

#

@zinc birch and any function that takes long data and produces short data won't be reversible, because there will always be two (or many more) inputs that produce the same output.

mint jewel
#

Though it is worth noting that the reason hash functions are irreversible is not because of information loss, because if you know a value that becomes a specific hash, then the hash uses meaning. A perfect hash function assigns a unique value to every input that cannot be reversed

onyx root
#

it's really important to note that there are different kinds of hash functions for different purposes. sha1() is different than Python's hash() function.

ember imp
#

.help

stark bridge
fiery cosmos
#

im not sure where this question goes but what is django? i heard its a python framework but nothing more, what can i accomplish with it and where or why would i apply this framework

#

have you tried to google it? There are many resources that explain what Django is and how to use it in much more depth than you would get from Discord

onyx root
#

@fiery cosmos Django is a web framework. you use it to build web applications

fiery cosmos
#

When working with trees, they can commonly either be represented as nodes with connections, or with dictionaries mapping some object to it's children.

What are the advantages/disadvantages of each?

amber loom
#

@fiery cosmos they work almost the same, just you're calling dict[node] for left and right instead of node.left and node.right

#

usually i use a class because the syntax is cleaner

#

but the advantage of the dictionary is that it doesnt require storing copies of the root or another node if you want to go back in a one-way tree

fiery cosmos
#

can someone teach me time space complexity in simple terms

#

Are you familiar with polynomials?

#

yes.. polynomial expressions

#

Think of O as something like 'time units' and of n as the amount of inputs:

O(n) means there is a linear relationship between the two. For 10 inputs, you need 10 time-units. Think of iterating over a list: The iteration takes twice as long, when the list is twice as long, ...
O(2n) still describes a linear relationship, but now, for example, you iterate through a list and backwards. Doubling the list size means the time units taken are doubled too, but the increase is faster.

O(n²) is a quadratic relationship. This might be iterating through a list once for every element in the list. If the list has size 10, 10² time units are required.
n = 10: 10² = 100 time units

Doubling the list size now gives
n = 20: 20² = 400 time units.

Time units isn't rigorously defined here. It's just an approximation.

#

The same thing applies to space complexity. O is no longer a undefined unit of time, but an undefined unit of storage.

#

hmm ok.. what I can gather from this is, n is if for every input, the time spent operating on it was proportional is O(n)

tribal pendant
#

Are you familiar with limits?

fiery cosmos
#

what are those

tribal pendant
#

limits of a function. If you don't know them it's ok 🙂 No need to bother with them

fiery cosmos
#

Can you elaborate what you mean by n is if for every input?

#

number of inputs being proportional to the time to act on them

#

Yeah! That's the relationship it describes.

#

Generally you'll want the lowest time / space complexity possible, which is

O(1): O is independent from input size. 

Worst case is something like:

O(e^n): Exponential increase
#

ok.. so O(1) is a constant.. maybe a index look up, O(n) can be iterating through a list..

#

I don't understand exponential or quadratic increase

#

I do see that O(1) is the lowest, then O(log N) then O(n)

#

Okay, an example of quadratic increase is bubblesort.

#

Are you familiar with that algorithm?

#

not really

#

Okay, the algorithm essentially requires you to iterate through the entire list for every element. (In it's worst case)

#

For longer lists, not only the length of iterations change, but also the amount of iterations

#

is it like

#
for i in y:
  for x in i:
#

Not exactly, this would assume a list of lists, it's something like: ```py
for element in list:
for other_element in list:
#do something

#

What you have above is still linear time, except when the size of i changes proportionally to the size of y.

#

yes, I meant to indicate they were lists themselves.. but my bad

#

I understand from your example this is quadratic.. o(n^2)

#

if there was another inner loop would it be o(n^3)?

#

Yes

#

yay

#

so what's exponential increase

#

It's a bit hard to come up with a good example, do you know how chess computers operate in principle?

#

😄

#

think of all possible moves?

#

Yeah, it thinks of all possible moves. Then for each of those moves, it thinks of all the possible moves again and so on.

#

like.. next move that can be made, next move opponent can make and so on

#

Yeah, precisely haha

#

That's approximately exponential time and space complexity.

#

Another example is maybe brute forcing a password

#

oh that's a much easier example to remember

#

what is space complexity

#

The same concept, but with space requirement instead of time requirement.

#

Often there is a distinction made between the space that's needed beyond the space of an input, and the total space needed.

#

The extra space when iterating through a list is generally constant, so the auxiliary space would be O(1), but when you count the input as space needed, the space complexity is O(n), since you need to store the list.

#

hmm I don't get it

#

like I understand time means time taken to execute a program..

#

what does space mean here

#

like memory?

#

Yeah, it's memory

#

Essentially memory required to execute a program:
auxiliary space being extra memory, beyond the memory required by the input and
space complexity being input memory + extra memory together

#

Imagine you have a program, like this: ```py

def program(n):
n_copy = n.copy()
return n_copy

#

Takes a list as an input, copies it and returns it

#

so it's O(1) for the input received, and O(n) for the copy?

#

yes, in auxiliary space

#

Extra space needed is O(n)

#

But when counting memory required by the input too, it's O(2n)

#

ok then

#

Is everything clear?^^

#

yes, I'll need to look up more examples for space complexity but I understand the concept now

#

thanks a bunch

#

One thing that's important to note is that they are really just rough estimates. Even when operations take longer for some kinds of inputs, usually it'll fit roughly anyways.

#

You're welcome^^

fiery cosmos
#

I have a file that looks like this

--------------Time step: 1 ---------------
Accumulated rewards: 1.5
Alpha: 660
Beta: 173
TCP_Friendliness: 1
Fast_Convergence: 1
State: 3
Retries: 0.0
---------------------------------------------------------------
---------------Time step: 2 ---------------
Accumulated rewards: 2.724744871391589
Alpha: 193
Beta: 0
TCP_Friendliness: 0
Fast_Convergence: 0
State: 3
Retries: 0.0
---------------------------------------------------------------
---------------Time step: 3 ---------------
Accumulated rewards: 3.869459113944921

I'd like to extract the time step values into an X array and the Accumulated rewards value into a Y array, I have no idea how to do that as I have 0 python experience, but this is my initial loop i've written that skips the first couple of lines that I have not included in the example(gibberish data)

with open('Tuner_result_1.txt') as f:
    for _ in range(11):
        next(f)
    for line in f:
        x = [line.split()[0] for line in lines]
        y = [line.split()[1] for line in lines]

obviously the actions inside the 2nd for are incorrect, idk how to read the lines i want properly.

eager hamlet
#

@acoustic oracle idk, but i would get the text of each line with

timeStepNum = 1
for v, line in enumerate(f):
    pass  # do some stuff here, maybe check if "Accumulated rewards" is in the thing```
dark egret
#

@eager hamlet I hope you know that this skips the 1st 11 lines of the file

for _ in range(11):
        next(f)
eager hamlet
#

also, i'm doing this problem:

Farmer John would like to create a triangular pasture for his cows.
There are N fence posts (3≤N≤105) at distinct points (X1,Y1)…(XN,YN) on the 2D map of his farm. He can choose three of them to form the vertices of the triangular pasture as long as one of the sides of the triangle is parallel to the x-axis and another side is parallel to the y-axis.

What is the sum of the areas of all possible pastures that FJ can form?```
Would i brute-force this by checking all the possible triangles that are possible within a point (then removing that point from the list), then adding the areas to the total, or is there a more clever way that I'm not aware of?
(ping 2 reply thx)
#

@dark egret yeah i know that, i don't see what it's needed

dark egret
#

I also dont know why its required to skip 1st 11 lines

#

@eager hamlet Is the format of the data in the file consistent?

#
if 'Time step' in line:
  time_step = int(line[line.find(':')+1:line.rfind(' ')])
elif 'rewards' in line:
  # try to come up with something like I did. This should be easy given that I did the tough one
#

Now regarding the question
N=[3,100] is pretty small. The time complexity of the brute force solution will be O(N^3) and this shouldn't be much of a concern

#

@eager hamlet

magic ruin
#

OCTONIONS

exotic hatch
#

🐙

eager hamlet
#

@dark egret actually sorry

#

um it isn't actually 105, it's actually 10^5

runic kestrel
#

Yo im trying to implement held karp into python. I've got most of the algo down, but am struggling with some weird phenomenon that I cant quite figure out. Anybody down to try to help?

#

@ me if so

dark egret
#

@runic kestrel I can give it a shot

runic kestrel
#

so this is my implementation

#
def hk(arr):
        size_n_routes = set()

        outer_dict = defaultdict(dict)

        def get(k, S):
            return outer_dict[k][S]

        def put(k, S, value):
            outer_dict[k][S] = value
            # breakpoint()

        #Arr is length n, but index 0 included, so n-1, which is innate to range(x, len(arr))
        for k in range(1,len(arr)):
            put(k, frozenset([k]), int(arr[0][k]))

        for s in range(2, len(arr)):
            for S in itertools.combinations(range(1,len(arr)),s):
                for k in S:
                    for m in S:
                        if (m == 0 or m == k):
                            continue
                        else:
                            #the complement of S
                            
                            S_c = set(S)
                            S_c.remove(k)

                            #Might need to be implemented if S_c or m is not a valid key
                            # if (m not in outer_dict and S_c not in outer_dict[m]):
                            #     put(frozenset([S_c]), m, arr[][])
                            
                            #outer_dict[k][S] = min((get(frozenset(S_c), m) + temp)) doesnt work because min of a single number
                            S_c = frozenset(S_c)
                            S = frozenset(S)
                            outer_dict[k][S] = (get(m, S_c) + arr[m][k])
#

for some reason, its computing multiple instances of the same paths, though

#

as well as giving those exact same paths different distance values

#

frozenset({V}) represents a path

oblique panther
#

I'm responding on reddit to someone who says that memory management is important for writing efficient algorithms

#

my thinking is that efficient programs != efficient algorithms, and algorithms exist independently of their implementation.

#

But tell me if I'm wrong.

mint jewel
#

yes, though it sounds pedantic to stress this.

oblique panther
#

The discussion is about someone who's trying to learn algorithms for a CS education

#

and learning algorithms and data structures in C, in my thinking, can cause you to quickly miss the point of the algorithms.

fiery cosmos
#

Memory / Time is basically a trade-off. You can have a very efficient algorithm that uses O(n^2) additional space, but runs in T(log_2 n)

#

I think it's necessary to manage memory, but it's important to know how an algorithm behaves and scales memory / time wise

mint jewel
#

most C implementations of algos is just allocate big array, do math, deallocate big array

#

but for data structures, managing memory is a sizable part of using them

quasi oracle
#

I don't know how detrimental that is. If you're good at writing code in C, writing classic algorithms doesn't have to be such a big deal

#

But high level languages provide more abstraction and let you focus more on the algo itself, sure

oblique panther
#

I guess my point is that algorithms are mathematical and in my experience are studied mathematically, so worrying about the low-level implementation details on an actual machine kind of misses the point.

quasi oracle
#

I'm not sure about that. Algorithms and data structures are very need-driven, and while an algorithm can be entertaining in theory it might not have much practical use because of the constants hiding in the asymptotic analysis. So worrying about such details can have an advantage sometimes. You're also usually implementing them after you're done with the theoretical analysis anyway.
As a side note, I find that being able to use pointers can be pretty convenient for implementing an algorithm such as Kruskal's

silk dagger
gaunt forge
#

Has anyone had any experience/luck creating trees/dependency charts in Python? I'm unsure how to have two different nodes point to the same child, for example, without using pointers

#

I guess a tree vs a dependency chart are two different things, on second thought I don't think trees can point to the same node

sullen gate
#

Use any tree to create a tree

#

Nd as everything in python is an object u can have them. Point to a single child

lean dome
#

I'm unsure how to have two different nodes point to the same child, for example, without using pointers
@gaunt forge everything in Python is a pointer (well, reference). Just make two nodes hold a reference to the same object.

#

you have pointers in Python, they're just not called pointers.

fervent juniper
#

I know that os.urandom(1) gives a hexadecimal representation of a byte. The part that I am confused about is this:

Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data
(python docs on bytes)
If you had this byte: 00000001, the resulting hex value would just be \x1, but, this isn't two digits, so, why does it say that?

lean dome
#

A pair of hex digits can be anything from 00 through FF. Because the base is 16 and F represents 15, that's a 15 in the sixteens place and a 15 in the ones place, which is (15 * 16) + (15 * 1), which is 255. A single byte can hold values between 0 and 2**8 - 1, which is 255. So, two hex digits can precisely represent every value that can be represented by 8 binary digits.

fervent juniper
#

Oh, okay, so it would just be \x01 for above. Thanks for the explanation :D

lean dome
#

yeah, exactly. It's not saying that there aren't any byte values that can be represented in a single hex digit - 0b00000000 through 0b00001111 can, as 0 through F. It's saying that every byte value can be represented in two hex digits.

fervent juniper
#

👍

lean dome
#

and - this may be obvious, but - 0b00001111 is generally written as 0F and not just F because usually you're describing more than one byte at a time., and if you represented 0b00001111 as just F then it would be ambiguous whether FF means two 0b00001111 bytes in a row, or one 0b11111111 byte.

fervent juniper
#

Ah, that makes sense, one more thing, how come you are doing 0b<bits>?

mint jewel
#

That is the python syntax for base2 int literals

lean dome
#

!e

print(0b00001111)
halcyon plankBOT
#

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

15
fervent juniper
#

Ah, okay

#

Thanks!

fiery cosmos
#

can someone suggest me some resource to learn Tkinter and GUI with pytho?

#

thanks in advance

halcyon plankBOT
#

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

fiery cosmos
#

what are permutations and combinations used for

#

i'm using itertools to solve some problems.. I want a general idea of cases we use them for

lean dome
#

that's a very broad question. both are pretty useful for brute forcing things. permutations can show you every way to rearrange a sequence, like for checking every possible ordering of 7 letters to figure out what words your scrabble tiles can spell. combinations can be used for figuring out every 3 letter word made from the letters a through z, or something.

torn scarab
#

figuring out every 3 letter word made from the letters a through z
that would still require permutation
combinations are where the order of elements in the set do not matter, eg. when you're looking to see how many different teams you can create from n amount of people

#

{joe, ves, lemon} is the same as {ves, lemon, joe} when you're building a team, so the order doesn't matter

#

conversely, if you're trying to see all possible outcomes of a race then {joe, ves, lemon} would mean joe's the winner, while {ves, lemon, joe} means that ves is the winner. in that case, the order is important and therefore permutations should be used

lean dome
torn crag
#

!e

halcyon plankBOT
#

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

balmy siren
#

Hey everyone..
i'm learning Graph DS and i think, it is better to create a visualization of graphs alongwith code. So, anyone know how to create such visualization in matplotlib ?

mint jewel
#

easiest would be using networkx draw features

balmy siren
#

@mint jewel yeah just heard about it. Also, do you know about pydot3 and graphviz ?

fiery cosmos
#

how do I upload a simple python file to my github? do I just upload the .py file or do I need to upload anything else like a source or something? do I make a new project or new repository ? what's the difference? what do I do ?

fiery cosmos
#

do you have the repo already?

#

@fiery cosmos

#

@fiery cosmos I don't. I know how to make one, but I was wondering what the tradition is, do I just upload a single .py file to present my small python project, or is there something I am missing?

#

just clone the repo ,copy the files in, commit, and push

#

alright thanks

fiery cosmos
#

@fiery cosmos if you are just starting to develop and use github and you only require one script your one name.py is all that is required. You can also add a README to get in the habit of it and requirements.txt file along with a .gitignore file

#

thanks

fallow yew
#

Hey so i remember a few months ago i got reccomened some websites where you can practice programming with exercises i think one was called hackerrank any others that are similar?

exotic hatch
#

@fallow yew leetcode is similar

last blaze
#

Hey so i remember a few months ago i got reccomened some websites where you can practice programming with exercises i think one was called hackerrank any others that are similar?
@fallow yew
Hackerrank, CodeSignal, codewars are the three most similar. All have their merits.

fallow yew
#

@exotic hatch @last blaze what about edabit?

fiery mortar
#

Hey guys, so i've been struggling with a problem for a couple of time now, and i thought you guys could help me,
The problem is the following:
If we have a game, where at each step we teleport the player in a random place in a 15x15 grid around the player, (we teleport in a 15x15 from the original position, then the player gets teleported , and we can re-teleport the player in a 15x15 grid around the player's new position), The question is: What is the probability of reaching said coordinates, after a precise number X of iterations ?
The problem is , that i need to account for conditional probability , and the different paths needed to reach said position
I tried muscling it out with code, but i was unsuccessful
maybe with your better knowledge of maths and computer science, you could help me
Don't hesitate to send me a private message if you think you have something! If you could share the message around, that would be much appreciated!

quasi oracle
#

What is the total size of the grid and the starting position?

fiery mortar
#

we'll say the the total grid is a whole plane

#

and the start is at 0 0 0

#

or 0 0 if we do it in 2d

summer reef
#

you mean, the problem is "random walk with bigger steps", what is the probability of ending up on any arbiraryly chosen point after N steps ?

summer reef
#

Are you allowed approximations ? Then you could use https://en.wikipedia.org/wiki/Central_limit_theorem, saying that the overall translation along X is the sum of N random variables following an uniform law on ⟦-15;15⟧ (and same for Y). (I guess there is an equivalent with discreet variables, should that prove necessary)
If you really need an exact computation, at the moment, I can see nothin but "brute-forcing" the algorithm (take all possible paths, count how many lead where you want), as (I think), the probability you're looking for depends on the target X and Y in a way I don't get (yet)…

quasi oracle
#

In the x axis alone it would be [-7, 7] because it's 15x15 around the current position

summer reef
#

right you are ^^

quasi oracle
chrome yew
#

hey guys, can anyone tell me the best coding challenge i can join right now, am a newbie but am ready to dive in

#

i want to improve my coding skills

#

while studying

acoustic jackal
#

how do people come up with test cases?

#

for example how would I come up with test cases to see if I've written an algorithm that solves the n-queen problem correctly

quasi oracle
#

Start from cases that should have an obvious answer

#

Add a little complexity then

#

And then start thinking about edge cases that you think your code might stumble on for any reason

#

Sounds generic, but you get better at it as you gain intuition on where things usually fail

brave oak
#

it helps if you state the problem in an abstract form, in terms of postconditions

#

for example, say you want to write tests for a division function. you could have a test case for each of the following aspects:

  • dividing by zero gives a specific error
  • signs are properly dealt with
  • the result multiplied by the divisor is equal to the dividend in terms of magnitude
fiery cosmos
frail flare
#

Hello o/ I kinda need some help with calculating the time complexity for an algorithm. It's a simple one, but I have only basic knowledge of the big-O notation, and was kinda hoping someone here would help figure out it's complexity from some description.

#

The core goal of it is to achieve "lexicographically smallest topological ordering", that is to sort a list of items that depend on other items in the same list, in such a way that for each item, its dependencies appear before it in the list, and each sequential item appears in the final list as soon as it's possible for it to do so. Essentially, it's a stable topological sort.

#

Here's some pseudocode:

from collections import deque

items = deque([...])  # items to process
final_list = []  # final ordering
recheck_list = []
while items:  # repeat until there are items to process
    item = items.popleft()
    if item.dependencies_exist(final_list):
        # all dependencies are already there
        final_list.append(item)
        if recheck_list:
            # add the missed items back in their original order for them to get rechecked
            items.extendleft(reversed(recheck_list))  
            recheck_list = []  # reset the list back to empty
    else:
        # missing dependency
        recheck_list.append(item)

print(final_items)  # final ordering is here
#

Not sure if this is the best place to ask, but this barely has to do with programming on itself, as it's a time complexity calculation thinkcoco

summer reef
#

if item.dependencies_exist(final_list):
Well, even assuming no circular dependencies (witch allows us to say that your algorithm terminates), the hard point is how many items get pushed back into the deque (with items.extendleft(reversed(recheck_list))).
I'll take a guess, and say O(n) in total (meaning a roughly fixed proportion of items gets unsatisfied dependencies when it is processed).
This allows us to say the main loop (while items:) will run O(n) + O(n) =O(n) times [first O(n) : length of the deque ; second O(n) : additionnal items].
Now what's the time complexity of the content of the loop ?
Well, all items are O(1) (thanks to the chained list/deque structure), but for one : if item.dependencies_exist(final_list):. It has to iterate, at least once, over final_list, and thus runs in O(n). Also, it iterates over a list of dependencies, but we will take it either as small enough not to matter (meaning length <= k, with k not bound to n), or, if it's big enough, it could be a set, witch allow for membership checking in O(1) [Big picture : this list of dependencies does not matter.]

The overall complexity is therefore O(n * (n+1+1+1+…)) = O(n*n) = O(n*2).

Note that we may discuss the "all items are O(1) (thanks to the chained list/deque structure)", it depends on the actual Python implementation, but even if it were not O(1), it would be O(n), witch doesn't change our final result.

frail flare
#

right, so that dependencies_exist method just does a simple dependency in final_list check, for each dependency the item has. Something like all(d in final_list for d in item.dependencies)

#

roughly

#

Hmm, how would this compare if the algorithm would be changed to this?:

from collections import deque

items = deque([...])  # items to process
final_list = []  # final ordering
while items:  # repeat until there are items to process
    item = items.popleft()
    if item.dependencies_exist(final_list):
        # all dependencies are already there
        final_list.append(item)
    else:
        # missing dependency
        items.append(item)  # add to the end of items

print(final_items)  # final ordering is here
#

This is a simpler version where, instead of extending it to the left so that they're rechecked immediately, the items are appended to the end of the deque. This means that if there's a missing dependency, the next time item is gonna be checked only after all of the "main" ones were.

#

This breaks the stability of the algo, but if the speed increase would be worth it, I'd consider going with this.

#

When I tried to calculate the notation, I came up with a worst-case scaneario concept of a list of 10 items where the first one depends on the second, second depends on the third, and so on. The last item is the one that doesn't depend on anything, meaning that it'd need to go through all 10 items first, add the last one to the final list, recheck the remainning 9, again add the last one to the final, recheck all 8, etc.

#

This 10+9+8+7... makes it O(!n) for the worst case if I'm correct?

#

This seems to be the case in both of those, the previous one, and this one that recycles items to the end of the deque

last blaze
#

No. Of its just summing consecutive numbers, the time complexity is o(n**2)

frail flare
#

Huh

#

Right, factorial is multiplication, not addition

#

Would this second one have better average big-O notation tho? Or the same one?

fiery cosmos
#

Is there a way to compress files into a fixed size image, instead of setting max output params (with Pillow) ```
try:
with Image.open(image) as i:
i = Image.open(image)
i.thumbnail(output_size)
i.save(image_path)
except IOError:
print(f"Could not create thumbnail for {image_path}")

frail flare
#

Pretty sure this doesn't belong here, as it's a strict coding question, regarding a 3rd party lib

#

or maybe it does, idk

fiery cosmos
#

That wasn't helpful, but thanks.

#

Solved the issue, for those interested I ll leave a snippet

#
try:
   with Image.open(image) as i:
       i = Image.open(image)
       i = i.resize(output_size, Image.LANCZOS)
       i.save(image_path, optimize=True, quality=85)
except IOError:
        print(f"Could not create thumbnail for {image_path}")
summer reef
#

@frail flare Your second algorithm has the same complexity as the first one (O(n) loops, O(n) per round = O(n²) overall), but that doesn't mean it's faster, or slower ; you know the definition of big-O, the execution speed is also about the proportionnality constant (read higer up in this thread if you don't remember ^^). In general (including in this case), it also depends on what data exactly is fed, as well ; your algorithm will work faster on an already-oredered list ! (Reasoning about the worst-case scenario, as you did, is what is done most often, but it may be a very rare, or degenerate, case, as the one you pointed out : you almost never need to work on a reverse-sorted list)

frail flare
#

Hmm, right. Yeah, I am aware that O(1) can mean it'll take an hour to complete, even tho it's constant Hehe Was just wondering if it'd be faster overall.

summer reef
#

Well, I guess the second code is a better idea, beacause then you resolve all the "simple" cases (iterate over the whole array) before going to the problematic ones, but you don't guarantee then that items are put as early as possible, witch was your original problem to work on, I belive. Also, smaller code (except for what's found in #esoteric-python 😃) is often faster.

frail flare
#

Makes sense to me

#

I'll ask the codebase author if he'd like a stable or non-stable-but--technically-faster solution, and adjust accordingly then

#

Thank you for helping lovebun

weak vessel
candid osprey
#

First, are you aware about limitations of floating point?

#

Now, printing upto two decimal places is simple, the main thing is mentally separating data and "representation". What that means is, displaying up to two decimal places is simply a question of representation, and you can use string formatting for it

#

One way to do it is f"{n:.2f}" if I'm not mistaken

#

Where n is your variable

stable pecan
#

i think he wants to use Decimal class

candid osprey
#

String formatting should have no issues with decimal class too i believe

#

But I did want to mention the floating point arithmetic regardless as a good to know type of deal

stable pecan
#

well, in any case, you don't need anything special for Decimals, just put them in your string normally:

In [15]: a = Decimal('3.14')                                                                                                              

In [16]: a                                                                                                                                
Out[16]: Decimal('3.14')

In [17]: print(a)                                                                                                                         
3.14

In [18]: f'{a}'                                                                                                                           
Out[18]: '3.14'
whole ingot
#

im tryna install pygame on my macbook using terminal but it just gives me an error

#

anyone care to help pls 🙏

#

thx

fiery cosmos
#

im tryna install pygame on my macbook using terminal but it just gives me an error
@whole ingot same

tribal pendant
#

what error do you face?

#

Normally it just install smoothly

rare thorn
#

@summer reef Can you say that for and while function like AND in a logical operation and if, else function as an OR ??

summer reef
#

Hardly…
If I get what you're thinking right, you can build both AND and OR using for/while (on an array), or if/else (on only two pieces of data)

#
>>> def and_loop(*values) :
    for elt in values :
        if not elt :
            return elt
    else :
        return True

>>> def or_loop(*values) :
    for elt in values :
        if elt :
            return elt
    else :
        return False
#
>>> def and_if(v1, v2) :
    if v1 :
        return v2
    else :
        return v1

    
>>> def or_if(v1, v2) :
    if v1 :
        return v1
    else :
        return v2
#

(note the "else" with the "for" loops, it's not necessary, it's just there for the parallel with the "if" version)

topaz pulsar
#

@summer reef its not actually needed with the if versions either because if the condition is true and the top condition is run, the function exits so the else wont be run anyways

candid osprey
#

Gave me a headache but seems like the first one isn't quite correct. Are you imagining an and between multiple values one by one?

#

If so, the short-circuit ing at the end means you should return the last value, not the boolean True

topaz pulsar
#

also, the parameter is called values and the iterable you use for looping over is called value

summer reef
#

the short-circuit ing at the end means you should return the last value, not the boolean True
@candid osprey
Yeah, I agree, but then what about the case when the iterable is empty ? Note I could have managed all the cases, but it would then be harder to read and understand the purpose, so I decided not to in the end.

#

@topaz pulsar right you are, I corrected it ^^

candid osprey
#

Fair enough. If it's a deliberate choice, then sure

drifting sun
#

Hi, this might be a stupid question but there is a program called XAMPP on my C drive, i googled and found it's used for setting up servers? I'm not going to set up any servers and I don't remember installing it so I'm not sure it's something I should mess with. Should i uninstall it?

runic kestrel
#

Anybody know of an ILP for TSP that utilizes the fact that the shortest distance from i to j is (i,j)

worthy crown
#

@drifting sun searched "why is XAMPP on my pc", can't see anyone who just randomly has it. So the reason it's there is not obvious

fiery cosmos
#

Hi, this might be a stupid question but there is a program called XAMPP on my C drive, i googled and found it's used for setting up servers? I'm not going to set up any servers and I don't remember installing it so I'm not sure it's something I should mess with. Should i uninstall it?
@drifting sun its a software stack to let you run a webserve on your pc, so if it's there someone installed it

candid osprey
#

Basically, you can uninstall it if you're the only one using your system

balmy roost
#

@shy
Just uninstall

tiny dew
#

is it possibe to add music in python with a pakage?

open bloom
#

anyone know a good place to learn algorithms and databases in python?

#

like Heaps, AVL tree, Dijkstra, searches, dynamic programming, topological sort etc...

quasi oracle
#

Define a place. A book? a course? some kind of simulations?

#

Are you using something already?

summer reef
#

is it possibe to add music in python with a pakage?
@tiny dew
Pygame has it, I belive

tiny dew
#

ok thank you @summer reef

#

@summer reef what kind of code

last blaze
#

anyone know a good place to learn algorithms and databases in python?
@open bloom
There's a good course in the pins

open bloom
#

@last blaze thank you so much!

reef mantle
#

Hello, what laptop would everyone recommend for undergrad cs? Would a RAM of 8gb (instead of 16gb) suffice? What about a storage of 256gb?

Also quite concerned about the battery life 🤔

tribal pendant
#

I'd recommand 16Gb of RAM, you'll be able to use your laptop much longer. 256Gb seems enough, SSD would be a must.

gusty grove
#

8 is probably fine, 16 is awesome 🙂

summer reef
#

8 is more than enough for now for me ; the algorithms I write/use as of now don't take much memory, the most memory-sensitive stuff is video games 😄

sick oar
#

Not sure if the programs you run/compile in the future would consume a lot of memory or not. If affordable, I would also recommend 16G

pine spire
#

just pick what u can afford i doubt u will write a programm in uni which takes more than 8gb of ram^^

tribal pendant
#

That was my point, better spend a bit more today and not having to buy a new laptop at the end of uni

bronze gazelle
#

!off-topic

halcyon plankBOT
primal dock
#

Can anyone help me finding my error in my implementation of Dijkstras, I tried following Wikipedia's pseudocode

reef mantle
#

Thanks for all the input!

waxen meadow
#

guys
i need a help
do you know about selenium?

half lotus
mystic osprey
#

which func do we have to use to use get_string

gusty grove
#

if i have a plane at position P with the normal N and another point S on that plane, how would i calculate the u/v coordinates of S?

runic tinsel
#

what's u v

fiery cosmos
#

its a thing

runic tinsel
#

ok that's just x y for some reason, looked it up

fiery cosmos
#

yeah

runic tinsel
#

hmm

#

so like naively, you could rotate the whole thing so that x y coincides with u v

gusty grove
#

how would i get the inverse transformation matrix?

#

i would first need to find a transformation matrix that translates i,j,k to N and invert that

#

probably missed something super obvious

#

N is the normal

#

P is some point on the plane

#

h is the ray hit point

#

v is some arbitrarily picked vector

runic tinsel
#

i don;t know

pale ginkgo
#

Hey y'all, learning algorithms. Quick question: when using linear search, does the algorithm have to use a while loop? or can I use for loop? It seems either will work since it's merely a sequential search over an array. Any input helps. thanks!

quasi oracle
#

@pale ginkgo any for loop can be written as a while loop, just go with whatever looks cleaner

pale ginkgo
#

@quasi oracle Nice, thanks!

modern snow
#

Guys, what would be an example of NLP that does not use some sort of ML or DL, but is still classified as an AI?

rocky lake
#

hi

hazy tangle
#

I am working on CNN currently. how i can get no of training samples in one variable and no. of testing samples in second variable? now i am getting this way Found 807 images belonging to 23 classes. Found 164 images belonging to 23 classes. how i can save it like "train_samples" = 807 and "test_samples" = 164 etc this way? i need these variables in cnn algorithm

old moth
#

Hey

fiery cosmos
#

Shallow Learning ??? Why don't we see it in such diagrams ?

#

But we do see Deep Learning.

exotic hatch
#

Deep learning is a buzzword. It means your model has a lot of parameters (layers and nodes)

fiery cosmos
#

So what is Shallow Learning ? It gives results on searches.

gusty grove
#

just less neurons/parameters

#

not as many layers

loud trail
#

i like to define "deep learning" as a catch-all phrase for a collection of related neural network model building techniques such as CNN and LSTM

#

"machine learning with deep neural networks"

tawny apex
#

Hi guys! Can I have questions?
So there a string: "asd" and that produces a hash called "BQFC3Q"
is it true that there is another string that produces the same ("BQFC3Q") hash? Let's say that is SHA-256.

languid vessel
#

yes, that is very likely

#

i guess there is no way to prove that another string has exactly this hash, but hash collisions must occur in general

#

a hash algorithm produces output of a fixed length e.g. sha256 hashes are always 256bits long

#

that means, it can only have a maximum of 2^256 different output, but there are more than 2^256 possible inputs

#

thus there must be different inputs that generate the same output

tawny apex
#

Ah, okay thanks for the explanation. 😄

#

I know that may sound dumb but why 2^256? 😄

languid vessel
#

Let's look at a 3 bit string as an example

#

You have 3 places, each of them can be 0 or 1.
Now you can start enumerating all possible combinations: 000, 001, 010, 011, 100, 101, 110, 111

#

With each additional binary digit you double the possible combinations

#

Maybe starting with 3 was not smart, let's start with a single bit

#

There it's obvious that it can only have 2^1 = 2 states, 0 or 1

#

Now if we go to 2 bits, each of them can have 2 states, giving us a total of 4 combinations.
First you keep the left bit a 0 and now you still have the two combinations of the right bit to choose from, giving you 00 and 01

#

Now you set the left bit to 1, and again you have the two combinations of the right bit to choose from, giving you 10 and 11

#

Now you can recursively keep adding new bits to the left. With 2 bits we could do 00, 01, 10 and 11

#

With three bits we can put the leftmost bit to 0 again, and then go through the 4 combinations of the other two bits. Then we can put the leftmost bit to be 1, and go through the 4 combinations of the other bits again

#

So with each bit you double the amount of possible combinations

#

And since the first bit had 2 combinations, and each "doubling" means multiplying by 2, we get 2^n combinations for a bit string of length n

quasi oracle
#

Technically speaking any network with more than one hidden layer is "deep"

#

But the term is used as said for networks with many layers and nodes

oblique surge
#

What is the best method of creating a fuzzy search?

#

i need to essentially make a search engine that if the results match exactly send that as the highest order then everything else bellow it by how it matches

quasi oracle
#

A search out of a given set of possible results?
You could start by creating a function to measure the distance between two phrases

oblique surge
#

thats sorta what i was thinking but im unsure whats going to be the best method

#

atm im doing it off of a sorta 'weight' method ordering by the weight of each object

#

weight being determined by diffrent factors

#

im just messing with different methods of adding weight but they're pretty inefficient imo

#

like counting the amount of whole words that the searches match to the search terms etc...

quasi oracle
#

You also have this kind of distance:
https://en.wikipedia.org/wiki/Levenshtein_distance

In information theory, linguistics and computer science, the Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-character edits (insertions, deletion...

oblique surge
#

Ooh

#

that looks rather interesting

#

I shall check it out

#

with the search term being assassin its not too bad

tropic dawn
#

Anybody has experience with CSS?

torn scarab
#

@tropic dawn you will have better luck in #web-development, this is a channel for computer science

tropic dawn
#

Lol I didn’t notice that thanks

dense mauve
#

Hello everyone, I seek some help with Pandas excel formatting and I am aware that DS people are fairly profficient in Pandas, BUT this isn't a DS question, so is this the right channel or is there a better one? 🙂

#

whops, this is for sure the wrong one 😄

fiery cosmos
#

Anyone here knows good resources to study the basics of comp sci like algorithms and stuff like that?

#

I already know how to code but I figured I want to make algorithms that solve puzzle and stuff

#

So I guess this stuff could be useful

last blaze
#

In the pins is a great course from MIT

#

for specifically algorithms

fiery cosmos
#

Thanks man

#

Sorry for asking then

last blaze
#

There's nothing wrong with asking, that's what this channel is for. There's lots of resources, just the one in the pins is one that I really like

#

If you're new to CS in general, MIT 6.001 might be better. It starts with more basic stuff and assumes less knowledge

#
still crystal
#

how can I open BIOS in SONY VAIO

tawny apex
#

Hi guys, can somebody explain me why doesn't the regex (^1$|^2$|^3$) matches the string "111"? I don't want it to match it, but right after I wrote this regex I started thinking about, what if I try to match "111" because it starts with one and ends with a one! 😄

quasi oracle
#

@tawny apex your pattern specifies a single "1", so it can't match more than one of those. If you wanted to match at least one 1, you could write 1+ instead

#

If you're using something such as findall and wondering what it doesn't find anything when you try it with 111, that's because you specified in your pattern that 1 is the beginning and end of the string to match

tawny apex
#

Thanks!

fiery cosmos
#

yo, i made a script that converts a PNG to a .raw image

#

now my issues is that when the PNG has transparency, it breaks and outputs an image that has solely white or black colors

#

does anyone know how can i remove alpha channel in PIL?

summer reef
#

yeah
use the convert method ; your image is RGBA, you want it RGB.

#
img_noalpha = img.convert("RGB")
fiery cosmos
#

nah that didn't work

#

it was in 'I' mode not RGBA, eventually i had to calculate the rgb values and therefore the grayscale values myself

terse plover
#

how can i read all text in a screen shot ?

marble basalt
dull wraith
#

what is binning data?

#

i need to do this for a fourier transform

high nexus
#

In the case of fourier transformation i would guess make the array the length of the powers of 2

#

like 1024 or 512

south swift
#

Hi I don't know if this is a the right channel for this, but I have an idea, and I want some feedback on it to see if it's stupid or not. I want to cluster sentences in a document into k topics, and I was wondering if I could find the cosine similarity between the word vector of the topic and the average sentence vector. The sentences with the least cosine distance to certain topics would get assigned to that topic

candid osprey
#

Sure, it's worth a shot. You'd have to do an insane amount of cleaning on the sentences to have any hope of getting good vectors though

fiery cosmos
#

how can I open BIOS in SONY VAIO
@still crystal try holding the delete key on boot

cyan gull
#

Hey guys ik this is a python server but i have a quick basic c question if anyone can help pls

candid osprey
#

try the offtopic room

mossy scarab
#

using an ANN

fiery cosmos
#

anyone know good sources I can learn backend development with Python?

pulsar thistle
#

google

#

and youtube

last blaze
#

!resources has lots of links. You want to look at flask/Django stuff first probably

anyone know good sources I can learn backend development with Python?
@fiery cosmos

halcyon plankBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

fiery cosmos
#

Thank you!

sharp oak
#

@mossy scarab you can curve fit anything, but you're going to quickly find out that some data will generate inaccurate models with w/e method due to the nature of the data.

like random data without any discernable pattern wont give you a very useful model

mossy scarab
#

oh ok

#

thanks @sharp oak

celest heron
#

Hello, I'm new to this channel and I don't know whether my question about computer vision fits this channel.
But does anyone have an idea how to locate 3D position of an object given 2 images? For further details i have also posted my question on stackoverflow: https://stackoverflow.com/questions/62716117/finding-3d-position-of-an-object-given-2-images
If anyone has an idea you can also private message me 🙂 thanks for your help

fiery cosmos
#

Can anyone help me with a thing:

#

How do I create a custo Mic/webcam input on my Linux pc

#

Like real time Mic changers do

#

In python please

#

Thanks

zinc brook
#

So are there like any good texts on software architecture? I am finding a lot of really informative blogposts and sort of less rigorous books, but wondered if there was anything really formal put into print that anyone could strongly recommend.

orchid lark
#

Hi I don't know if this is a the right channel for this, but I have an idea, and I want some feedback on it to see if it's stupid or not. I want to cluster sentences in a document into k topics, and I was wondering if I could find the cosine similarity between the word vector of the topic and the average sentence vector. The sentences with the least cosine distance to certain topics would get assigned to that topic
@south swift
Sure, it's worth a shot. You'd have to do an insane amount of cleaning on the sentences to have any hope of getting good vectors though
@candid osprey Hi all, I'm new here! I have a little bit of experience in NLP. When cleaning your sentences you'd want to:

  • convert all characters to lowercase, unless you'd like to extract information from casing (which can be tougher)
  • tokenize (split) words by spaces
  • remove special characters (unless you'd find them informative in some way). Basically anything in string.punctuation. You may also want to remove numbers, depending on your data set
  • some people remove common "stop" words, which tend to be less informative; examples include 'is', 'the', 'for', and so on. In very short sentences, you may opt not to omit those, as doing so may strip the sentence of syntactical information
  • you may try to remove typos and proper names by scanning for the X most common words in the set, and dropping all others.

Note that Keras (from Tensorflow) has some built-in functions for all of this, but if you don't plan to move on with deep learning, it might be overkill.
Hope this helps/addresses your question!

fiery cosmos
north zealot
#

You should write the truth table of this set of gate and see if that correspond to any existing gate

last blaze
#

You can also infer what the final gate is just by thinking about what this collection of gates does together

solemn parrot
#

i would write out the truth table for it and then make a k-map to simplify down the logic

manic phoenix
#

TIL k-map, thanks

zenith dagger
#

does anyone have experience with object tracking? specifically noisy bounding polygons

oblique panther
#

@azure inlet your remark on Turing completeness got me thinking: I assume that since matlab is designed to be a platform for doing math, the fact that it's Turing complete doesn't mean that you can do all the things you can do in Python

#

so is there a subset of Turing complete languages that can "do things" that aren't necessarily "problems" that TMs solve?

zenith dagger
#

what do you mean by that?

oblique panther
#

@zenith dagger a language is Turing complete if it can instruct a machine to do the same things as a Turing machine

#

and a Turing machine is a theoretical machine

#

saying that a Turing machine is "a theoretical machine" really just moves the question somewhere else

#

but I still haven't thought of a good way to describe them.

quasi oracle
#

Turing completeness is strictly about computation. Both python and Matlab can simulate a Turing machine. Whether there's something python can do that Matlab can't is a question of what resources and hardware components each have access to

oblique panther
#

I see

quasi oracle
#

I can't think of anything like that. It might be just less convenient in matlab

mint jewel
#

Matlab can call C libraries, so I would say it can have the same effects as python can.

north zealot
uncut jetty
#

How to convert datetime to seconds

#

Not based on epoch

marble basalt
#

based on what then

#

seconds since when

#

Assuming you mean since midnight, you can do something like this

#

!e

import datetime
print(datetime.datetime.now() - datetime.datetime.combine(datetime.date.today(), datetime.time.min))
halcyon plankBOT
#

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

marble basalt
#

kek

uncut jetty
#

Well, I need a sleep time for a future date

#

Well

#

NVM

#

I made it

#
def sleep_time_from_dt(dt: datetime.datetime):
    return (dt - datetime.datetime.now()).total_seconds()
marble basalt
#

It sounds like you want a timedelta

uncut jetty
#

Well, I got it

#

Thanks anyway

#

Is this the correct place btw?

#

@marble basalt

#

I don't know this is the right place or not

marble basalt
#

not really, it would fit better in a help channel

uncut jetty
#

yeah

marble basalt
#

this isn't really computer science specific

uncut jetty
#

I am a user here since 3 month?

#

Well, it is right, I am here for three months

marble basalt
#

?

dapper sinew
#

json question
So say there's this json file that's always changing
I save the original copy and then 5 secs later, when it'll have changed I check it again
How do I compare the two json's and get the ADDED fields only
Like it's always being added to every 5 secs as an example

oblique panther
dapper sinew
#

kk

somber flume
#

does anyone know how to make python print elements that are common in a list?

marble basalt
#

Not computer science either

fiery cosmos
#

@somber flume here is an efficient algorithm i threw together:

def find_common_elements(some_list):
    # Create new instance of the built-in set class
    common_elements_set = set()

    for i in range(len(some_list)):
        # Use the set class's add method to add new elements to the set
        # Trying to add items already existing in the set does nothing! No duplicates can exist!
        common_elements_set.add(some_list[i])

    return common_elements_set```
#

oh wait i messed this up

#

Ok it's fixed

#

So there's a very useful data structure called a set. It's a built in class that is very similar to a list, except it cannot have duplicate values,, and searching for values in a set is super duper ULTRA efficient. Like O(1) time, if you are aware of Big O notation. Basically as fast as it can get. Almost instant. Way better than searching through a list. So this basically adds all the elements from the list passed into the function to a set. If a value is a duplicate and you call the add() function, nothing happens. So this works beautifully. Items in sets are automatically ordered from least to greatest, which is nice to read too. Let me know if you have any questions.

#

pass in a list as a parameter btw

fiery cosmos
#

If you want to include a count for each common item, i can make some changes

#

i would have to use a dictionary, which is similar to a set except it contains key-value pairs

#

in a dictionary you access the key similar to how you would access an index in a list, except you provide the key name, and then it returns the value for the key

#

in fact, dictionaries are just like lists, except the keys have to be set, whereas lists have keys that start at 0 and go up by 1. Just like lists, dictionaries can't have duplicate keys.

blissful wedge
#

guys where can i go to practice requests?

ebon fern
#

The Python module requests?

blissful wedge
#

Yea

crude glacier
#

I'd like practice too

oblique panther
blissful wedge
#

Really? @oblique panther

oblique panther
#

yeah, that doesn't fall under computer science per se.

crude glacier
#

Wow

shrewd rampart
#

has anyone here worked on python implementation of certain Multi-Population evolutionary algorithm(s) ?

#

I am in need of official codes/implementation of State of the art algorithms for benchmarking purposes.

marble basalt
#

what state of the art algorithms?

turbid latch
#

Just reticulating some splines, right?

cursive cloud
#
number_of_ways = 0

class ClimbingStairs:
    @staticmethod
    def rekursive_climb(rest_number_of_stairs: int):
        global number_of_ways
        if rest_number_of_stairs == 0:
            number_of_ways += 1
        elif rest_number_of_stairs == 1:
            ClimbingStairs.rekursive_climb(rest_number_of_stairs - 1) # one step
        else:
            ClimbingStairs.rekursive_climb(rest_number_of_stairs - 1) # one step
            ClimbingStairs.rekursive_climb(rest_number_of_stairs - 2) # two steps

    @staticmethod
    def climbing_stairs(number_of_stairs: int) -> int:
        if number_of_stairs <= 0:
            return 0
        else:
            global number_of_ways
            number_of_ways = 0
            ClimbingStairs.rekursive_climb(number_of_stairs)
            return number_of_ways
#

Regarding the code aboive, how would you save the number of ways?

oblique panther
#

As an aside, you don't need to make a class as a container for static methods as you can just make regular functions in the module-level scope.

#

what do you mean by save?

cursive cloud
#

Using a global variable like I did, does work. But it seems to me it is bad practice and should be avoided

oblique panther
#

you could just have one function, and define a second function (the recursive one) within the first one.

#

then the number that gets incremented is only in one function

#
def my_func(num):
    count = 0
    def recursive_func(num_):
        count += 1
        # do stuff with num_
        recursive_func(num_)
   return recursive_func(num)
stable pecan
#
nonlocal count
...
oblique panther
#

salt, will what I wrote not work? 😮

cursive cloud
#

Oh, I thought about making a function that starts the recursion but thought it will not work because the recursive func could not access the variable.

#

Never defined a function in a function

#

Thanks!

stable pecan
#
>>> def my_func(num):
...     count = 0
...     def recursive_func(num_):
...             count += 1
...             recursive_func(num_)
...     return recursive_func(num)
... 
>>> my_func(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in my_func
  File "<stdin>", line 4, in recursive_func
UnboundLocalError: local variable 'count' referenced before assignment
>>> 
oblique panther
#

😮

cursive cloud
#

Oh yes I got the same, that's what I thought would happen.

stable pecan
#

precede the count += 1 line with nonlocal count

oblique panther
#

aha

#

Thanks!

stable pecan
#

np

gusty grove
#

nonlocal is a keyword?

oblique panther
#

yeye

gusty grove
#

as bad as global?

oblique panther
#

global and nonlocal let you play with the scope of stuff

gusty grove
#

hehe

stable pecan
#

you could keep the static methods and increment a class or instance attribute

#

nonlocal isn't as bad a global

#

it's often used in decorator or decorator-factories

gusty grove
#

does it just elevate by one scope?

stable pecan
#

yep

gusty grove
#

ah cool

#

TIL

oblique panther
#

what if you're a few levels deep? can you stack it?

stable pecan
#

i don't think so

oblique panther
stable pecan
#

well, you might be able to declare nonlocal in each function

gusty grove
#

similar to how you cant stack break or continue 😦

candid osprey
#

Sounds like it would be a headache inducing code to read anyways