#algos-and-data-structs
1 messages · Page 78 of 1
two elements with the largest possible shortest path between them?
@last blaze No that would be the longest path in the graph. I want to find the longest path for a given vertex, X
So from vertex X to the furthest vertex away from it
well, how are you defining distance?
The number of edges that we have to travel
Sounds like you're describing something kinda like the traveling salesman then, where you're trying to visit every edge in the graph but also ending at the target node
I'm probably dumb - but the phrasing/presentation of the problem doesn't make sense to me
But do we really know what that target node is (the furthest node) when we start moving around the graph
distances d(x, y)```
If this makes more sense ^
So we have to find the 'length' which is the largest
from X to any other node
@last blaze
with a tree, I think the problem is slightly different
I'm not sure exactly how you'd do it, but its eems to me the nodes you're lookign for are something like the nodes with the greatest total distance between their first common root if that makes sense
i linked it above @sturdy prairie
you're looking for the eccentricity of a node
you can view the source of networkx's algorithm
it simply looks at the shortest path distance to all nodes and picks the longest
it simply looks at the shortest path distance to all nodes and picks the longest
just a quick questin regarding xor
print(1 ^ 1 ^ 1 ^ 1 ^ 1)```
here i always thought that if we exclusively get 1 th output should be 0
however, i have since remembered that there is another rule to xor which states that if the amount of 1's is odd then the output should be 1, am i right?
if the amount of 1's is even then 0 in this case
just apply them one after the other, what do you get? 1 ^ 1 -> 0; then 0 ^ 1 -> gets you 1… etc
the rule you are talking about is directly derived from this
yes, the rule seems correct, i just tend to think thinking of it as a rule rather than a simple deduction of the underlying principle is not that useful.
hi. does anyone know of a scientific way to measure/represent randomness via an online graph?
I don't even know how to define randomness
I'm pretty sure there's some way to define entropy, can't remember how off the top of my head
as a crude proxy you could feed it into an advanced compression algorithm and see how compressible it is - pure noise will be very hard to compress
there's a program called "ent" that roughly guess how much entropy a file has -- https://www.fourmilab.ch/random/
ENT: A Pseudorandom Number Sequence Test Program
scipy.stats has an entropy function
Sorry for asking stupid question ( I'm just a newbie) : What Cicada 3301 actually is ?
Has anyone here gone through the Princeton “Algorithms” course?
@orchid walrus https://en.wikipedia.org/wiki/Cicada_3301
seems to be some weird ARG
No one does
hey guys I'm new to discord, ive been struggling alot to find any platform online that can answer questions i have as i continue my learning in python. Ive just started as at u of t working on a CS major and im trying to build a stong foundation of knowledge
if this isnt the right place to ask these questions it would be great if you could point me to the right place
Hey @short pier!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
does anyone have experience with binary search tree implementation
i'm going through the Python course videos on PluralSight currently (free for the month) and am really struggling to understand Classes. Is this common or am i just dense? any other recommended free videos/resources for me to get this fundamental concept? I've watched the pluralsight videos twice now, and paused/rewatched sections, and I'm just not getting it.
have you ever worked with classes before?
no. python is my first programming language
what specifically is confusing you about classes?
if you open up your python console and type
type(3)
your return value would be
<class 'int'>
i'm getting hung up on defining classes. maybe it's just the syntax that's confusing me
i can somewhat follow along with what they're building but would not be able ot do it on my own
here's an example where they're using self in both init and the two new functions below
okay so self represents the 'Aircraft' you are initializing
the class works with one thing at a time
so the statements in dunder init are initializing those values i pass into it?
and then i need to continue to reference them in a generic way in the other funtions by using self._model or self._registration?
the self._model and those other initialized values refer to the information for that SPECIFIC aircraft
but yes u got it
you initialize the value for that SPECIFIC aircraft when you create it
oh ok. and thats the purpose of the dunder init function.. so essentially take those values in and initialize/create those values for that specific aircraft at time of creation
yes exactly
so is it safe to assume that anything used in that class must be included in the dunder init function? i.e. i cant use self._newVariable in a fucntion unless it was first initialized in the dunder init funtion?
the init is specifically for your class attributes
you implement methods in your class like registration is a method available through the Aircraft class
i hope i was able to help!
yes, that helps a lot. thank you!
I have a problem in Complex Numbers....
What's the problem?
I am trying to solve for Arc Sine (Z), using a formula, I only have logarithmic formula as a reference so far
Here's an example: ArcSine(0.4+0.7i) = 0.32746 + 0.684553i
how is that calculated?
I am trying to interpret that, in purely algebraic form.
that is to say, using Ln(z), and mul(Z), etc.... which are routines I have.
remind me, i*z is not conjugate, but what is it called?
-ilog((ia) + sqrt(1-a*a)) okay, Octave says this works.
def __delete__(self, item: Any) -> None:
"""Remove *one* occurrence of <item> from this BST.
Do nothing if <item> is not in the BST.
"""
if self.is_empty():
pass
elif self._root == item:
self.delete_root()
elif item < self._root:
self._left.__delete__(item)
else:
self._right.__delete__(item)
def delete_root(self) -> None:
"""Remove the root of this tree.
Precondition: this tree is *non-empty*.
"""
if self._left.is_empty() and self._right.is_empty():
self._root = None
self._left = None
self._right = None
elif self._left.is_empty():
self._root = self._right._root
self._left = self._right._left
self._right = self._right._right
elif self._right.is_empty():
self._root = self._left._root
self._left = self._left._left
self._right = self._left._right
else:
self._root = self._left.extract_max()
def extract_max(self) -> object:
"""Remove and return the maximum item stored in this tree.
Precondition: this tree is *non-empty*.
"""
if self._right.is_empty():
max_item = self._root
self._root = self._left._root
self._left = self._left._left
self._right = self._left._right
return max_item
else:
return self._right.extract_max()
tree = BinarySearchTree(10)
tree.insert(9)
tree.insert(12)
print(tree.__contains__(12))
tree.insert(11)
tree.insert(14)
tree.__delete__(12)
tree.__contains__(12)
this is my bst implementation as well as my test
when i run my test i get this assertion error
if self._left.is_empty() and self._right.is_empty():
AttributeError: 'int' object has no attribute 'is_empty'```
PLEASE GOD SOMEONE TELL ME WHY i have put this question on 5 websites and no one will answer my question
and when i check the type(self._left) and type(self._right) in the console it says they are BinarySearchTree objects, not ints
in this case it would be type(tree._left) and type(tree._right)
you haven't posted the complete code, so I can't run it
I'd simply print(self._left, self._right) just before the failing line
also I have the vague sense that it's a bad idea to write your own __delete__ and __contains__, although I can't tell you why
they are directly from my professor which is why i am confused
its too long to send all at one but one sec
self._root = self._left.extract_max() looks like you're assigning an int to the root
this is one of those cases where a statically-typed language would help
the last part is meant to reassign the root value when the deletion has happened, extract_max() should be returning the node that the new root should be
what is the type of self._root supposed to be?
Is it supposed to be a tree, or the stored object?
from __future__ import annotations
from typing import Any, List, Optional, Tuple
class BinarySearchTree:
# === Representation Invariants ===
# - If _root is None, then so are _left and _right.
# This represents an empty BST.
# - If _root is not None, then _left and _right are BinarySearchTrees.
# - (BST Property) All items in _left are <= _root,
# and all items in _right are >= _root.
# The item stored at the root of the tree, or None if the tree is empty.
_root: Optional[Any]
# The left subtree, or None if the tree
_left: Optional[BinarySearchTree]
# The right subtree, or None if the tree
_right: Optional[BinarySearchTree]
def __init__(self, root: Optional[Any]) -> None:
"""Initialize a new BST containing only the given root value.
If <root> is None, initialize an empty BST.
"""
if root is None:
self._root = None
self._left = None
self._right = None
else:
self._root = root
self._left = BinarySearchTree(None)
self._right = BinarySearchTree(None)
hm, _root is a misleading name. I'd have called it item or payload or something
this is just how my professor teaches it
item would represent the item you want to delete
a _root may carry that value
if it does you want to delete
def is_empty(self) -> bool:
"""Return whether this BST is empty.
"""
return self._root is None
def __contains__(self, item: Any) -> bool:
"""Return whether <item> is in this BST.
"""
if self.is_empty():
return False
elif item == self._root:
return True
elif item < self._root:
return item in self._left # or, self._left.__contains__(item)
else:
return item in self._right # or, self._right.__contains__(item)```
these are my other methods and they work fine
"""Insert <item> into this BST, maintaining the BST property.
Do not change positions of any other nodes.
>>> bst = BinarySearchTree(10)
>>> bst.insert(3)
>>> bst.insert(20)
>>> bst._root
10
>>> bst._left._root
3
>>> bst._right._root
20
"""
if self._root is None:
self._root = item
elif item < self._root:
if self._left is None:
self._left = item
else:
self._left.insert(item)
else:
if self._right is None:
self._right = item
else:
self._right.insert(item)
but for some reason the same calls are creating an error in the deletion implementation
in insert I see self._left = item
you're assigning what I assume is an integer to self._left
and yet I'm pretty sure that should be a tree not an integer
you're using type annotations, but it seems you've never run mypy; I just did and it's full of errors
Well, my Complex # project works now... How about that. Things we learn.
mypy is why you have those -> Any and similar notations
it sanity checks you -- makes sure you're not e.g. assigning an int to a variable that's supposed to hold a tree 🙂
💐
!close
not really - mypy checks them but type annotations can be used with many other tools
really? What other tools?
huh, didn't know that
typehints make pycharm much nicer to use
mypy is the best though
I do know that pycharm does type checking about 1000 times better than my kludged-up emacs+lsp 😦
those annotations are a pain unless you add them from the beginning
so i installed the mypy package
if i import it at the top of my code does it do it automatically or do i have to put it in a if name==main
no you don't need to import anything
just run mypy while inside your package and it does checking for you
alright so i got that working
so my code works but these are the mypy errors
is there a way i can make sense of these? also shouldnt all these errors mean that my code probably wouldnt run properly and gice me my return values?
I think it's complaining that you haven't handled the None case. But it's not clear
ugh i just don't get how i can be getting so many errors when this is literally code from the professors textbook
heh
are you assuming your professor's texbook code is perfect 
In heapsort, why start with the half of the array and go down to make a max heap?
for(int i = arr.length / 2 - 1; i >= 0; i--) {
heapify(arr, arr.length, i);
}
aka, how does this code work
RE: earlier discussion on mypy.
mypy is for static type analysis. It is a great tool, but it is extremely opinionated and doesn't support various things out of the box (yet?) (example, higher ordered generics https://github.com/python/typing/issues/548)
If your code uses duck typing, dynamic reassignment including with types, monkeypatching of methods, or assumes things about branches which is always true for your inputs, but may not actually handle a case which could occur, then mypy will point that out (and complain about it)
I think bronco is being bitten by that last one
"I know I said Optional[Frotz] but at this spot in the code it's clearly not None"
I think you can use https://docs.python.org/3/library/typing.html#typing.cast in that case
Yo Scott...
Do you know which hash function python actually use under the hood?
@north zealot I think this has a lot of information: https://effbot.org/zone/python-hash.htm
Pretty cool link, thanks!
you may want to be careful about posting people's emails @fiery cosmos
(not sure -- maybe they're public anyway)
your righttt let me delete it and put tests XD
Hey everyone :)
I want to make each dictionary in this list as an instance of the class user can someone help me? haven't used classes before...
lstAttributes = [{'color': '#C12424', 'dbname': 'test1dbname test1lastdbname', 'login': 'test1.test1@test.com', 'name': 'test1name test1lastname'}, {'color': '#C12424', 'dbname': 'test2dbname test2lastdbname', 'login': 'test2.test1@test.com', 'name': 'test2name test2lastname'}, {'color': '#C12424', 'dbname': 'test3dbname test3lastdbname', 'login': 'test3.test1@test.com', 'name': 'test3name test3lastname'}]
class Users:
def __init__(self, color, dbname,login, name):
self.color = color
self.dbname = dbname
self.login = login
self.name = name
i think i fixed it now... sorry about this very new to programming
class Data:
def __init__(self, a, b):
self.a = a
self.b = b
l = [{'a': "value a", 'b': "value b"}, {'a': "other value", 'b': "something else"}]
instances = [Data(atr_values['a'], atr_values['b']) for atr_values in l]
instances
Out[19]: [<__main__.Data at 0x2cfee1fe630>, <__main__.Data at 0x2cfee1fed30>]```
a bit confused but let me try using this...
you can also use a normal for loop
class Data:
def __init__(self, a, b):
self.a = a
self.b = b
l = [{'a': "value a", 'b': "value b"}, {'a': "other value", 'b': "something else"}]
instances = []
for values in l:
instance = Data(values['a'], values['b'])
instances.append(instance)
o thank god XD sorry' i'm not advanced enough to understand them one liners
haha thats fine
thanks so much Leterax.... a lot of my co workers went on something called furlough so they can't work... so i got stuck making this script even though i am literally a beginner
what does this do?
so instead of
instance = Data(values['a'], values['b'])
you have
instance = Data(**values)
it used the values dict as keyword arguments
so if the dict is {'key1': value1, 'key2': value2}
if calls the function Data like this:
Data(key1=value1, key2=value2)
that ofc only works if its expecting a argument called key1 and key2
o thats fab! yeah they keys are constant through all users
yup 🙂
if the names match up this is a bit nicer
if your data class had different names for its args than your dict you would have to use the other code
i see thanks for letting me know,
not gonna lie this whole script is a mess right now not even sure if I'm doing it right XD
haha
one step at a time i guess
yup!
I need to convert a XML into a pdf using python
this is just one step of parsing the stupid xml file
Hey, going back to this. how would I be able to find the instance using the instance attribute? for example if i have the instance attribute Steve how would i know it will be in the instance instances[2]?
my Goal is to use one instance attribute to find the instance and return another instance attribute of that instance.
for index, instance in enumerate(instances):
if instance.name == "Steve":
return index
thats if you want the index
if you just want the instance:
for instance in instances:
if instance.name == "Steve":
return instance```
you amazing human....
you could also use filter
list(filter(lambda user: user.name=="Steve", users))
filter takes a function and a iterable
it will return a generator that yields all elements for which the function returns true
so in this case the function returns true if the name is "Steve"
and then convert to a list because we dont need a generator
chose one of the options you like best 🙂
omg it worksssssss this is so amazinggg 😭
both workss
how can you just do this on the spot mannn
practice
I should really stop playing animal crossing....
hah
if b, e, and n are given, how can i figure out if b**e > n without calculating it
im trying to make a failsafe so it doesnt try to calculate this b**e if it will be larger than e.g. 2^64
see if (e * log(b)) > log(n)
if b and n are integers, and you don't mind an approximate answer, you might be able to save some zorkmids by using the bit length of b and n instead of their logarithm -- those values are pretty similar
yeah I wasn't thinking it was euler's number
it doesn't matter
I think if b is > 0 you're fine
otoh I don't think calculating b**e is going to be particularly expensive. Are you doing this a zillion times in a loop or something?
then you get a domain error
heheh
yeah
i figure i can just use abs of everything since i only care about magnitude
def safe_pow(a, b, log2n=64.):
"""don't allow a^b if it would be over a 64bit int."""
# a^b > n -> (b * log(a)) > log(n)
if (abs(b) * math.log2(abs(a))) > log2n:
raise ValueError
return pow(a, b)```
you can use the complex log
In [393]: cmath.log(-2)
Out[393]: (0.6931471805599453+3.141592653589793j)
i got pi
lol
an imaginary pi
delicious
should get pi for every negative number
In [396]: cmath.log(-3)
Out[396]: (1.0986122886681098+3.141592653589793j)
In [397]: cmath.log(-5)
Out[397]: (1.6094379124341003+3.141592653589793j)
ha, i remember something
that's the angle of the number
hello if I have a solution for a leetcode problem could I post my python code here and and ask what the big-o is and if it is optimal? Or is there a better channel/server for that?
That'd probably be ok for here
Okay awesome well here is the question https://leetcode.com/discuss/interview-question/542597/ and here is my code https://leetcode.com/playground/7JHSxm68
Basically I think my time complexity is O(MNlog(k)) but I'm not sure if that is the most optimal solution or if there is a better way to do this. Any advice would be greatly appreciated I've been trying to figure this out for so long
Can anyone point me in the right direction for a good website to get professionally recognized certificates from? Professional grade courses, I mean.
Hi all! Incoming volunteer opportunity (pre-approved post):
This volunteer opportunity is for software engineers or others in the tech industry who know how to code and are interested in teaching!
TEALS is a Microsoft Philanthropies program that trains high school teachers to code and teach CS and builds up CS pathways at local schools. We do this by creating teaching teams of industry professionals who help support the teacher in the classroom as they build up their ability to teach the course. We are currently looking for volunteers interested in supporting schools across the US and in BC, Canada.
Our application to be a volunteer for the 2020-21 school year is open now! You can find the application here: https://www.microsoft.com/en-us/teals
I’m biased, but it really is an awesome program. Plus one of the languages we help teach is Python!
Feel free to ping me if you have any questions.
For the record the above post was approved by me, no need to pings mods or whatnot 👌
TEALs
can i post my python scripts here?
hey guys
a bit of an architectural question:
does anyone has any idea how does instagram does the simulation of comments for recorded live videos? like if u go to a recorded live video and seek to any particular time, the comments at that time will come in view
im trying to find what is the best way to do that
and how do i cache the data efficiently?
so that i dont fetch again if user seeks to that particular time again?
so i have a problem and would like to develop a efficient (!) algorithm to solve it. how do i go about this?
i've tried my naive aproach but that grew exponentially with n...
got very slow very fast..
I've just bought this book about algorithm design that was suggest in the pytricks book, maybe it has some valuable information in there http://www.algorist.com/
have you read it?
Skiena is very useful. Think CLRS but organized more as an minimum viable intro + a reference. Both are more accessible compared to CLRS, though if you want deep enough detail for some referenced algos, you have to look elsewhere. Basically, if CLRS is the book a strong student wants at uni, Skiena is a fundamentals algo book you want on your work desk, if for no other reason than the well-organized reference, or to quickly understand the very basics of an area new to you.
Hey guys, I have a quick question. When I create objects they get assigned a memory adress and we can print it with object.data. For example we get <memory at 0x000001E69C17C520>. Is there any way I can print out the exact bits/bytes that are stored at this memory adress or any adress in general?
probably not easily, and it'd be a bad idea if you could
I wonder what class of object that is, that has a data attribute? I don't think python itself puts that attribute there
hm it worked for a numpy array so it probably is a np thing then, but you can still get object adresses for any object. Why would it be a bad Idea if you could?
hello maby this isn t the right channel to ask but can someone tell me a project idea in python to use oop, i m new in oop
@past lava model a customer record using a class
Hey I have a general CS/DEV question. Is there a rule of thumb of when to combine 2 functions that do similar, but different things into one function?
Like if 40% of the code is the same, is it worth it to make the extra effort to merge it into one flexible function? Or keep them seperate?
I don't have a rule of thumb honestly
I will often not do it if it's just two functions, but if there's three then I grit my teeth and do it.
But it depends on how much code is shared, and how nasty it is.
ultimately refactoring has both costs and benefits, you will eventually get a feel for both
@violet gust 
Thanks 🙂
i personally came across this issue in a project of mine that i'm currently working on. i had two functions: one which would send a command to a device and then read a response, and one which would send a command to a device with additional data, without expecting a response. to avoid writing very similar code between these, i made a helper function that just sent a command to a device with additional data if it was given any, and then it would return a response if it got one. the other two functions could then use that helper function separately and would provide additional data or handle a response in their own ways if necessary. @violet gust
it does depend on a case-by-case basis. generally speaking, if parts of your code are repeated at all, it's best to put them in a function so that you only have to modify one area, rather than having to edit the many reoccurrences if you spot any amendments that have to be made, among many other reasons. you may or may not be familiar with this already, but it's still important to keep in mind.
Kobutsu: I think it depends on a couple of things.
For example, what language are you writing in?
Are you planning on using “decorators”? If so, then compiled language like Haskell or C should be good to go because of how fast they are
A compiler can really aggressively optimize your code in a variety of ways. Inlining, for example
Interpreted languages might face a slow down if you try to use decorators though. Using a function as a parameter could potentially mean having to jump around looking for that function every time it’s called
I think it also depends heavily on what you’re writing. If you're working on a game, my understanding is that nothing matters as much as speed and so it may be worth it to copy a bit of code in order to avoid the possible slow down
A few kB of wasted memory on a hard drive is nothing, but even one ms can be a lot for calculating things in a timely manner
But if you're writing a library for a set of data structures that all share some property (let's say traversal), then it's kind of dumb to write a traversal function for each one when just one is necessary
You also have to consider the paradigm that you’re using. I think OOP has a bunch of best practices for how to deal with all the crazy inheritance stuff, but there's no inheritance in functional programming (in the same sense as OOP)
My recent (and limited) experience with OOP has made me not want to share functions anywhere unless the things being touched were 100% guaranteed to be the same everywhere
(But that might be because I no longer really know C++)
Whereas with functional languages, I think it’d be dumb not to combine and remove as much duplication as possible
Hi I have an issue with coding a piece of logic can i post here?
Hey guys, I have a problem and made a little Wetransfer link isolating the part of the program I'm stuck with https://we.tl/t-nazp00aUn3.
I'm trying to parse a XML file using python but having problems with parsing a child tag in a parent tag putting them in an Object in python. I've made an txt file explaining it more.
Are you using Beautiful Soup?
nope I've kinda just lxml import etree
`data = "test.xml"
tree = etree.parse(data)
lstTag = []
lstTagText = []
lstAttributes = []
for p in tree.iter():
lstTag.append(tree.getpath(p).replace("/", ".")[1:])
lstTagText.append(p.text)
lstAttributes.append(p.attrib)`
Tagtext
My professor suggested that i add functions to my rock,paper,scissors program. Do you guys have any suggestions has to where i could add more. https://github.com/geoccifer/RockPaperScissors
Combine ```
Display what the player chose:
Display what the computer chose:``` into one function
# Display and record the win/loss/tie:
Turn that into a function
if you assign numeric values to rock paper and scissors you can eliminate all the conditionals
and just use arithmetic to find the outcome
from random import randint
user = "rsp".find(input("Choose rock[r], paper[p], or scissors[s]: "))
computer = randint(0, 2)
print(f"The computer chose {('rock', 'scissors', 'paper')[computer]}.")
print(("It's a draw!", "You lose!", "You win!")[user - computer])
@stable pecan I've thought about that, but can't figure out how to make < and > work
why do you need < and >
I dunno
we just take advantage of the negative indexing
i think he may be gone anyway
well I'm confident he won't understand it, and I'm itching to show it off 🙂
import itertools
names = ['rock', 'paper', 'scissors']
def rps(him, me):
assert him in names
assert me in names
thing = itertools.cycle(names)
while c := next(thing) != him:
pass
if next(thing) == me:
return False
elif next(thing) == me:
return True
raise Exception('wtf')
seems a crime not to use a cycle
all the assertions and the exception are irksome though
I guess the last clause should be "tie", and not "wtf"
return next(thing) != me
🤔
you assign to c but don't use it
this is similar to my solution though, i'm basically using modular arithmetic, which is just a cycle
so, like minds
genius
print(("It's a draw!", "You lose!", "You win!")[user - computer]) is just fun to do
oooh I didn't even realize that's where the logic was
do you have a Lisp background? 🙂
ok you win, yours is cleaner by far
i've played with lisp in the past, but i wouldn't say i have a background in it
i would say that i use arrays a ton though
referencing the tuple like that just seems like a lispy thing to do
so indexing like this is something i'm used to
someone once asked for ways to flip a boolean without using logical operators
so i gave them:
b = 0
b = (1, 0)[b]
b = (1, 0)[b]
A boolean value or boolean type? :Kappa:
heh, you're hard-core
you could define all the logical operators with arrays
Terrible
and_ = lambda p, q: [[0, 0], [0, 1]][p][q]
i have my own
https://coq.inria.fr/library/Coq.Init.Logic.html
That's how you define logic
Anything different is a crime
In [101]: tt = TruthTable('p and (~q or (p and r))', 'p or (q and r)', '(p or q) and (p or r)')
In [102]: tt.display()
┌───┬───┬───┬─────────────────────────┬────────────────┬───────────────────────┐
│ p │ q │ r │ p and (~q or (p and r)) │ p or (q and r) │ (p or q) and (p or r) │
├───┼───┼───┼─────────────────────────┼────────────────┼───────────────────────┤
│ F │ F │ F │ F │ F │ F │
│ F │ F │ T │ F │ F │ F │
│ F │ T │ F │ F │ F │ F │
│ F │ T │ T │ F │ T │ T │
│ T │ F │ F │ T │ T │ T │
│ T │ F │ T │ T │ T │ T │
│ T │ T │ F │ F │ T │ T │
│ T │ T │ T │ T │ T │ T │
└───┴───┴───┴─────────────────────────┴────────────────┴───────────────────────┘
(I'm just joking, I've seen your stuff and it's pretty cool)
i just watched a beazly talk on his SLY parser and now i want to do something similar as well
😫 😫 🤯
so if the length of the list is 10, its range(10-1, 0, -1) so it will return the indexs for range(10) in reverse (9,8,7,6,5,4,3,2,1)
tbh i prefer counting up and then reversing. more readable imo
It would hurt memory for very large loops though
I'm implementing BFS and DFS algorithm. Anyone has the .py or .ipynb file? Share me pls
Hey @distant glacier!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @distant glacier!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @distant glacier!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @distant glacier!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
so i gave them:
b = 0 b = (1, 0)[b] b = (1, 0)[b]
@stable pecan That's pretty cool. I would just go for b = 1 - b
Hello guys i need help with creating a program that returns the circuit of an undirected Euler's graph
@fiery cosmos What do you need help with specifically?
An undirected edge is just two directed edges going both ways
There might be a simpler solution, but that's how you would use the link on an undirected graph
guys, can a flow chart's decision entitiy only have one branch?
do you think I will be able to learn this without much knowledge of python
@tight pier we don't have much information to go on: we don't know what course it is, and we don't know what you already know. Why ask a Python discord about a C++ course? 🙂
@tight pier
1: this is a python discord server not a general programming/c++ server
2. You didn't give us any extra details on the course
3. Python isn't "a must learn" as a programming beginner, some people thinks it's a weak programming language because it has easy syntax but that's because they're brainwashed like I was in the beginning...
Python can do many things. If you're learning it to be able to learn other languages then I should tell you that you don't need to learn it.
@tight pier unless you're a prodigy, you probably will find it extremely hard to understand c++ for your first language
I think if you learn C++ that will keep you a better pathway to learning others (OOP languages)
give*
that was my first language
I would still work my way up from a more simple language like python or javascript
I wouldn't recommend C++ to start though; it's a very complicated language
but there's a school of thought that you should start with a language that is useful too, so C++ is fine if you agree with that
@tight pier my personal recommendation is that you start by copying from other people, now i know people are going to be like, oh you need to write your own code, but I did the same, and learnt c# in 2 months, as my first language, then python was a piece of cake, if i were you i would start with a mid tier language (something like c#), not quite c++. c# tutorials are a great way to start, i learnt by downloading a ps3 black ops 2 cheat (pc executable) and modify it. Also, you can only truly learn something if you have a need to learn it (from my experience)
https://paste.pythondiscord.com/ekejatunac.py
@distant glacier 👍
https://paste.pythondiscord.com/kukodarafo.py
@distant glacier 👍 Thank you, you save my life
Hi guys!
I’m pretty new to Python and overall just coding, and I have a school assignment to do (creating a simple game). I’m pretty sure I’ve fulfilled all the requirements that the school has given on the assignment brief, but I would like to ask for a code review to make sure that everything’s efficient and short.
Would anyone want to review my code?
sure
i would be happy to
is it the dice one? for the NEA? (just curiosity, and also because i kind of have the ultimate one)
Would JavaScript be a better path to learning c++ than python
The best way to learn C++ is to dive into C++, unfortunately
Neither python / javascript can help you get into C++
brings back memories of me being 18 and having "introduction to programming 1" class
The pointers, you won't see them anywhere else. So your best bet is just dive into it
No, I started with JavaScript and it is an easy way to get into C++
similar syntax
and it has the curly braces
when writing statements
Once you know how to program, different syntax won't be what'll stop you

Greetings, is there a channel for python xlib? I use a translator
5000 numbers are being input which should have either 1 digit (e.g. 5), 2 digits (e.g. 36), 3 digits (e.g. 149) or 4 digits (e.g. 8567). Write an algorithm, using pseudocode, which inputs 5000 numbers outputs how many numbers had 1 digit, 2 digits, 3 digits and 4 digits outputs the % of numbers input which were outside the range.
help please
Hey @plucky turret!
It looks like you tried to attach file type(s) that we do not allow (.docx). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .md.
Feel free to ask in #community-meta if you think this is a mistake.
Hey @edgy plover ! I tried the question you gave in here. I don't know how to send you the pseudo code though. I can't upload a .docx file here. 😕
- convert numbers to a string
- get length of string
- keep track of the count of the strings in a hashmap, using the length as key.
- do any calculations needed
or hack you can even use an array to count the occurrences, with the number at the i-th index representing the count of i-digit numbers
Hey guys I am newbie to programing and python and I have finished python but still learning and I am about to finish selenium can anyone help what was your path what I should do and not etc for beginner
Thank youuu
is there a way to get the return of a nested function without initiating the parent function?
no the nested function is only visible inside the parent function
If you really need to use the nested function, you should either move it out of its parent function or make it a class
ok thanks 🙂
Hi there. I have good experience in web development (php, js, frontend). Just start to learn python because it very useful in AI & machine lerning technologies. Can someone help me to understand what exactly I need to know in python for I can continue the next steps?
for python you need to know the basics: vairables, classes, scopes, control flow, common built-in data structures. and a couple packages: numpy, scipy.
and you need to brush up on linear algebra and calculus
ok, thanks
right mate so here is the int
011100100110010111110011
in decimal its :7497203
now here is the question
What pair of single precision floating point numbers could be represented by these 24-bits
what could i do to find 2 numbers out of one lol
i understand that we can have 2 decimal places as to give a float to the exponent, the significant and mantissa
but
i dont understand man
a quick answer will help out alot for reference
hmmm, do you have any examples?
most examples are given in either 32bit or 8 bit
they have a totally different solving method compared to 24-bit int
if you cant help its okay this is really difficult
this is actually interesting
I found a question which is exactly the same as yours
.....\
I don't actually understand what's happening though... 🤔
or where the formula significand * (2 ** (exponent - 15)) / (2 ** 6) is coming from
. Apply NB classifier on the data
(https://www.dropbox.com/s/ru76l3hoxmw521j/crash_car.csv?dl=1). Use "Damage" as y and choose x by yourself. Discuss the analysis
results.
can anyone explain that to me?
how to get 'submit' button using django in our website
@tough widget what u want to understand about this??
well I've written what i think should run it but my sklearn import doesnt work properly so idk
@simple echo tried troubleshooting with sklearn and no luck. If someone could try to run my code and see if it works that would be great lol
would this be the correct way to add two arrays together in python?
from numpy import *
arr1 = array([1,2,3,4])
arr2 = array([2,4,6,8])
for i in range(1):
arr3=arr1[0:5]+arr2[0:5]
print(arr3)
print('Goodbye')```
no, you can just do
arr3 = arr1+arr2
hi i wanted to know where i could find syntax for win32api for python
specifically im looking for getkeystate and general keyboard press detection
its alright figured it out XD
im pretty new to python and coding in general and finished my first project, i wanted to start getting more into dictionaries so are there any beginner friendly projects that might use dictionaries that anyone might recommend?
i don't think that is the correct way to think.. u can check a tutorial about dictionaries.. dictionaries are a tool in the lang.. u should pick a project and think how u will use the lang tools to solve the problems facing you in this project..
@runic crest
hello, i'm fairly new with python and need help
i need to make a code that adds up all the denomination from pennies to 100$ bill
for example:
How many PENNIES do you have? 1
How many NICKELS do you have? 2
How many DIMES do you have? 3
How many QUARTERS do you have? 4
How many $1 BILLS do you have? 5
How many $5 BILLS do you have? 6
How many $10 BILLS do you have? 7
How many $20 BILLS do you have? 8
How many $50 BILLS do you have? 9
How many $100 BILLS do you have? 10
You have $1716.41 in total.
the user should only be entering integers
What about it are you struggling with?
Are you familiar with dictionaries?
What about lists?
yeah i know how to do that
Okay
i was doing this
totalmoney = [2, 4, 7, 12, 3]
totalsum = sum(totalmoney)
print sum(totalmoney)
but idk how to make it so it's set to like 0.01 for pennies
denominations = ['pennies', 'nickels', ..., '$100 bills'] # Fill in the rest
values = [1, 5, ..., 10000] # Fill in the rest
amounts = []
for i in range(len(denominations)):
amount = int(input(f'How many {denominations[i]} do you have? '))
value = amount * values[i]
amounts.append(amount)
print(sum(amounts))```
also i forgot to account for the values lol
oh
amounts.append(int(input('How many {denom} do you have? ')))
so for that
would i just change the denom to like pennies
ohh
so what is the f used for in line 6 by the input
The f at the start of the string (stands for format) does something called string interpolation, it automatically inserts the value of denominations[i]
i get a parseerror: bad input on line 6
In generally if you put an f at the start of the string, you can put variables into it by surrounding them with brackets

?
i might've written it wrong
it might just be that python mini doesn't have string interpolation
denominations = ['pennies', 'nickels', ..., '$100 bills'] # Fill in the rest
values = [1, 5, ..., 10000] # Fill in the rest
amounts = []
for i in range(len(denominations)):
amount = int(input('How many ' + denominations[i] + ' do you have? '))
value = amount * values[i]
amounts.append(value)
print(sum(amounts))```
If so, that would fix it
how weird
but it doesn't add the pennies
oh i accidentally appended amount instead of value
it gives me a solid number, not a 111.(this)
i think you forgot to put the . for the pennies
so it's printing out like this "10006" instead of "100.06"
oh
yeah it gives you the amount in cents
I trust you know enough about string manipulation and arithmetic to do that part yourself
what r some projects i can do as a beginner
i want to clone an py repo, and use conda as a venv, should i clone it directly at the venv?
hahaha
hi so idk what channel to put this in but basically I want to create a script where there is a variable x that is set to 0 by default, but when you hold down left click, it sets it to 1, and when you release the click it goes back to 0. How would i do this, also what modules do i need to import for this to work
Is there a constant time algorithm to find n choose k modulo 3?
I have found an O(log n) algorithm through intense staring at Pascal's triangle but it is not enough for my application:
def choose_mod_3(n, k):
if k < 0 or k > n:
return 0
elif n == k == 0:
return 1
elif n % 3 == 0:
return choose_mod_3(n // 3, k // 3) if k % 3 == 0 else 0
else:
return (choose_mod_3(n - 1, k - 1) + choose_mod_3(n - 1, k)) % 3
i can't think of a wy to do that because n choose k can't be constant time from my understanding because you need to find n! and k! which are both O(n) operations so if there is a way of doing so you will need to find a way around finding n choose k with the usual formula
My function above is O(log n)
There is a lot of information coded in pascal's triangle related to modulo 3. The blue numbers are all multiple of 3.
No wait
They're not
Let me find the true picture
Hmmm
i know what it looks like i made a programme to generate the patterns
i just wasn't aware of any other ways of finding n choose k other than n! / ((n-r)! * r!)
this pattern right?
Yep
Oh there isn't, apart from building Pascal's triangle from scratch. But I don't need n choose k, just n choose k modulo 3
Just like I don't need to calculate the square of 9274267145715741 to know that it is equal to 1 mod 2
so your trying to work out the patterns of each % remainder, sounds interesting
Spent a lot of time on it
It is related to this problem: https://www.codewars.com/kata/5a331ea7ee1aae8f24000175/train/python
Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.
that actually looks really interesting, i might give it a go later
@stable pecan Thanks!
should be close to log n with that
or somewhere between logn and n if i was guessing
My modulo is constant so that should be constant, right?
the product of binomial coefficients is pretty cheap to compute for small primes as each m_k and n_k is less than p
so really the complexity grows with the length of the base-p representation of the number
which is log n
Implemented it and the constants are a little bit worse than my previous solution sadly (despite implementing n<3 choose k<3 as an array CHOOSE = [[1, 0, 0], [1, 1, 0], [1, 2, 1]])
did you try it for large n
Yep, the tests are massive
CHOOSE = [[1, 0, 0], [1, 1, 0], [1, 2, 1]]
def choose_mod_3(n, k):
prod = 1
while n > 0 and k > 0:
prod *= CHOOSE[n%3][k%3]
n //= 3
k //= 3
return prod % 3
do you short circuit if one of the terms is 0
Ooooh, smart
you can reduce the product by % 3 every iteration so it doesn't get large
you can also divmod in one operation
The (very unlikely) maximum would be 2 ** log3(100000) ~= 5000
Will do
I confirm that it is slower to take the mod every time
i blame python ints
because in c you could use a uint8
Somehow using divmod is slower than taking the two separately, weird
Very small speed up indeed
Or not at all, in fact
def choose_mod_3(n, k):
prod = 1
while n and k and prod:
n, nd = divmod(n, 3)
k, kd = divmod(k, 3)
prod *= CHOOSE[nd][kd]
return prod % 3
like this?
I tried to speed it up by using a bit shift to multiply by two and to do nothing when the coefficient is 1 but it is slower too:
CHOOSE = [[1, 0, 0], [1, 1, 0], [1, 2, 1]]
def choose_mod_3(n, k):
# Lucas Theorem
prod = 1
while n > 0 and k > 0:
mult = CHOOSE[n%3][k%3]
if mult == 0:
return 0
elif mult == 2:
prod <<= 1
n //= 3
k //= 3
return prod % 3
you could memoize divmod
I don't think it will improve the result by much () but worth a try
Fastest code so far by removing the "el" from the elif and using while n and k (thanks)
i sure do love a speed challenge!
this would be easy to cythonize
could someone give me the link to the og message? i cant find it 😦
oh, are these coefficients properly matched
@stable pecan https://stackoverflow.com/questions/30079879/is-divmod-faster-than-using-the-and-operators
divmod is indeed slower than // followed by %
@gusty grove Are you asking for the message that started the conversation? It was at 12:34
thanks
Can't use Cython in the codewars interface
divmod is a function, sure it is slower
from numpy import base_repr
from math import prod
CHOOSE = ((1, 0, 0), (1, 1, 0), (1, 2, 1))
def choose_mod_3(n, k, p):
n = base_repr(n, p)
k = base_repr(k, p, padding=len(n))
return prod(CHOOSE[n_][k_] for n_, k_ in zip(n, k)) % 3
wait, i switched the padding
Fastest code so far
CHOOSE = [[1, 0, 0], [1, 1, 0], [1, 2, 1]]
def choose_mod_3(n, k):
# Lucas Theorem
prod = 1
while prod and n and k:
prod *= CHOOSE[n%3][k%3]
n //= 3
k //= 3
return prod % 3
prod is more likely to short-circuit first than n and k
from numpy import base_repr
from math import prod
CHOOSE = ((1, 0, 0), (1, 1, 0), (1, 2, 1))
def choose_mod_3(n, k, p):
k = base_repr(k, p)
n = base_repr(n, p, padding=len(k))
return prod(CHOOSE[n_][k_] for n_, k_ in zip(n, k)) % 3
is this the right way
i'm tired
one of those paddings
oh, forgot to convert to int
The first one seemed good
don't live code
base_repr is much slower than doing the work manually (and being able to short-circuit)
well, dunno, numpy is implemented in c
I'll try to optimize the other half of the program
so it gets to use the small ints
but you have to make sure your timeit isn't including the import
It includes it only once for the 300 tests
And the difference was about 4 seconds
So not the reason
don't you still need to compute base_repr so that you can match coefficients
i mean if k is 4 digits and n is 8 digits, you need to pad
wait no you don't
this generates digits in reverse order
told you i'm tired
Yeah that's the funny thing. Numpy probably reverses the digits in its function and it makes our lives harder
you could try a dict look up for CHOOSE instead of tuple of tuples
i dunno if that's better
probably the same-ish?
I just removed CHOOSE entirely and got better results :
@lru_cache(None)
def choose_mod_3(n, k):
prod = 1
while prod and k and n:
ni = n % 3
ki = k % 3
prod *= (ni >= ki) + (ni == 2 and ki == 1)
n //= 3
k //= 3
return prod```
Oh wait no, that was actually slower
Don't know the order of the numbers
With a hash function and everything, it's probably slower with a dict
maybe, but python dicts are fast
but hard to beat a small tuple
CHOOSE = {(0, 0): 1,
(1, 0): 1,
(2, 0): 1,
(0, 1): 0,
(1, 1): 1,
(2, 1): 2,
(0, 2): 0,
(1, 2): 0,
(2, 2): 1}
still you could try it
well i can't think of any other speedups
Same, I don't think Lucas Theorem is going to cut it
Back to recursive solutions
There are some nice patterns
For n = 81 (or any power of 3, really):
81 choose 0 = 1
81 choose 1..80 = 0
81 choose 81 = 1
well, there's nice patterns for all of them
Don't know
you can get there from the chaos game too
from random import choice
import numpy as np
import matplotlib.pyplot as plt
PHI = (1 + 5**.5) / 2
def make_base(n=3):
base = []
arc = 2 * np.pi / n
for i in range(n):
theta = i * arc
base.append([np.sin(theta), np.cos(theta)])
return base
def chaos_game(*, force_new_corner=False, niter=10000, base_points=3, ratio=.5):
previous = None
xs, ys = [], []
base = make_base(base_points)
point = np.array([1, 1])
for _ in range(niter):
if force_new_corner:
while True:
corner = choice(base)
if corner != previous:
break
previous = corner
else:
corner = choice(base)
point = x, y = point - (point - corner) * ratio
xs.append(x)
ys.append(y)
plt.scatter(xs, ys, s=1)
plt.show()
if __name__ == "__main__":
chaos_game()
chaos_game(base_points=5, ratio=1/PHI)
TypeError: unsupported operand type(s) for -: 'tuple' and 'list'
remove that errant comma
works
point was supposed to be a numpy array not a tuple
@gusty grove i made a numpy sudoku solver you might like
i've never understood how those work
do they just test stuff recursively?
or is there a smart way to do it
yeah, simple recursive solution
with backtracking
import numpy as np
grid = np.array([[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]])
@np.vectorize
def possible(y, x, n):
"""Return True if a cell can take the value n"""
gx = x - x%3
gy = y - y%3
return not ((grid[y, :] == n).any() or (grid[:, x] == n).any() or (grid[gy: gy + 3, gx: gx + 3] == n).any())
ns = np.arange(1, 10)
def solve():
for y, x in np.argwhere(grid == 0):
for n in np.argwhere(possible(y, x, ns)).flatten() + 1:
grid[y, x] = n
solve()
grid[y, x] = 0
return
print(grid)
Apparently you can also use a* to solve sudokus. Don't understand how though
that looks deceivingly simple
but then you see stuff like return not ((grid[y, :] == n).any() or (grid[:, x] == n).any() or (grid[gy: gy + 3, gx: gx + 3] == n).any())
and then you realize its magic
that just checks row, column and box for the number
a bit obfuscated, i had 3 separate conditionals at one point
@stable pecan We didn't have to check n > 0, since n is always greater than k
TypeError: unsupported operand type(s) for +: 'int' and 'str'```
we don't talk about that
Hi, I've read this article about backpropagation in convolutional layers: https://medium.com/@2017csm1006/forward-and-backpropagation-in-convolutional-neural-network-4dfa96d7b37e.
How does it work for calculating the gradients of the biases?
Hello, I was wondering if anyone has any experience with spatial data processing, and how to implement?
(continued from #user-interfaces ) Well pretty much, originally I just had one audio file on loop and it got very annoying, so I thought of adding more than one audio file, however I realized that if the same music is playing in the same way every time, it would still be annoying, so I thought about doing it randomly. However, making the order of the audio and which audio files to play random turns out to be harder than it originally sounded unless FFmpeg has a tag for random files in a loop which I've just not found out yet. Since it's going to be complicated anyways, I thought it would make sense to tackle another harder-sounding problem I was having before which was the audio cutting off halfway through at the end of the video, but if finding the closest match is such a complicated problem in itself, I'm not sure if it's worth bothering for now
i'd say you could probably do ok just selecting random files until the total duration is over the required, and then remove the last few files and try to find a closer match just from the end
this way you get random sounding, and you can get reasonably close to the end
and it's not so complicated to implement
or just fade the composite file out at the exact duration of the video.
Feels sensible that since I've moved channel, to redescribe my issue. This time I'm just going to plainly say exactly what I'm trying to do instead of going into how I've tried to tackle it already and why I've ended up with this issue. I have a ton of music files, all different lengths, and I have a video file, always a different length. I would like to add the music in such a way that it matches the length of the video as closely as possible. I cannot hardcode the lengths of the music files since they are subject to change and the user also has the ability to change them. Is there an FFmpeg tag for such a thing and if not, I need to get the lengths of the video and audio files and I need to know how to find the best combination of the audio lengths to the video length
Since the video length is always going to be quite a lot different each time the program is run, finding the closest match should make a different combination every time meaning that it'll do what I was looking for in the first place anyways, meaning no need to add noise to the 'closest match' to make it random-sounding, if that's what you're inferring
well, what if it selects the same audio file multiple times in a row because the duration matches exactly
Which should I learn first?
C++ or Python?
Python lol
is Python better than C++?
And the chances of that happening are so slim that if it were to happen, it would still be different to the last combination meaning it wouldn't be as monotone anymore, anyways
While arguably C++ can do more than Python in a more optimal way, Python is a lot easier to learn and can do close enough to everything that C++ can do
is Python better than C++?
@finite coral
are screwdrivers better than hammers? is milk better than orange juice? yes. no. it depends.
this question isn't really suitable for this channel, though.
Oh and salt, you're inferring that randomness would be any better. If it's random, the audio is still just as likely to be the same file every time
you can design around that to prevent repeats.
the standard library has several tools for shuffling and rotating a list of items, for example.
so you could just shuffle your list of files and rotate through it.
That's the problem though- with this, yes, there is a ton of things that could possibly go wrong, and while they would be slightly inconvenient, solving all of them means more designing around needed making things more and more complicated. I feel like it's not worth it to go into details on all of these since they're not likely to happen, anyways
i mean i have a knapsack function somewhere if you want to use that
but you have to integerize all the durations
If we were going to go that technical, anyways, you'd argue that playing different music every time could be annoying aswell if they liked the music meaning that the only solution is to make an AI that learns how humans best like mixes of music to be formatted and use the AI to form the best combination which obviously isn't the optimal solution and not really worth it haha
def knapsack(cap, weight, P, n):
arr = [[0 for i in range(cap+1)] for j in range(n+1)]
for i in range(n+1):
for j in range(cap+1):
if (i == 0) or (j == 0):
arr[i][j] = 0
elif weight[i-1] <= j:
arr[i][j] = max((P[i-1] + arr[i-1][j-weight[i-1]]), arr[i-1][j])
else:
arr[i][j] = arr[i-1][j]
return arr, arr[n][cap]
import numpy as np
def knapsack2(values, weights, capacity, n_items):
table = np.zeros((n_items + 1, capacity + 1))
for i, (weight, value) in enumerate(zip(weights, values)):
table[i + 1, :weight] = table[i, :weight]
new = table[i, :-weight] + value
old = table[i, weight:]
table[i + 1, weight:] = np.where(new > old, new, old)
return table[-1, -1]
two versions
I don't even know what knapsack is ;-;
https://en.wikipedia.org/wiki/Knapsack_problem --- the subset sum problem is just an instance of the knapsack problem
where values == weights
Welp I've got to go now 😕 I'll come back to this problem later. It's an interesting problem, though!
Well i am gonna create a web app that can take data from csv files, xml, or json and have the data be outputted into a map. It would show up on the map as either points.
the parenthetical values are the heuristic distances
and im suppose to find the A* search
So I believe the decision tree would be
- S - starting point
SA = 15 / SC = 15 / SB = 13 - Thus we choose SB because its the shortest distance, next:
SBC = 13 + 10 = 23- This is the only choice, next:
SBCD = 23 + 3 = 26 / SBCG = 23 + 12 = 35 / SBCE = 23 + 13 - Thus we choose SB because its the shortest distance, next:
SBCDG = 23 + 10 = 33. The decision tree is done and this is the path selected.
This is correct right? The only thing i'm not sure about is if on step 3 if SBCG is selected because the goal node is reached even tho SBCD contains a shorter path? Any help would be appreciated.
Alright, so the date for the event I was making the video generator for is happening soon today instead of tomorrow so I'm not going to have time to love further into audio.
I'll likely look into it for next week's event, though!
can someone help me? I have a question about binary search tree
class Node:
def init(self,key):
self.left = None
self.right = None
self.val = key
def insert(root,node):
if root is None:
root = node
else:
if root.val < node.val:
if root.right is None:
root.right = node
else:
insert(root.right, node)
else:
if root.left is None:
root.left = node
else:
insert(root.left, node)
def inorder(root):
** if root: **
inorder(root.left)
print(root.val)
inorder(root.right)
I don't get "if root" mean here
id guess here that its checking if its a root right
if not it should be a None and it doesnt print
and it continues to recusively call until your done
i believe it should be root is not None
because oyu want to test object identity correcT?
thanks very much.
: )
def foo(array):
sum = 0
product = 1for i in array: sum += i for i in array: product *= i return f"{sum} | {product}"print(foo([1, 2, 3, 4, 5]))
What is the runtime of this code?
It is the first example of the Cracking the Coding Interview book.
In the book, it says its runtime is O(N). It didn't make sense.
o(n)
wouldnt it be O(2n) because you do the loop 2x and then you can leave the constant away?
That's what i thought too.
because its still linear so its O(n)
that's also valid
just a guess btw, i have no idea what im talking about
no
you have to leave constants away
because you are just interested in how it scales
not the actual values
you get O(n) with either approach
I'm sorry but i didn't get it. There are two loops.
yeah, but you have to drop the 2 eventually since it's constant
you can go 2N -> N, or pick the dominant one immediately
@gusty grove I think you do know
hehe thanks, im not taking any cs courses so this is all just from watching this channel 😉
@stable pecan @quick tapir
if i understand the problem correctly its finding songs that match in length to a video.
why dont you try this:
def find_combinations(numbers: list, desired: int, max_deviance: float) -> list:
"""Find all combinations of numbers that has sum equal to the desired amount."""
results = []
def _inner(current: list, leftover: list):
"""Recursively get a new number."""
if sum(current) > desired + max_deviance*len(current):
#print(f"{current}'s sum surpassed our limit")
pass
elif desired - max_deviance*len(current) < sum(current) < desired + max_deviance*len(current):
# print(f"{current}'s sum is exactly {desired}!")
results.append(current)
else:
for index, number in enumerate(leftover):
# print(f"Picking {number} out of {leftover} for {current}")
_inner(current + [number], leftover[0:index] + leftover[index+1:])
_inner([], numbers)
return results
print(find_combinations(numbers=[1.5, 2.5, 3.5, 4], desired=5, max_deviance = .5))
[[1.5, 3.5], [1.5, 4], [3.5, 1.5], [4, 1.5]]```
numbers is a list of song lengths in this case, desired is the video length and max_deviance is how much "fading" or "transition" or whatever is allowed between two songs
and then it will return all song combinations that sum to desired +- max_deviance * num_songs
@runic tinsel Got it, thanks.
Hey guys I have something like this
EventInstances = []
for x in lstTag:
if "Event" in x:
tempList = []
if "param" not in x:
currentNumber = lstAttributes[lstTag.index(x)]
tempList.append([currentNumber])
elif 'param' in x:
currentNumber = lstAttributes[lstTag.index(x)]
tempList.append([currentNumber])
EventAttributes.append(tempList)```
I want to to do is if it has param in x append it to the last list
!codeblock
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
• These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
It would be better if you could activate the highlighting of the syntax 😉
Easier to review
did i not??
o i get you!
it's not letting me because its around 4000 characters with the list included
Hey @fiery cosmos!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
here is a snippet though https://paste.pythondiscord.com/zeruroboci.py
I'm pretty sure that your soup elements are not being garbage collected because of how you're recursively calling monitor. Try putting the function in a while loop with a status code representing success.
then break on that conditional
why are you asking here
is it? i've had several thousand node graphs in networkx
graph_tool uses c types, and would use less memory if you have enormous graphs
seems doable in networkx, but networkx is kinda chunky
oh, graph drawing algotihms are notoriously slow, i wouldn't try it for such large graphs
you can try force atlas
using 100% memory
https://github.com/bhargavchippada/forceatlas2 this may be able to do it
just another layout algorithm
you can use that for your pos=
it can handle larger graphs
oh, i don't think he implemented it for directed graphs
maybe graphviz has something
altnatively, graph_tool may still be able to do it
this is graphics made with graph_tool
that's neural network
can i easily convert a nx graph to graph_tool?
biological one
cool!
is graph-tool out for 3.7?
hmm, i can't find anyway to load from numpy array which seems odd to me, considering it returns arrays
graph-tool needs to be installed from package manager, or built from source -- it takes a lot of RAM to compile it manually though
so you can't pip it
that will convert between the two
can anyone help me with an A* search algorithm question?
worked, thank you @fair pelican !!
sooo @stable pecan how do i make cool graphs with graph-tool? 😉
ok, so now im doing this:
def draw_term_graph(terms):
# noinspection PyUnresolvedReferences
import matplotlib.pyplot as plt
import networkx as nx
from graph_tool.all import graph_draw
from networkx.drawing.nx_agraph import write_dot, graphviz_layout
g = nx.DiGraph()
for term in terms:
if term.lhs:
g.add_edge(term.lhs, term)
if term.rhs:
g.add_edge(term.rhs, term)
write_dot(g, 'test.dot')
pos = graphviz_layout(g, prog='dot')
nx.draw(g, pos, arows=True, with_labels=True)
plt.show()```
they are kinda close together but idk why
Don't know if this is best place for beginner questions, but I am trying to create a string from a function that returns 3 items, (2 numbers, and 1 alpha-numeric)... could use a little assistance please.
return function does this --> return (UTMZone, UTMEasting, UTMNorthing) I am trying to turn that into a String before it returns.
I figured it out apparently... how about that!
Surprising there isn't a "beginners corner" or something for us guys. 🙂
@stable pecan Why isn't there a "Beginners Corner" here? or where is it please?
Hi, I made a script that finds the correct "Books" for SB, a simple while loop that loopps thru the formula until hit the correct value. It works fine on my computer, but super slow on my raspberry pi, and I know why :P
SB = max(0.1, min(300, SB))
Books = 1
sb = 0.0
while sb < SB:
sb = Books ** (1/2.125) * SM * RM
Books = Books + 1
I'm horrible at math. But I think their is a way the switch the sb = Books ** (1/2.125) * SM * RM formula right? so I can just input sb to get the books, and not loop it until i find the correct value.
can we have a look at the question you are trying to solve if it's an algo question
Not a algo question, just a math formula I try to find a better way of solving.
Maybe I'm in the wrong place 😛
Was looking for somewhere for math newbies 🙂
so SB = 10000 ** (1/2.125) * .156 is 11.89. If I have 11.89, how do I switch the formula around to find 10000 ?
Now I just loop that number and +1 until I hit that number, which work, but seems really brutforce, and it shows when I trying to run it on a raspberry pi 😛
oh, thanks, I was thinking sqrt or something 😛
SB/0.156 = x ** (1/2.125)
Is “The art of electronics” good to learn electronics if I have zero knowledge in electronics? I thinking about to learn electronics + C
In back propagation in convolutional layer, does the stride is the same stride as the forward propagation or always a stride of 1?
IBM will start to offer free COBOL courses if anyone's interested
i've been thinking about at least learning the basics, just for curiosity sakes, i've not heard it was fun or anything, but i do wonder what it looks like, and it could be a good retirement plan if it's still around in 20-30 years 😄
anyone interested in a python implementation of Conway's Surreal numbers:
In [61]: zero = Number()
In [62]: print(zero)
{|}
In [63]: one = Number(L={zero})
In [64]: print(one)
{{|}|}
In [65]: one > zero
Out[65]: True
In [66]: zero > one
Out[66]: False
In [67]: m_one = Number(R={zero})
In [68]: m_one > one
Out[68]: False
In [69]: one > m_one
Out[69]: True
In [70]: one + m_one
Out[70]: Number({{|{|}}}, {{{|}|}})
In [71]: alt_zero = one + m_one
In [72]: alt_zero == zero
Out[72]: True
well, at least 1 - 1 == 0
so we got that
If you're whole year depends on this then we probably can't help you with it, and we definitely wont do it all for you.
If you need help with something specific, or a particular concept then we can help
@river citrus your whole year?! woah. thats a pretty simple assignment. what do they mean by "if you solve with a function definition you will get extra credits"?
have you learned about for loops?
I have this function that given 2 rectangles (coordinates of lower left square and right upper square) checks if they are intersecting, and if so, gives me the area of the intersection, but the code I made doesn't work, since there's no dinstiction between "lower" 5 or "upper" 5.
As in , the code https://bpaste.net/CWYQ doesn't work for this https://imgur.com/a/7xrWHoo.
It's supposed to give me the coordinates of 6,5,6,5, since it's lower and upper bound are the same. BUT since it's the same it skips it
Any ideas?
So, A is 5, B is 4, and so on and so forth.
It's checking if the most lower left point of a rectangle(in this case, a square) is lower than the right most point of another.
But there's no descrampancy between "upper" 5 and lower" 5, it's just 5
It's supposed to return the area of intersection
so, 1
but it returns 0, since it claims there is no intersection
Maybe I'm just thinking too much inside the literal box
i think the if statement might only need two >=
the other two are just >
lemme test this
yeah I just drew it on paper and placed the values in
(E>=C) or (F>=D) these two are triggering True since they're both equal
i think they should be (E>C) or (F>D)
Let's see
Aight, it works 😄
Let's hope it just works for bigger cases when I test it after lunch
Thanks for the help Salami 🙂
actually
that might not be the problem
return (tr_x - bl_x)+1 * (tr_y - bl_y)+1 you're multiplying 1 with (tr_y - bl_y) here instead
which just becomes (tr_x - bl_x) + (tr_y - bl_y) + 1
Ah I see what you mean
It's still sadly not working.
I mean, my problem IS fixed
but some new rose up
Fixed ^-^
hi
if all files open with latin1 encoding, but only some open with utf8, is it safe to use latin1 across all? Or could i lose information for the files which utf8 worked with
idk if this is computer science or not tbh, font encoding? 🤔
you may indeed lose information
utf8 can encode pretty much any character -- hundreds of thousands of them
latin1 can encode exactly 256
since 100,000 > 256, there are plenty of characters that cannot be encoded in latin1
any of these e.g. 你好, 早晨, こんにちは, 안녕하세요
How to learn to make algorithms, does math increase ones ability in solving problem?
@desert cliff yes it does.
is just high school math enough for easy and intermediate problems or the more the better?
When it comes to knowledge, the more is always the better
Is this statement accurate in context of RT(Random Tree) and RRT(Rapidly exploring Random tree) planning algorithms? RT selects a node at random from the tree and adds an edge in a random direction, but an RRT first selects a goal point, then tries to add an edge from the closest node in the tree toward the goal point.
not a python question, but why does this always work? The problem is to find the non-unique number in an array where numbers occur twice except for one.
I can picture the bitwise operations in my mind and see how the solution always comes to the correct one but I'm lost on why. It seems like magic
maybe it's because each of the numbers that occur twice light its respective bits both on and off (just now thought of this)
so all that is left is the lonely number
yeah, nevermind. I think I figured it out as I typed in the question.
Can you have an O(n) runtime sorting algorithm if you're willing to have a high space complexity?
I'd guess so
if you're sorting integers, e.g., allocate a list of booleans that can hold as many elements as the largest integer, then for each item in your sequence, flip the corresponding boolean to True, then traverse the list from start to finish and report the indices of the True elements
import random
sort_me = random.choices(range(1000), k=100)
largest_item = max(sort_me)
bools = [False for _ in range(largest_item + 1)]
for elt in sort_me:
bools[elt] = True
sorted = []
for index, elt in enumerate(bools):
if elt:
sorted.append(index)
print(sorted)
@oblique panther 
@stark bridge 
🤷
Someone suggest me a good source to learn OOP concepts in python. I understand Classes, decorators etc but don't understand inheritance and stuff like that much
there's many resources provided from this community: https://pythondiscord.com/pages/resources/
you could choose which way you'd prefer to learn and go from there
We're a large, friendly community focused around the Python programming language. Our community is open to those who wish to learn the language, as well as those looking to help others.
I have a server, 2vCores, 8GBRam, / 80 GB ssd dont know what to do with it. Help ? any ideas? tag me
Use it for science? Like proteins folding
Can you have a dual boot setup insiden of a vm?
e.g. Ubuntu and Arch or Windows on the same virtual hard drive?
@fiery cosmos https://foldingathome.org/
does anyone here have knowledge on the A* algorithm
here's a good article about A* https://www.redblobgames.com/pathfinding/a-star/introduction.html
sorry if i'm posting in the wrong thread
We've annotated heads and lips in video for some machine learning task. I've made a short script that will "extract" the annotated areas and store them as new images. Now, the need has arisen to only have heads that are facing the camera (i.e. you can actually see the face). The solution we've come up with is to see whether within the head area there exists a lips annotation.
The way I do the extraction is with opencv, which reads each frame into a numpy array and I "crop" it using list comprehension using the x,y,h,w from the annotations. crop_img = img[y:y+h, x:x+w]
One way might be to see if x_lips, y_lips are somewhere within the x_head+w_head, y_head+h_head area, but there are case where even tho there are lips, the x,y of the lips box was outside of the head box.
So I was thinking that since every sub-array comes from the same image, it must have some common elements. Would there be some way to check if a numpy array partially contains another?
Any idea on why my BFS algorithm is only going one vertice in a random direction, despite the input graph having way more?
Not without seeing the code
yes that works but if its an argument in a function, like this:
def myfunc(*args):
mylist = list(args)
print(mylist)
myfunc((1, 2, 3))
it prints: [(1, 2, 3)]
That's normal
You pass the argument (1, 2, 3)
But, you use a wildcard argument
So args became ((1, 2, 3), )
Then, when you pass it to the list constructor like this list(((1, 2, 3), ))
So the constructor unpack the first one element tuple, and construct the list
so I have to unpack it twice?
Yes, either in the list() call, or in the myfunc() call
Unpacking in myfunc() would make the most sense, or simply remove the wildcard argument
Sure, you reconstruct the list twice
The second list() call doesn't do anything, you gave it a list already
(well, actually it is creating a duplicate)
uhh so i have to pass a list in the argument instead?
def myfunc(args):
mylist = args
print(mylist)
myfunc(list((1, 2, 3)))
this worked
def myfunc(arg):
mylist = list(arg)
print(mylist)
myfunc((1, 2, 3))```This should work too
I am working on minCostpath problem using dynamic programming
import copy
a = [
[1,3,1],
[1,5,1],
[4,2,1],
]
# dp = [[0 for x in range(len(a[0]))] for x in range(len(a))] #Method 1
dp = copy.copy(a) #Method 2
for i in range(len(a)):
print(a[i])
for i in range(len(a)):
print(dp[i])
for i in range(len(a)):
for j in range(len(a[0])):
# dp[i][j] += a[i][j] #Uncomment this if using method 1
if (i > 0 and j > 0):
dp[i][j] += min(dp[i-1][j],dp[i][j-1])
elif i > 0:
dp[i][j] += dp[i-1][j]
elif j > 0:
dp[i][j] += dp[i][j - 1]
# print(a[i])
# print(dp[i])
print('After finding minCost')
for i in range(len(a)):
print(a[i])
for i in range(len(a)):
print(dp[i])```
I am getting correct answer when I used both method but grid array gets changed when using deep copy method. Can anyone tell me why is that so?
@lofty forum @tribal pendant I don’t know how to do folding at home on Ubuntu w no gui, and also would it help w anything it’s only 2vcores it’s smallest server
There are other services that use the same system
fishnet is a good open source that aims to use computers to freely analyse chess games
Would this channel be the right one to ask about some issues related to programming language design? 
probably
Okay so, I'm designing a language with a pretty high level of abstraction, in the same (but less violent) fashion than python. This language should be capable of abstracting memory management and pointers so the programmer doesn't have to deal with all those things. The issue that I have, is that you can assume that realloc, the memory relocating method can be called on any objects at any moment. But, this function is meant to increase or decrease the amount of memory allocated to this object. The way the buddy block memory design works (the one that I'll be using) doesn't move the objects if it is in the first half of the block, but it does if it is in the second half. My issue is about keeping pointers in sync. What design does languages usually use to deal with that, to make sure that the pointer is still linked even if the object move? Thanks for your help 
god I have no idea
that's waaay above my pay grade
read the python source, see what they do shrug
They are the same thing
Ugh a lot? Algebra, linear algebra, discrete math, statistics, number theory,
The list goes on
read the python source, see what they do shrug
@stark bridge python actually use dicts under the hood, they map the name to the memory address, so you only need to update the address in one place, but it makes resolving a name really slow
@fiery cosmos What do you by 'master algorithms'?
How can I make a program that create a new paste on the desktop? It should work on windows and unix too
How can i get the directory to do that?
I found an answer https://stackoverflow.com/questions/13741873/how-to-get-users-desktop-path-in-python-independent-of-language-install-linux
alright... i got a few questions regarding computer vision..so was hoping someone could help me out with that... first question is about masks (opencv). Let me explain a bit about my project... so i am attempting to use live / real-time detection (using mss to screenshot & crop the monitor) and apply object detection techniques on that cropped display. One of the problems (firstmost) is masking. I have a mask that I made in gimp and was hoping to export that to opencv some-way. I am not opposed to creating a mask with another method, its just using opencv to point at each coordinate to create a polygon can be quite challenging (I think, im not 100% sure).
My next question. So I have a large image (~10,000px by ~10,000px) and I have a smaller image that i need to find within that larger image (in real-time). My thoughts were to find the image the first time (which takes awhile...) and then find my position in regards to the first position that was found. So if the smaller image is moved west by 1 pixel, it wont try and find the smaller image within the larger image again, instead, just give the results of the smaller image that was found previously in the larger image, with an updated value, lets say -1 on the X axis
anybody with mips knowledge?
So I am fairly new to Python and was hoping someone would help me out:
I have found a connect 4 template (has a grid: a-g and 1-6) annd I am trying to place tokens which I have defined but can't seem to be able to. the moves are generated from a list. e.g. ['b', 4]
in that case token 4 will be placed in B
hey everyone i am trying to scrap the information off of this website: https://www.usgovernmentspending.com/compare_state_debt
but i am quite new to web scrapping
any advice
yes, confine yourself to one channel
Do you know how I would place them?
More specifically how to place the tokens based on generated moves
dumb question and I'm not sure if it belongs here, but here goes. I need to create a jar file of a java program I have. currently to run it I would first compile it with
javac Main.java
and then to run it I would
java -cp .:./mysql-connector-java-8.0.19.jar Main
my question is how do I make my whole program into a jar file
Hey sir I want help
I have a school project due to lockdown
Built a Cloud Security with face recognition
Can please someone help me out?
none of this is related to computer science nor python
I guess we can do it python ? @feral shale
face recognition can be built with python and including cloud API? builds a complete application ?
@feral shale I thought my question was because it required knowledge of class paths and unix commands to package the final product
sorry :/
quick question environment variables and command line arguments are stored in the stack or above the stack? In gdb it seems that stack shifts because of environment variable differences but all other segments like code segment doesn't shift
so my professor wants us to do cramer's rule on python and i dont think he knows that linalg exists in numpy to calculate determinant
do you think it is cheating a bit? he didnt forbid us to use it
the right answer to these sorts of questions is almost always to ask the professor
and if he's a professor setting assignment in python - he probably knows numpy exists
nono the class is numerical analysis and my professor only started teaching with python from last year
he is mostly c++ background
but you are correct
he still almost certainly knows numpy exists
