#algos-and-data-structs

1 messages · Page 77 of 1

past flare
#

There's a way to fix this?

warm marsh
#

looks like you switched the encoding

#

it says UTF16-BE in the lower right corner of the window. Click that and switch back to probably UTF-8

past flare
#

the problem is i had closed the file before

#

so i can't even UNDO

#

I changed to utf-8 again and nothing happened

spiral swallow
#

hm, it probably read it as utf16 and now it needs to read it again, the question would certainly be better in #tools-and-devops though

fiery cosmos
stark bridge
#

someone showing off their LaTeX chops?

spiral swallow
#

i wish, my linear algebra skills are almost nill 😦

stark bridge
#

I don't think there was ever a time when I'd have understood that, and I was, ostensibly, a math major

hidden pebble
#

@hidden pebble I'd reccomend the MIT OpenCourseware introduction to Computer Science
@last blaze huh ty ill check it out

fiery cosmos
#

Damn does really ML people that are hired at companies earn $120 000 - $500 000 a year?

stark bridge
#

sure why not?

spiral swallow
#

it certainly depends on the place

#

but i don't doubt some people do

fiery cosmos
#

Hey guys, I'm taking the CSA CollegeBoard course this year, does anyone have tips?

#

Last year I took a practice, thought I did well and ended up getting a 3...

eager hamlet
#

hey lepto i though CSA was java

eager hamlet
#

but anyways, I don't even know how to do this problem:
The cows have not only created their own government but they have chosen to create their own money system. In their own rebellious way, they are curious about values of coinage. Traditionally, coins come in values like 1, 5, 10, 20 or 25, 50, and 100 units, sometimes with a 2 unit coin thrown in for good measure.

The cows want to know how many different ways it is possible to dispense a certain amount of money using various coin systems. For instance, using a system of {1, 2, 5, 10, ...} it is possible to create 18 units several different ways, including: 18x1, 9x2, 8x2+2x1, 3x5+2+1, and many others.

Write a program to compute how many ways to construct a given amount of money using supplied coinage. It is guaranteed that the total will fit into both a signed long long (C/C++) and Int64 (Free Pascal).

PROGRAM NAME: money
INPUT FORMAT
The number of coins in the system is V (1 <= V <= 25).

The amount money to construct is N (1 <= N <= 10,000).
Line 1: Two integers, V and N
Lines 2..: V integers that represent the available coins (no particular number of integers per line)
it probably involves dynamic programming, but I've only done one and that was with a google search, so can someone help me on this one?

orchid palm
#

ik that i postde this in another channel but this is the place to put it

#

Any parts worth Salvaging from a printer
that i can use with my raspberry pi 4

half lotus
orchid palm
#

oh how

#

:0

solid cloud
#

scanners are way more fun to salvage

#

especially the 10-20kv transformer that'll burn you like you never felt before if misused

fiery cosmos
#

What is this made with? The 3D stuff and the characters? And how have they been able to do so they move by their self and learn in the 3D world? https://youtu.be/atcKO15YVD8

❤️ Check out Weights & Biases here and sign up for a free demo: https://www.wandb.com/papers

Their blog post and their CodeSearchNet system are available here:
https://www.wandb.com/articles/codesearchnet
https://app.wandb.ai/github/CodeSearchNet/benchmark

📝 The paper "Subsp...

▶ Play video
south parcel
#

Ooh, 2-min papers! Have you checked the description?

#

Turns out it's a Ubisoft Montreal paper

fiery cosmos
#

So it’s like a 3D software they have put in objects and then trained them?

south parcel
#

At it's very foundation, yes.

#

The paper covers a wide swath of topics though

#

Like GPU optimization

#

Which is fitting considering both training and physics utilise the GPU

#

Yeah, pretty cool stuff

fiery cosmos
#

Yeee

#

How is even 3D software made? I mean what is it that does so it can make 3D stuff?

south parcel
#

What part of '3D' are you interested in? How rendering works, how to make 3D animations/games, what software's out there, there's a whole lot to explore!

fiery cosmos
#

How to make a software so it can render 3D stuff

#

How to code that

#

Like c4d

tribal pendant
#

I think the module panda3d does that

south parcel
#

If you're talking about python, yeah try what @tribal pendant said

#

There are lots of 3d graphical libs out there

#

But for general stuff, you could look into OpenGL? That's real low level stuff though

spiral swallow
#

panda3d is a high level abstraction on top of OpenGl yeah, to do OpenGl directly it helps a lot to understand matrix math, to understand how the projection from 3d to 2d works, and how to manipulate 3d objects, compute lights and stuff, lots of math involved, but it can be a lot of fun.

south parcel
#

Woah, thanks @spiral swallow ! Didn't know!

fiery cosmos
#

@south parcel yeah but I mean from scratch. Ex how to code from scratch from 0 to make a cube in 3D and then later render it out and get I image of a 3D cube. I just want to understand how it’s done from scratch

south parcel
#

Like tshirtman said, panda3d is a good way to start understanding how 3d works while still writing in python.

#

Or maybe you'd like to look into graphing in 3d with matplotlib?

gusty grove
#

opengl is a great way to learn about that stuff

#

if you want me to i can give you a quick overview of how you get to a image of a 3d cube

gusty grove
#

does anyone know a fast 3d floodfill approach?

fiery cosmos
#

Alright panda3d look like something to start with!

fiery cosmos
#

Is it required to know c++ if you ex are a master at python, linear algebra, creating Neural networks, and can do the most stuff with that, but then if you would like to create a self driving car ex, then i guess that skills isnt enough?

sly patio
#

@fiery cosmos are you reading Computer Vision by Richard Szeliski?

#

@fiery cosmos That is the algorithm for DLT (Direct Linear Transformation) that is if you have to sets of known vectors and you want to find a given matrix (e.g. let's say a 3x3 matrix A) where all the points are know scalar factors to equation k. You would first have to get rid of the unknown scalars. That is the weird looking matrix in Section(4) in which he applies the anti-symmetric matrix, in order to obtain the homogenous equations

#

@fiery cosmos If you wanto know what that means in layman's term. If you use the OpenCV library. the perspective function that you apply prior to the warp function is implementing some of that mathematics under the hood. The OpenCV library is almost entirely derived from that book. FYI

fiery cosmos
#

I am trying to implement the warpperspective function in python without using the inbuilt opencv function

#

I have successfully got the homography matrix and applied to the respective x,y values in the source image

#

But then idk what to do next

#

@sly patio can you provide some guidance?

#

@fiery cosmos are you reading Computer Vision by Richard Szeliski?
@sly patio Yes I am

sly patio
#

I have read it a number of times. What are your questions?

fiery cosmos
#

Q1. Now that you have the new x'/lambda, y'/lambda, lambda after applying homography to x,y,1 what do I do next

#

I have read it a number of times. What are your questions?
@sly patio and I am having trouble even going through it for the first time

#

lol

sly patio
#

@fiery cosmos what is your actual task? that's where we need to start. that way we can reason about your chosen algorithm

fiery cosmos
#

I want to project the classic lena image on to a fiducial tag in real time without using the warpperspective function

sly patio
#

@fiery cosmos That's a start. can you pseudo code your algorithm because fiducial systems can fall into two categories based on the shape of the tags: square tags with a blackand white border on the outside; and tags with other shapes.

#

Therefore, which one did you choose?

#

@fiery cosmos are you doing just the homography part in Python right?

fiery cosmos
#

@fiery cosmos are you doing just the homography part in Python right?
@sly patio yes sir

sly patio
#

@fiery cosmos have you tried singular value decomposition?

#

using the least squares methos

fiery cosmos
#

yes, thats how i got my homography matrix

sly patio
#

@fiery cosmos Ican you post your code or you can just IM it to me if you prefer

#

@fiery cosmos let me fire up Emacs real quick and see what I can come up with some of my old recycled code

#

@fiery cosmos did you send it?

fiery cosmos
#

Hi

haughty sleet
#

function for disjoint set system

#

def Find(Set, value):
if parent[value] == value:
return value
else:
parent[value] = Find(Set, parent[value])
return parent[value]

#

getting error
IndexError: list index out of range

buoyant patrol
#

*target

lament portal
#

I need to set up a Venv inside of Visual Studio Code...
Can someone help me to do it?

#

nvm

earnest basalt
#

Hii

golden flume
#

@sly patio are you familiar with computer vision, i need some help. i am trying to set up a single camera + laser system for position measurement, my problem is that i don't know how i could use the knowledge that the laser is esentially just a plane which intersects with the object surface to recover the depth from the image.

long swallow
#

you want to retrieve distance from the camera to an object using a laser?

#

just get a sensor for that

#

rather than a red dot laser

proven folio
#

can you suggest good computer science and concept resource for beginners ?

#

SICP ?

spiral swallow
#

so i was reading on that the other day, on the wikipedia page, and it says the MIT course that used it was replaced to use python instead of lisp, as they considered the thing quite outdated (took them over 10 years to actually replace the course, so they wanted to do it for a long time), and there as been a number of work since designed to provide better books, though i can't judge them or the original effort.

sly patio
#

@golden flume that's fairly standard liner algebra. What is the actual task that you're trying to accomplish

#

@snof the little schemer, then read SICP

golden flume
#

@sly patio i want to get the 3D points of a laser point viewed through a camera

#

i dont see how it's just algebra? i think there will be some plane fitting involved, but not sure. if it is just algebra i'd like some more information if possible!

sly patio
#

@golden flume use themapping3d module from the opencv contrib library

#

Specifically, from lines 193

#

Can not exam (gotta work on my keyboard swiping skills) lol

#

You have to convert the 3D matrix (in pixels) to the LOS calibrated ray off your camera (which is in meters) if not you'll be off.

tardy forge
#

yo guys, between an ipad 2019 10.2 and a galaxy tab s6.. which one should i choose

north zealot
#

iPad I'd say

#

Even if I'm not a fan of Apple products, I think they do the best tablets

golden jacinth
#

Depends on what you’ll use it for

#

TBH is get a surface

#

I’d*

glacial wagon
#

I got an iPad pro 3rd generation for art, but I use it daily for other stuff too. I fell in love with it

eager hamlet
#

um kinda off topic

unique ferry
#

Hi, could someone help me fix my spectrogram?

unique ferry
#

Can someone at least explain me how to find a dominant frequency in a wav file?

spiral swallow
#

@unique ferry do you use a FFT (fast fourier transform) on the signal?

unique ferry
#

G: Yeah.

#

G: Actually I have to find first and second dominant frequency.

#

G: It's for car horns, that I have to compare tones to the musical notes.

#

G; I think I have to use signal peaks, but I'm not sure.

spiral swallow
#

the FFT will tell you the amount of energy in each frequency, basically, so the strongest one should be dominant, and so on.

burnt wren
#

Why if priveleged code faults the system must crash, but if user code faults the system can keep going forward?

tribal pendant
#

What's "priveleged code"

warm marsh
#

user processes are pretty isolated and controlled by the kernel. kernel code... well, not.

burnt wren
#

let's say for example a kernel

warm marsh
#

imagine a school class. if one of the students acts up, they will be thrown out and the lesson continues. If the teacher breaks down, nothing works.

burnt wren
#

but there's no difference between them, a user program and a kernel is just code in memory, just one has rights to special instructions and is protected

burnt wren
#

lets say a page fault happens in the kernel, a page fault interrupt gets called by the cpu, the interupt handler is in the kernel and it checks if the faulted instruction is in the kernel, if yes then shutdown the system and display an error message (like a bsos or a kernel panic)

#

why can't we just jump back to the kernel, it's in memory, we have the context

last blaze
#

Are you asking how bubble sort works, or for someone to do you homework?

spiral swallow
#

@burnt wren as i understand it, the teacher/pupil analogy holds, the kernel enforces the rules for other processes, if the kernel code stops working correctly, there is nobody to enforce the rule on itself, all bets are off.

burnt wren
#

@spiral swallow the kernel handles always handles all faults, all faults that happened in user programs and the kernel, if a fault happened in a process, the handler for the fault just kills the process, but if it happened in the kernel, it shutdowns all disk activity and displays a bsod

#

why can't the kernel have a routine that would try and fix everything, that the handler could jump to

#

why can't we just jump past the faulted code or jump back to the code that called the faulted code

spiral swallow
#

because the kernel code doesn't obey the same restrictions as the non kernel code, so if an issue is discovered in its process, then a lot of assumptions it needs to do to continue working, are not possible to do anymore?

burnt wren
#

the kernel is still in memory that means we can jump anywhere in it

#

i just can't understand why don't we do something like that

#

in the end we can just ignore the fault

spiral swallow
#

because it wouldn't be safe

#

sure, the kernel could try to do things that maybe would work, but kernel devs are not the kind to want do to these things

#

if they can't say what the proper source of action is, they'd rather raise the error and crash

burnt wren
#

all i can think of is that it's just much more easier to reset the computer and to start everything over

spiral swallow
#

well when you say "easy" they say "the only acceptable course of action"

#

if there was a solution, even hard, they would take it, they don't like crashing anymore than you

#

but if they do that, it's because other ways are unsafe

#

you don't want a machine to start doing random things when it discovers some error it can't safely recover from, you want it to stop doing things

lone siren
#

Hey guys, off-topic question here. I'm building a PC for our lead developer, where price is not an issue. I've never done it before. Our company is mostly involved in machine learning and data analytics, and some of the more complex tasks will be carried out on her computer.

#

Would anyone be able to suggest a suitable CPU/GPU/motherboard combination please?

bronze gazelle
#

Sounds like a good question for an off-topic channel

hazy topaz
#

Not sure if this is the right place to ask, but I'm looking for an explanation on what an abstract type is (and maybe it's easier to first explain an abstract class in Python as I know a fair bit of Python and classes already)

#

My understanding of an abstract class now is that it's basically just a class meant to be a parent of other classes and never gets instantiated itself

spiral swallow
#

That's technicaly correct, but i would say what's important about an abstract type, is what it's for.
It's a way to declare the properties/aspect/interface of a type, without actually explaining how it works, that's the reason it can't be instaciated, the code to make it work just is not there.

#

But if you get an object who is of this type, you know how you can use it, because it has all the thinge the abstract type defines.

#

To be able to create an object of this type, you must actually create an object of one of it's subclasses, as the type itself is abstract.

#

But code manipulating it can completly ignore the exact type it is and how it works, as it knows it has the interface defined by the abstract type.

#

@hazy topaz

balmy siren
#

Hey guys ... I'm doing Tree DS and recently done some traversal orders and basic questions related to it and Binary Trees. In short, I've done the intro part and binary trees part and topic next after it are Generic Trees (N-Ary Trees) and Binary Search Trees.. So, i'm not sure what to do next, I mean, most of the people said that you should start with Binary Search Trees once you done with Binary Trees but is that anything special about Generic trees which I should know right now (Also, I'm doing self learning of DS with a book and random blogs, tutorials).. so, is there anything which is related with Generic Trees and binary search trees?

fiery cosmos
brave oak
#

can pattern matching (the kind they have in functional languages) fully (and sensibly) replace if-elif-else?

#

like would it be weird if a languge did that?

stark bridge
#

I think it can

#

haven't done it in a while

spice ravine
#

as long asyou can match on values and not just types

#

even if your conditions are completely different (i.e. not based on values of the same variable), you can just fall back on the fact that if-elif-else can be replaced with if-else{if-else}

brave oak
#

yeah, definitely on values, too

#

now...would it be something people would want to use?

stable pecan
#

here's a multiset with choice implementation meant to be fast: (so you don't have to keep making a list to choose items at random)

"""
Setch is a portmanteau of set and choice.  A setch is set-like object (containment is O(1)) except
one can pick items at random from the set without converting it to a list. This is a multiset
implementation of a setch.

Note most list operations are O(1) except for indexing in `remove`.
"""
from collections import defaultdict
from random import choice

class MultiSetch:
    def __init__(self, *items):
        self._item_to_position = defaultdict(list)
        self.items = []
        for item in items:
            self.add(item)

    def add(self, item):
        self.items.append(item)
        self._item_to_position[item].append(len(self.items) - 1)

    def remove(self, item):
        position = self._item_to_position[item].pop()
        last_item = self.items.pop()
        if position != len(self.items):
            self._item_to_position[last_item].pop()
            self.items[position] = last_item
            self._item_to_position[last_item].append(position)

    def choose(self):
        return choice(self.items)

    def pop(self):
        """Pop a random item."""
        item = self.choose()
        self.remove(item)
        return item

    def __len__(self):
        return len(self.items)

    def __contains__(self, item):
        return item in self._item_to_position

    def __iter__(self):
        return iter(self.items)

    def __repr__(self):
        return f'MultiSetch({{{", ".join(map(str, self.items))}}})'
royal kestrel
#

You can choose items at random from a non-random-access iterator with reservoir sample algorithms

stable pecan
#

I think that's too slow for me

oblique panther
#

I'm struggling with how to solve recurrence equations.

#

My solution is cut off. I wrote T(n) = 2 + 2T(n/2) + 2

#

I would say that that's O(n), but I don't know how to prove that.

ocean sedge
#

Slightly off topic but how do I post python code in that nice marked up format (like @stable pecan)

stable pecan
#

!code-block

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!')
vale parrot
#

I am wanting to study into computer science can someone describe how their experience was and what they did

last blaze
#

Are you asking about someone who has graduated from university? As in how they found the course, and their experience after graduating?

vale parrot
#

yes

last blaze
fiery cosmos
#

Hi. I need some regex help I have the following:

someCategory%someCategory.categoryFoo#value%someCategory.categoryBar#other value%....
As you see it always starts with someCategory, afterwards it repeates (1 to many) "key-value" pairs
the key-values are seperated by hashtag, and each pair is seperated by a percentage symbol
My regex (that doesn't work): ^([\w\s.]+)(?:%\1\.([\w\s]+)#([\w\s]+))+

brisk dawn
#

is it the good room to talk about opencv/preprocessing

#

? 🙂

gusty grove
#

Sure

wintry oracle
#
# Just curious how many iterations there are.
iteration_count = 0


def breadth_first_search(arr):
    global iteration_count

    # Length of the input array.
    arrayLen = len(arr)

    # Store traversed index here as proof.
    indexArray = []

    # Loop through the level as the divide will be exponential.
    for i in range(1, arrayLen):
        # Break out of loop when indexArray is complete.
        if len(indexArray) == arrayLen:
            break

        # levelArrayLen is the length of array split by the exponent amount.
        levelArrayLen = arrayLen // i

        # Start at 0 at the beginning of a level loop.
        first = 0

        # Loop through and start splitting into logarithmic amount.
        for x in range(1, i + 1):
            # Want to see how many times it ultimately iterated.
            iteration_count += 1

            # last is the length of array multiplied by how many times splitted.
            last = levelArrayLen * x

            # mid point of each split within a level.
            mid = (last - first) // 2 + first

            # Store mid point into indexArray and check its neighbour too.
            if mid not in indexArray:
                indexArray.append(mid)
            elif (mid + 1) not in indexArray and (mid + 1) < arrayLen:
                indexArray.append(mid + 1)
            elif (mid - 1) not in indexArray and (mid - 1) > -1:
                indexArray.append(mid - 1)

            # If the value in that index is True, break out.
            if arr[indexArray[-1]]:
                return indexArray

            first = last + 1

    return indexArray


testArray = [False, False, False, False, False, False, False, False,
             False, False, False, False, False, False, False, False]
print(breadth_first_search(testArray))
print('Iterated %s times.' % iteration_count)
#

So I made this attempt of breadth-first-search by attempting to divide the testArray down logarithmically. The idea is checking the middle of each logarithmic split of the testArray to see if it is True. The testArray is supposed to represent a sample which should only contain either True or False with the possibility of "clusters". These codes are working about as what I expected and basically it's just cycling through indexes logarithmically and add the middle index value into another array to signify that it has been "checked". The checking part, which is not shown here but may potentially be computationally heavy, doesn't get executed unless it's not part of the indexArray, in my attempt to be efficient with the check. However, if you see the print statement of Iterated X times., you will see that depending on the size of the sample, it can iterate many more times than its actual sample size. For example, if you replace the single True in the testArray and run it, you will see that it iterated 21 times. I am just curious about how bad that could be in a scalable sense and whether you guys can help me think of a way to minimize extra iterations? I am hoping just looping through and manipulating integer (index value) is pretty trivial in and so more iteration isn't the worst thing. Ultimately, given the structure of the array which can have "clusters", logarithmic search makes more sense than linear search. However, given the iteration is more than the sample size, I'm just curious if y'all got an opinion about it.

long wind
#

Hello, new to the discord world, if I have questions on manipulating large excel sheets using pandas would this be the best channel?

last blaze
#

or just use a help channel by doing !free in bot commands to find one

long wind
#

Thanks!

tawdry perch
#

hello?

#

need help with my code

#

`import itertools

def sum_to_n(n):
'Generate the series of +ve integer lists which sum to a +ve integer, n.'
from operator import sub
b, mid, e = [0], list(range(1, n)), [n]
splits = (d for i in range(n) for d in itertools.combinations(mid, i))
return (list(map(sub, itertools.chain(s, e), itertools.chain(b, s))) for s in splits)

print(list(sum_to_n(7)))`

#

this code gets all the possible ways you can add to get a number using integers

#

for example, the above code would output this:

#

[[7], [1, 6], [2, 5], [3, 4], [4, 3], [5, 2], [6, 1], [1, 1, 5], [1, 2, 4], [1, 3, 3], [1, 4, 2], [1, 5, 1], [2, 1, 4], [2, 2, 3], [2, 3, 2], [2, 4, 1], [3, 1, 3], [3, 2, 2], [3, 3, 1], [4, 1, 2], [4, 2, 1], [5, 1, 1], [1, 1, 1, 4], [1, 1, 2, 3], [1, 1, 3, 2], [1, 1, 4, 1], [1, 2, 1, 3], [1, 2, 2, 2], [1, 2, 3, 1], [1, 3, 1, 2], [1, 3, 2, 1], [1, 4, 1, 1], [2, 1, 1, 3], [2, 1, 2, 2], [2, 1, 3, 1], [2, 2, 1, 2], [2, 2, 2, 1], [2, 3, 1, 1], [3, 1, 1, 2], [3, 1, 2, 1], [3, 2, 1, 1], [4, 1, 1, 1], [1, 1, 1, 1, 3], [1, 1, 1, 2, 2], [1, 1, 1, 3, 1], [1, 1, 2, 1, 2], [1, 1, 2, 2, 1], [1, 1, 3, 1, 1], [1, 2, 1, 1, 2], [1, 2, 1, 2, 1], [1, 2, 2, 1, 1], [1, 3, 1, 1, 1], [2, 1, 1, 1, 2], [2, 1, 1, 2, 1], [2, 1, 2, 1, 1], [2, 2, 1, 1, 1], [3, 1, 1, 1, 1], [1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 2, 1], [1, 1, 1, 2, 1, 1], [1, 1, 2, 1, 1, 1], [1, 2, 1, 1, 1, 1], [2, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1]]

#

how do i change it so that i can limit the size of the addends to be <= y?

#

for example, if i want to sum to 7 using numbers <= 4, i can do this:

#

so 3 and 4 is ok

#

5 and 2 are not

#

6 and 1 are not either

#

2 and 2 and 2 and 1 are ok

fierce inlet
#

could pop a filter on the end

#

filter(lambda numbers: all(number < some_value for number in numbers), result)

#

something like that

#

perhaps not the cleanest, elegant or efficient way

#

@tawdry perch

stable pecan
#
def partitions(n, m=None):
    if m is None or m >= n:
        yield [n]
        start = n - 1
    else:
        start = m

    for m0 in range(start, 0, -1):
        for partition in partitions(n - m0, m0):
            yield [m0] + partition
#
In [66]: list(partitions(7, 4))
Out[66]: 
[[4, 3],
 [4, 2, 1],
 [4, 1, 1, 1],
 [3, 3, 1],
 [3, 2, 2],
 [3, 2, 1, 1],
 [3, 1, 1, 1, 1],
 [2, 2, 2, 1],
 [2, 2, 1, 1, 1],
 [2, 1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1, 1, 1]]
#

@tawdry perch

tawdry perch
#

@stable pecan that's pretty much what i want, but how do you change it so that it gives all the permutations of each partition? ex. 1 + 1 + 2 can also be 1 + 2 + 1 or 2 + 1 + 1

#

do i put in itertools.permutations() somewhere?

#

i tried doing so but then it gets 4 duplicates of 1 + 1 + 1 + 1

stable pecan
#

more_itertools has unique permutations

#
In [4]: from more_itertools import distinct_permutations
   ...: for partition in partitions(7, 4):
   ...:     print(list(distinct_permutations(partition)))
[(3, 4), (4, 3)]
[(1, 2, 4), (2, 1, 4), (2, 4, 1), (1, 4, 2), (4, 1, 2), (4, 2, 1)]
[(1, 1, 1, 4), (1, 1, 4, 1), (1, 4, 1, 1), (4, 1, 1, 1)]
[(1, 3, 3), (3, 1, 3), (3, 3, 1)]
[(2, 2, 3), (2, 3, 2), (3, 2, 2)]
[(1, 1, 2, 3), (1, 2, 1, 3), (2, 1, 1, 3), (1, 2, 3, 1), (2, 1, 3, 1), (2, 3, 1, 1), (1, 1, 3, 2), (1, 3, 1, 2), (3, 1, 1, 2), (1, 3, 2, 1), (3, 1, 2, 1), (3, 2, 1, 1)]
[(1, 1, 1, 1, 3), (1, 1, 1, 3, 1), (1, 1, 3, 1, 1), (1, 3, 1, 1, 1), (3, 1, 1, 1, 1)]
[(1, 2, 2, 2), (2, 1, 2, 2), (2, 2, 1, 2), (2, 2, 2, 1)]
[(1, 1, 1, 2, 2), (1, 1, 2, 1, 2), (1, 2, 1, 1, 2), (2, 1, 1, 1, 2), (1, 1, 2, 2, 1), (1, 2, 1, 2, 1), (2, 1, 1, 2, 1), (1, 2, 2, 1, 1), (2, 1, 2, 1, 1), (2, 2, 1, 1, 1)]
[(1, 1, 1, 1, 1, 2), (1, 1, 1, 1, 2, 1), (1, 1, 1, 2, 1, 1), (1, 1, 2, 1, 1, 1), (1, 2, 1, 1, 1, 1), (2, 1, 1, 1, 1, 1)]
[(1, 1, 1, 1, 1, 1, 1)]
#

@tawdry perch

tawdry perch
#

oh

#

how do i get these all into one list like the above?

stable pecan
#

chain

#

from itertools

tawdry perch
#

like [[4], [3, 1], [1, 3] .......

#

so how would i use that?

#

i am confused

young plover
stable pecan
#
In [9]: list(chain.from_iterable(distinct_permutations(partition) for partition in partitions(7, 4)))
Out[9]: 
[(3, 4),
 (4, 3),
 (1, 2, 4),
 (2, 1, 4),
 (2, 4, 1),
 (1, 4, 2),
 (4, 1, 2),
 (4, 2, 1),
 (1, 1, 1, 4),
 (1, 1, 4, 1),
 (1, 4, 1, 1),
 (4, 1, 1, 1),
...
tawdry perch
#

thanks!

stable pecan
#

np

#

oh, don't need the tuple you can leave it as a generator

tawdry perch
#

wait

stable pecan
#

that means we can map it

tawdry perch
#

it got this error

#

NameError: name 'distinct_permutations' is not defined

#

and it doesn't work if i type itertools. before it

stable pecan
#

distinct_permutations is from more_itertools

tawdry perch
#

oh

#

and i liked the above functions, but i don't like tuples within list

#

how do i make it give me lists within lists?

stable pecan
#

well, tuples take up a lot less memory but if you want lists we can do that

#
In [17]: list_of_tuples = list(chain.from_iterable(map(distinct_permutations, partitions(7,4))))

In [18]: list_of_lists = list(map(list, list_of_tuples))

In [19]: list_of_lists
Out[19]: 
[[3, 4],
 [4, 3],
 [1, 2, 4],
 [2, 1, 4],
 [2, 4, 1],
 [1, 4, 2],
 [4, 1, 2],
tawdry perch
#

thanks!

stable pecan
#

np

tawdry perch
#

here was the reason i wanted lists

#

i want to convert the numbers to words

#

using this:

#
for curWordNum, curWord in enumerate(myList):
    for curLtrNum, curLtr in enumerate(curWord):
        curLtr += 64
        myList[curWordNum][curLtrNum] = chr(curLtr)
    myList[curWordNum] = "".join(curWord)
print(myList)
#

and i wanted to limit it at 26 because 26 is Z

#

i am trying to do a little puzzle i like to call the A1Z26 checksum

#

so assume A is 1, B is 2, ..... Z is 26

#

now take the word you want and add up all its values

#

and we will call the sum the "A1Z26 checksum"

#

now i want to see if it's possible to get the original word back from the A1Z26 checksum

stable pecan
#
In [25]: import string
    ...: translate = {letter:value for value, letter in enumerate(string.ascii_lowercase, start=1)}
    ...: my_string = 'hi there'
    ...: sum(translate.get(char, 0) for char in my_string)
Out[25]: 73

you want to figure out the word from 73

tawdry perch
#

well, here is my code, which i somehow broke

#

i'm confused

#

our com-sci classes are far too basic

#

(this is not for a class)

#

(i just wanted to make a fun puzzle)

stable pecan
#

my code is confusing?

#

i can explain it

tawdry perch
#

i'm confused by my own code

stable pecan
#

oh

tawdry perch
#

your code encodes the checksum

#

i'm doing the opposite

#

so if someone gives you the checksum 7, here are the possibilities

stable pecan
#

it just seems like there's going to be a lot of words that sum to 73

tawdry perch
#

yes

stable pecan
#

or whatever

halcyon plankBOT
#

Hey @tawdry perch!

It looks like you tried to attach file type(s) that we do not allow (.txt). 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.

tawdry perch
#

this is a sample output

#
*** English words that have an A1Z26 checksum of 24 ***
X
AW
CU
ES
FR
HP
IO
KM
LL
MK
NJ
OI
PH
RF
SE
TD
VB
WA
ACT
ADS
ARE
AVA
BOG
CAT
CBS
CFO
CHM
DOE
EAR
EMF
ENE
ERA
FAQ
FEM
GAP
GEL
GOB
GPA
IAN
IBM
INA
JAM
KID
LBJ
LEG
MAJ
NEE
ODE
OED
RAE
SAD
ADAR
ADEN
BAIL
BALI
BANG
CRAB
DADO
DANE
DEAN
DENA
EDNA
ELBE
FLEA
GLAD
IBID
IEEE
LEAF
AGANA
BALED
BLADE
CAKED
CECAL
CHAFF
JADED
ACHEBE
BABBLE
BEDDED
CACHED
CADGED
CANADA
DEFACE
JABBED
stable pecan
#

you trying to find all the possibilities? that is a partition problem so you're on the right track

tawdry perch
#

i figured that out

stable pecan
#

don't do this though len(list(partitions(73, 26)))

#

or do do it, if you want, but it's incredibly large

tawdry perch
#

is there a way to make it save RAM though @stable pecan ?

#

when i put in a large number like 27 it uses 10GB+ of RAM

#

and my computer only has 8GB

stable pecan
#

partitions, like most combinatorial objects explode violently in number of possibilities as you increase size

#

you can chunk it and dump it to hard drive

#

but you could run out of that too

tawdry perch
#

how would i save the list to my hard drive?

stable pecan
#

partitions is a generator, so you can generate the first, say, 1000, elements and save them to disk, and then generate the next 1000 and so on

tawdry perch
#

how do you do that?

stable pecan
#

you can use islice

#

as one method

tawdry perch
#

but how would i type it in my code?

stable pecan
#
In [44]: parts = partitions(73, 26)

In [45]: list(islice(parts, 100))
Out[45]: [[26, 26, 21], [26, 26, 20, 1], [26, 26, 19, 2], [26, 26, 19, 1, 1], [26, 26, 18, 3], [26, 26, 18, 2, 1], [26, 26, 18, 1, 1, 1], [26, 26, 17, 4], [26, 26, 17, 3, 1], [26, 26, 17, 2, 2], [26, 26, 17, 2, 1, 1], [26, 26, 17, 1, 1, 1, 1], [26, 26, 16, 5], [26, 26, 16, 4, 1], [26, 26, 16, 3, 2], [26, 26, 16, 3, 1, 1], [26, 26, 16, 2, 2, 1], [26, 26, 16, 2, 1, 1, 1], [26, 26, 16, 1, 1, 1, 1, 1], [26, 26, 15, 6], [26, 26, 15, 5, 1]
...
#

that gives me the first 100 partitions, if you use islice again with the same exact code, it will give the next 100

tawdry perch
#

oh

#

but do i just save it in a txt?

stable pecan
#
In [46]: list(islice(parts, 100))
Out[46]: [[26, 26, 11, 8, 1, 1], [26, 26, 11, 7, 3], [26, 26, 11, 7, 2, 1], [26, 26, 11, 7, 1, 1, 1], [26, 26, 11, 6, 4], [26, 26, 11, 6, 3, 1], [26, 26, 11, 6, 2, 2], [26, 26, 11, 6, 2, 1, 1], [26, 26, 11, 6, 1, 1, 1, 1],...
#

txt or jsn or i dunno, some pickler

tawdry perch
#

how should i change the code to make it save to hdd?

#

because i just did this to make it in ram

#

allCombos = list(map(list, list(itertools.chain.from_iterable(more_itertools.distinct_permutations(partition) for partition in partitions(userChecksum, 26)))))

stable pecan
#

yep, pickle or jsn, but they aren't very memory efficient

fiery cosmos
#

Hi

#

Does big oh notation equal the number of steps needed for the code?

#

like O(n^2) does that mean if i have 10 numbers, for example, there would be 100 steps in the algorithm?

serene helm
#

basically yes

bronze gazelle
#

It's generally not that literal, but it does explain to you the trend of how your algorithm performs as the number of inputs increases

tawdry perch
#

@stable pecan hello?

ionic glacier
last blaze
#

an O(1) operation happens O(log n) many times

ionic glacier
#

and is log n the concept of just splitting in half?

fiery cosmos
#

I think spliting is log 2

ionic glacier
#

ah ok. i just didnt understand where he got this "log2" or "log n " stuff from. prob missing some background

sleek hare
#

if you have a list of N things, and you split that into N/2 things, and then again into N/4, things and so on until the result is of length 1

#

the number of splits is O(Log N)

fiery cosmos
#

Is quicksort's space complexity O(log n) or O(n)?
I am confused since some websites say O(log n) or O(n)

stable pecan
#

i don't think it's either

#

O(n log n) maybe

fiery cosmos
#

no

#

Quicksort (sometimes called partition-exchange sort) is an efficient sorting algorithm. Developed by British computer scientist Tony Hoare in 1959 and published in 1961, it is still a commonly used algorithm for sorting. When implemented well, it can be about two or three time...

stable pecan
#

Mathematical analysis of quicksort shows that, on average, the algorithm takes O(n log n) comparisons to sort n items. In the worst case, it makes O(n2) comparisons, though this behavior is rare.

#

so it's O(n log n)

fiery cosmos
#

space complexity

#

Is quicksort's space complexity O(log n) or O(n)?
I am confused since some websites say O(log n) or O(n)

#

Not time complexity

#

I guess it depends on the implementation

#

Using tail-recursion or iteration the largest sub-array can only ever be half of the input size

#

so in that case the space complexity is O(log n)

royal kestrel
#

The space complexity is O(log n) because you either

  • need to store log n stack frames for a recursive implementation
  • need to store log n elements in a stack if you implemented it iteratively
#

Though one could argue in the worst possible case the space complexity could reach O(n) in certain implementations under very specific conditions

tribal pendant
#

you wrote time, but you meant space @royal kestrel , no?

royal kestrel
#

yes

fiery cosmos
#

@royal kestrel thanks

thick flicker
#

Is there a relationship between logical addresses and Virtual Memory?

north zealot
#

Depends on the implementation

thick flicker
#

It seems to me that we have to go through several layers before accessing the real memory. I mean, first we have logical addresses for the processes, and then the Virtual Memory Space, and only after is the physical memory accessed.

#

Am I right?

north zealot
#

Well, the logical adresses are inside the Virtual Memory Space, which are just address range of the physical memory

#

And the Virtual Memory is the technique capable of mapping the logical adress to the physical address, and assign the memory space

thick flicker
#

So the Memory Management Unit is the responsible for Virtual Memory

stable pecan
#

anyone ever played with generating sets of non-intersecting circles?

#

i spent some time today playing with it

#
class Word:
    def __init__(self, word1=None, word2=None, concat=True):
        if word1 is None:
            self.word = '()'
        elif concat:
            self.word = f'{word1.word}{word2.word}'
        else:
            self.word = f'{word1.word[0]}{word2.word}{word1.word[1:]}'

    def __repr__(self):
        return self.word

    def __add__(self, other):
        return Word(self, other)

    def __rshift__(self, other):
        return Word(self, other, concat=False)

    def __eq__(self, other):
        return self.word == other.word

    def __hash__(self):
        return hash(self.word)


def all_words_length(n):
    if n == 1:
        yield Word()
        return
    for word in all_words_length(n - 1):
        yield word + Word()
        yield Word() + word
        yield word >> Word()
        yield Word() >> word

you can generate them with a simple grammar:

In [152]: set(all_words_length(4))
Out[152]: 
{(((()))),
 ((()())),
 ((())()),
 ((()))(),
 (()(())),
 (()()()),
 (()())(),
 (())(()),
 (())()(),
 ()((())),
 ()(()()),
 ()(())(),
 ()()(()),
 ()()()()}

where this set represents the non-intersecting circles

#

but there's a lot of redundant words using this method

#

can anyone think of a way to get all the non-intersecting circles without the redundancy

thick flicker
#

How far should I learn CS to become a better programmer.

#

I have some basic knowledge of Computer Architecture and Operating System.

candid osprey
#

Depends. Cs knowledge usually only helps, so more the merrier. You can focus on the things in your critical path first though, such as data structures, logical operators and io

torn pine
#

Does anyone know any good learning programs? Other then codecademy, ping me if you respond please

compact vine
#

@torn pine sololearn

torn pine
#

Thanks

woven wind
#

What's a good book for data structures and algorithms? Just preparing before data science

royal kestrel
#

Algorithms + Data Structures = Programs by Niklaus Wirth

woven wind
#

I have a question, is it necessary for me to be able to code an algorithm if I can understand it completely? for example, if I know how bubble sort works, but I can't write code that does bubble sorting, is it ok?

runic tinsel
#

no, that's likely unacceptable

#

knowledge is something for you

woven wind
#

I'm having problems writing code like that, what's the first something I should do, make a flowchart? pseudocode?

candid osprey
#

If you know how it works, why can't you code it?

runic tinsel
#

writing the code is what you're good for

woven wind
#

Coding it seems more complicated

candid osprey
#

Pseudocode isn't a bad idea. But point being, you might need practice then

#

Because if you can understand something end to end, you should be able to code it up. It might take a bit, but it's a very important skill to solidify

#

You might think it's not important for algos. But think of it this way, What's the use of coming up with a solution if you can't give it life?

woven wind
#

Because most of these algorithms are built in

#

like libraries or built-in functions, methods

candid osprey
#

That's what I meant, The skill applies to solutioning beyond just algos.

woven wind
#

So how should I start trying to code one of them

candid osprey
#

Tricky, because usually understanding the logic is the hard part.

#

Well i suppose, if you say you understand an algo.. Can you write it as a series of steps in plain English?

woven wind
#

yes

candid osprey
#

Well defined instructions. One instruction per sentence. In order.

#

OK. That's a good start. Then take one sentence at a time, and try to translate that to code

#

Don't proceed till you make sure one sentence is translated and works

woven wind
#

TYSM, I'm gonna try that, I hope it helps

candid osprey
#

Fingers crossed

fiery cosmos
#

Hi. As homework, I've got to calculate the millionth prime number in under 1 second. What's the best algorithm to go about this, and should I bother doing it in Python? Thanks!

#

Does this sound sensible? I'll estimate the millionth prime using pi(n) = n/log(n), and then use the Sieve of Eratosthenes to calculate all the primes up to there?

serene helm
#

What's the point of estimating first?

fiery cosmos
#

The sieve doesn't calculate primes, but only finds primes upto a certain number. Making it sieve specifically upto 15,485,863 (the millionth prime) would be cheating.

serene helm
#

Pretty sure there's a way to implement it without having to stop at any specific number

fiery cosmos
#

That's great! What's the way?

serene helm
#

I did it by nesting filters, but that's way too slow

#
def primes():
    numbers = itertools.count(2)
    while True:
        prime = next(numbers)
        yield prime
        numbers = filter(lambda num, prime=prime: num % prime, numbers)
fiery cosmos
#

Thank you!

gusty grove
#

I would estimate the range that the nth prime is in and check for it in there

vital quiver
#

So I have a slightly headache-inducing problem. Let's say I have a number of jobs, denoted with an ID. Each of those jobs has parents, and I need to map out all job chains given the parents so given the data on runtime/memory for those jobs, assign priority to them.

gusty grove
#

No need to sieve all the way up to the nth prime

vital quiver
#

Jobs can have multiple parents, and jobs can have multiple children, for reference.

gusty grove
#

@fiery cosmos until when do you need this done?

swift breach
#

@fiery cosmos https://en.wikipedia.org/wiki/Sieve_of_Atkin
If you're doing it in python, make sure the startup cost of the interpreter doesn't count against your timing. Other than that, any modern method of generating primes should be fine

In mathematics, the sieve of Atkin is a modern algorithm for finding all prime numbers up to a specified integer. Compared with the ancient sieve of Eratosthenes, which marks off multiples of primes, the sieve of Atkin does some preliminary work and then marks off multiples ...

fiery cosmos
#

@gusty grove There's no urgency, but the sooner the better obviously. Thanks for the help

#

@swift breach Thanks. I've tried it with the Sieve of Eratosthenes, and got about 5-6 seconds.

#

Any ideas to make it go down to 1s, or should I try a new algorithm entirely? Any supercomputers I can rent out for 10 seconds? :p

gusty grove
#

im working on something, but its not quite working yet 😉

swift breach
#

It's certainly doable

In [7]: m.nth_prime(1000000)
Out[7]: 15485863

In [8]: %timeit m.nth_prime(1000000)
217 ms ± 7.52 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

(this is timing from some old code)

I'd suggest looking for a faster means of generating primes. Sieve of atkin and some wheel based options both work much faster.

fiery cosmos
#

Tysm @gusty grove

#

@swift breach Thanks, I'll look into that

swift breach
#

There are a handful of way to improve the speed at which you're checking in python as well.

Division across a numpy array is faster than divison across each element of a python list.

There's also little ways to only check specific numbers along the way.

Observations like:
All primes > 3 are of the form 0 = p mod 6 ± 1
let you reduce your search space.

fiery cosmos
#

tysm!

stable pecan
#

i've got a numpy sieve that's quite fast, but not so readable

#
In [95]: %timeit primesfrom2to(6000000)
43.9 ms ± 718 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
#

though i have a pure python version that's really close to the limit:

In [98]: %timeit sieve(6000000)
890 ms ± 7.25 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
urban gust
#

I have a question dealing with Scraper API and Python. Can someone help?

#

how do i insert code in here? I haven't used the site in a while and forget

topaz pulsar
#

use ``` to open code block

fiery cosmos
#

@stable pecan Thank you so much! Do you think if I run my sieve in numpy it'll become faster?

stable pecan
#

yes, numpy is written in c, so you get to replace slow python loops with fast c-loops

fiery cosmos
#

This is my current code. How would I go about sticking numpy in here? An array of zeroes perhaps?


start = time.time()

#limit = pass + 1 # Prime number theorem

limit = 16000000

flags = [True] * (limit) # Start with all numbers as potential primes
flags[0] = flags[1] = False # 0 and 1 are not primes

for i in range(2, int(limit ** 0.5)):
    if flags[i] is True:
        for j in range(i * i, limit, i): #Start at prime squared, step by prime
            flags[j] = False

print([i for i, n in enumerate(flags) if n == True][999999])

end = time.time()

print(end - start)
#

Thanks - that sounds promising about numpy

stable pecan
#

you can speed that version up with slice assignments

#

but numpy lets you flip flags to false even faster

fiery cosmos
#

Excellent! What function should I use in numpy to do that?

#

I tried using slice, but I got some error about integer iteratives

stable pecan
#
In [76]: import numpy as np
    ...: arr = np.zeros(20, dtype=bool)
    ...: arr
Out[76]: 
array([False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False])

In [77]: arr[::3] = True
    ...: arr
Out[77]: 
array([ True, False, False,  True, False, False,  True, False, False,
        True, False, False,  True, False, False,  True, False, False,
        True, False])
#

you can use slice assignment like so for a numpy array

fiery cosmos
#

thank you very much!

stable pecan
#

np

#

if you have more questions about numpy lemme know

fiery cosmos
#

Is there any difference if I use an array of ones?

#

Just to make it easier, cos it represents true

stable pecan
#

no difference, but boolean arrays will take less memory so be slightly faster to traverse

fiery cosmos
#

I'm going with np.ones(n, dtype=bool). is that the same?

stable pecan
#
In [78]: import numpy as np
    ...: arr = np.zeros(20, dtype=np.uint8)
    ...: arr
Out[78]: 
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      dtype=uint8)

you uint8 is the smallest integer data type i think

fiery cosmos
#

tysm! even faster than bool?

#

Also, what's the fastest way to change those 1s to 0s?

stable pecan
#

np.ones will just start you with all Trues, so whichever one works

fiery cosmos
#

great, thanks

#

How do I change them? Just using python, or using numpy?

stable pecan
#

use the numpy slice assignments as above arr[::3] = True will make every third element True

fiery cosmos
#

ah, thanks a lot!

stable pecan
#

you can do that for arbitrary n

#

to sieve

fiery cosmos
#

yep, thanks a lot

stable pecan
#

you can put the starting number at the beginning as well

fiery cosmos
#

And if I just need to set flags[0] and flags[1] to 0, what's the quickest way to do that?

stable pecan
#

arr[n**2::3] = True

fiery cosmos
#

thanks

stable pecan
#

maybe this is more illustrative of slice-assignments:

In [79]: arr = np.arange(20)

In [80]: arr
Out[80]: 
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19])

In [81]: arr[::3]
Out[81]: array([ 0,  3,  6,  9, 12, 15, 18])

In [82]: arr[::3] = 100

In [83]: arr
Out[83]: 
array([100,   1,   2, 100,   4,   5, 100,   7,   8, 100,  10,  11, 100,
        13,  14, 100,  16,  17, 100,  19])
fiery cosmos
#

tysm you've been so helpful

stable pecan
#

np

fiery cosmos
#

np - nice pun lol

#

just one q - what's the quickest way to set flags[0] and [1] to 0? with python alone?

stable pecan
#

you can do it like normal, but that's slow, you want to replace this whole loop:

        for j in range(i * i, limit, i): #Start at prime squared, step by prime
            flags[j] = False

with the single slice assignment:

flags[i * i:limit: i] = False
fiery cosmos
#

yep, that's the plan

#

thx for the detailed answer!

stable pecan
#

if you need to flip a single flag you can index like before

fiery cosmos
#

index? soz

stable pecan
#

flags[i] = False

fiery cosmos
#

ah, thanks

#

am I going with = 0 instead of = False?

#

or is it the same thing?

stable pecan
#

whichever you want

fiery cosmos
#

if im using dtype uint8, whats better?

stable pecan
#

False, True will automatically get converted to 1,0 for a uint array and vice-versa for a boolean array

fiery cosmos
#

ah tysm!

stable pecan
#

boolean array just uses less memory

fiery cosmos
#

tysm

#

so im using true and false, but as for the dtype, whats faster?

stable pecan
#

boolean

fiery cosmos
#

tysm!

#

got it in 0.2 seconds. tysm!

#

my compsci teacher has a bit of a prize waiting :D

#

so yeah, thanks for your invaluable help - it was super useful

stable pecan
#

no worries, numpy should blow other solutions out of the water

fiery cosmos
#

thats so helpful, seriously tysm

stable pecan
#

oh, there's a faster method than enumerate for recovering the integers

fiery cosmos
#

numpy.flatnonzeros(flags)[999999]

#

thx a lot :)

stable pecan
#

that works

#
In [84]: arr = np.random.randint(0, 2, size=20, dtype=bool)

In [85]: arr
Out[85]: 
array([ True,  True, False, False,  True,  True,  True,  True,  True,
       False, False, False,  True,  True, False,  True,  True, False,
        True, False])

In [86]: np.nonzero(arr)
Out[86]: (array([ 0,  1,  4,  5,  6,  7,  8, 12, 13, 15, 16, 18]),)
#

you don't have to flatten it though

fiery cosmos
#

oh wow, thanks

#

i get an error without flat, but it blows the 1s mark out of the water, so im happy

#

tysm gtg

stable pecan
#

take care

sand coral
#

I want to start a project. The project is a chat app like this, with voice and everything. I would like to make it lik skype and completly free. So, to start, I need some guidance on what to learn. I need to know some libraries, some pattern and everything, but first I need to know if I can start a free software project. I'm one person team by now, but I would like to get people envolved.
Just want to know If it's doable, and what stuff I need to work on first. I would like to create it from scratch, and get developing this app through time. Like 2 years or more. I really would like a speaking foreing language chat app available for free for Linux.

#

!subscribe

fiery cosmos
#

@stable pecan I've worked it to use np.bool and got it to under 10 milliseconds. Tysm!

stable pecan
#

anytime

past lance
sand coral
#

Thank you!

minor chasm
#

just a quick question ... before starting to learn path finding algorithm do u need to have knowledge of other algorithm and concepts ??

runic tinsel
#

of course

#

of course not

minor chasm
#

oh sweet thnx bud

tribal pendant
#

depends on the complexity of the algorithm, and the time complexity you want to achieve.

royal kestrel
#

You most likely need to be familiar with graphs, and some form of priority queue

solid umbra
#

I am planning to use python for competitive programming.. is it good idea?

ripe flame
#

What are you going to be competing against?

solid umbra
#

I am planning to compete in Hackerrank Hackathons or CodeChef

radiant vault
#

I don't think so

fiery cosmos
#

In competitive programming it doesn't really matter what language you use. Its about you knowledge in algorithms, datastructures, maths, etc

#

Some languages make it easer to implement a solution to a given problem, but you need to know what to do

#

For instance in ProjectEuler, just brute forcing problems won't work

#

that being said,Python is very handy since you do have numpy, and scipy

tribal pendant
#

python is one of the best language then, with its huge stlib

last blaze
#

Speed does matter - there are some languages where bruteforcing will work, and then there are some algos that you can implement in a less optimised way if you don't do it in Python

#

most just default to C++ afaik - or Java or another compiled lang

tribal pendant
#

ah ok

fiery cosmos
#

does anyone know how to show enum values in a combo box c# UWP?

tribal pendant
#

I didn't even understand the question, so afaik I can't help, sorry

fiery cosmos
#

does anyone know c# here

#

I mean numpy, and scipy are written in C so they will run fast as well. And again as I mentioned, it comes down to knowledge not what language you use

last blaze
#

You don't want to be calling in and out of C for your logic

#

Also, judging environments don't even necessarily allow libraries

fiery cosmos
#

Don't sure I'm asking in right channel, but why there's a numpy.array([...])? Why do not just a = [...]?

last blaze
#

This isn't really the right channel. But basically, numpy arrays are faster than python lists

tribal pendant
#

If it’s about speed it’s the right channel

umbral shuttle
#

New to python trying to figure out how to read a file into an array

#

I have a textfile with a sudoku in it

#
0 0 0 0 0 0 2 0 0 
0 8 0 0 0 7 0 9 0 
6 0 2 0 0 0 5 0 0 
0 7 0 0 6 0 0 0 0 
0 0 0 9 0 1 0 0 0 
0 0 0 0 2 0 0 4 0 
0 0 5 0 0 0 6 0 3
0 9 0 4 0 0 0 7 0
0 0 6 0 0 0 0 0 0 
stark bridge
#

what will the array have in it?

#

I'm guessing you want integers in rows and columns

#

@umbral shuttle ^^

umbral shuttle
#

yeah

#

I found a way to do it

#

Not very elegant though @stark bridge

#

def readSudoku(directory):
# { 
    file = open(directory) 

    sudoku = []

    for i in range(9):
        row = []

        for i in range(9):
            row.append(int(file.read(1)))
            file.read(1)
        
        sudoku.append(row)
        
        # file.read(1)

    file.close()

    return sudoku
# }

def printSudoku(sudoku):
# {
    for y in range(9):
        row = ""
        
        for x in range(9):
            row = row + str(sudoku[y][x])
            row += " "

        print(row) 
# }

printSudoku(readSudoku("puzzle.txt"))
stark bridge
#

heh

#

that's not terrible but I see what you mean

#

the one change I would make, is: instead of reading one byte, turning it into an int, and then reading another byte and just disacarding it ...

#

... I'd read the entire line, then use .split to get a list of integers

umbral shuttle
#

yeah thats what I was looking for

#

what the method was called

#

I actually do know js funnily enough

stark bridge
#

is this homework?

umbral shuttle
#

no

#

I am doing a python course but it is very slow

#

I want to brute force some puzzles for funzies because it is raining out and I have some free time

#

Trying to quit league of legends actually haha

stark bridge
#

I can show you how I'd do it -- there's a lot of little differences, but some might inspire you

#
def readSudoku(directory):
    with open(directory) as inf:

        sudoku = []

        for line in inf:
            row = [int(field) for field in line.split()]
            sudoku.append(row)

        return sudoku


def printSudoku(sudoku):
    for row in sudoku:

        for index, col in enumerate(row):
            if index > 0:
                print(' ', end='')
            print(col, end='')
        print()


printSudoku(readSudoku("puzzle.txt"))
#

it's more general -- you could have two- or three-digit numbers in your puzzle if you wanted

#

and it could have any number of rows or columns

umbral shuttle
#

what does map(int, ['1', '2']) do?

#
                
def readGrid(directory):
    with open(directory) as file:
    
        grid = []

        for line in file:
            grid.append(list(map(int, line.split())))

        return grid


def printSudoku(sudoku):
# {
    for y in range(9):
        row = ""
        
        for x in range(9):
            row = row + str(sudoku[y][x])
            row += " "

        print(row) 
# }

printSudoku(readGrid("puzzle.txt"))
#

this is what I have so far

#

I am going to do a validation step

#

and a generic printing method

#

as well as a brute force solver after lunch

#

thanks for the help!

stark bridge
#

map(int, ['1', '2']) returns [1, 2]

#

it runs the int function on each string in the list, and returns a list of the results

umbral shuttle
#

How does accumulate differ from reduce?

#

I find it kind of difficult

stark bridge
#

I used to know that 🙂

#

they might be the same thing. it's been so long since I did scheme that I can't remember

#

reduce certainly takes a sequence and returns a single value; "accumulate" sounds like it'd do the same thing

umbral shuttle
#

accumulate returns an array?

#

what...

stark bridge
#

dunno

umbral shuttle
#

oh

stark bridge
#

I wonder if you're looking at docs for numpy

umbral shuttle
#

The summation of list using accumulate is :[1, 4, 8, 18, 22]
The summation of list using reduce is :22

stark bridge
#

shrug

#

dunno what you're reading

umbral shuttle
stark bridge
#

accumulate() returns a list containing the intermediate results

#

that sounds like the crucial difference. Use whichever you like, as long as it works

umbral shuttle
#

reduce works exactly the same as it does in js

#

which is what I was looking for

#

any way to neaten this up?

#
import functools 
                
def readGrid(directory):
    with open(directory) as file:
    
        grid = []

        for line in file:
            grid.append(list(map(int, line.split())))

        return grid

def printGrid(grid):
    for row in grid:
        print(functools.reduce(lambda x,y:x+" "+y, map(str, row)))

printGrid(readGrid("puzzle.txt"))
#

grid = []

#

operation

#

return grid

#

is really messy

#

can I somehow shove this all into one argument?

#

@stark bridge ^

stark bridge
#

mmmm maaayyybe

#

lemme think

umbral shuttle
#

map(lambda x:grid.append(list(map(int, x.split()))), file)

#

is not working

#

I am trying to use a map

#

instead of grid = []

#

then appending

#

then putting that in a list

#

YEAH!

#

I AM FEELING IT!

#

PYTHON POWER!

#
import functools 
                
def readGrid(directory):
    with open(directory) as file:
        return list(map(lambda x:list(map(int, x.split())), file))

def printGrid(grid):
    for row in grid:
        print(functools.reduce(lambda x,y:x+" "+y, map(str, row)))

printGrid(readGrid("puzzle.txt"))
#

PYTHON POWER!

stark bridge
#
def readGrid(filename):
    with open(filename) as file:
        for line in file:
            yield map(int, line.split())


def printGrid(grid):
    for row in grid:
        print(" ".join(map(str, row)))
        

printGrid(readGrid("puzzle.txt"))
#

don't need functools in mine

umbral shuttle
#

I'm jelly

#

what does yield do?

stark bridge
#

oy

#

it ... kinda ... returns, but saves its place, so that the next time you call the function, it takes up where it left off.

#

it's weird.

#

funny how the two functions are pretty similar 🙂

umbral shuttle
#

oh wow lol

#

.join make alot more sense here

#

instead of doing reduce + a lambda

#
def readGrid(filename):
    with open(filename) as file:
        for line in file:
            yield map(int, line.split())
#

I don't understand yield here

#

you don't have a return statement?

#

this whole thing confuses me

#
return list(map(lambda x:list(map(int, x.split())), file))
#

isn't very good either though

#

because its very hard for me to understand

stark bridge
#

you gotta read about yield; it's as weird as you think it is

umbral shuttle
#

I think I prefer using the lambda in this case

#

yield is too weird for me

fiery cosmos
#

Hello

umbral shuttle
#

Hi

umbral shuttle
#

how can I have a function with attached storage?

#

such that the function contains a set and I can pass a flag to it which dumps the contents of the set or and also takes another argument which is stored regardless

#

I have heard this refer to as a functor

#

Also I am aware this could be done with a global variable

#

BUT I to encapsulate the contents of the function

#

And return a bool which is if the contents are unique or not

stark bridge
#

sounds like a job for a decorator -- maybe something like memoization

tiny jay
#

maybe a class, with a callable instance

feral gulch
#

Hey guys

#

I have a question about pseudocode

#

Can I post here?

last blaze
#

That'd probably be fine

thick eagle
#

guys whys it so hard to read x86 assembly

warm marsh
#

I don't think this is a question anybody can give a satisfying answer to 🤔

north zealot
#

Because ASM?

minor chasm
#

so i was trying to undersand the rasterisation rule(for without multi sampling) but i couldnt understand the top edge and left edge rule. can some pls explain it to me. ty 😄

#

actually i got it waat it means :() was just me being dumb lol

#

so from what i understoo it sud fill that top part based on top edge rule isnt it ???

daring plinth
#

Hello 🙂
I hope this is the right channel for a question like this.

I'm currently looking for an efficient way to read a random chunk from an audio file in order to train a neural network.
The most efficient way I could come up with was using
from scipy.io import wavfile
wavfile.read(file, mmap=True)

I'm not too familiar with mmap but it seems to be fast because it's not loading it in memory but using virtual memory to map to the storage drive.
I was interested if anyone knows a better way to do, like only reading the header of the file to get meta-data and then seek to the random position to read the sample.
If possible I'd like to keep files as mp3 or mp4 (audio only) in order to not take too much storage, but I didn't find any library with ~ same efficiency as scipy.wavfile.

Thanks for any insights 🙂

lucid nest
#

Write a function that takes the name of the shape as input and then automatically calculates the output for the respective shape. For simplicity, you may write the function for triangle and rectangle because both the functions take base and height as input.

#

Can anyone guide me ?!

candid osprey
#

Can you do this task if I told you to write it for just a triangle?

loud prism
#

Hi

silk stone
#

Hi,
While I'm learn the fundamentals of programming, through solving problems and coding challenges, but I have an important question:
Should I learn algorithms and data structures first or after spending some time with coding challenges ?
because I got stuck very while I solving problems now
thanks 😃

runic tinsel
#

don't focus on a thing maybe?

#

i bet you didn't choose between learning extensor control and playing with gravity prediction when you were learning to walk

fiery cosmos
#

name chacks out

fiery cosmos
#

Has anyone here used the Runestone course to learn data structures and algorithms? How was it?

spiral swallow
#

@thick eagle because it's very low level, and it has (afaik) a lot of very optimized instructions for particular situations, it's not done for humans, it's done for compilers, some cpu architectures have less instructions set, and so simpler circuits, and they can certainly be easier to read, but that's not what x86 (and x86_64 in particular) is designed for. Also, as it's low level, the code has to care about a lot of details, which makes it harder to understand the high level objective of the code.

gusty grove
#

most of the time you use some kind of pathfinding (something like A* or less advanced)

bronze gazelle
#

You might be able to glean some insight from some of the modding tools folks have created. At a glance it looks like they're using splines but I am totally unfamiliar with pathfinding algorithms

stable pecan
#

you can also hard code millions of paths pretty cheaply and just use one at random

#

i have no idea if that's what they did

gusty grove
#

by hand

#

the level designers will mark the areas as "walkable" or "drivable"

gusty grove
#

normally they just mark the vertices

#

this is how unity's navmesh agents handle it. id assume others do it similarly

quasi oracle
#

Considering the police can track you down I doubt the paths are hard coded

bronze gazelle
spiral swallow
#

I'd just make the vehicles take random directions at intersections, its not like the player is going to check if it makes sense, and yeah, maybe have a small amount of them and move them around when the player doesn't look

north zealot
#

The fancy way : GTA V actually destroy any vehicules or NPC out of range, so you could just spawn them using a circle around the player, and target an intersection node at other intersection on the circle and recalculate them as the player moves

fiery cosmos
#

Just make sure you don’t duplicate The GTA methods disappearing vehicles right next to you because you panned the camera. Us camera whippers notice that lazy coding real quick.

sour wigeon
#

gta uses ai

#

idk maybe not

#

but it looks that way whenever i play

round plume
#

Everytime i download python it DELETES ALL MY FILES

gusty grove
#

Yeah probably they just pathfind to the player. But im pretty sure gta wil spawn cops in front of the player

spare tree
#

is there any name for a diagram that just shows the relationship between the methods in a class?

spiral swallow
#

@spare tree what kind of relationships? method1 calling method2 ? i guess i flowchart could do, or maybe boxes nested in boxes

#

but i don't know how that last one would be named

spare tree
#

yeah basically that's my intent

#

and is it good to have more classes?

#

in general, for places where you dotnt neded as many classes

spiral swallow
#

no, don't do classes you don't have a need for

#

you can make one that you know are going to be handy, but only if you know they are going to be handy really soon, not in some distance future

#

because we always get that wrong and it makes things unnecessarily complex, and makes the design harder to evolve

spare tree
#

oh kk cos i wanted my exam project to look more complex hehe

#

anyway, thanks

stark bridge
#

man I hope you're joking

last blaze
#

In the UK w/ a levels, you'd get more marks for a massively overcomplicated oop structure than for actual good code. It's ridiculous, but exam boards are dumb like that

stark bridge
#

sigh

gusty grove
#

how would a 3d scanline boundary/flood fill work?

fiery cosmos
#

@last blaze i can vouch for this

graceful forum
#

oh dear im planning to take a levels

#

i can code decently already but something about it scares me

boreal verge
#

@graceful forum im doing a levels rn

#

Im doing the international Cambridge 9608 syllabus

#

If u have any questions, Id be more than happy to help

graceful forum
#

aye thanks

fiery cosmos
#

is anyone here good at scheme? @/dm if you are pls

stark bridge
#

I used to be but a) I'm only here sporadically and b) I don't do direct messages

fiery cosmos
#

y is this giving an error

#

plt.xlabel("correct" + class_names[test_images[i]])

#

TypeError: only integer scalar arrays can be converted to a scalar indexerror

hot latch
#

@fiery cosmos You'd probably be better asking that in one of the #help channels, from 0 to 7, that's more where you're going to get help for things like this. #help-kiwi looks like it's been free for some time now. You can check free channels in #bot-commands by doing !f.

Looking at this, it looks like the test_images array you're using is meant to hold a different data type than what can be accepted as an array index.

I don't know what libraries you're using, and am only* assuming this is python, so I'd recommend adding more information to the question and posting it to the other channel ( #help-kiwi ).

hot latch
#

Something I wanted to discuss/ask about:
Can you have a class which as a part of it's constructor, creates a new instance of that same class, except encapsulated within the first instance?
Is this recursion?
How does this relate to first-class objects/functions/etc?

stark bridge
#

I guess you could do that, but eww

#

how would the newer one know not to itself create third sub-instance?

hot latch
#

MAybe have the constructor function pass some number to the next instance, so that it only goes down a certain amount of times?

#

Also, this is recursion then?

stark bridge
#

heh

#

it is but a strange kind

#
class Turtle:
    def __init__(self, size):
        if size > 0:
            self.beneath = Turtle(size - 1)
# >>> t = Turtle(10)
# >>> t
# <__main__.Turtle object at 0x106f3c430>
# >>> t.beneath
# <__main__.Turtle object at 0x107163fa0>
# >>> t.beneath.beneath
# <__main__.Turtle object at 0x107146970>
# >>> t.beneath.beneath.beneath.beneath.beneath.beneath.beneath.beneath
# <__main__.Turtle object at 0x1071b8340>
# >>> t.beneath.beneath.beneath.beneath.beneath.beneath.beneath.beneath.beneath
# <__main__.Turtle object at 0x1071b8820>
# >>> t.beneath.beneath.beneath.beneath.beneath.beneath.beneath.beneath.beneath.beneath
# <__main__.Turtle object at 0x1071b8580>
# >>> t.beneath.beneath.beneath.beneath.beneath.beneath.beneath.beneath.beneath.beneath.beneath
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# AttributeError: 'Turtle' object has no attribute 'beneath'
# >>>
hot latch
#

hahahaha

stark bridge
#

I guess there might be a legit use for this, but I've never run across one

hot latch
#

So is there a way to then do something where you'd build/draw a sort of tree like this, in turtle?

#

Set the angles a bit off, draw a line forward a bit, repeat?

stark bridge
#

I guess, but it seems inconvenient

hot latch
#

I just don't know where to put the self.forward()call

stark bridge
#

I would rather have a simple list of things, than something that you have to traverse using attribute access

hot latch
#

What is allowed in the __init__ of objects like that?

#

Can methods of an object be called in it's init?

stark bridge
#

I guess, seems like a bad idea though

#

I keep __init__ about as bare-bones and dumb as I can

hot latch
#

as little work as possible done there

#

yeah makes sense to do that

#

What if you were to kill the instances off as they completed some task?

#

Could this be used for some kind of recursive search around a filesystem?

#

or is that better done with traditional recursion

stark bridge
#

if I were searching a filesystem in python, I'd use os.walk, like my granddaddy did

hot latch
#

true

#

no need to reinvent the wheel yeah

errant ferry
#

Learning about ADTs

#

Wouldn't all the data types in Python be considered abstract data types?

last blaze
#

They would be implementations of those adts

spark night
#

Is anyone here good at decoding

#

RID THAT DUES TOY HEM FONT THAT WON TITHE FARE NO NO

#

How do I decode this

stark bridge
#

I think "abstract" means: certain operations are deliberately undefined, with the expectation that someone will subclass the type, and provide those operations

magic crypt
#

Hello, I'd like to learn about Natural Language Processing(NLP).
so far I got lost because it's too vast(for me). The more I read or watch some tutorial the more confused I get, so I don't know where to start anymore.
I'm thinking about trying with simple data like CSS files to understanding how NLP does. since it's also easy to get CSS files anywhere to train with.
and so which module I need to use and what tutorial I need to read about this case?

dry agate
#

@spark night you want to program a decoder or decode this specific sentence?

spark night
#

No, I just want to decode it

spark night
#

Like, it’s an anagram that says a day and time in it, and I can’t even find that itself

stark bridge
#

I'd pull out "Monday", "Tuesday", etc and see what's left

#

unfortunately that's long enough that it'd take ages to compute all the anagrams (at least, with my not-terribly-fast anagram checking thingy)

#

might's well try months, too, since those are pretty big words; if you find a month in there, removing those letters might let you brute-force what remains

jolly seal
#

is there anything wrong with this

magic crypt
#

why not 'else' for the last 'if'?

tiny jay
#

because else can be related only to a single if

open flume
#

my cmd isnt recognizing pip

#

how do i download it

tiny jay
#

run these commands one by one and tell me the output:

py -V
python -V
python3 -V
spice ravine
#

py -0 too [that is a zero]

open flume
#

@tiny jay r u talking to me

tiny jay
#

yes

open flume
#

k

#

thats what it returns

#

i wanted to install flask but it isnt recognizing pip

tiny jay
#

@open flume ok so py

#

@open flume next question - are you using some sort of editor to write your code? A programming editor perhaps?

open flume
#

yes

#

the python idle

#

wait i figured out y python wasnt working

#

i didnt add it to system path

tiny jay
#

I strongly suggest using a better editor than IDLE - it is really bad

open flume
#

like

tiny jay
#

I suggest https://thonny.org - it is based on IDLE so you can consider it a upgrade - and it has very nice features for beginners - including a graphical package manager frontend to pip

open flume
#

kk

#

so now i just do pip install django

#

right

tiny jay
#

if you did the path thing correctly, yes

#

otherwise py -m pip install django

#

to use pip from py

open flume
#

thx

#

appreciate ur time

charred reef
#

Hey are there any good math geniuses here? Stuck on something!? Would really appreciate some help! cheers

worthy star
#

@charred reef How complex?

charred reef
#

Well im trying to make an algorithm that can cycle through each possibility

#

In other words, I need the system to cycle through each buy and sell possibility that I have in my txt file. (Its a trading system) i want to force it to buy and sell everything so i can understand what factors makes a profit of loss

#

If that makes sense @worthy star

worthy star
#

Sort of, but what maths do you envisage it'll require?

charred reef
#

are you willing to jump into a quick voice chat? Its almost impossible to explain with words xD

worthy star
#

Don't have a mic, so won't be able to speak.

#

I'm not a maths genius either, but your problem doesn't seem to require complex maths.

#

Calc is my limit (pun intended).

charred reef
#

So as a quick example @worthy star I have a time period from 1 - 10 (lets say minutes) and at each time frame I have price data values so: (open, close, low, high etc.) What i need the program to do is place a trade, so buy and sell, at each time frame. So: BUY @ 1 - SELL @ 2, then : BUY @ 1 - SELL @ 3, then: BUY @ 1 - SELL @ 4 ---- i need it to keep doing this until it runs out of buy and sell combinations so it should end at BUY @ 10 - SELL @ 10

#

Is this a maths problem or just a simple loop code?

worthy star
#

Loops

#
for buy in range(1, 11):
   for sell in range(1, 11):
charred reef
#

is that legit it?

halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied mute to @worthy star until 2020-03-26 15:07 (9 minutes and 59 seconds) (reason: newlines rule: sent 106 newlines in 10s).

charred reef
#

Lol wtf?

cobalt crater
#

!unmute 566591369309847567

halcyon plankBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @worthy star.

charred reef
#

Well thanks @worthy star anyways!

mossy gorge
#

!paste

halcyon plankBOT
#

Pasting large amounts of code

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

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

worthy star
#

Haha.

charred reef
#

lmao

mossy gorge
#

Might want to use the hastebin we host for long outputs like that

worthy star
#

Thanks @cobalt crater .

mossy gorge
#

The bot gets a bit touchy when it sees that many newlines

worthy star
#

I see, thanks.

#

@charred reef The code is:

for buy in range(1, 11):
    for sell in range(1, 11):
        print('Buy:', buy, 'Sell:', sell)
#

That should work.

charred reef
#

@worthy star Legend it worked thanks!!

#

So simple xD

worthy star
#

You're welcome!

wild bronze
#

hey I have a question about RSA keys. I have a file that contains rsa public key. I looked it up and got the idea how they are generated by two prime numbers. So my file (I think) contains a number which is base 64 encoded but when I decode it back with base64 I get unprintable characters not numbers(I expected numbers). Does that mean my RSA key numbers are encoded with a different encoding rather than utf and then base64 encoded??

north zealot
#

No they're just raw bytes representing your key

wild bronze
#

but when I look at the wikipedia page

I see statements like

c(m) = m^17 mod 3233``` so do raw bytes not represent 3233 and 17?
#

@north zealot

north zealot
#

I think they do, but I'm not sure

stark bridge
#

I'd be surprised if the numbers were as small as 3233 and 17, but I think those raw bytes do indeed encode integers

wild bronze
#

could this be the case like the difference between binary 1 and printable character 1?
lets say my key is (n = 255 e=5)
11111111 00000101 binary version

stark bridge
#

something like that

#

there are lots of ways to encode numbers into bytes, and I don't know which one the RSA key uses -- but I bet it's a fairly common, and well-documented one

wild bronze
#

How can you tell looking at the base64 encoded 'G+glEae6W/1XjA7vRm21nNyEco/c+J2TdR0Qp8dcjP' string with a lenght of 42 characters is 32 bytes long?

north zealot
#

Yes you can

#

Base64 have an overhead of exactly (100/3)%, rounded up

#

So you can exactly calculate the length of the decoded string

charred reef
#

Hi guys, can someone tell me why this code is in-consistent? :

#

''' for buy in dataPrice:
for sell in dataPrice:
if sell >= buy:
outcome = ('\x1b[0;31;40m' + "Loss")
else:
outcome = ('\x1b[0;34;40m' + "Profit")
print("Buy:", buy[3], "Sell:", sell[3], outcome) '''

#

and how the hell do I paste code in discord correctly lol

worthy star
#

Use three back-ticks before the code and three after.

#

@charred reef Back-tick is the (`) symbol next to the 1 key (on a QWERTY keyboard)

charred reef
#
    for sell in dataPrice:
        if sell >= buy:
            outcome = ('\x1b[0;31;40m' + "Loss")
        else:
            outcome = ('\x1b[0;34;40m' + "Profit")
        print("Buy:", buy[3], "Sell:", sell[3], outcome) ```
#

Ah lovely

#

cheers

worthy star
#

What's the problem?

charred reef
#

Heres a little snippet of the output code:

#

Buy: 1.5016 Sell: 1.5017 Profit
Buy: 1.5016 Sell: 1.5015 Profit
Buy: 1.5016 Sell: 1.5017 Profit
Buy: 1.5016 Sell: 1.5016 Loss

#

now the 2nd line, the Sell value is lower than the buy value, but it's still registering as a profit where it should be a loss

#

cant figure out why

worthy star
#

It could be that the difference is so small.

#

Which python version?

charred reef
#

3

#

3.7

#

even though in my code it states that if sell >= buy:

#

But in this case sell is less than buy

#

but output still seems to be a profit

worthy star
#

You are checking sell >= buy yet you are printing buy[3] and sell[3]. Print buy and sell instead and see the result.

charred reef
#

Nope same issue, I just get the entire list printed rather than that column [3]

worthy star
#

Can you show the output?

charred reef
#

Buy: ['GBPUSD', 20010102.0, 234900.0, 1.5011, 1.5012, 1.5009, 1.5009, 4.0] Sell: ['GBPUSD', 20010102.0, 230100.0, 1.5021, 1.5021, 1.5018, 1.5018, 4.0] Profit
Buy: ['GBPUSD', 20010102.0, 234900.0, 1.5011, 1.5012, 1.5009, 1.5009, 4.0] Sell: ['GBPUSD', 20010102.0, 230200.0, 1.5019, 1.5019, 1.5019, 1.5019, 4.0] Profit

#

thats just 2 rows, i have thousands

#

hold on

#

actually it technically worked

#

but i only wanted it to print column [3] instead of all of them

worthy star
#

What's your code now?

#

But also, try changing sell[3] >= buy[3]?

charred reef
#
    for sell in dataPrice:
        if sell[3] >= buy[3]:
            outcome = ('\x1b[0;31;40m' + "Loss")
        else:
            outcome = ('\x1b[0;34;40m' + "Profit")
        print("Buy:", buy, "Sell:", sell, outcome)```
worthy star
#

Now just change print("Buy:", buy, "Sell:", sell, outcome) to print("Buy:", buy[3], "Sell:", sell[3], outcome)?

charred reef
#

ah

#

let me try

#

its worked

#

Buy: 1.5011 Sell: 1.5009 Profit
Buy: 1.5011 Sell: 1.5011 Loss
Buy: 1.5009 Sell: 1.5021 Loss

#

but the values are opposite let me cvhange that

#

yeah perfect its working

#

One more thing @worthy star Any idea why the colours are abit dodgy?

royal kestrel
#

Because the colour carries over

#

You need to reset it

worthy star
royal kestrel
#

colourama is just a wrapper around ANSI codes

#

doesn't really matter

charred reef
#

lovely thanks alot guys

sharp atlas
#

can someone explain how pyramid image blending works

#

like i get the whole gaussian and laplacian pyramid part but im having trouble visualizing how it would make a nicely blended image

#

like how does blending the resulting laplacian pyramid mashed together make a normal image

#

it seems that most of the colors in the laplacian pyramid are just black

sharp atlas
#

this is probably easier

#

my confusion starts past line 35, because i dont understand why apple_orange_pyramid[0] is a small color blended image when its generated from a laplacian pyramid

#

it looks like the laplacian images are mostly black with outlines of the objects which makes sense

#

or is the first image so small that those outlines are enough to make up the entire image?

lean pawn
#

Hi everyone. I just used python for computer vision. I need lots of references for pixel interpolation in images using python.

I have an RGB image like the following. In that picture, I have a white unknown pixel. I want to interpolate the unknown pixel starting from the point (x0, y0) using the colour intensity information along the blue line. Can someone provide code samples for interpolating at point (x0, y0) with any interpolation technique? The input is a collection of coordinate colour references x,y = np.where(np.all(img == [0,0,255],axis=2)) and pixel coordinates (x0, y0). The output is pixels (x0, y0) which have been interpolated.

How to Interpolate Unknown Pixel given Coordinates references?

fiery cosmos
#

I want to make sure I am on point here. A word is a simple piece of data that is used within an instruction. An instruction is stored in a register?

#

I am reading a book on computer architecture. I get confused on some things.

stark bridge
#

a "word" is a unit of storage. How big it is depends on the computer

#

I didn't think anyone talks about "words" anymore

#

some ancient computers had 36-bit words

#

instructions can be stored in registers; in fact they have to be put into a register before being used, iirc

#

most of your instructions, though, are in memory, waiting to be run

warm marsh
#

I think the unit "word" still used in context of assembler or lower level C code.

stark bridge
#

I guess

#

people still do assembly and C? :-}

warm marsh
#

of course they do 😄

bright cedar
#

hi could someone help me im trying to write a function to create a lightened grayscale image. image by adding 75 to the red, green, and blue components of every pixel. Since higher numbers are closer to white, this make the pixel lighter. Now, grayscale for the new image

drifting drum
#

@bright cedar iterate through all the pixels and add 75(Making sure to actually take max(value + 75, 255) in case you overshoot) ?

gusty grove
#

if its already a np array you can just add it directly

#

gray = np.clip(gray + (75, 75, 75), a_min=none, a_max=255)

#

@bright cedar that should be a lot faster than looping over it

#

and more pythonic

#

with numpy you will always want to use numpy operations if you can

stable pecan
#

you can also use cv2 to do it for you

#
In [51]: arr = np.random.randint(0, 256, size=(10, 10, 3), dtype=np.uint8)

In [52]: cv2.cvtColor(arr, cv2.COLOR_RGB2GRAY)
Out[52]: 
array([[ 64, 120, 128, 123,  69, 169, 100, 165, 111, 101],
       [179,  72,  93, 200,  87,  66, 207, 198,  42,  93],
       [ 58, 141, 177,  17,  34, 177, 156, 126, 107,  56],
       [ 85,  99,  75, 106, 143,  74, 114, 177, 189,  92],
       [206, 189,  72, 111,  85,  32, 230,  45, 208,  42],
       [ 53, 153, 166, 117,  81,  98, 136, 141, 192,  93],
       [133, 121,  84, 159, 105, 117, 137, 159,  93, 134],
       [ 91, 175,  68, 206, 109, 108,  58, 125,  35,  88],
       [ 80, 200,  86, 202, 187,  63, 135, 198, 212,  39],
       [ 63, 117,  72, 114, 238,  81,  52, 173, 140, 186]], dtype=uint8)
fiery cosmos
#

um, this is kind of a stupid question but how do i run my python script in vs 2019?

#

pls ping me

night ruin
#

VS2019 iirc has a Python runner

fiery cosmos
#

how?

#

i tried f5 to run the script, but it wouldnt work

night ruin
#

did you install Python ?

#

in the VS installation

fiery cosmos
#

yes

#

about 7gbs

night ruin
#

that sounds like too much for Python

fiery cosmos
#

its just a python script i made long ago, i want to test it out with vs

night ruin
#

you need to run the installer, select Modify, then select the Python Development workload

#

then continue

fiery cosmos
#

oh

#

k

#

yup, its already checked

#

@night ruin sorry for the ping, ^^

night ruin
#

np

fiery cosmos
#

and the python dev workload is already checked

night ruin
#

yea

#

that looks right

fiery cosmos
#

so..?

night ruin
#

you have python installed on yoru pc right

fiery cosmos
#

yes

#

all of that shit is already installed lol

night ruin
#

then you need to create a python environment so vs knows you want to run python

fiery cosmos
#

how?

#

already have a couple of envs installed

#

python 3.7.5 32-bit and 64-bit

#

i just want it to run on cmd, like a normal script lol

#

i guess i could just code on vs and then run the script from the .py file itself

azure inlet
#

@fiery cosmos @night ruin I don't think this is related to computer science.

#

Feel free to use a free help channel.

fiery cosmos
#

oh, apologies

azure inlet
#

No problem.

errant ferry
#

Learning about Big-O etc

#

def convert_dec(n):
    binary = 0
    for i, _ in enumerate(str(n)[::-1]):
        binary += i * 2
    return binary

Would this be O(n)?

last blaze
#

Yes, it would be

errant ferry
#

@last blaze

#

If I added a random x = 2 at the bottom, that does nothing

#

It would be 1n + 2

#

Still O(n) right?

north zealot
#

Yes

errant ferry
#

Thanks

north zealot
#

O(n) just says that the computation time is proportional to the input size

bright cedar
#

@gusty grove @stable pecan @fiery cosmos sorry kinda fell asleep im still a beginner in python and my professor required we use the latest verison of pycharm to grayscale from rgb

#

so the question that was ask was Write a function to create a lightened grayscale image. First, lighten the image by adding 75 to the red, green, and blue components of every pixel. Since higher numbers are closer to white, this should make the pixel lighter. Now, grayscale the new image.

fiery cosmos
#

@bright cedar lol i think you tagged the wrong ppl haha

bright cedar
#

ah shoot my bad

drifting drum
#

you can also use cv2 to do it for you
@stable pecan the code after that, you converted rgb to gray, where's it adding the 75s though?

stable pecan
#

it's not, just do arr + 75 before hand

drifting drum
#

oh, you were talking about the latter part

#

aight

clear rose
#

is there any advantage of using apache spark over pandas dataframes? How would you integrate both?

atomic olive
#

I think this is appropriate channel. The ACM digital library is free till June due to covid

#

It’s full of research papers on various topics.

spiral swallow
#

nice

feral spindle
#

1585674071

#

what kind of time is this?

#

how can i turn it into hours days or whatever

fiery cosmos
#

That is epoch time

#

Use time.strftime to convert it

stark bridge
#

datetime.datetime.fromtimestamp iirc

#
>>> import datetime
>>> import pytz
>>> datetime.datetime.fromtimestamp(1585674071, tz=pytz.utc).isoformat()
'2020-03-31T17:01:11+00:00'
>>> 
valid mantle
#

Looking for some help on getting started with ML classification.
I have product listings, categories, and descriptions from a number of websites.
I have my own categories that I want to group these listings.
I have manually categorized a large number of the listings.
What's next? Does anyone have a good example project or guide that goes through something similar.

grand barn
#

Tensor Flows and Pytorchs websites are quite good. Most documentation in this field is quite good as well

#

Although be warned, they don't hold back on the maths so you probably need to know calc and matrix operations at a minimum

valid mantle
#

I'm looking into pytorch and text classification now and finding useful resources

#

thank you!

grand barn
#

No worries

split geyser
#

Guys, Does anyone know any good way to train a chatterbot?

stark bridge
#

I think I seeded mine with a bunch of hand-selected quotes, but I also let it just accumulate stuff from the channel

fiery cosmos
#

@split geyser This might help

#

Using a corpus file instead of seeding it with bunch of quotes!

split geyser
#

Tyy

woven wind
#

Hello, does anyone have an idea how I can make a minimax function given the state of a tic tac toe board?

fiery cosmos
#

does anyone know why in boolean logic a inverted gate requires two transistors

#

while a non inverted boolean gate requires 3 transistors?

#

I am reading a computer architecture book and it is not really explained well

half forum
#

@woven wind tic tac toe is either a win/loss or tie

#

so the psuedocode would look something like this

#
self.game = Game() # surrounding scope of the MinMax function

def MinMax(self):
    if self.game.Winner() == self.game.CurrentPlayer(): # current is X or O
        return WIN
    elif self.game.Winner() == opposite(self.game.CurrentPlayer():
        return LOSS
    elif self.game.Winner() == TIE:
        return TIE
    
    result = LOSS
    for move in self.game.LegalMoves():
        self.game.Play(move)
        tmp = oppositeResult(MinMax()) # opposite turns WIN into LOSS, LOSS into WIN and TIE into TIE
        self.game.Undo()
        result = max(tmp, result) # assumes WIN > TIE > LOSS
    return result
#

important functions here are checking terminal state, playing and undoing moves, and being able to find all legal moves for a given state (empty points in tic tac toe)

lean sleet
#

why do yall like python so much?

soft patrol
#

development time

#

it's very easy to get something pumped out and functioning with python, much faster than in other languages

#

there's a performance cost, but there are ways you can take advantage of multithreading and async and call C code to speed up your program

#

it's also not as broken as JavaScript

woven wind
#

@half forum so opposite result is the recursive function?

#

I have a terminal function, a result function and I'm gonna create an undo function

woven wind
#

it's supposed to return the optimal action for the AI tho, not the result

elfin sundial
#

@half forum thats litrally python not pseudo code

#

there is no defMinMax(self): in pseudo

woven wind
#

Python is very similar to pseudocode you could just call it pseudocode lol

wild bronze
#

I want to ask something about Kernel and CPU.
What exactly is a syscall?
Assume I have an application which just prints 'hello world' by printf().
I think what happens in the background is that Printf() makes a syscall to write(). In lower level, does it mean my application running in the user space has an INTx80 instruction which is basically a jmp instruction in assembly which jumps to kernel application in memory to execute codes

half forum
#

if its on a linux system then yes

#

and its not exactly a jmp instruction

#

if you look up what an interrupt is, it saves the state of the currently running process, then handles the interrupt in kernel space

wild bronze
#

I always think of kernel as a process that I can see in gdb

#

when you say it handles the interrupt in kernel space I think of code execution in other process which is not accessable by gdb

#

@half forum on 32 bit systems, kernel space would be 1 gb, user space would be 3 gb in ram. As far as I know cpu won't execute some instructions in user space because this area is protected. Kernel mode however I don't know what it means in this context

half forum
#

yeah kernel mode

fiery cosmos
#

Hi

cursive owl
#

I'd like to build a simple word-order-based LSTM RNN to produce imitations of people in a chat room. I've found the keras library and wow is there a lot going on there. Could anyone recommend any resources or terms to research to send me in the right direction?

cursive owl
#

I tried my hand at figuring it out on my own and managed to produce the word "wererererere" from a few paragraphs of classic literature. 🤔

soft patrol
#

why is it that "werererere" is easier to understand than shakespeare?

#

seems like your RNN is learning well

rancid birch
#

Hi everyone. I'm trying to write a ast.NodeTransformer subclass that does something similar to constexpr in C++. My attempt and the ideal desired API can be found here: https://hackmd.io/7Mr6f1HORxeg_RD5viZ_IA

#

Full disclaimer, I'm a newbie at AST manipulations, so be gentle.

fiery cosmos
#

I will be gentle

#

can't help with the question though

hearty maple
#

Hello, I am sort of a beginner to Python. I am currently in grade 11 so don't know much about advanced python coding. I am trying to make a 2d game where upon screen update the enemy will go towards the player. My problem is it happens too fast and i would like to make it so it takes a while for the enemy to get there. If anyone can help me with that it would be awesome

spiral swallow
#

well, "toward" is a direction, you want to be able to define the distance, and also, "upon screen update", you want to compute the amount of time that was spent since the previous update, and use that to adjust the distance.

#

fixing framerate to a fixed value usually make things easier, if you can.

sturdy prairie
#

What is an algorithm to find the farthest vertex from a given vertex, X, in an undirected graph?

last blaze
#

two elements with the largest possible shortest path between them?