#algos-and-data-structs
1 messages · Page 81 of 1
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?
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
If you care about efficiency, doesn't the generator expression give you the same thing for memory/cpu?
let's take a looksee at ye olde timecomplexity site...
but it shows up in interview q, so I think I have to learn it anyways
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
is there an easy / intuitive resource for learning ds/algo and their implementations?
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
any recommendations?
you want something specific tailored towards coding interviews or like
a general textbook
mostly 1, but maybe 2 for reference material
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
ok, thanks
@split obsidian to practice, try doing problems on https://leetcode.com
i found that it helps a lot
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
what is cs mainly about??
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!
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 try python's builtin list.copy() method?
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
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

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
Anyone knows any algorithm that calculates the link relevance of each vertex of a tripartite graph?
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.')
@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
Hello
@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))
https://github.com/JTexpo/Sudoku_Solver @amber loom heres the code if you wanted to take a look, just finished commenting it
nice
@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
@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!
@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?
@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!
@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
@jovial creek alright I'll post an optimised result for ya asap :)
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
Ooooooh so you’re saying that if there was a board it previously solved that matched to just paste that?
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
Okay! Looking forward to it!
@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
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
you'd be surprised
's all generators
and consider this
do you care about size?
Huh interesting
Lmao, well on my 8GB computer yes haha
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
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!
ah aye, but you should check the runtime of that code
Haha I have no doubts that what you provided is faster 😄
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
Haha thank you a lot for your feed back, I will be looking into something like this for other projects!
👍
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'
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
Can someone do my schoolwork python coding for me it's a small amount
Do anybody who would ?
definitely #❓|how-to-get-help
/help
@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
I dont understand it, I dont understand the type of python I'm supposed to be doing and my teacher wont help me
well whats the assignment and we can work it through in baby steps
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
are you using turtle?
Idk I'm really new at this stuff can just send a picture of it?
sure drop a pic here
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
no I need to make it night I just cant get the moon right
the moon looks great to me
Yeah I think it dose to hut it has to be exactly right
If tony knows fun I choose stark
@fiery cosmos wym
The whole design
computer science --- how to define
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])
@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
i had adversion to CLASS -- maybe i need to learn how to use ,, or why to use
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
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
i don't complely follow
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```
so how would i fix this
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
ok thanks for the help
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
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
where can i ask linux related python questions
DFS would be the easiest to code but BFS I think would be the better algorithm
Hm? They are pretty much the same right?
Hey, does anybody know a good computer science course for beginners?
@finite summit SoloLearn
@jovial creek Thanks'.
Np
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?
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
Thanks lakmatiol, you explained that perfectly - I understand now. You're the best!
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
?
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?
@past flare Yes I do,but with insertion algorithm
okay
I know how insertion works, but what I don't understand is the step where you determine what is the smallest number
Selection or insertion sort?
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
@mint jewel aren't they the same?
No
isn't that what you needed ?
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
@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
yup exactly
@everyone anybody know how i can write html in a python file?
pyxl, though generally you use a templating engine
also, pinging everyone is generally bad form
what do you mean @mint jewel
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
Sure ill take a look
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
With pyinstaller yes afaik
it has smtplib
@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
what about o(n*2)?
You mean O(n^2)?
yes
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
has anyone connected to sql developer using cx oracle/ oracle instant client from python?
@quasi oracle thank you 🙂
@fiery cosmos like in terms of just editing a .db file? Cause python has an SQLite3 lib that works wonders
does that use the oracle client? @jovial creek
I don’t believe so, but what’s the goal?
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?
Oh yikes, hrmmmmm... honestly I’d recommend webscrapping it as a all else fails solution. Websrape and make it into a CSV
i just need to extract the data from the sql query into python for pandas
would sql lite not work?
Idk if you can connect to a file that isn’t local
i'll look it up . thanks. oracle instant client lets you connect to a file but im having installation trouble with that
Ah yeah oracle I’m never to happy with using
sorry I couldn’t get ya a better answer
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
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
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
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.
the "standard signals" table at https://www.man7.org/linux/man-pages/man7/signal.7.html shows what the default action is for each signal if the application doesn't handle it.
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.
I know how to fix that from the command line, but I don't know how to fix it from VS Code.
@lean dome well VSCode uses powershell
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
you did 0v instead of -v
OK - and how about
git diff --name-only master orrigin
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.
you didn't run my last command at all there.
git push
run that, then:
git push --set-upstream origin master
thank you so much. i'll be sure to watch a video on git tutorial
you were a lot of help.
👍
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
hey guys im really new to python can anybody help me out?
!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 ^
thanks man
@lean dome umm.. what?
what's in the git log, @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"
I have no idea what that is...
thats the log.
yeah, I mean - I have no idea what that error message might mean.
I think what happened was
I tried to do a "full" commit but literally wrote the word full somewhere and f'd everyhing up
is there a full/ directory in the repo?
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
Guys can you help me with a thing
How do i make an operating system withpython?
I mean using pythkn
Python
How do i make an operating system withpython?
@fiery cosmos you can't.
You probably can make OS with any programming language, but why?
there's a python-based os already
@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
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.
Im assuming were making a list that contains ints
nums.sort()
and what does -> mean?
That's the return type of the function
It returns an integer
In Java it would be public int singleNumber(...
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?
can somebody help me with it
!rule 5
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.
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
go ahead and ask your problem so someone could take a look and see
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
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
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?
Im using json
Okay
or any other NoSQL database
Thanks
ok so can u share your json structure?
ok, post it here and ping me
I most likely won't be able to help but somebody else likely will
When i can i will do, thanks alot
👍
@tardy drift This channel (and this server) is not for dumping random reddit links, please don't do this
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.
I think it might be n log n. The inner loop is doubling each time
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.)
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?
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)
Why is Bubble sort is considered less efficient than insertion sort and selection sort, even though they have the same running time complexity?
You'd have to look at average complexity
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
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
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.
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')]
`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?
Anyone here understands the theory of pushdown automatas?
@frank vessel a bit rusty, but yes.
` 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
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:
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 intois key(A)<key(B) ?.
Now, you don't seem to get lambda functions : they're just a quicker way to write functions, instead of writingdef key(x) : return value, you writekey = 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).
Hi guys I'm having trouble with this question. Can you guys pls help? Thank you
Semi colon idk
@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?
Hello there, can someone help me understand why C.f(n) should upper bound T(n)?
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
@exotic hatch makes sense, thanks for the info!
👍
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
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)
`
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
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 withis_dir
!pep 471
I'm aware of scandir, however scandir is actually slower due to the complexity of the objects it returns
did you benchmark it?
np, sometimes if you do additional checks within scandir or listdir, the complexity of the check may be the bottleneck instead
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
lo
Hello, does anybody is familiar with Hoare's logic ?
just looked up hoares logic O.O
ping me when you get back im going on an errand run
@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 *
Hey guys, anyone can share some good resources to learn Graph DS ?
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)
you dont even need threading
asyncio is perfect for this
with asyncio.sleep or asyncio.wait_for(..., timeout=)
ok! I'll give a look on that! Thx!!
https://runestone.academy/runestone/books/published/pythonds/index.html
@fiery cosmos It's a decent resource for learning data structures and algorithims in Python
An interactive version of Problem Solving with Algorithms and Data Structures using Python.
thank you!
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
^+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
hello sir I am a new learner of python so can you please help me learning it
I want to master python
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
ok thank you sir
If you need any pointers on where to start, as far as I know there's this page:
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
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
sir I'm a 13 year old child and does'nt have any experience of python so how
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
Based on your age though you might also like to do some Minecraft hacking with this book:
https://www.amazon.com/Learn-Program-Minecraft-Transform-Python/dp/1593276702
I don't know of any good free resources on the topic, but if you need some I could help you finding something
Also you might get interested with game development with PyGame. A good point to start is https://realpython.com/pygame-a-primer/
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
@restive vale maybe Pendulum
well, Python's time.strftime will do the job as well, I think, as long as you know the input date's format
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...
@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
So it's just because that's the use of it?
People don't want hash functions to be reversible?
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
Thank you
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
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
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
unless there is some kind redundancy/repetition/pattern
which is usually not the case after using a hash function
Yeah, if you do not need to be able to store every 128byte string, you can obviously use fewer bytes
@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.
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
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.
.help
#❓|how-to-get-help maybe?
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
@fiery cosmos Django is a web framework. you use it to build web applications
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?
@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
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)
Are you familiar with limits?
what are those
limits of a function. If you don't know them it's ok 🙂 No need to bother with them
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^^
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.
@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```
@eager hamlet I hope you know that this skips the 1st 11 lines of the file
for _ in range(11):
next(f)
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
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
OCTONIONS
🐙
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
@runic kestrel I can give it a shot
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
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.
yes, though it sounds pedantic to stress this.
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.
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
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
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
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.
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
https://twitter.com/larsonc_/status/1274027680195805184?s=20 To those that want to get more involved in computer science
Are you a maintainer of an open source project? Or do you work at a tech company and you strive to learn and teach others?
Join us here: https://t.co/TlQ39Hc9BH
Application: https://t.co/ReMgv2V1rY
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
Use any tree to create a tree
Nd as everything in python is an object u can have them. Point to a single child
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.
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?
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.
Oh, okay, so it would just be \x01 for above. Thanks for the explanation :D
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.
👍
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.
Ah, that makes sense, one more thing, how come you are doing 0b<bits>?
That is the python syntax for base2 int literals
!e
print(0b00001111)
@lean dome :white_check_mark: Your eval job has completed with return code 0.
15
can someone suggest me some resource to learn Tkinter and GUI with pytho?
thanks in advance
You are not allowed to use that command here. Please use the #bot-commands channel instead.
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
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.
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
true, my "every 3 letter word" example requires https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement
!e
You are not allowed to use that command here. Please use the #bot-commands channel instead.
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 ?
easiest would be using networkx draw features
@mint jewel yeah just heard about it. Also, do you know about pydot3 and graphviz ?
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 ?
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 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
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 leetcode is similar
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.
@exotic hatch @last blaze what about edabit?
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!
What is the total size of the grid and the starting position?
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
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 ?
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)…
In the x axis alone it would be [-7, 7] because it's 15x15 around the current position
right you are ^^
Here's a nice read I've just found on the probability of a sum of random variables
https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter7.pdf
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
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
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
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
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 
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.
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
No. Of its just summing consecutive numbers, the time complexity is o(n**2)
Huh
Right, factorial is multiplication, not addition
Would this second one have better average big-O notation tho? Or the same one?
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}")
Pretty sure this doesn't belong here, as it's a strict coding question, regarding a 3rd party lib
or maybe it does, idk
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}")
@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)
Hmm, right. Yeah, I am aware that O(1) can mean it'll take an hour to complete, even tho it's constant
Was just wondering if it'd be faster overall.
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.
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 
https://docs.python.org/3/library/decimal.html
can anyone explain how does printing decimal of a list of price values in two decimal point work in python 3.8?
First, are you aware about limitations of floating point?
If not, this will help. https://docs.python.org/3/tutorial/floatingpoint.html
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
i think he wants to use Decimal class
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
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'
im tryna install pygame on my macbook using terminal but it just gives me an error
anyone care to help pls 🙏
thx
im tryna install pygame on my macbook using terminal but it just gives me an error
@whole ingot same
@summer reef Can you say that for and while function like AND in a logical operation and if, else function as an OR ??
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)
@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
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
also, the parameter is called values and the iterable you use for looping over is called value
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 ^^
Fair enough. If it's a deliberate choice, then sure
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?
Anybody know of an ILP for TSP that utilizes the fact that the shortest distance from i to j is (i,j)
@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
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
Basically, you can uninstall it if you're the only one using your system
@shy
Just uninstall
is it possibe to add music in python with a pakage?
anyone know a good place to learn algorithms and databases in python?
like Heaps, AVL tree, Dijkstra, searches, dynamic programming, topological sort etc...
Define a place. A book? a course? some kind of simulations?
Are you using something already?
is it possibe to add music in python with a pakage?
@tiny dew
Pygame has it, I belive
anyone know a good place to learn algorithms and databases in python?
@open bloom
There's a good course in the pins
@last blaze thank you so much!
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 🤔
I'd recommand 16Gb of RAM, you'll be able to use your laptop much longer. 256Gb seems enough, SSD would be a must.
8 is probably fine, 16 is awesome 🙂
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 😄
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
just pick what u can afford i doubt u will write a programm in uni which takes more than 8gb of ram^^
That was my point, better spend a bit more today and not having to buy a new laptop at the end of uni
!off-topic
Off-topic channels
There are three off-topic channels:
• #ot0-psvm’s-eternal-disapproval
• #ot1-perplexing-regexing
• #ot2-never-nester’s-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Can anyone help me finding my error in my implementation of Dijkstras, I tried following Wikipedia's pseudocode
So I have followed Wikipedia's pseudocode for Dijkstra's algorithm as well as Brilliants. https://en.wikipedia.org/wiki/Dijkstra's_algorithm#Pseudocode https://brilliant.org/wiki/dijkstras-short-...
Thanks for all the input!
guys
i need a help
do you know about selenium?
This isn't the right channel. Claim an available help channel #❓|how-to-get-help @waxen meadow
which func do we have to use to use get_string
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?
what's u v
its a thing
ok that's just x y for some reason, looked it up
yeah
hmm
so like naively, you could rotate the whole thing so that x y coincides with u v
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
this is what ive come up so far:
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
i don;t know
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!
@pale ginkgo any for loop can be written as a while loop, just go with whatever looks cleaner
@quasi oracle Nice, thanks!
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?
hi
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
Hey
Shallow Learning ??? Why don't we see it in such diagrams ?
But we do see Deep Learning.
Deep learning is a buzzword. It means your model has a lot of parameters (layers and nodes)
So what is Shallow Learning ? It gives results on searches.
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"
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.
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
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
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
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
A search out of a given set of possible results?
You could start by creating a function to measure the distance between two phrases
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...
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...
Ooh
that looks rather interesting
I shall check it out
Ive got this so far
with the search term being assassin its not too bad
Anybody has experience with CSS?
@tropic dawn you will have better luck in #web-development, this is a channel for computer science
Lol I didn’t notice that thanks
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 😄
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
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
There's that one https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/
how can I open BIOS in SONY VAIO
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! 😄
@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
Thanks!
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?
yeah
use the convert method ; your image is RGBA, you want it RGB.
img_noalpha = img.convert("RGB")
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
how can i read all text in a screen shot ?
In the case of fourier transformation i would guess make the array the length of the powers of 2
like 1024 or 512
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
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
how can I open BIOS in SONY VAIO
@still crystal try holding the delete key on boot
Hey guys ik this is a python server but i have a quick basic c question if anyone can help pls
try the offtopic room
anyone know good sources I can learn backend development with Python?
!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
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Thank you!
@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
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
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
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.
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!
Can anyone help simplify this into one gate?
You should write the truth table of this set of gate and see if that correspond to any existing gate
You can also infer what the final gate is just by thinking about what this collection of gates does together
i would write out the truth table for it and then make a k-map to simplify down the logic
TIL k-map, thanks
does anyone have experience with object tracking? specifically noisy bounding polygons
@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?
what do you mean by that?
@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.
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
I see
I can't think of anything like that. It might be just less convenient in matlab
Matlab can call C libraries, so I would say it can have the same effects as python can.
Here is the research paper by Sir Turing himself, if you are interested by the concept of Turing completeness I'd highly recommend you to read it, it is really interesting https://www.cs.virginia.edu/~robins/Turing_Paper_1936.pdf
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))
You are not allowed to use that command here. Please use the #bot-commands channel instead.
kek
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()
It sounds like you want a timedelta
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
not really, it would fit better in a help channel
have you read #❓|how-to-get-help
yeah
this isn't really computer science specific
?
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
@dapper sinew take a look at #❓|how-to-get-help. This channel is for computer science.
kk
does anyone know how to make python print elements that are common in a list?
@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
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.
guys where can i go to practice requests?
The Python module requests?
Yea
I'd like practice too
@blissful wedge @crude glacier that's a question for #web-development
Really? @oblique panther
yeah, that doesn't fall under computer science per se.
Wow
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.
what state of the art algorithms?
Just reticulating some splines, right?
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?
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?
Using a global variable like I did, does work. But it seems to me it is bad practice and should be avoided
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)
nonlocal count
...
salt, will what I wrote not work? 😮
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!
>>> 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
>>>
😮
Oh yes I got the same, that's what I thought would happen.
precede the count += 1 line with nonlocal count
np
nonlocal is a keyword?
yeye
as bad as global?
global and nonlocal let you play with the scope of stuff
hehe
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
does it just elevate by one scope?
yep
what if you're a few levels deep? can you stack it?
i don't think so

well, you might be able to declare nonlocal in each function
similar to how you cant stack break or continue 😦
Sounds like it would be a headache inducing code to read anyways