#algos-and-data-structs

1 messages · Page 78 of 1

sturdy prairie
#

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

last blaze
#

well, how are you defining distance?

sturdy prairie
#

The number of edges that we have to travel

last blaze
#

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

sturdy prairie
#

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

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

stable pecan
#

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

sturdy prairie
#

@stable pecan how can you put it in simple algorithm?

#

Like in plain english

stable pecan
#

it simply looks at the shortest path distance to all nodes and picks the longest

waxen lotus
#

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

spiral swallow
#

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

waxen lotus
#

oh i see

#

but its essnetially correct then

spiral swallow
#

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.

waxen lotus
#

hi. does anyone know of a scientific way to measure/represent randomness via an online graph?

stark bridge
#

I don't even know how to define randomness

feral shale
#

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

stark bridge
royal kestrel
#

scipy.stats has an entropy function

orchid walrus
#

Sorry for asking stupid question ( I'm just a newbie) : What Cicada 3301 actually is ?

errant ferry
#

Has anyone here gone through the Princeton “Algorithms” course?

royal kestrel
#

Cicada 3301 is a nickname given to an organization that on three occasions has posted a set of puzzles to recruit codebreakers from the public. The first internet puzzle started on January 4, 2012 on 4chan and ran for approximately one month. A second round began one year late...

#

seems to be some weird ARG

orchid walrus
#

Hmmmm

#

IDK who's behind =/

royal kestrel
#

No one does

short pier
#

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

halcyon plankBOT
short pier
#

does anyone have experience with binary search tree implementation

edgy wren
#

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.

short pier
#

have you ever worked with classes before?

edgy wren
#

no. python is my first programming language

short pier
#

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'>
edgy wren
#

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

short pier
#

okay so self represents the 'Aircraft' you are initializing

#

the class works with one thing at a time

edgy wren
#

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?

short pier
#

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

edgy wren
#

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

short pier
#

yes exactly

edgy wren
#

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?

short pier
#

the init is specifically for your class attributes

edgy wren
#

ah ok

#

that makes sense

short pier
#

you implement methods in your class like registration is a method available through the Aircraft class

#

i hope i was able to help!

edgy wren
#

yes, that helps a lot. thank you!

short pier
#

👍

#

please if ANYONE can help me with the bst deletion implementation lmk

stuck folio
#

I have a problem in Complex Numbers....

pseudo wave
#

What's the problem?

stuck folio
#

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?

stable pecan
stuck folio
#

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.

short pier
#
 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)

stark bridge
#

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

short pier
#

they are directly from my professor which is why i am confused

#

its too long to send all at one but one sec

stark bridge
#

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

short pier
#

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

stark bridge
#

what is the type of self._root supposed to be?

#

Is it supposed to be a tree, or the stored object?

short pier
#
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)
stark bridge
#

hm, _root is a misleading name. I'd have called it item or payload or something

short pier
#

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

stark bridge
#

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

stuck folio
#

Well, my Complex # project works now... How about that. Things we learn.

short pier
#

@stark bridge that was the problem thanks so much 🙂

#

whats mypy

stark bridge
#

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

feral shale
#

not really - mypy checks them but type annotations can be used with many other tools

stark bridge
#

really? What other tools?

last blaze
#

flake8, pycharm

#

fastapi

feral shale
stark bridge
#

huh, didn't know that

last blaze
#

typehints make pycharm much nicer to use

feral shale
#

mypy is the best though

stark bridge
#

I do know that pycharm does type checking about 1000 times better than my kludged-up emacs+lsp 😦

short pier
#

using those would probable help alot

#

do you use multiple at once?

stark bridge
#

those annotations are a pain unless you add them from the beginning

short pier
#

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

feral shale
#

no you don't need to import anything

#

just run mypy while inside your package and it does checking for you

short pier
#

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?

stark bridge
#

I think it's complaining that you haven't handled the None case. But it's not clear

short pier
#

ugh i just don't get how i can be getting so many errors when this is literally code from the professors textbook

stark bridge
#

heh

feral shale
#

are you assuming your professor's texbook code is perfect lemon_smug

indigo hare
#

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

swift breach
#

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)

stark bridge
#

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"

feral shale
stuck folio
#

Yo Scott...

north zealot
#

Do you know which hash function python actually use under the hood?

keen umbra
north zealot
#

Pretty cool link, thanks!

keen umbra
#

you may want to be careful about posting people's emails @fiery cosmos

#

(not sure -- maybe they're public anyway)

fiery cosmos
#

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

gusty grove
#

could you edit that to use real '?

#

‘color' -> 'color'

#

also you are missing some ,

fiery cosmos
#

i think i fixed it now... sorry about this very new to programming

gusty grove
#
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>]```
fiery cosmos
#

a bit confused but let me try using this...

gusty grove
#

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

o thank god XD sorry' i'm not advanced enough to understand them one liners

gusty grove
#

haha thats fine

fiery cosmos
#

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

gusty grove
#

np 🙂

#

@fiery cosmos you can also do this:

l = {'a': 1, 'b': 2}
Data(**l)
fiery cosmos
#

what does this do?

gusty grove
#

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

fiery cosmos
#

o thats fab! yeah they keys are constant through all users

gusty grove
#

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

fiery cosmos
#

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

gusty grove
#

haha

fiery cosmos
#

one step at a time i guess

gusty grove
#

yup!

fiery cosmos
#

I need to convert a XML into a pdf using python

#

this is just one step of parsing the stupid xml file

fiery cosmos
#

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.

gusty grove
#
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```
fiery cosmos
#

you amazing human....

gusty grove
#

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 🙂

fiery cosmos
#

omg it worksssssss this is so amazinggg 😭

#

both workss

#

how can you just do this on the spot mannn

gusty grove
#

practice

fiery cosmos
#

I should really stop playing animal crossing....

gusty grove
#

hah

gusty grove
#

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

stark bridge
#

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

gusty grove
#

i should call e differently. i dont mean eulers number

#

just any number

stark bridge
#

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?

gusty grove
#

yeah

#

sadly

#

what if b is < 0?

stable pecan
#

then you get a domain error

gusty grove
#

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)```
stable pecan
#

you can use the complex log

#
In [393]: cmath.log(-2)
Out[393]: (0.6931471805599453+3.141592653589793j)
#

i got pi

gusty grove
#

lol

stable pecan
#

an imaginary pi

gusty grove
#

delicious

stable pecan
#

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

dusky forge
#

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?

last blaze
#

That'd probably be ok for here

dusky forge
#

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

neon tide
#

Can anyone point me in the right direction for a good website to get professionally recognized certificates from? Professional grade courses, I mean.

spring yarrow
#

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.

cursive drum
#

For the record the above post was approved by me, no need to pings mods or whatnot 👌

eternal moat
#

TEALs

warped mica
#

can i post my python scripts here?

pseudo pilot
#

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?

gusty grove
#

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

north zealot
#

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/

gusty grove
#

have you read it?

north zealot
#

Not yet

#

I just finished pytricks, I should start tonight

ionic topaz
#

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.

vale cypress
#

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?

stark bridge
#

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

vale cypress
#

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?

past lava
#

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

uncut grail
#

@past lava model a customer record using a class

violet gust
#

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?

stark bridge
#

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 this

violet gust
#

Thanks 🙂

sharp robin
#

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.

pseudo wave
#

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

modern storm
#

Hi I have an issue with coding a piece of logic can i post here?

crystal crane
#

any embedded programmers here?

#

@modern storm ofc you can post it

fiery cosmos
#

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.

pseudo wave
#

Are you using Beautiful Soup?

fiery cosmos
#

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

fiery cosmos
#

Tagtext

tawdry dragon
pseudo wave
#

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

stable pecan
#

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])
stark bridge
#

@stable pecan I've thought about that, but can't figure out how to make < and > work

stable pecan
#

why do you need < and >

stark bridge
#

I dunno

stable pecan
#

we just take advantage of the negative indexing

stark bridge
#

may I post how I did it? (i.e., is this homework)?

#

yeah it's homework 😐

stable pecan
#

i think he may be gone anyway

stark bridge
#

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"

stable pecan
#

return next(thing) != me

stark bridge
#

🤔

stable pecan
#

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

stark bridge
#

genius

stable pecan
#

print(("It's a draw!", "You lose!", "You win!")[user - computer]) is just fun to do

stark bridge
#

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

pseudo wave
#

Just one of many examples and of how math helps with programming

#

🤷

stable pecan
#

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

stark bridge
#

referencing the tuple like that just seems like a lispy thing to do

stable pecan
#

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]
pseudo wave
#

A boolean value or boolean type? :Kappa:

stable pecan
#

that is you can define a not operator with a 2-tuple

#

not_ = lambda b: (1, 0)[b]

stark bridge
#

heh, you're hard-core

stable pecan
#

you could define all the logical operators with arrays

pseudo wave
#

Terrible

stable pecan
#

and_ = lambda p, q: [[0, 0], [0, 1]][p][q]

pseudo wave
#

That's how your device booleans

stable pecan
#

i have my own

pseudo wave
#

Anything different is a crime

stable pecan
#
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           │
└───┴───┴───┴─────────────────────────┴────────────────┴───────────────────────┘
pseudo wave
#

(I'm just joking, I've seen your stuff and it's pretty cool)

stable pecan
#

i just watched a beazly talk on his SLY parser and now i want to do something similar as well

candid rivet
#

😫 😫 🤯

elfin sundial
#

hey guys can somone explain this range?

#
for k in range(len(numbers)-1,0,-1):     
fiery cosmos
#

len(numbers)-1

#

going to 1

#

stepping down

topaz pulsar
#

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)

gusty grove
#

tbh i prefer counting up and then reversing. more readable imo

north zealot
#

It would hurt memory for very large loops though

peak wigeon
#

I'm implementing BFS and DFS algorithm. Anyone has the .py or .ipynb file? Share me pls

halcyon plankBOT
quasi oracle
#

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?

quasi oracle
#

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

waxen lotus
#

guys, can a flow chart's decision entitiy only have one branch?

tight pier
#

do you think I will be able to learn this without much knowledge of python

onyx root
#

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

steel trout
#

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

steel shell
#

@tight pier unless you're a prodigy, you probably will find it extremely hard to understand c++ for your first language

restive ermine
#

I think if you learn C++ that will keep you a better pathway to learning others (OOP languages)

#

give*

#

that was my first language

steel shell
#

I would still work my way up from a more simple language like python or javascript

pseudo wave
#

What?

#

C++ is a pretty common starting language

feral shale
#

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

fiery cosmos
#

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

peak wigeon
royal quest
#

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?

fiery cosmos
#

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)

tight pier
#

Would JavaScript be a better path to learning c++ than python

leaden barn
#

The best way to learn C++ is to dive into C++, unfortunately

#

Neither python / javascript can help you get into C++

left solstice
#

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

steel trout
#

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

quasi oracle
#

Once you know how to program, different syntax won't be what'll stop you

fiery cosmos
full granite
#

Greetings, is there a channel for python xlib? I use a translator

edgy plover
#

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

halcyon plankBOT
#

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.

plucky turret
#

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

daring harbor
#
  1. convert numbers to a string
  2. get length of string
  3. keep track of the count of the strings in a hashmap, using the length as key.
  4. 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

velvet ivy
#

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

edgy plover
#

Thank youuu

frigid ice
#

is there a way to get the return of a nested function without initiating the parent function?

daring harbor
#

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

frigid ice
#

ok thanks 🙂

rain talon
#

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?

daring harbor
#

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

rain talon
#

ok, thanks

elfin sundial
#

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

verbal phoenix
#

hmmm, do you have any examples?

elfin sundial
#

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

verbal phoenix
#

this is actually interesting

#

I found a question which is exactly the same as yours

elfin sundial
#

.....\

verbal phoenix
#

I don't actually understand what's happening though... 🤔

verbal phoenix
#

or where the formula significand * (2 ** (exponent - 15)) / (2 ** 6) is coming from

tough widget
#

can anyone explain that to me?

simple echo
#

how to get 'submit' button using django in our website

#

@tough widget what u want to understand about this??

tough widget
#

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

simple echo
#

i have seen yours. it's all mixed xD

#

i think u have check ur coding'

rose canyon
#

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')```
gusty grove
#

no, you can just do
arr3 = arr1+arr2

rose canyon
#

oh

#

ok

frail wedge
#

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

runic crest
#

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?

cobalt violet
#

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

fiery cosmos
#

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

valid anvil
#

What about it are you struggling with?

fiery cosmos
#

i do not know how to do it

#

i know how to do inputs and turn them into ints

valid anvil
#

Are you familiar with dictionaries?

fiery cosmos
#

not really

#

im really new to python

#

and I need help with this for school

valid anvil
#

What about lists?

fiery cosmos
#

yeah i know how to do that

valid anvil
#

Okay

fiery cosmos
#

i was doing this

#

totalmoney = [2, 4, 7, 12, 3]
totalsum = sum(totalmoney)

print sum(totalmoney)

valid anvil
#

yeah that's a good base

#

I would do something like this;

fiery cosmos
#

but idk how to make it so it's set to like 0.01 for pennies

valid anvil
#
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))```
fiery cosmos
#

wow uh

#

that's super confusing lol

#

but i trhink i understand

valid anvil
#

also i forgot to account for the values lol

fiery cosmos
#

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

valid anvil
#

The f at the start of the string (stands for format) does something called string interpolation, it automatically inserts the value of denominations[i]

fiery cosmos
#

i get a parseerror: bad input on line 6

valid anvil
#

In generally if you put an f at the start of the string, you can put variables into it by surrounding them with brackets

fiery cosmos
#

?

valid anvil
#

i might've written it wrong

fiery cosmos
#

well im using python mini

#

does that change anything?

valid anvil
#

oh dear

#

idk lol

fiery cosmos
#

here can i screenshare?

#

and show you what is goin on

valid anvil
#

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

fiery cosmos
#

yeah it does

#

thank you

valid anvil
#

how weird

fiery cosmos
#

but it doesn't add the pennies

valid anvil
#

oh i accidentally appended amount instead of value

fiery cosmos
#

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"

valid anvil
#

oh

#

yeah it gives you the amount in cents

#

I trust you know enough about string manipulation and arithmetic to do that part yourself

fiery cosmos
#

fosure

#

let's just say im learning how to do

verb = raw_input("enter a verb")

civic quest
#

what r some projects i can do as a beginner

dire swift
#

i want to clone an py repo, and use conda as a venv, should i clone it directly at the venv?

#

hahaha

mortal heart
#

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

mortal heart
#

@tender lily

#

please somebody

small finch
#

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
topaz pulsar
#

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

small finch
#

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

topaz pulsar
#

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

small finch
#

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

topaz pulsar
#

so your trying to work out the patterns of each % remainder, sounds interesting

small finch
#

Spent a lot of time on it

topaz pulsar
#

that actually looks really interesting, i might give it a go later

small finch
#

@stable pecan Thanks!

stable pecan
#

should be close to log n with that

#

or somewhere between logn and n if i was guessing

small finch
#

My modulo is constant so that should be constant, right?

stable pecan
#

the product of binomial coefficients is pretty cheap to compute for small primes as each m_k and n_k is less than p

small finch
#

Oh no, my bad

#

Well I've got to go, I'll be back in 30 minutes

stable pecan
#

so really the complexity grows with the length of the base-p representation of the number

#

which is log n

small finch
#

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

stable pecan
#

did you try it for large n

small finch
#

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
stable pecan
#

do you short circuit if one of the terms is 0

small finch
#

Ooooh, smart

stable pecan
#

you can reduce the product by % 3 every iteration so it doesn't get large

small finch
#

We're back to the same constants

#

It's already unlikely to get large

stable pecan
#

you can also divmod in one operation

small finch
#

The (very unlikely) maximum would be 2 ** log3(100000) ~= 5000

#

Will do

#

I confirm that it is slower to take the mod every time

stable pecan
#

i blame python ints

small finch
#

Why?

#

I think it would be the same everywhere

stable pecan
#

because in c you could use a uint8

small finch
#

We basically multiply by 1 80% of the time

#

Ah, true

stable pecan
#

which is so much tinier

#

you might get a bit of speed up tuple-izing CHOOSE

small finch
#

Somehow using divmod is slower than taking the two separately, weird

#

Very small speed up indeed

#

Or not at all, in fact

stable pecan
#
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?

small finch
#

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
stable pecan
#

you could memoize divmod

small finch
#

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)

gusty grove
#

i sure do love a speed challenge!

stable pecan
#

this would be easy to cythonize

gusty grove
#

could someone give me the link to the og message? i cant find it 😦

stable pecan
#

oh, are these coefficients properly matched

small finch
#

@gusty grove Are you asking for the message that started the conversation? It was at 12:34

gusty grove
#

thanks

small finch
#

Can't use Cython in the codewars interface

north zealot
#

divmod is a function, sure it is slower

stable pecan
#
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

small finch
#

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

stable pecan
#
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

small finch
#

The first one seemed good

stable pecan
#

don't live code

small finch
#

Can't use prod, the interface uses 3.6.0

#

Not math.prod at least

stable pecan
#

gross

#

well you can fake it with reduce and operators

small finch
#

base_repr is much slower than doing the work manually (and being able to short-circuit)

stable pecan
#

well, dunno, numpy is implemented in c

small finch
#

I'll try to optimize the other half of the program

stable pecan
#

so it gets to use the small ints

#

but you have to make sure your timeit isn't including the import

small finch
#

It includes it only once for the 300 tests

#

And the difference was about 4 seconds

#

So not the reason

stable pecan
#

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

small finch
#

Yeah that's the funny thing. Numpy probably reverses the digits in its function and it makes our lives harder

stable pecan
#

you could try a dict look up for CHOOSE instead of tuple of tuples

#

i dunno if that's better

#

probably the same-ish?

small finch
#

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

stable pecan
#

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

small finch
#

Done

#

It's slightly slower

stable pecan
#

well i can't think of any other speedups

small finch
#

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

stable pecan
#

is that sierspinksi's

#

sic

#

or is that for base 2

#

i don't remember

small finch
#

For all bases it seems

#

Or maybe only primes

stable pecan
#

well, there's nice patterns for all of them

small finch
#

Don't know

stable pecan
#

you can get there from the chaos game too

small finch
#

That's not exactly Sierpinski

#

What chaos game ?

stable pecan
small finch
#

Oh yeah, I did something like that once

#

Didn't remember

stable pecan
#
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)
small finch
#

TypeError: unsupported operand type(s) for -: 'tuple' and 'list'

stable pecan
#

remove that errant comma

small finch
#

works

stable pecan
#

point was supposed to be a numpy array not a tuple

#

@gusty grove i made a numpy sudoku solver you might like

gusty grove
#

i've never understood how those work

#

do they just test stuff recursively?

#

or is there a smart way to do it

stable pecan
#

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)
last blaze
#

Apparently you can also use a* to solve sudokus. Don't understand how though

gusty grove
#

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

stable pecan
#

that just checks row, column and box for the number

#

a bit obfuscated, i had 3 separate conditionals at one point

small finch
#

@stable pecan We didn't have to check n > 0, since n is always greater than k

stable pecan
#

that's true

#

product will 0 out anyway

rose canyon
#
x = 69
print(x + "nice.")```
#

pretty sure like arm should hire me or something

last blaze
#
TypeError: unsupported operand type(s) for +: 'int' and 'str'```
rose canyon
#

we don't talk about that

naive marsh
glacial yoke
#

Hello, I was wondering if anyone has any experience with spatial data processing, and how to implement?

pseudo wave
#

What are you trying to do?

#

My only experience is with metric spaces and trees

quick tapir
#

(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

stable pecan
#

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

uneven geyser
#

or just fade the composite file out at the exact duration of the video.

quick tapir
#

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

stable pecan
#

well, what if it selects the same audio file multiple times in a row because the duration matches exactly

finite coral
#

Which should I learn first?
C++ or Python?

quick tapir
#

Python lol

finite coral
#

is Python better than C++?

quick tapir
#

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

uneven geyser
#

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.

quick tapir
#

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

uneven geyser
#

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.

quick tapir
#

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

stable pecan
#

i mean i have a knapsack function somewhere if you want to use that

#

but you have to integerize all the durations

quick tapir
#

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

stable pecan
#
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

quick tapir
#

I don't even know what knapsack is ;-;

stable pecan
#

https://en.wikipedia.org/wiki/Knapsack_problem --- the subset sum problem is just an instance of the knapsack problem

The knapsack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large a...

#

where values == weights

quick tapir
#

Welp I've got to go now 😕 I'll come back to this problem later. It's an interesting problem, though!

glacial yoke
#

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.

sly vale
#

the parenthetical values are the heuristic distances

#

and im suppose to find the A* search

#

So I believe the decision tree would be

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

quick tapir
#

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!

left stratus
#

can someone help me? I have a question about binary search tree

sly vale
#

whats th question i might be able to

#

also @royal gyroers

left stratus
#

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

sly vale
#

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

left stratus
#

I got it.

#

I switch it with root != None and it works well

sly vale
#

i believe it should be root is not None

#

because oyu want to test object identity correcT?

left stratus
#

thanks very much.

sly vale
#

: )

olive falcon
#

def foo(array):
sum = 0
product = 1

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

runic tinsel
#

o(n)

olive falcon
#

Why?

#

There are two loops.

runic tinsel
#

you choose the slowest one

#

however many there is

#

since they aren't nested

gusty grove
#

wouldnt it be O(2n) because you do the loop 2x and then you can leave the constant away?

olive falcon
#

That's what i thought too.

gusty grove
#

because its still linear so its O(n)

runic tinsel
#

that's also valid

gusty grove
#

just a guess btw, i have no idea what im talking about

olive falcon
#

So we are dropping the undominant one?

#

@runic tinsel O(2n) is also valid?

gusty grove
#

no

#

you have to leave constants away

#

because you are just interested in how it scales

#

not the actual values

runic tinsel
#

you get O(n) with either approach

olive falcon
#

I'm sorry but i didn't get it. There are two loops.

runic tinsel
#

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

gusty grove
#

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

olive falcon
#

@runic tinsel Got it, thanks.

fiery cosmos
#

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

tribal pendant
#

!codeblock

halcyon plankBOT
#

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!')
tribal pendant
#

It would be better if you could activate the highlighting of the syntax 😉

#

Easier to review

fiery cosmos
#

did i not??

#

o i get you!

#

it's not letting me because its around 4000 characters with the list included

halcyon plankBOT
fiery cosmos
fair pelican
#

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

stable pecan
#

why are you asking here

gusty grove
#

hmm

#

what if my graph is too large for networkx 😦

stable pecan
#

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

gusty grove
#

87790 nodes

#

the real deal is 1116207 nodes in total 😦

stable pecan
#

seems doable in networkx, but networkx is kinda chunky

gusty grove
#

ya, its the drawing that fails.

#

can allocate that much mem it seems

stable pecan
#

oh, graph drawing algotihms are notoriously slow, i wouldn't try it for such large graphs

#

you can try force atlas

gusty grove
#

using 100% memory

stable pecan
gusty grove
#

in my case 26 out of 32 GB total..

#

whats force atlas?

stable pecan
#

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

gusty grove
#

oh wow

#

that looks cool

stable pecan
#

that's neural network

gusty grove
#

can i easily convert a nx graph to graph_tool?

stable pecan
#

biological one

gusty grove
#

cool!

stable pecan
#

uhh, i think so

#

lemme see, i think you'll want to do it through numpy

gusty grove
#

is graph-tool out for 3.7?

stable pecan
#

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

gusty grove
#

installing graph-tool is taking a while

#

but thank you in advance 😉

sly vale
#

can anyone help me with an A* search algorithm question?

fiery cosmos
#

worked, thank you @fair pelican !!

gusty grove
#

sooo @stable pecan how do i make cool graphs with graph-tool? 😉

fiery cosmos
#

why?

#

im new to python

gusty grove
#

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

gusty grove
#

using my own layout function

stuck folio
#

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?

fiery cosmos
#

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.

daring harbor
#

can we have a look at the question you are trying to solve if it's an algo question

fiery cosmos
#

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 😛

daring harbor
#

SB/0.156 = 1000 ** (1/2.125)

#

you want to find 1000

fiery cosmos
#

oh, thanks, I was thinking sqrt or something 😛

daring harbor
#

SB/0.156 = x ** (1/2.125)

fiery cosmos
#

I think I got it x = (11.98/0.156) ** 2.125

#

Thanks for the help!

fiery cosmos
#

Is “The art of electronics” good to learn electronics if I have zero knowledge in electronics? I thinking about to learn electronics + C

naive marsh
#

In back propagation in convolutional layer, does the stride is the same stride as the forward propagation or always a stride of 1?

burnt wren
#

IBM will start to offer free COBOL courses if anyone's interested

spiral swallow
#

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 😄

stable pecan
#

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

river citrus
#

@here

#

my whole year depends on this

sudden sinew
#

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

gusty grove
#

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

sinful swallow
#

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?

frigid quail
#

hold on lets do the maths here

#

you said it's supposed to return a rectangle right?

sinful swallow
#

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

frigid quail
#

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)

sinful swallow
#

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 🙂

frigid quail
#

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

sinful swallow
#

Ah I see what you mean

#

It's still sadly not working.

#

I mean, my problem IS fixed

#

but some new rose up

#

Fixed ^-^

edgy glen
#

hi

wheat laurel
#

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

stark bridge
#

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. 你好, 早晨, こんにちは, 안녕하세요

desert cliff
#

How to learn to make algorithms, does math increase ones ability in solving problem?

short cave
#

@desert cliff yes it does.

desert cliff
#

is just high school math enough for easy and intermediate problems or the more the better?

fiery cosmos
#

When it comes to knowledge, the more is always the better

fiery cosmos
#

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.

north barn
#

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.

oblique panther
#

Can you have an O(n) runtime sorting algorithm if you're willing to have a high space complexity?

stark bridge
#

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 this

oblique panther
#

@stark bridge lemon_hearteyes

stark bridge
#

🤷

fiery cosmos
#

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

high stratus
#

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

fiery cosmos
#

I have a server, 2vCores, 8GBRam, / 80 GB ssd dont know what to do with it. Help ? any ideas? tag me

tribal pendant
#

Use it for science? Like proteins folding

fiery cosmos
#

Can you have a dual boot setup insiden of a vm?

#

e.g. Ubuntu and Arch or Windows on the same virtual hard drive?

lofty forum
runic crest
#

does anyone here have knowledge on the A* algorithm

frigid quail
rain wren
#

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?

sinful swallow
#

Any idea on why my BFS algorithm is only going one vertice in a random direction, despite the input graph having way more?

last blaze
#

Not without seeing the code

frigid quail
#

How do I unpack a tuple from an argument to a list?

#

from (1, 2, 3) to a [1, 2, 3]

north zealot
#

list((1, 2, 3))

#

You can pass any iterable to the list constructor

frigid quail
#

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

north zealot
#

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

frigid quail
#

so I have to unpack it twice?

north zealot
#

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

frigid quail
#

ah ok thanks

#

mylist = list(list(args)) this still prints the tuple in the list

north zealot
#

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)

frigid quail
#

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

north zealot
#
def myfunc(arg):
    mylist = list(arg)

    print(mylist)

myfunc((1, 2, 3))```This should work too
frigid quail
#

oh

#

ah that makes sense

distant glacier
#

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?
tribal pendant
#

You don't use deep copy from what I see

#

it's copy.deepcopy()

fiery cosmos
#

@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

tribal pendant
#

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

north zealot
#

Would this channel be the right one to ask about some issues related to programming language design? lemon_pika

stark bridge
#

probably

north zealot
#

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 lemon_pika

stark bridge
#

god I have no idea

#

that's waaay above my pay grade

#

read the python source, see what they do shrug

fiery cosmos
#

hey

#

Why is it easier for someone who is good at math to master algorithms?

daring harbor
#

They are the same thing

fiery cosmos
#

What in Math?

#

Algebra?

daring harbor
#

Ugh a lot? Algebra, linear algebra, discrete math, statistics, number theory,

#

The list goes on

north zealot
#

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

pseudo wave
#

@fiery cosmos What do you by 'master algorithms'?

mint beacon
#

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?

runic wigeon
#

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

crystal crane
#

anybody with mips knowledge?

eternal owl
#

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

stable pecan
#

i have a connect4 made somewhere

#

if you want some reference

eternal owl
#

Yeah that might help

#

is it similar?

eternal owl
#

sadly not ;c
thanks though

#

Do you know how I would place them?

whole gyro
stark bridge
#

yes, confine yourself to one channel

eternal owl
#

Do you know how I would place them?
More specifically how to place the tokens based on generated moves

winged sun
#

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

rapid cedar
#

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?

feral shale
#

none of this is related to computer science nor python

rapid cedar
#

I guess we can do it python ? @feral shale

#

face recognition can be built with python and including cloud API? builds a complete application ?

winged sun
#

@feral shale I thought my question was because it required knowledge of class paths and unix commands to package the final product

#

sorry :/

feral shale
#

well there's a #unix for that

wild bronze
#

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

fickle heath
#

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

last blaze
#

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

fickle heath
#

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

last blaze
#

he still almost certainly knows numpy exists

fickle heath
#

yeah he does but maybe not about linalg

#

ah whatever he knows what he knows