#algos-and-data-structs

1 messages · Page 80 of 1

prime flame
#

is there any good guide on when one has to worry about rounding errors in python? With the ducktyping I never really thought about the datatypes used. But i'm thinking about implementing something thats dangerous in terms of rounding errors

#

something along the line of```python
value = (current-upgraded)/(current*costs)

#

where current and upgraded arent too different, but can grow huge, and costs could also go up a lot. also upgraded may be equal to current

stark bridge
#

I don't think python has much specific to say about that@prime flame

#

you might be able to use Decimal, which guarantees exactness at the cost of memory usage (and perhaps slowness)

prime flame
#

I don't think that would work. the values for current and upgraded will come from a supplied function wich somehow assigns a value to a game state

#

I think I'll just drop that approach for now. the target would have been to 'combine' two different functions by weighting their value as defined above

#

(wich I'm also unsure about if it would work as I would expect...)

turbid path
#
    res = [[]]
    for i in [tuple(i) for i in args]:
      res = [x+[y] for x in res for y in i]
    return res
print (product([1,2],[1,2]))```
#

thank you python

#

this is a readable cartesian product code

quasi oracle
#

@turbid path might as well do

def product(*args):
    return list(itertools.product(*args))
print(product([1,2],[1,2]))
stark bridge
#

👍

steel quarry
#

Is it better to have multiple packages or less? Or is this a personal opinion?

quasi oracle
#

As many as you need? the number of imports is negligible for the average program as long as you keep your namespace clean

#

Also not particularly comp sci related 😅

candid wadi
#

How can I use an array as a member in a class?

#

I defined this class:

class Overlay:
    def __init__(boxes, strings):  
        self.boxes = []
        self.strings = []
#

I tried to initialize one like this:
overlay = Overlay([], [])

#

But I get TypeError: __init__() takes 2 positional arguments but 3 were given

#

I basically want to treat it like an object

stark bridge
#

you forgot self

candid wadi
#

I want to append other class objects into the arrrays

stark bridge
#

def __init__(self, boxes, strings):

#

do dat

#

eet feecks

candid wadi
#

Ah, I'm retarded

#

🙂

#

Thanks, bud

stark bridge
#

💐

sly vale
#

If im trying to create a DFS its valid to insert each item in a list then pop that item out right?

sly vale
#

some actual code

sly vale
#
nodes = ['A','B','C','D']
def DFS():
    global nodes
    node = nodes.pop(0)
    children = node.get_children()
      for child in children[::-1]:   
        nodes.insert(0,a)       
    if nodes == []:
        return
    else:
        DFS()       
DFS()```
stark bridge
#

that's how I do a breadth first search

#

depth first, I think you can just use recursion

sly vale
#

im inverting the list

#

so if A had children 1,2,3, would the new nodes be

#

[1,2,3,B,C,D] then we pop 1 and if one has no children we recall and pop 2

#

etc..

quasi oracle
#

@sly vale the order of immediate children makes no difference. You insert to the beginning and pop from the beginning, so it works like a stack, though I imagine not the most efficient one, so in theory this should get you DFS. However I'm not sure why you're mixing a stack with recursion when either one or the other would give you a complete solution

gloomy lily
#

Hi guys, I'm a bit new to data structures. I'm trying to reverse a doubly linked list in Python - simply by swapping the head and the tail using

#

self.head, self.tail = self.tail, self.head

#

Any idea whether this is just..wrong or is there something in my code for traversal (from start or end) that is erroneous?

#

I created a list, reversed it and then tried traversing it again and I'm getting an error:

#

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-102-65d98c8b6d59> in <module>
----> 1 mylist.contentsFromStart()

<ipython-input-94-7df8fc721289> in contentsFromStart(self)
     23         elements = []
     24         current = self.head.next
---> 25         while(current.next!=None):
     26             elements.append(current.data)
     27             current = current.next

AttributeError: 'NoneType' object has no attribute 'next'
quasi oracle
#

The problem is that self.tail.next is None

#

You make it the head, but it doesn't help with the links in your list

#

So now the head is pointing at None

gloomy lily
#

I was thinking self.head and self.tail are both objects of the class. So swapping them should swap their previous and next values too right?

From what I think my mistake is, according to what you said, is that the self.head.next and self.tail.previous point to None instead of the list elements. Am I correct?

quasi oracle
#

Correct. An easier solution would simply be to swap only the data they hold

gloomy lily
#

self.head and self.tail have no data values though, they're both None...

quasi oracle
#

Oh you want to reverse the whole thing

gloomy lily
#

Yes yes

quasi oracle
#

Then no, swapping the head and tail won't do it. Make yourself an example on a piece of paper and look at the reversed version vs the result of what you did

gloomy lily
#

Okay, I'll have a look. Thank you very much!

quasi oracle
#

Also are you making the head and tail hold None by definition? Because there's nothing preventing them from holding a value just like any other node

gloomy lily
#

Yes, while initializing the node class, the default value that any created node takes is None. So since I haven't created the head and tail nodes by giving a parameter of some value, their value is None

#
class node:
    def __init__(self, data = None):
        self.data = data
        self.next = None
        self.previous = None
 
class ll:
    def __init__(self):
        self.head = node()
        self.tail = node()
        self.tail.previous = self.head
        self.head.next = self.tail

Like so

quasi oracle
#

I'd set the head and tail of an empty list as None, instead of an empty node

gloomy lily
#

Oh, yes that makes sense

sly vale
#

@sly vale the order of immediate children makes no difference.
@quasi oracle so it doesn’t matter if which child I search as long as once I get those children I add it to the stack

quasi oracle
#

Yes that's right. BFS / DFS just says what the distance of the next traversed node should be from the root

#

In DFS you get as far away as you can, in bfs you stay as close as possible, from the nodes still not visited

#

Though in binary trees you traditionally visit the left child first

sly vale
#

Yea that makes sense thanks

fiery cosmos
#

can i use python to discover vulnerabilities?

fiery cosmos
#

Can someone verify my SysML Block definition diagram and my Parametric diagram?

tribal plume
#

Hi, can somebody help me to solve this question?
shuffle.py Write a function that takes a word, splits it in half, recombines it in the reverse order, and then returns it.

runic tinsel
#

"antilope"[:2] becomes "an"

#

that's how you split

#

+ to combine

rocky lagoon
#
from math import floor
s = "antilope"
s[:floor(len(s)/2)]
#

that would be half

#

@tribal plume

runic tinsel
#

yikes

junior locust
#

define a function largest(n) ): that recursively finds the largest digit in the number stored in n,
and return it. Can someone help me with this

runic tinsel
#

the last digit of a number: n % 10
all the other digits: n // 10

#

then you find the largest digit in the n // 10

#

then you have 2 candidates, return the larger one of them

junior locust
#

the problem is this is my school's assignment and i cannot use a loop or max function i have to do it using recurssion only so how should i find the largest digit of n//10

runic tinsel
#

max function? just do it by hand

#

out of 2 numbers, which is what you have, 2 candidates

#

it's the complete algorithm I gave, pretty much just write exactly that

junior locust
#

alright

runic tinsel
#

largest(n)

#

well not n, but it's largest(something)

#

now you make what they call a base case

#

at the start

#

how can you detect if n has 1 digit?

#

I guess you can aslo detect if it's 0

#

more boring

junior locust
#

i am really sorry but i am just a beginner and i am not getting whatever u r trying to say so will u mind sending the source code .... no need to put a check if n has 1 digit or n is 0 i will do that

runic tinsel
#

I was going to ask you to send yours

rocky lagoon
#

yikes
@runic tinsel Why do you say yikes when I am posting the solution to a question?

runic tinsel
#

I reacted like that because it crashes

rocky lagoon
#

What crashes?

runic tinsel
#

the code you sent crashes

rocky lagoon
#

hmm it shouldn't

runic tinsel
#

so it's like objectively embarassing

rocky lagoon
#

There, corrected it. However, you should check your attitude

#

You could tell me without being a giant ass about it

#

Everyone makes mistakes, especially when giving a quick example

#

And besides, you didn't have the approach right with your answer, so maybe it's not up to you to point fingers

runic tinsel
#

nah, that would be self-reflection

junior locust
#

def largest(n):
largest = 0
while (n):
r = n % 10
largest = max(r, largest)
n = n // 10
print(largest)

#

this is what i have done

#

but cant do that because loop is not allowed

#

@runic tinsel can u help me now what should i do?

runic tinsel
#

@junior locust you;re not allowed to print

#

surprise

#

surprise

junior locust
#

i am allowed to print

runic tinsel
#

that's why it's a surprise, you didn;t know

#

you're not allowed to print the answer, that's not how it works

#

a function returns the answer

junior locust
#

def largest(n):
largest = 0
while (n):
r = n % 10
largest = max(r, largest)
n = n // 10
return(largest)

#

is it ok now?

runic tinsel
#

it's usually without () but that's minor

#
def largest(n): 
    if n is 1 digit return n
    r = n % 10
    n = largest(n//10)

return the r or the n, the larger one

junior locust
#

yeah thats because i replaces print with return so forgot to remove it

#

ok

#

def largest(n):
if n <10:
if n>r:
return n
else:
return r
r = n % 10
n = largest(n//10)

#

is this u want me to do ?

runic tinsel
#

yeah but not in this order

#

that part where you return the larger one, it's at the end

#
  if n <10:
     return n
```and that's the base case
#

@junior locust congrats, that's it

junior locust
#

Thanks for ur help

frigid quail
#

I'm trying to wrap my head around kd trees, but can't seem to get the searching part

sharp onyx
#

Just out of curiosity, are you using kd trees from scipy, scikit, or your own implementation?

pseudo wave
#

SciPy has metric trees?

#

Oh damn. This is so useful to know

sly vale
#
def dfs_recursive(graph, vertex, path=[]):
    path += [vertex]

    for neighbor in graph[vertex]:
        if neighbor not in path:
            path = dfs_recursive(graph, neighbor, path)

    return path


adjacency_matrix = {1: [2, 3], 2: [4, 5],
                    3: [5], 4: [6], 5: [6],
                    6: [7], 7: []}

print(dfs_recursive(adjacency_matrix, 1))```
#

I have a question as to the order in which this is traversed

#

it goes from 1 -> 2 -> 4-> 6-> 7

#

which makes sense

#

however then it goes back up and the next thing it executes is 6

#

is that because the

#
    for neighbor in graph[vertex]:
        if neighbor not in path:```
#

hasnt finished running yet?

#

so it finishes checking that right

#

then it returns path for that value then it jumps to 4: for neighbor in graph[vertex]: if neighbor not in path:

#

then 2 etc...

#

i def like using stacks better for DFS

royal kestrel
#

What exactly do you mean "next thing it executes is 6"

#

As you said 1 -> 2 -> 4-> 6-> 7 makes sense

Then since 7 has no children, you go back up the tree, back to where you came from, so 6

6 has no more children, so you go back up to where you came from, 4, once again no other children, so you go back up to 2

2 has another child, 5. You now go to 5. 5 has one child, 6, but you've already visited it so you return back up to 5.

5 has no other children, so you go back up to 2

2 has no other children, go back to 1

1 has another child, 3 go into it. 3 has a child 5, which is already seen, go back to 3. 3 has no other children and the traversal is complete

#

Do note that since you have path=[] repeated calls to this function will start showing incorrect results due to how list.__iadd__ is implemented

#

Default values are evaluated only once and path += [vertex] adds to that empty list

#

You can see this in effect if you change the function to be ```
def dfs_recursive(graph, vertex, path=[]):
path += [vertex]

return path```temporarily, then call it twice with the same arguments
sly vale
#

in other words the first time we called 6 it checks for 7 then after 7 is done running the for loop for 6 hasto still finish

royal kestrel
#

yes

#

The loop that 6 started called 7 inside it

#

7 finishes so the loop is continued

#

the loop terminates as there is no more items and the same effect cascades up the entire tree

sly vale
#

Ok that’s what I thought thanks

frigid quail
#

Oh scipy has kdtrees? I'm implementing my own though as I'm going to make another in a different language

#

Just saw that it's open-source, I'll be looking at how they do it. thanks

grave rover
#

Hi

#

my problem is quite simple

#
top_list = []
top_val = -1
second_list = []
second_val = -1
for x in user_dict:
  cost = user_dict[x]["redemption_costs"]
  if cost > top_val:
    second_list = top_list
    top_list = [x["user"]]
    second_val = top_val
    top_val = cost
  elif cost == top_val:
    top_list.append(x["user"])
  elif cost > second_val:
    second_list = [x["user"]]
    second_val = cost
  elif cost == second_val:
    second_list.append(x["user"])```
#

user_dict is a dict that looks like

{
  "some_random_numbers": {
    "user": user, 
    "redemption_costs": 0, 
    "days_redeemed": [False for x in range(process_time)]
  }
}
#

Is there a faster way to do this?

fiery cosmos
#

@grave rover you forgot to mention what the problem was fam

grave rover
#

this is currently o(n) right?

#

Oh 4Heed

#

I have to get 2 lists, the users with the highest and the second highest "redemption_costs"

fiery cosmos
#

optimization of the code, aight headin out

grave rover
#

XD

#

i dont think there is a o(logn) solution

#

but i dont know.

#

or simply a better way to do it.

quasi oracle
#

If the point is to go over each element in the dict, then it has to be O(n) at least
Though I'm honestly not sure what the goal is

stable pecan
#

are you trying to make two lists are just grap the top two users by redemption costs

#

i see, you can do this with less code if you use standard library Counter, or heapq

#
from heapq import nlargest

user_to_costs = {sub['user']: sub['redemption_costs'] for sub in user_dict.values()}
first, second = nlargest(user_to_costs.values(), 2)
firsts = [user for user, costs in user_to_costs.items() if costs = first]
seconds = [user for user, costs in user_to_costs.items() if costs = second]
onyx spindle
#

hello

grave rover
#

@stable pecan is that faster?

lean dome
#

What you have is O(N), AFAICS, @grave rover - it makes one pass through the list and inspects each key only once.

grave rover
#

Yes I know

stable pecan
#

it isn't faster! but it's easier to read, at least for me

pastel siren
#

hey guys, this is not realated to python but can anyone explain what two way logic is?

lean dome
#

I can only find a small handful of papers that use that term after a quick search - where did you see it? How did they define it? @pastel siren

pastel siren
#

Yeah I’m not so sure either, I guarantee my lecturer wouldn’t know either.

north zealot
#

Would someone know a good paper about parser engines, like regex engines?

royal kestrel
north zealot
#

Thanks!

past flare
#

Hi guys

#

can someone explain me big and little endians? I googled it and figured out it's the order of the bytes, for example a big endian is ordered from the most important byte to the least one

#

But what the most important byte should be?

north zealot
#

To make things simple, the most significant bit is the bit that carry that yield the most numbers when you convert to base 10

#

For example, 0b001

#

If the most significant bit is the right bit, you have 0 * 4 + 0 * 2 + 1 * 1 = 1 in base 10

#

If the most significant bit is the left bit, you have 1 * 4 + 0 * 2 + 0 * 1 = 4 in base 10

past flare
#

so which is better to use?

north zealot
#

There sin't really any better one, that depends on the arch you're working on

past flare
#

Btw

#

bin(10) is 1010

#

but why if 10%2 = 0; 5%2=1

#

etc

#

so we get 0101

#

not 1010

dapper osprey
#

you have to read the from the bottom up

#

why, no idea tho :p

sand abyss
#

top_list = []
top_val = -1
second_list = []
second_val = -1
for x in user_dict:
cost = user_dict[x]["redemption_costs"]
if cost > top_val:
second_list = top_list
top_list = [x["user"]]
second_val = top_val
top_val = cost
elif cost == top_val:
top_list.append(x["user"])
elif cost > second_val:
second_list = [x["user"]]
second_val = cost
elif cost == second_val:
second_list.append(x["user"])

hexed pike
#

Hi Guys!!! There was such a problem: installed the library pillow, started PyCharm, created a new project on the python file and try to start the library pillow with the pip command (pip3) install but the following error appears: "pip" is not internal or external
command, executable program or batch file. The library itself is installed in my lib -> site-packages. My python version is 3.8.2. If anyone has this problem or knows how to solve it, write to me

fiery cosmos
#

Hello, so recently I've been working on a project a simple cookie clicker game to get my started with programming. I have started to make it but ran into a problem ( I am using tkinter to make this ) how would I display variable (e.g variable named Cash) in a Label and it loops like every 1 second to update the Label for the user gui.

  • Thanks!
vital quiver
#

with connections.scdb() as db: dataset = db.fetch(sql) for item in dataset: pk = item['BARCODE'] self.__barcodes[pk] = item pk = item['SAMPLE_ID'] self.__samples[pk] = item pk = item['IDENT'] self.__num_samples[pk] = self.__num_samples.get(pk,0) + 1

Regarding this code which I have had passed to me, I wonder about the assigning of item. Would barcodes[pk] and samples[pk] point to the exact same element in memory, or is it two separate instances?

last nacelle
#

Hello guys please i need your help here

#

Describe the difference between objects and values using the terms “equivalent” and “identical”. Illustrate the difference using your own examples with Python lists and the “is” operator.

Describe the relationship between objects, references, and aliasing. Again, create your own examples with Python lists.

Finally, create your own example of a function that modifies a list passed in as an argument. Describe what your function does in terms of arguments, parameters, objects, and references.

Create your own unique examples for this assignment. Do not copy them from the textbook or any other source.

raw furnace
#

I dont think helping with graded assignments is allowed here

marsh bone
#

Hi guys, is anyone here familiar with tesseract ? I am sort of new to python, but i am familiar with other languages,
when i try to get the text off this image I just get "AN afi" not even a number, i tried to invert the image but still got a similar result, any ideas?

import pytesseract as tess
from PIL import Image
import PIL.ImageOps


# inverted_image = PIL.ImageOps.invert(img)
# inverted_image.save('new_name.png')

img = Image.open("text.png")
text = tess.image_to_string(img)
print(text)
#

here is the image

arctic tusk
#

Hi there guys!

I am trying to count a row from a csv file and see the frequency of "apples, bananas and oranges in the file. Any pointers, i am stuck

marsh bone
#

perfect I will follow up later when i try it!

exotic aspen
#

can I just have an object's __hash__ be its memory address ?

hidden raft
#

Doesn't sound very useful @exotic aspen

#

equal objects should have equal hashes, but no two objects are going to have the same memory address

stable pecan
#

maybe they're all singleton objects

shadow nova
#

does anyone here know how to use a lexer to create a grammar tree?

#

my remaining brain cells are currently getting nuked by a lexer

feral shale
#

<@&267629731250176001>

wind idol
#

!ban 516040052237664256 the content you've posted is absolutely unacceptable and not tolerable here at all.

halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied ban to @atomic granite permanently.

wind idol
#

thanks @feral shale

exotic aspen
#

after I raise an error, how do I get it to immediately terminate at that line ?

#

I raise an error, but it still performs the next line after the raised error

royal kestrel
#

Make sure you don't have any weird syntax issues, raise terminates control flow in the function

nocturne nacelle
#

Question. I'm started this OSSU curse and there is a lots of new code to learn and my problem is i cant exactly remember to all codes. Is this ia big problem? Should i stop and check it out again? i make a lot of notes about codes and how to use them so whenever i have to do an assignment i know what i need to use but maybe i just forget a little part of the code but i just open my notes check it and write the code. So what do you think?
(Sorry for my english)

exotic aspen
#

is there a succinct way of doing something like this:
checking if there's an object with a particular value in a set
like usually how we do if a in set or if a not in set, but I wanna do something like if a.val not in set, where the elements in set are assumed to all be objects of the same class as a

stable pecan
#

i'm not exactly sure what you want, but you can give the objects a __hash__ based on the val attribute

exotic aspen
#

OHHHH youre right
i was thinking about it wrong lmfao

#

ty

knotty shore
#

what is the advantage of doing computer science for GCSE

topaz pulsar
#

@knotty shore doing it for GCSE in particular or just doing it in general? An advantage of computer science is that it teaches you how to approach complex problems and find ways to break that problem up and tackle real world issues, it also can teach you about how computer systems work in good detail which is good knowledge to have in a world where technology is now used in almost every industry

knotty shore
#

for GCSE

#

thanks, that helps a lot

quasi nebula
#

can anyone help me with a c language program

#

#include <stdio.h>

int main()

{
float sp = 0;
printf("Enter the selling price:");
scanf("%f",&sp);

float gain_or_loss_per = 0;
printf("Enter the gain or loss percent:");
scanf("%f",&gain_or_loss_per);

float gain_or_loss = 0;
printf("Enter if it is gain or loss:");
scanf("%f",&gain_or_loss);

printf("%f",gain_or_loss);

char gain_or_loss1 = 0;
gain_or_loss == gain_or_loss1;

char gain = 0;
char loss = 0;

if (gain_or_loss1 == gain)
{
    
    float cp1_with_gain = 0;
    cp1_with_gain = 100+gain_or_loss_per;
    
    float cp2_with_gain = 0;
    cp2_with_gain = 100/cp1_with_gain;
    
    float cp3_with_gain = 0;
    cp3_with_gain = cp2_with_gain*sp;
    
    printf("The cost price is:");
    printf("%f",cp3_with_gain);
    
}

else if (gain_or_loss == loss)
{
    
    float cp1_with_loss = 0;
    cp1_with_loss = 100-gain_or_loss_per;
    
    float cp2_with_loss = 0;
    cp2_with_loss = 100/cp1_with_loss;
    
    float cp3_with_loss = 0;
    cp3_with_loss = cp2_with_loss*sp;
    
    printf("The cost price is:");
    printf("%f",cp3_with_loss);
}

else
{
    printf("Please only write gain or loss. If you have write anything else .Please change the same");
}
    
return 0;

}

#

pls if anyone can help me

#

the problem is that gain_or_loss variable is not taking any value and if i assign it with 'char'. it doesn't ask for input

bronze gazelle
#

This is a Python server

quasi nebula
#

well but the channel is computer science. isn't it ?

bronze gazelle
fiery cosmos
#

#bot-commands

fleet oak
#

@quasi nebula you need to make it a char*

#

and then convert using atof

#

this is why you use python duh

#

🤭

hushed turret
#

!tempban 676888464351821867 7d that type of language is not appriciated here, take som time to read our rules again

halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied ban to @bleak bear until 2020-05-27 17:47 (6 days and 23 hours).

lost orchid
#

Hey guys, is there a way to convert old pcs into private servers

shrewd gulch
#

Yes.

sly vale
#

Hey when doing a minmax search without progressive depending you only evaluate the board state at the depth limit correct?

#

however if thats the case how do we check for both minimizer and maximizer? do i just check each individually

#

I can share my code but there are alot of objects/function from different modules

digital gate
#

Somebody could help me with this?

#

I'm trying to get a list as an input

#

for my my function

sly vale
#

you are giving it three strings

#

make it a list

digital gate
#

I tried putting the input without the ' '

#

But it didn't run 😦

#

I tried strand (T, A, G)

sly vale
#
def strand (dna):
  symbols = dna
  return symbols
strand(['A','B','C'])
digital gate
#

Oh I see

#

So, the list brackets shouldn't be used it the definition

#

But when invokating the function.

sly vale
#

yes also no return print

daring patrol
#

print returns nothing, so your function would return nothing in that case

digital gate
#

It worked, thanks brzing

#

*brzig

#

But if I don't put print how are the results are being displayed?

#

Does the "return" substitutes the print when invoking?

#

Oh, I think I get it

sly vale
#

print the function

digital gate
#

Only use print when using the funciton

sly vale
#

yea print tells us something return tells the computer something

digital gate
#

Now it's clear!

#

Thank you very much!

sly vale
#

great to hear!

#

of course

#

Hey when doing a minmax search without progressive depending you only evaluate the board state at the depth limit correct?
however if thats the case how do we check for both minimizer and maximizer? do i just check each individually? I can share my code but there are alot of objects/function from different modules

obsidian jolt
#
prog =  re.compile(r'(')

#word is an array of characters
word = list("(one(()))")

#loop thru the list of chatracters and match it
count = 0
for char in word:
    if prog.match(char, pos=len(char) ) != None:
        print('there is a pair of parentheses')
        count = count +1
    else:
        print('there isn\'t any' )
#

hey guys im trying to find a pair of parentheses present in a string

#

here is the following code that i wrote but im gettin an error can anyone help

olive mango
#

if anyone has the time, i need help with some python code... it has to do with widgets, pillow, and a csv file

gusty gate
#

well first off you dont need regex to find parentheses

balmy siren
#

Hey everyone..
last night i was doing hash tables and today i got a new task to design a Hash Map.. so i checked it on google and i see that people were using a dictionary for implementing Hash.. it's like they put (key, value) pair in a dictionary
dict[key] = value

Do i need to do the same or is there any other ways of implementing Hash Map ?

bitter atlas
#

hey y'all

#

i want to learn discrete math. but, i'm currently in physics degree, so i don't get that topic. Can you suggest me books or courses that good to learn discrete math?
and sorry for my bad english

gusty grove
#

@balmy siren well a dictionary is a hash map. it lets you look something up (value) by checking the hash of the key (key) -> key:value pairs

pseudo cliff
#

could someone explain to me how confidentiality of a document can be achieved when a sender sends the document to a receiver using asymmetric cryptography?

fiery cosmos
#

what is unittest actually?

past flare
#

How to translate bytes to human readable text ?

#
import scapy.all as scapy
from scapy.layers import http

def sniff(interface):
    scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet)

def process_sniffed_packet(packet):
    print(packet)

sniff("Realtek 8821CE Wireless LAN 802.11ac PCI-E NIC")
#

im getting packets like these

uncut jetty
#

How can I sort this with xps?

"701465933041893427": {
        "435394854017826817": {
            "xps": 3140,
            "level": 8,
            "last_message": 1588350254
        },
        "660702877546840075": {
            "xps": 1685,
            "level": 7,
            "last_message": 1589561109
        },
        "702722966039035965": {
            "xps": 585,
            "level": 4,
            "last_message": 1587915578
        },
        "703469461927362613": {
            "xps": 40,
            "level": 0,
            "last_message": 1587792479
        },
        "614120525761085450": {
            "xps": 95,
            "level": 1,
            "last_message": 1587878540
        },
        "693401671836893235": {
            "xps": 0,
            "level": 0,
            "last_message": 0
        }
    }
versed trellis
#

What's XPS? @uncut jetty

uncut jetty
#

I made it

gusty grove
#

You mean sort with relation to xps?

#

Is it a dict?

versed trellis
#

I don't understand what you want to do

gusty grove
#

He wants to get the Id or whatever that contains the largest xps

#

max(dict.values(), key=lamda value: value["xps"])

#

Something like that

#

Oh you want sorted not max

#

So replace max with sort

compact birch
#

That was big

#

I would have had no idea what that meant had I not learned Numpy the other dya

#

'learned Numpy' I mean, I'm still clueless

#

but I can fill those NaN's

#

Thanks for listening!

#

Just saw this and it reminded me of that

molten jacinth
#

Is anyone actually using the coding generator from OpenAI to code for us? Like is it out yet :laugh:

brisk swan
#

Ok, I might have a few of the details wrong on this so if anyone finds flaws then let me know. But for @pseudo cliff:

Asymmetric cryptography uses a pair of keys for both encrypting and decrypting messages: a public and private key. Messages encrypted with the public key can be decrypted with the private key, and messages encrypted with the private key (bad idea) can be decrypted with the public key.

Given two users Alice and Bob who are communicating with each other, Alice would have Bob's public key and vice versa. Alice would encrypt her message for Bob using Bob's public key, and when Bob receives the encrypted text he would be able to obtain the original message by decrypting with his private key.

With asymmetric cryptography, someone with the public key is able to encrypt a message, providing confidentiality, and then only the person in possession of the private key is able to decrypt it.

elfin pecan
#

I m not sure if this question fits here.
But i would like to create a blog for my personal use so that i can keep track of all the new things and concpets I learn about.
Like a section for new general concepts of programming a section for all the math a learn through and so on
So what will be the best way to initiate this approach and what r ur views on it?

shell abyss
#

@elfin pecan I tried that many many years ago and I couldn't force myself to keep it updated. Nowadays I keep track of my projects using gitlab (you can use any git alternative you want of course). Imo it is way easier. Build an implementation of a concept that you have learned. Document it thoroughly because you will forget about it. Then you can use it as a perfect cook book.

elfin pecan
#

@shell abyssOkay cool, that sounds like a better appraoch to my problem.Thank you for your advice.

shell abyss
#

@elfin pecan No problem, hope it helps 🙂

atomic rock
#

how would you guys go about training a nn to play tictactoe ?

#

should it learn from its mistakes or feed it tons of data ?

#

former one would be neater i think

floral sundial
#

Where is the correct place to put a class (readonly/final, private) string?

lean dome
#

Where is the correct place to put a class (readonly/final, private) string?
@floral sundial

Python doesn't have those.

floral sundial
#

ok, lemme rephrase then: what is the best way to make a string, loosely tied to a class, that wont be duplicated multiple times in memory, and can't be modified during runtime

stark bridge
#

well no string can be modified at runtime, so you don't need to worry about that

#

make it a class attribute I guess

last blaze
#

You could make it a property and have the setter raise an error

floral sundial
#

ah, thanks. ill take a look into that then

last blaze
raven socket
#

is there a better/quicker way of creating a random 32-digit integer other than

random.randint(10**32, 10**33-1)``` ?
halcyon plankBOT
#

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

foggy mural
#

can someone help me understand what ASCII and UTF-8 mean while encoding. What is it used for and why do we need it. This topic is so confusing to me

dark egret
#

@raven socket
x=random.randint(0, 10**33-1-10**32)+10**32
I think this runs fast

#
import timeit

one='''
import random
x=random.randint(0, 100000)
'''
print(timeit.timeit(one, number=10000))

two='''
import random
x=random.randint(10**32, 10**33-1)
'''
print(timeit.timeit(two, number=10000))

three='''
import random
x=random.randint(0, 10**33-1-10**32)+10**32
'''
print(timeit.timeit(three, number=1000))

timeit script

raven socket
#

wow

#

thx

lean dome
#

can someone help me understand what ASCII and UTF-8 mean while encoding. What is it used for and why do we need it.
@foggy mural

At some level, computers only deal with numbers. In order to deal with text, we assign numbers to letters, and it works fine as long as everyone agrees on which letter gets what number. One of the early encodings, ASCII, defined a mapping for 128 characters to the numbers 0 through 127. That covered every English digit and letter (upper and lowercase) and most common punctuation, and a bunch of other stuff. For a while that was enough, because programming languages were being used by English speakers, or people who could type text that looked like English by dropping some accent marks. Later, people from other countries wanted to be able to have computers render their text, so a bunch of incompatible encodings were developed - many were compatible with ASCII for the numbers 0 through 127, and used 128 through 255 for local characters. That worked OK, except Asian languages often have thousands of characters, so they need an entirely different approach. Unicode is that different approach - it's a mapping of every character used by any language on Earth to a unique number. UTF-8 is a mapping of those Unicode numbers representing characters to a particular binary representation.

#
foggy mural
#

ok thanks so much

lean dome
dense meteor
#
import numpy as np
import matplotlib.pyplot as plt

def euclidean_distance(query, data):
    euclidean_distance = np.sum(np.power(data-query,2),axis=1)
    return euclidean_distance
#
def fuzzy_cmeans(data, n_clusters=15, n_iterations=100):
    n_instances, n_features = data.shape
    
    #cluster intiliazation
    clusters = np.zeros((n_clusters, n_features))
    dist_inst_cluster = np.zeros((n_instances, n_clusters))
    for i_instances in range(n_instances):
        dist_inst_cluster[i_instances,:] = np.random.dirichlet(np.ones(n_clusters), size=1)

    for i_clusters in range(n_clusters):
        clusters[i_clusters,:] = np.average(data,weights=np.power(dist_inst_cluster[:,i_clusters],2),axis=0)

    for i_iter in range(n_iterations):
        for i_instances in range(n_instances):
            ##### code implementation ####
    
        for i_clusters in range(n_clusters):
            clusters[i_clusters,:] = np.average(data,weights=np.power(dist_inst_cluster[:,i_clusters],2),axis=0)    
        
    return clusters, dist_inst_cluster
    ```
#

i am so stuck any ideaaas

topaz pulsar
#

@dense meteor i think when calculating euclidean distance u got to sqrt at the end after you take the sum of the values squared

eager pendant
#

I've managed to unearth a laptop that used to have ransomware on it from years ago. Tried to boot it up and the lights are on, but it automatically opens the CD drive with nothing displaying on the screen. Does this mean the BIOS or OS have been wiped and I'll need to flash one onto it?

lean dome
#

if it had ransomeware, it's probably safest to wipe it either way.

native tiger
#

is the value returned by a perlin noise function where all inputs are integers always 0?

gusty grove
#

Shouldn't be

native tiger
#

then my understanding of the algorithm is wrong

#

oh just the dotproduct there is zero

eager pendant
#

It's a laptop so it'll prove difficult to wipe.

#

Still I'll make sure to once I get a docking station.

bronze gazelle
#

!off-topic

halcyon plankBOT
eager pendant
#

Is this not still related?

bronze gazelle
#

Discussion of general computer science, algorithms, data structures, and maths as they relate to solving problems with Python.

#

I don't see "identify hardware" there

eager pendant
#

WHOOPS

#

I forgot topics exist, entirely my bad.

faint apex
#

Is looking at the Train vs Validation loss enough to paint a picture on how accurate your model will be or do you have to look at RMSE to conclude how good your model really are??

brisk swan
rotund mortar
#

Can you set the return from a function directly to a variable?

serene breach
#

Sounds pretty normal

rotund mortar
#

yeah I can't figure out how to do it, anyone know how?

serene breach
#

foo = round(1.5)

dreamy valley
#

do y'all know of any good free online courses for discrete math? I've been looking for a few days and can only find traditional courses for a fee, free courses with poor ratings, and free courses that look kind of like discrete math course but not completely

fiery cosmos
#

Maybe this will help u guys out

hidden merlin
#

Hey Everyone,
If anyone needs to do a particular course on Coursera, then you can register here for getting the Premium License to access the curated course in the organization catalog.
You can register under the Non MIT-WPU section & can share it with anyone who's interested for the same.
link: https://thescriptgroup.in
This in an Initiative taken by The S.C.R.I.P.T Group to provide courses to other Institutions where this program has not been introduced.

dreamy valley
#

@hidden merlin thank you!! very useful link

hidden merlin
#

Welcome @dreamy valley

#

Hope you received the invitation aswell @dreamy valley

near cloud
#

any idea guys why pool.imap() gives unordered list?

stark bridge
#

what is an "unordered list"?

#

In my experience, lists are ordered

#

do you mean the order isn't what you expected?

#

Or do you mean the result is a set, not a list?

near cloud
#

I'm creating a list here

#

yes, so it's starting with like 3001 and then instead of 3002 it goes to 3005

stark bridge
#

so the order is not what you expected?

near cloud
#

and theen goes back to 3003

#

yes

stark bridge
#

I'd guess it's because the various threads or subprocesses don't all finish in exactly the same order in which you started them.

#

some take a little longer than others, for more or less random reasons, having to do with whatever else your computer is doing at the moment

near cloud
#

is there any fix for that?

cerulean vine
#

sorry im not super familiar is the pool command required it would seem to me that pool would cause the sudo randomness but i may not understand it well enough to say for certain

near cloud
#

actually pool has a function where you can make the list unordered pool.imap_unordered()

stark bridge
#

@near cloud I think the fix is "don't worry, be happy" 🙂

cerulean vine
#

lol

stark bridge
#

if you want, I guess you could sort the results by the order in which you started the process

#

I've never even heard of imap; maybe I'd better read about it now

near cloud
#

actually this is a little confusing because sometimes using unordered function gives order list

#

and using ordered function gives unordered function

#

lol

stark bridge
#

also it's confusing because the docs for imap_unordered strongly imply that plain imap will indeed preserve the order

near cloud
#

yes that's the confusing part

#

and some time, and it happen to me, if I use imap_unordered it will give order list

#

but if I only use imap() it won't

cerulean vine
#

may i ask what you are trying to accomplish with this code, i assume its a small part of a much larger mechanism... if you simply need to list the items from least to greatest i believe there is a way to slice the list and rearrange i apologize though i cannot remember the method its been a while since i read that

near cloud
#

trying to bruteforce a website lol

#

using requests

stark bridge
#

hmm, mine seem ordered

near cloud
#

really?

stark bridge
#
import multiprocessing


def double_and_add_one(x):
    return x * 2 + 1


if __name__ == "__main__":
    with multiprocessing.Pool(processes=4) as pool:
        results = pool.imap(
            double_and_add_one,
            range(100),
            chunksize=10
        )
        print(list(results))
# [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 101, 103, 105, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199]
cerulean vine
#

i would definitely consider another technique most brute force attacks can be circumnavigated by finding an open back door rather than crashing in the front door... might be worth doing more recon. good luck with your project though 😄

near cloud
#

no no, this is a ctf challenge actually

#

so he just want you do bruteforce the date, so you need to find the server date and try to bruteforce based on that

#

which you can find the server date with curl --head <url>

#

and based on that you can bruteforce the rest

fiery cosmos
#

does your ctf have a link?

near cloud
#

I could just do it without pool

#

but I need to make things faster

#

@near cloud I think the fix is "don't worry, be happy" 🙂
@stark bridge for you information, doing it using unordered list actually solved the challenge for me, so you don't really need it ordered, but I'm just curious

stark bridge
#

I am too; when I tried it, imap returned things in order, even after I added a random sleep to the function.

#

and imap_unordered clearly showed the ordering was mixed up.

near cloud
#

maybe the http request is doing something

#

or maybe my vm is doing something weird here

#

I'm actually printing it, and it still unordered, I'll try another vm and see

#

@stark bridge I can confirm requests lib is the reason here

stark bridge
#

weird

acoustic jackal
#

Can we talk about how operating systems work here?

#

Or is that considered off-topic in the channel?

stark bridge
#

🤷

dusky forge
#

Hello all

sly vale
#

ok so I am trying to get a minmax search algo to work I have generated all the game states in the proper DFS order in a list but im not sure how to now get the values from the list...

sly vale
#

sorry im just so frustrated cause im almost there but i cant quite finish it

fiery cosmos
#

Im currently learning C, but next year I will learn python at school. So my question is: will it an advantage to already know a language or how a pointer works, or will it be a disadvantage because I will do some mistakes such as syntax mistakes

mint jewel
#

the main advantage will be knowing programming already. You will need to get used to not having to manage memory

fiery cosmos
#

i've tried python one time, and i was doing a lot of mistakes like typing printf instead of print, or adding ; at the end

mint jewel
#

you will get used to it in time

#

that will not be a large problem from my experience

fiery cosmos
#

roughly does python look like C?

mint jewel
#

if you squint really hard and ignore all of the parts that are entirely different

fiery cosmos
#

😆

mint jewel
#

python is a more complicated language than C, but easier to actually write code in, as a lot of things are already handled for you

fiery cosmos
#

thank you ❤️

formal remnant
#

@timber harness

timber harness
#

bruh

formal remnant
#

Hello!

timber harness
#

the channels with the green checkmark

formal remnant
#

Oh okay. Sorry I'm new here

sly vale
#

is anyone familar with minmax search i could really use some help

hearty kraken
#

somone knows something about artificial neural networks?

#

and if i give him my code, can he tell me what i do wrong?

fiery cosmos
#

Hopefully this doesn't mean spamming in here

vernal obsidian
#

Does anyone here use pygame?

wintry merlin
#

hi, coming from C++ and used to using our STL, like vector, list, unordered maps, hashs, what is the equivalent of the STL in python

stark bridge
#

just the various stuff you can import that comes with python

#

of course python has nothing remotely resembling templates

#

C++ templates are a bizarre hack

lean dome
#

@wintry merlin - Python's dict and C++'s std::unordered_map are both hash maps. Python's list and C++'s std::vector are both dynamic arrays. Python's collections.deque and C++'s std::deque are both doubly linked lists of dynamic arrays. I can't think of anything analogous to std::list or its singly linked variant - I don't think Python ships with a linked list individual elements.

#

and the builtin set type is analogous to std::unordered_set

indigo tiger
#

Hi all, working on leetcode and having issues with loops when dealing with list[i + 1]. For ex: I want to check

i = 0
while i < len(nums):
  if nums[i] == nums[i + 1]:
    # Do something

and my issue is where IndexError: list index out of range. I understand why thats the problem, but how do i go about that everytime i do something with list[i + 1]

lean dome
#

you either need to stop before the last element, or start after the first, @indigo tiger - so, either make your while i < len(nums) - 1 or start at i = 1 and check if nums[i - 1] == nums[i]

indigo tiger
#

Thanks! @lean dome

loud trail
#

here's a general computer science algorithm :)

if is_possible_to_occur(bad_thing):
    bad_thing_will_occur = check_for(bad_thing)
    if bad_thing_will_occur:
        dont_do_bad_thing_and_show_an_error_instead()
#

that should apply to your i+1 case, along with many others

blissful wedge
#

!e

halcyon plankBOT
#

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

proven sparrow
#

This is my way to find two the greatest numbers in list.
def two_largest(A): ... max1, max2 = 0,0 ... for number in A: ... if number>max1: ... max2 = max1 ... max1 = number ... elif number>max2: ... max2=number ... return max1,max2

latent wasp
#

@proven sparrow you can also do:

A.sort(reverse=True)
max1, max2 = A[:2]
stable pecan
#

you can also use nlargest from the heapq module

proven sparrow
#

@proven sparrow you can also do:

A.sort(reverse=True)
max1, max2 = A[:2]

@latent wasp What about time complexity?

#

you can also use nlargest from the heapq module
@stable pecan Isn't it O(nlogn) time complexity?

stable pecan
#

i don't know if it assumes a heap or not

#

or if it sorts or not

proven sparrow
#

@stable pecan hm... it says Equivalent to: sorted(iterable, key=key, reverse=True)[:n] So it sorts beforehand. The best sorting algorithms are nlogn.

stable pecan
#

functionally equivalent to --- the implementation is more sophisticated

#

which i linked

proven sparrow
#

ok

zenith wasp
#
# X_OFF and stuff are set here

def transform(self, x, z):
    camera = self.fsys.camera

    # TODO: use Ortho Indoors

    camPos = camera.lookat.camPos
    target = camera.lookat.target
    forward = vmath.unit(vmath.sub(target, camPos))
    right = vmath.unit(vmath.cross(forward, camera.lookat.camUp))
    up = vmath.unit(vmath.cross(right, forward))
    p = vmath.sub(vmath.vec(x, target.y, z), camPos)

    aspect = camera.persp.aspect
    tanFov = camera.persp.fovysin / camera.persp.fovycos

    IR3 = vmath.dot(forward, p)

    IR1 = vmath.dot(right, p)
    SX = X_OFF - (IR1/(-IR3 * aspect * tanFov)) * X_OFF

    IR2 = vmath.dot(up, p)
    SY = Y_OFF + (IR2 /(-IR3 * tanFov)) * Y_OFF
    return (SX, SY)
```The method takes in-game coordinates and converts it to on-screen coordinates, and now I need to write the inverse of this function. Any ideas? (vmath is a small lib I use for vector math)
#

basically, figure out the x and z passed to this function based on the SX and SY. camPos, target, forward, right and up will have the same values for this, same with aspect and tanFov

#

but when it comes to such complex vector math my brain just stops working

brisk mango
#

Heyo

knotty sphinx
half vine
#

def invert_dict(d): inverse = dict() for key in d: val = d[key] if val not in inverse: inverse[val] = [key] else: inverse[val].append(key) return inverse
so, I am rather new to Python and coding as a whole, and I got stuck on this here function. Simply I want it to create a reverse dictionary of a dictionary argument that returns a list of values for each key. But I cannot for the life of me wrap my head around how to workaround the fact that the funcion needs to work with lists mid-execution. Anyone be so kind to give me a hand?

runic tinsel
#

i didn;t get it

#

what is the prob;em?

#

that needs working around

zenith wasp
#

@half vine Won't be possible, as lists cannot be used as keys due to them not being hashable afaik

#

you could try using sets instead maybe?

runic tinsel
#

is that it, that values can be lists?

half vine
#

I know that, but I have seen that some one managed to make this function turn this:
{“London city”:[“ChelseaFC”, “West HamFC”,”FulhamFC”]}

into this {“ChelseaFC”:[“London city”], “West HamFC”:[“London city”],”FulhamFC”:[“London city”]}

#

by modifying it

#

I'm trying to figure out what did they change

runic tinsel
#

oh ok

#

the values will be lists guaranteed, got it

#
def invert_dict(d):
     inverse = dict()
     for key in d:
          for val in d[key]:
              if val not in inverse:
                   inverse[val] = [key]
              else:
                   inverse[val].append(key)
     return inverse
#

that's doing something

solid garden
#

anyone idea how I can see whether my computer fan are on or off ? I want to control the fan speed via python

harsh plover
#

anyone here? I need desperately help

heady python
#

I need help too

#

I want to learn python

stark bridge
#

!how-to-get-help

#

sigh

harsh plover
#

i need help with f sharp, i can pay too

stark bridge
heady python
#

Wow

fiery cosmos
#

Rate my video. Its on std::map in c++:

mint jewel
#

<@&267629731250176001> spam

#

in every topical channel

#

dealt with

hidden pebble
#

Is learning graph theory worth it

#

I'm a high school student

#

It seems pretty long

mint jewel
#

depends on what you want to do in the future

#

gamedev, yes

queen orchid
#

on python is there a command to clear output? I'm using Jupyter notebook to code

undone estuary
#

Anyone know how to use the remind.reminder module? i know how it exists, but i can't find any info or the documentation for it.

gusty grove
#

@queen orchid depending on your os you can try os.system("cls") or os.system("clear")

#

that will clear the terminal output

frigid quail
#

Hey ya'll, I found this thread on StackOverflow about implementing data structures for collision detection, and one user talked about "loose grids". In their implementation, which is in C++, they're using indexes instead of object pointers. Is there a difference in speed and memory in keeping indexes instead of the object pointer itself? Especially in a dynamically typed language like Python?

orchid granite
#

Well C++ gives you control over if the object you have is a pointer or not

#

Python doesn't

#

So the question is, is storing a bunch of objects in one unified array faster than a bunch of objects with references

#

If we can see python's list object

#
    assert(self->ob_item == NULL);
    assert(size > 0);

    PyObject **items = PyMem_New(PyObject*, size);
    if (items == NULL) {
        PyErr_NoMemory();
        return -1;
    }
    self->ob_item = items;
    self->allocated = size;

We can see that the list is actually a list of pointers for PyObject

#

So regardless of what we do in python, we'll ultimately just end up with a list of pointers instead of a list of objects

#

So theoretically, this would just be outright slower than having a bunch of addresses, because you now need to dereference the array pointer, index the array, and also dereference the object pointer

#

And most dynamic typed languages follow a similar design I believe

#

I can't think of an immediate example that doesn't at least

#

This implementation is also specific to CPython Interpreter

frigid quail
#

I see, so all the arrays in Python are just pointers

orchid granite
#

No the objects themselves are pointers

#

So you make an array

#

Or a python list object

#

Inside this object is a pointer to the internal array

#

This internal array will be declared of type PyObject ** as we can see above

#

It's a pointer to a pointer

#

So we have PythonList Object -> Internal Array -> some index -> PyObject pointer

#

So anything in python isn't stored in the array, we just store a bunch of pointers/references in the array for each of our PyObjects

#

I can't stress enough how much these speed differences don't matter in a language like Python though, they're cool little points to explore about how the language works, but generally you should not be thinking about this when writing code

frigid quail
#

Then there would be less instructions just storing the pointer/reference than indexes?

#

Yes the speed probably would be negligible, I just find it interesting to know how it works for Python

#

compared to another language

orchid granite
#

Then there would be less instructions just storing the pointer/reference than indexes?
I don't know what you mean by this

plush sparrow
#

I don't know if this is the right section of the python server to ask questions but what are recommendation algorithms?

orchid granite
#

There's a few out there @plush sparrow

#

They're probably very google-able

plush sparrow
#

Yeah but I don't really understand xdd

orchid granite
#

If you google popular examples like how Netflix recommends movies, or how spotify recommends music it thinks you'll like (A seminar was run at my university on this and was very interesting)

#

Well it's hardly a simple topic

plush sparrow
#

Ah ok ok thank you!

frigid quail
#

Oh sorry, I am talking about storing the index instead, rather than the object directly in a data structure (like a Quadtree) which points to an element in an array in Python

#
// Storing indexes
node = Node([0, 2, 5, 7])

// Storing references themseleves
node = Node(elements[0], elements[2], elements[5])
orchid granite
#

Yes but what I'm saying is due to how python works underneath your array is already a list of references

#

not the actual objects

#

So indexing the array = object lookup

#

reference from element = object lookup

#

It won't make a difference 🤷‍♂️

#

Infact indexing might even be slower, because that list of integers will need to perform the additional lookups on the int objects too

#

So these aren't the sort of optimizations we make in Python

#

Because we can't

#

The underlying implementation will always be dereferencing at least one pointer

#

Also even in langauges like C/C++ dereferencing a pointer shouldn't be that slow :b

mint jewel
#

pointer deref is often free in C/C++

austere sparrow
#

Well, a consecutive array can still be faster because reading stuff in sequence is faster than randomly, and something something cache magic.

#

But that's impossible with Python objects, since they all occupy different amount of space.

#

You could store them consecutively, but then accessing an element by index would be O(n)

lean dome
#

You can't store objects at all, not in any meaningful sense of the word. Each Python object is independently allocated, and storing an object in a list is actually storing a reference (i.e. pointer) to it. There's an indirection either way, that is.

silk wadi
#

is there a clean way to split a shorthand list comprehension over >1 line?

my_filter = request.params.get('status') # boiler just for this example
my_shard = get_shard(my_pool, shard_id) # boiler
my_commands = [command for command in my_shard['ommands'] if command['status'].lower() == my_filter.lower()] # can I linebreak?

I am looking to reduce line length <80
Thanks in advance

pallid coral
#

Well, list comprehensions naturally break in a few places

#
a = [
      my_long_function(i+15 % 32)
        for i in long_function_2()
        if matches_long_3(i) 
          and matches_long_4(i, another_var)
]
#

But I'd advise that 80 chars is probably a narrow line limit and 100/120 is more practical, and I'm not sure that one should be broken up just for style concerns

silk wadi
#

okay thanks. your example made it much more clear what the structure of a list comprehension can look like.
I am new to Python so I am just following Google's stylesheet which recommends 80chars
Thanks for the guidance, your time is appreciated

pallid coral
#

👍

cloud junco
#

Anyone have an idea about an ideal way to store a trie into a database maybe I should use #databases ?

nocturne forge
#

!rules 6 @fiery cosmos We do not allow advertisement here. If it were a tutorial on python, maybe, in #303934982764625920 .

halcyon plankBOT
#

6. No spamming or unapproved advertising, including requests for paid work. Open-source projects can be showcased in #show-your-projects.

granite forge
#

Would anyone be able to help with a quick question about inputs?

frigid quail
granite forge
#
for _ in range(int(input())):
    N, K, P = [int(_i) for _i in input().split()]
    S = []
    for _i in range(N):
        S.append([int(__i) for __i in input().split()])

# Test Cases
# 2
# 2 4 5
# 10 10 100 30
# 80 50 10 50
# 3 2 3
# 80 80
# 15 50
# 20 10```
So when I run the code with this test data it goes through the first iteration and then asks for another input before ending. I'm trying to make it so I don't have to to do the second input and it just takes the data I've put in.
nocturne forge
#

Use a variable for the input, before the loop?

granite forge
#

Do you mean the first input? python T = int(input()) for _ in range(T): Like this?

nocturne forge
#

For instance, and the other one if it doesnt change?

granite forge
#

Ahh sorry I'm really tired could u elaborate?

nocturne forge
#

Does N, K, P change in every iteration of for _ in range(int(input())):?

granite forge
#

Oh yes

#

its 2, 4, 5 in the first and 3, 2, 3 in the second

nocturne forge
#

Wait, so what is it you're asking?

#

What are you trying to do

granite forge
#

Can I post a gif of it in here?

nocturne forge
#

Probably

granite forge
#

Sorry if its not clear

fiery cosmos
#

@nocturne forge ok np

#

my bad

nocturne forge
#

What are you inputing there?

granite forge
nocturne forge
#

You could either hardcode the test data, or have it query for the numbers before running the loops

granite forge
#

Hmm alright

#

Thanks

balmy siren
#

Hey guys,
I'm reading graphs now and just want to know the difference between graphs in Discrete mathematics and the one in data structure

#

should i go for Discrete mathematics first before studying graphs in DS&Algo.

latent wasp
#

@balmy siren I feel like discrete mathematics is quintessential to learning data science and algorithms

#

It helps you shape the problem and the situation better

balmy siren
#

@latent wasp thanks for replying
yeah you're right about shape the problem and understanding the problem better mathematically. So, should i go for graphs in Discrete because it will help me in understanding the mechanics of graphs better and then i can implement it in python.

hidden merlin
#

Hi guys, we at The SCRIPT Group have launched our podcast finally, we're calling it
"Pretty Epic"

Find the first episode on https://youtu.be/qRqhR0JQtcU

We're open to topic suggestions for our next episode, and it doesn't necessarily need to be tech!
Just send me your topic suggestion on 8452047071 and if it's epic enough, we'll take it up in the next episode.

Don't forget to like, share and subscribe❤️

#prettyepic #thescriptgroup #stayathome

Pretty Epic is a podcast where members of The SCRIPT Group, a tech-driven community talk about "epic" stuff happening around the world, and how they matter.

Have epic stuff to suggest for our future episodes?
Join our community on: ht...

▶ Play video
steep wave
#

Hey, can you give me an example for two algorithm with the first having better time complexity in the worst case, but worse complexity in the best or average case ?

mint jewel
#

quicksort vs merge sort is a common example

steep wave
#

they have the same best and average cases 🤔

steep wave
#

Another question, how can i calculate the probability of the best case, average case , and worst case?

amber loom
#

depends on the algorithm

#

for example, for quicksort you have to calculate in which case the algorithm makes the least and most comparisons

nocturne bear
#

I have an algorithm question. Basically, we are given an array called foodTimes.. foodTimes [i] tells us how many food i we have left. A customer try the food one by one. After eating one food, the customer will move to eating next food. And by next food, i mean next available food, a non-zero food. We are also given k, which tells how many times the customer can eat. The task is to find next food the customer will eat after he has eaten k times.Also if there are no food left, then return -1.
Example: foodTimes = [3, 1, 2], k= 4, then
Eat food 0, foodTimes = [2,1,2], k=3
Eat food 1, foodTimes = [2,0,2], k=2
Eat food 2, foodTimes = [2,0,1], k=1
Eat food 0, foodTimes = [1,0,1], k=0
After k times, the customer will eat food 2, since there is no food 1 left, we skip to food 2.
Here is my solution

def solution(food_times, k):
  answer = 0
  i = 0
  numOfZeros = 0
 
  while k > 0:
    # reset number of zeros when at first i
    if i == 0:
      numOfZeros = 0
    
 
    # if there ares still remaining food i
    if food_times[i] > 0:
      # reduce the number of that food
      # and the seconds
      food_times[i] = food_times[i] - 1
      k = k - 1
    else:
      # otherwise, add number of zero food
      numOfZeros = numOfZeros + 1
    
 
    # if we are at the end of the list and there are no more food left
    if i == len(food_times)-1 and numOfZeros == len(food_times):
      return -1
    
 
    # go to next food
    i = i + 1
    i = i % len(food_times)
    
 
  # go to nearest non-zero food to the right
  # if we reach the end, return back to beginning
  while food_times[i] == 0:
    i = i + 1
    i = i % len(food_times)
  
 
  # answer is the last i we are standing on
  # return i
  answer = i
  return answer
 
print(solution([3, 1, 2], 4)) # 2

But I was told my solution is not efficient enough

bronze gazelle
#

Probably not going to have the easiest time getting help for not Python on a Python server

steep wave
#

depends on the algorithm
can you recommend a good resource to read for that?

#

he can change function to def. and problem is solved xD

nocturne bear
#

@bronze gazelle I mean, the language doesn't matter, I am looking for an improvement, or another algorithm

#

maybe using different data strucutre

bronze gazelle
#

It does matter

#

This isn't Python

nocturne bear
#

I can change it to python, would that be ok?

#

I have changed the code to python

steep wave
#
def solution(food_times, k):
  answer = 0
  i = 0
  numOfZeros = 0
 
  while k > 0:
    # reset number of zeros when at first i
    if i == 0:
      numOfZeros = 0
    
 
    # if there ares still remaining food i
    if food_times[i] > 0:
      # reduce the number of that food
      # and the seconds
      food_times[i] = food_times[i] - 1
      k = k - 1
    else:
      # otherwise, add number of zero food
      numOfZeros = numOfZeros + 1
    
 
    # if we are at the end of the list and there are no more food left
    if i == len(food_times)-1 and numOfZeros == len(food_times):
      return -1
    
 
    # go to next food
    i = i + 1
    i = i % len(food_times)
    
 
  # go to nearest non-zero food to the right
  # if we reach the end, return back to beginning
  while food_times[i] == 0:
    i = i + 1
    i = i % len(food_times)
  
 
  # answer is the last i we are standing on
  # return i
  answer = i
  return answer
 
print(solution([3, 1, 2], 4)) # 2
#

that is the same code but with hightlights

nocturne bear
#

@steep wave thanks

naive meadow
#

I'm thinking of doing OSSU anyone done it?

past flare
#

why isnt this possible to decode?

fiery cosmos
#

@past flare What's the file?

#

Maybe a weird character

lean dome
#

Your locale is set to UTF-8, and that string contains non-UTF-8 data. To decode it you'll need to know what encoding was used to encode it, @past flare

feral wadi
#

i kind of need advice I just started Data Structures in python i don't know how to memorize the algorithms i don't know how to become better in that can anyone help me

random quiver
#

Which algorithms?

feral wadi
#

just getting started with data structures

exotic hatch
#

do you have a textbook? a lot of the the examples involve making small code tweaks, those are good to get started before moving on to harder problems

feral wadi
#

no can you recommend an one in web page

north zealot
#

This big O cheat sheet is pretty handy

exotic hatch
#

if you'll need to recall algorithms for a test, practice performing the algorithm manually with pen and paper

#

otherwise just learn the names of the algorithms and what they do and look the details up when you need it

feral wadi
#

like manual tracing?

exotic hatch
#

ya

feral wadi
#

have you got any resource for data structures in

#

python

exotic hatch
#

the MIT opencourseware lectures, the board notes are in pythonesque psuedocode

last blaze
#

If you want something a bit longer, there's a course in the pins

exotic hatch
#

if you want a textbook

feral wadi
#

like a PDF

exotic hatch
#

CLRS is the Truth

feral wadi
#

that's nice thanks for that

old dragon
#

It'll equip you with basic and intermediate data structure and related algorithms

fiery cosmos
#

Can anyone say me how do i install pyplot?

#

Because when i run plotly.pyplot it gives an error

#

After i download it

loud trail
#

do you need matplotlib

thorn drum
#

and import it into your project

fiery cosmos
#

im working on a ethical hacking project so i need someone to make me hulk ddos tool into a exer
@me

#

exe

next aspen
#

does anyone know of a way to extract the icon from a file in python?

#

and save it to a file?

#

in windows 10?

north zealot
#

!rule 5 @TROLLIE#6481 even if it is an "ethical" project, we don't allow those

halcyon plankBOT
#

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

north zealot
#

Ah well, they left

#

@next aspen you want to access the preview icon of a folder?

mellow cedar
#

how do i implement it using lists?

loud trail
#

seems weird to use lists for this since the left, right, parent, and value are all "single" items

viscid spruce
#

hi, I am working on segregating webpages based on the responses, I have to segregate them based on 10 HTTP responses, what would be better to use, switches or if-else statements? or there is more pythonic way of doing it

mint jewel
#

you can use dictionaries

#

generally the best way if you can use that

viscid spruce
#

I am sorry, I will more precise. I have them in a dictionary. A json file which has the data as {'url':'', 'http_response':'404'}. Now i am trying to run some function, which checks them on the basis of what response code the have. so would using if dict[port] == '404': do this elif dict[port]=='200'...... or using a switch case instead of if-elif.

dull owl
mint jewel
#

python has no switch-case

dull owl
#

what do i do

mint jewel
#

you use dictionaries for the same things

{
  '404': some_function,
  '200': other_function
}
#

that is python 2 code, if you are following a tutorial, use a python 3 tutorial

dull owl
#

difficult

#

oh

viscid spruce
mint jewel
#

please do not use b]

viscid spruce
#

b], what?

loud trail
#

"b. With Python Classes"

#

do not

#

use that

viscid spruce
#

hi i need help with my code it says invalid syntax
@dull owl print(character + "text") I would suggest going this way, print(f'{character} walked down the street')

loud trail
#

actually dont use either of these

#

just use if/else

#

oh i see you already have a dict of functions

dull owl
#

im new so whats the f for

loud trail
#

then use a dict of functions, yes

viscid spruce
#

Thanks. @loud trail and @mint jewel

dull owl
#

thanks

mellow cedar
#

seems weird to use lists for this since the left, right, parent, and value are all "single" items
@loud trail ikr? that's what confused me so much, it was a task for friend's uni. here is how solution looks like

loud trail
#

what in the world

#

why would you do that

#

ok i guess it's like, the whole tree?

#

instead of individual nodes?

#

but the whole notion of left and right breaks down then

nova moss
#

super simple question:
Given a Trie data structure, most people describe it as having a search up time of finding if a word is in the Trie or not as O(n) where n is the length of the word searched up, shouldn't it be O(n * m) where n is the length of the word and m is the number of unique characters possible for all the children of a node?

barren hull
#

correct me if I'm wrong but I think it depends on how the trie is implemented

#

if you're storing child nodes in an array then yes, but if you're storing in an dictionary the lookup time for child node can be O(1)

#

another point to make is that O(mn) is still O(n) if m is a constant. I.E if we're talking about english words then m = 26 so O(26n) is still O(n)

ivory yacht
#

Well even if it's an array, you would just use a 26-long one and lookup by character value giving constant time lookups.

crystal plaza
#

can someone look at my java code and tell me why it won't run?

dusty pond
#

No, this is a Python server, sorry. There are plenty of other generic programming servers that can probably help.

north zealot
#

You could try to ask off-topic though, but a specialized server would be better yeah

hearty forge
#

Hi guys, I need to sum up approx. 23 columns from a panda dataframe imported from a csv file

#

how do I go about doing it?

fiery cosmos
#

what do you mean sum.. do you mean total of all rows or total under each column?

copper heron
#

any other good public server for tech stuff you would recommend?

#

am new to discord

near kestrel
#

hello! , i have to do a method so i can check if two nodes of a binary search tree are cousins, is there aynone who could help me ? since i dont know how to even start , thank you

zinc lance
#

Hey guys im implementing graphs in python

#

and i was wondering

#

is a graph still directed if for example we have [A -> B] and [B -> A] but also a bunch of one-directional connections?

#

such as [B -> C], [C -> D]

#

because for a graph to be undirected, its connection is always 2ways [A - B] etc

#

but i didnt know whether a graph is still directed if there is at least one double connection.

#

So, can we see a double connection as simply two directed connections to each other?

quasi oracle
#

@zinc lance yes

#

You can represent an undirected graph using a directed one

zinc lance
#

Cool, and to be clear, a graph is still directed, even if there is one or more occurences of a double connection between two different nodes?

quasi oracle
#

Yes

zinc lance
#

ok thanks 🙂

oblique panther
#

Also I've never once wanted to use a switch case.

#

At least, I've never thought "Oh golly, I sure wish Python has switch cases; guess I'll emulate one with a dict!"

silver quail
#

Hi I have a basic python question. How do I return from a nested function? Let’s say I have a function that calls another function. And Theres a condition in the inner function that I want to return from both functions. Is there a way to do that?

half lotus
#

No, not directly

#

You can return a value which indicates to the outer function that it should also return

#

e.g. return None, and then the outer function will also return if it sees the inner function returned None

#

This is of course assuming that the outer function is calling the inner function

#

If you're passing it off elsewhere then it's not possible afaik

#

Well, maybe if you like set a variable in the outer function's scope, but that's really really confusing control flow.

fiery cosmos
#

Anybody here good w matlab

#

lol

fiery cosmos
#

Isnt it used in the military?

finite lava
#

what

molten jacinth
#

@fiery cosmos think this is a python server

#

I could be wrong though 😄

atomic plover
#

http://puu.sh/FSXVY/80bcbc9dcd.png

Hey Guys, I have a question regarding global variables.
As seen in the screenshot, I want to set the "url"-variable in the main function, and after that, call a Scrapy-Crawler from the same function.
However, even though I set the global url before, it says that its empty in the Crawler-Class.

//Edit: I found a workaround, would still be interesting to know, but its not urgent

How do I get that url there?

chrome yew
#

Hey guys, I have a JavaScript base question, how do I grab a an index link that will allow me to run a parallel index numbers from 1 instead of zero

elfin pecan
#

Any pc simulator or a tool like that which can make me aware of all kinds of different hardware used in pc building?

fiery cosmos
#

What do you mean aware? If you want to monitor your hardware you can use HWMonitor. If you want to learn about pc-building and what hardware you need there are many videos on youtube that teach you this in a better way than reading about it on discord

smoky holly
#

Any pc simulator or a tool like that which can make me aware of all kinds of different hardware used in pc building?
@elfin pecan well i think you just got to really know the parts? if not just buy a built in pc. Youtube, google and everything is available online

elfin pecan
#

So any specific youtube channels you guys would like to suggest?

exotic hatch
#

Linus Tech Tips

stark bridge
#

I like Maru and Hana, but ... it's not particularly python-related 🙂

stark bridge
#

but it doesn't

#
>>> dates = {
  '1':{'a':0,'b':0},
  '2':{'a':0,'b':0},
  '3':{'a':0,'b':0},
  '4':{'a':0,'b':0},
  '5':{'a':0,'b':0}
}
dates['5']['a'] += 1
... ... ... ... ... ... >>> >>> 

>>> pp(dates)
{'1': {'a': 0, 'b': 0},
 '2': {'a': 0, 'b': 0},
 '3': {'a': 0, 'b': 0},
 '4': {'a': 0, 'b': 0},
 '5': {'a': 1, 'b': 0}}
>>> 
#

your problem is that you don't have five separate dicts as your values; instead you're using the same one

#
>>> a_b = {'a': 0, 'b': 0}
>>> dates = {
  '1':a_b,
  '2':a_b,
  '3':a_b,
  '4':a_b,
  '5':a_b
}
... ... ... ... ... ... >>> dates['5']['a'] += 1
>>> pp(dates)
{'1': {'a': 1, 'b': 0},
 '2': {'a': 1, 'b': 0},
 '3': {'a': 1, 'b': 0},
 '4': {'a': 1, 'b': 0},
 '5': {'a': 1, 'b': 0}}
>>> 
next aspen
#

@next aspen you want to access the preview icon of a folder?
@north zealot sorry im late, but what im trying to do is get the preview icon of the file/folder for a file explorer type thing.... but I have no clue on how I can do that

grave rover
#

Is there a math module that does not require cpython?

#

My problem is that the current math module uses the GIL and isn't kind to threads.

#

For example
math.factorial(1000000) will freeze all threads

stark bridge
#

maybe you could do that computation in a subprocess

grave rover
#

Or can I use multiprocessing?

#

I'm running it in an ThreadExecutorPool

#

I fucking hate the GIL

elfin pecan
#

@exotic hatchalright! Thanks!

fiery cosmos
#

hey

#

can someone help me please

exotic hatch
#

ask away, no promises m8

#

there are help channels too

fiery cosmos
#

Wanna go to pricate messages

#

or which channel please

exotic hatch
#

edit:sorry im dumb and dont know the rules @fiery cosmos

nocturne linden
mental mason
#

Hi everyone. I'm preparing for coding interview. Does anyone want to join me to solve puzzles at kattis.com|hackerrank together and discuss it?

hollow stump
#

that usually means "help me prepare for my interview for free and answer questions I have"

mental mason
#

For me it means "to have an ability to discuss|explain solution"

last blaze
#

that usually means "help me prepare for my interview for free and answer questions I have"
@hollow stump

I mean. You say that as though it's a bad thing, but helping others is kinda the point of this discord

fiery cosmos
#

hey guys, im in year 12 doing alevel computer science. i have a test tomorrow. ive never really revised properly so my question is how i should go about learning 6 sections for the test

frigid quail
#

what are those 6 sections you are trying to learn

fiery cosmos
#

programming techniques, software developement, exchanging data, networks and web topologies, data types and boolean algebra

mental mason
#

each topic is pretty broad. do you have list of books, articles and so on you should use for preparation?

fiery cosmos
#

did you go listen to lectures and do the exercises?

#

That's usually enough to pass, if you really did the exercises yourself that is.

#

There's no magical shortcut to learning this in a day obviously.

#

I'd recommend you skim through the chapters, mark stuff you don't understand yet and try working on that while you still have time.

#

Going on discord is kinda detrimental to effective learning as well

#

Shutdown all social media stuff while you're learning

#

i havent done very well in test scores this year because im much more interested in programming so ive missed out a lot of the theory work in lessons

#

and the reason im here asking is because i revised for hours yesterday for my math test i did today on every topic that it covers but i did badly because all the questions were on the parts i least expected

#

so im not really sure which sections come up the most for the test

#

well that's the whole point

#

If you knew in advance you'd not learn everything

#

But they cannot put everything on the test

#

So, unless you're well prepared for all topics of your lecture, you can't be sure to pass easily.

#

this is just new to me because for my gcses i just half-ass revised in the morning on the way to school and passed everything with ease

#

If you keep up with the exercises during the semester and start preparing for exams ahead of time you'll get passing grades again

#

Yeah, that doesn't work in uni/college

#

usually

#

Don't worry though, many students make this mistake at first

#

unrelated question but do you think it would matter for me in the future if i wanted to work in software developement (front and backend web developement for example) if i wasnt good at the theory side of computer science

#

Yes it would

#

probably a dumb question but why do i need it

#

The theory is your toolbox

#

If you only have a hammer in your toolbox you're going to face problems

#

And learning the theory prepares you to dive into more theory where needed

#

i just dont really see where i would need these topics im learning because in all my programming projects they havent helped me at all

#

The main goal is that you learn to teach yourself new stuff

#

and in my class im one of the bottom in tests but im one of the best on the coding side

#

Well, without an understanding of runtime complexity you can't really produce efficient code

#

i guess the only thing ive found to be important in theory that i used in my projects is database normalisation

#

well, obviously you'll learn stuff you won't use

#

but it is helpful, to be able to wrap your head around the theory

#

that's the main ability you're training with this

#

So you can understand the theory that is necessary for what you're doing right now

#

i guess i jsut have trouble in computing with the way they teach the subject too

#

it's often pretty removed from practical application, yes.

#

even the software based questions i dont do too well in because most of my knwoledge is self taught

#

which really confuses me sometimes

#

thanks for explaining this btw

#

do you work in software development?

#

You're welcome

#

No, I'm a math student with computer science as a side subject.

#

I've done a lot of programming in my free time though

#

i do math too but its a lot harder than last year

#

same

#

i only really get computer science from working on projects so lesson work is tough

#

what kind of programmes do you work on out of curiosity

#

right now, actually none

#

in general

#

I was most active in game hacking

#

so, reverse engineering and writing software that exploits whatever I figured out about the game

#

thats cool ive never done anythign like that

#

took ages to get into

#

i mostly worked on simple python programmes like console games but recently ive been really into databases and web development

#

You have to learn assembler for your platform, you have to dive very deep into operating system stuff

#

yeah, I also did webstuff later, but the project I was part of never went anywhere, with me as the only backend dev and the frontend devs never submitting anything but the landing page

#

so the project never got to a point where it could've been released

#

the closest ive been to hacking is making a programme that uses google search to find peoples' repls with certain names such as 'key' and checks the code for any variables called key or whatever then seperates the variable with its value and stores it in my file, then used it to gain access to twitter accounts or discord accounts

#

it was an interesting experience though, learned a bit about issues that can crop up when you work with a team of people

#

ive never worked on a project with more than 2 people so that sounds interesting

#

and it taught me that people don't read manuals

#

is it common for programmers to get really into a project but never finish it through because you find something new or is that just me

#

if you don't have any incentive to finish the project anymore, of couse it will stall, so it's pretty normal.

#

But it can also be more general problem

#

If you leave work unfinished a lot in general

#

yeah its pretty general

#

Yeah, scheduling planning and sticking to your plans

#

all great abilities which school doesn't teach

#

like for example im around halfway through my programming project which we havea year to complete within the first 2 weeks but i got bored so i made a chatroom site

#

my inability to properly lay down plans is often troubling to me, but I'm working on it 😅

#

yeah im very bad at planning

#

especially with coding

#

i work best when i just get into my zone and code for hours straight no breaks

#

so its tough to try note down how i made the code for the written side of the project

#

A general strategy that applies to all problem solving is to subdivide a project into smaller taks that can be finished in one sitting

#

in a software project you usually start out with a rough draft

#

you write down what kind of data you have to handle, what your application does with it etc

#

i do that already but its subconsciously if that makes sense

#

in an abstract informal way

#

having something written on notes or a blackboard can help you sort through things

#

and it can give you a guiding structure to approaching the task

#

i do that when im working with complex databases

#

i usually write in a notes file how i want the database to be formatted first

#

another question if you dont mind, can i use projects ive made as part of a resume of some sort when applying for a job

#

You definitely can

#

But your repositories for that purpose should be in tip top shape

#

what do you mean by that

#

You should make sure your code meets certain criteria they may be looking for

#

right

#

and the projects you list should have some relevance to the job you're applying for

ruby trail
#

Hello, I am a complete beginner at everything related to programming, I was just wondering if it is possible to make something that clicks on a button on a website whenever I get a notification from discord? If so would it be good to use Python ?

fiery cosmos
#

im not even sure if my projects are good enough to use though. im never really happy with the result

#

I get what you mean, there's always something that bugs you about old projects

#

even in a larger scale, im just not happy with what im able to do or not do

#

well, nobody is born a perfect coder 😉

#

Just keep learning as you go and do your best.

#

That's really all that matters, the rest is kinda up to chance.

#

thanks

#

ill keep doing what im doing i guess

#

Good luck, I'll get back to my studies now 🙂

#

me too thanks again

#

it might be small but can anyone help me understand what the question is asking

#

the bottom question*

#

What is required in the HTML code above to make the selectors show styles on the website

loud trail
#

i think they mean to ask "how do you get the css to apply to the html?"

fiery cosmos
#

i still dont understand what thats actually asking

#

like does it mean link the external css file??

loud trail
#

i think so

#

i can't imagine what else they'd be asking

#

very unclear question

fiery cosmos
#

i agree

dreamy root
#

write the lines where the css selector on the left applies

cobalt jetty
#

Hello guys, do you have datasets for network security or malware? It will be very helpful if you have it and are willing to share it with me

oblique tusk
#

can someone write the code for this question

#

The current high score for a videogame is 101500. Prompt the user to enter a score. If the new score beats the high score, change the high score AND output a congratulatory message. However, if the new score does not beat the current high score, ask the user to try again.

#

please dm me the answer

fair plover
#

Hi guys, is searching through a Binary Search Tree ALWAYS faster than searching through a list in Python?
It seems to be so

oblique tusk
#

please help me out guys

vernal creek
#

Bro that sounds like homework @oblique tusk

fair plover
#

^^ lol

#

spitting fax

amber loom
#

@fair plover if the list is sorted, then binary search is same speed as binary tree search

#

and python’s builtin ‘in’ operator is written in c, so it is faster than even binary search

austere sparrow
#

Not necessarily.

grave rover
#

is there a channel to discuss security?

austere sparrow
#

If the list is big enough, binary search is of course faster.

#

@amber loom Especially if the comparison operation is custom.

grave rover
#

❤️

austere sparrow
#

If you have a list of 1048576 elements, linear search will have to do 1048576 comparisons, and binary search would have to do about 20*2 = 40 comparisons, so it's obviously faster.

amber loom
#

@austere sparrow yeah you're right, but c is in general 10^2 to 10^3 times faster than python for calculations, and also to do binary search, you have to sort, which is O(n log n)

austere sparrow
#

Well, assuming the lists are sorted.

#

And assuming that the list contains numbers or strings, the 100 figure might be accurate.

#

But if the comparison operator is defined in Python, it doesn't matter how fast C is

obtuse jungle
#

Also, always is a strong word

austere sparrow
#

wdym?

obtuse jungle
#

Big o and whatnot being asymptotic

austere sparrow
#

That's why I said "for big enough inputs"

obtuse jungle
#

What I mean is like, the question could be a 'trick' question

austere sparrow
#

Due to how binary search works, it doesn't degrade into a worst case complexity on any inputs.

obtuse jungle
#

Something to keep in mind if it's homework or smth

oblique tusk
#

can anyone just help tho

austere sparrow
#

This is not the right channel.

pseudo seal
#

@oblique tusk it's pretty simple do a variable named 'currentScore' that equals to 101500 and create another variable named 'userScore'

#

Then do a print() and take the input of the user and assign it to userScore

#

And if userScore > currentScore:
currentScore = userScore
else:
Print("retry")

#

Sorry for the late response

oblique panther
#

and python’s builtin ‘in’ operator is written in c, so it is faster than even binary search
@amber loom

in has to call __eq__ as many times as there are elements in the list, and if eq isn't defined in C for either type, then that's executing python code.

#

Except when __contains__ uses hashing

#

I think

#

As far as the runtime complexity goes, not for which language is implementing the operation

#

Anyway, even though an O(n) operation being performed in C is going to be fast even for especially large values of n, eventually a O(logn) operation in python will be faster.

amber loom
#

honestly it depends on the context, for sorted lists binary search is always faster, but otherwise just use 'in'

#

o(n log n) for sort is almost always slower than o(n)

oblique panther
#

Well yes, nlogn is a slower runtime in general.

amber loom
#

@oblique panther to be fair, python's builtin sort is timsort, which is heavily optimized for average case, and also is written in hand-optimized C

oblique panther
#

I'm not sure what we're debating at this point.

#

Personally I would never seek out or hand-implement a binary search for checking if a data structure that I didn't write contains a certain value.

#

Is there actually an in-place sort with a better worst case than O(nlogn)?

exotic hatch
#

Depends on the method of computation

#

If youre using comparisons of two elements, no

#

see: radix sort

#

I havent read the conversation im not sure of the context dont know if this is useful

oblique panther
#

I think it was a conversation where we both wanted to state things that we know about runtime complexity, regardless of relevance. At least that's how I was approaching it.

split obsidian
#

Are there examples of the stdlib implementing features that use things like Trees, Searches, etc...?

lean dome
#

Like list.sort and the built-in sorted function?

#

There's also the heapq module

split obsidian
#

Yeah, more things like heapq would be interesting.

I think 99% of my workflow is lists, generators, dicts. Usually when they get more complex than that, there's a library that does the "cs thinking" part for me lol

For example, I don't think I've ever used heapq in anything ever. **outside of leetcode

lean dome
#

There's also bisect module for a binary search algorithm

split obsidian
#

Do you have any recommendations for intuiting the algorithms and knowing how to apply which strategy when? I think my CS fundamentals are weak

obtuse jungle
#

honestly i dont really find myself in a situation normally where a sophisticated data structure is that useful

#

aside from graph stuff

#

search algorithms are kinda just "remember some of them well enough that you think of them later" i think?

#

or at least how to find them again

split obsidian
#

My perspective is mostly for interviews. There's usually a data structure or algo question. You usually have to explain what it is, why you picked it, etc...

Also, usually they're efficiently coded in some 3rdparty library already. If I had to code it, it wouldn't be obvious to me (but I would like it to be). Some things are visually intuitive, but not code intuitive if that makes sense

lean dome
#

If you need to worry about performance, it may be worth writing in a different language. Python is real slow for CPU-bound stuff

obtuse jungle
#

oh yeah interviews

#

uh in that case like idk, dynamic programming and binary trees i spose?

#

if you want to really brute force it just crank out 200 leetcode problems

#

and you're p much set

split obsidian
#

yeah, my background is not in CS, so I'm not familiar with the common approaches. Most of the stuff I just learned on my own because it was relevant to whatever I was doing. >> weak theoretical understanding

obtuse jungle
#

theoretically/optimally you wont be getting problems that are genuinely just "know a specific algorithm and reproduce it"

#

it does sometimes happen

split obsidian
#

Most leetcode easy is np. Medium and hard are hit or miss. My solutions also never look anything like the most efficient ones in the discussion 😛

obtuse jungle
#

honestly leetcode problems are pretty similar to generic interview questions in my experience

#

like of varying difficulties

#

the more interesting ones are cool, but it's hard to really prepare for those specifically

#

some companies are heavier on the theoretical background though

#

esp for new grads

#

with less internship experience

#

in which case you want like

#

your "Standard platter"

#

of like idk

split obsidian
#

I am probably at E4

obtuse jungle
#

tree traversal, stacks and queues, object oriented stuff, some kinda 2d/3d grid stuff, hashes, big o, sorts, recursive fuckery with strings, and DP ™️

split obsidian
#

I think my actual day-to-day is fine, but the theoretical components common in interviews are not 😛

#

is it worth going through a data structures / algo course? I honestly find them really boring

obtuse jungle
#

..facebook?

#

i dont really know most of the big tech company tier names too well tbh

#

the real problem with theoretical shit is that it's like 99% of the time never touched on but then that 1% of the time it balloons into a massive bug-ridden, occasionally nearly-intractable headache because you are unsuccessfully emulating some big brain guy that already came up with the algo

#

when it would have been really helpful to go "Wait a minute, i could just blah blah it"

split obsidian
#

99% they also show up in one or more of the interviews 🙂

obtuse jungle
#

ah well and also interviews