#algos-and-data-structs

1 messages Β· Page 143 of 1

fiery cosmos
#

i explained it earlier to you.

#

and it's clearly written in the picture.

#

if you can't read the picture, how can you read our words?

rare dawn
#

you so rude

#

im also stress

#

so no need your bad input

#

go put your words where they belong in the toilet

fiery cosmos
#

you have four days to do this, and you claim it's for a career change. If you're stressed from this, then you're stressed because you're applying for a programming job with no experience. I suggest considering an entry level course in python

rare dawn
#

you so rude

fiery cosmos
#

in this context, they just want the largest number that's not in the array. So sort them, assign them to indexes, and then iterate until you find the first number that doesn't match the index. It's incredibly easy.

rare dawn
#

im bad but not that bad

fiery cosmos
#

i also said this earlier like half an hour ago

haughty mountain
#

the core task is, find the smallest positive integer that is not in the array. So conceptually:
start at 1, if it's not in the array it's the answer we were looking for, otherwise look at 2 and do the same thing, ...

sooner or later we will find a number that is not in the array, and that's the answer

rare dawn
#

i save it on notepad

#

still stuggled to understand

fiery cosmos
#

remove negative values, sort from zero, index from zero, then check value to index

rare dawn
#

im starting to understand

#

i think

#

i try

#

gimme 5

haughty mountain
#

no need to sort though, sorting is the more annoying solution to write as well

fiery cosmos
#

you dont have to even write sort because it's built in. but knowing this is part of actually knowing the skills they're being asked to demonstrate on the interview question.

#

writing a sort function would probably help them get the job.

haughty mountain
#

I'm not talking about the sorting part being annoying

#

this is the solution I instinctively went for

S = set(A)
i = 1
while True:
  if i not in S: return i
  i += 1
#

you can make it better by not using a hash set, but that's more of an implementation detail

fiery cosmos
#

A = A[A>-1]
A.sort()
if A[0] != 0:
A.insert(0, 0)
return [a.index if a.index != a for a in A]

#

code probably wont work like that but dont fix it, im not doing peoples code for them

#

the basic idea is correct

#

there are... 3 errors in this

rare dawn
#

guys

#

thank you for trying

#

but im screwd

#

i try again some other time

haughty mountain
fiery cosmos
#

like i said

#

3 errors

haughty mountain
#

there is a similar solution to that, but starting to mix indices into the mix is confusing at best

fiery cosmos
#

it makes the code a LOT simpler

#

also ,you disregarded my insert 0

#

the very first index which isnt the value is the answer?

#

I dont even know how to use set

haughty mountain
#

if I understand your code correctly it would check
0==0, ok
1==1, ok
1!=2, nope, so the answer is 2

fiery cosmos
#

1!?

#

you mean if there are redundant numbers

#

ah, but that's an exercise for another day

haughty mountain
#

yes, duplicate numbers breaks your approach

agile sundial
#

the approach can work, you can take into account duplicates

#

very annoying though

fiery cosmos
#

A = [i for n, i in enumerate(A) if i not in A[:n]]

haughty mountain
#

yeah, it's easy to fix, and the fix is to not use indices

agile sundial
#

n^2 πŸ₯΄

haughty mountain
#

^

fiery cosmos
#

select any two- memory, easy to write, fewest lines of code

#

i use indices for all my operations but i also use massively paralleized code

haughty mountain
#

err...the set solution is fine on memory, is easy to write and has few lines of code

#

and avoids a bunch of pitfalls of e.g. the sorting approach

agile sundial
#

maybe I'll just write them all and benchmark πŸ˜”

haughty mountain
#

the right data structure solves the task for you

#

and the set solution is obviously correct by inspection, it literally just does what the task asks, but with fast lookup

fiery cosmos
#

well, the right data structure is numpy.unique

#

sets are inferior to numpy, numpy is the future

agile sundial
#

but you can't use numpy

fiery cosmos
#

also, we want to select only positive values. with a list comprehension, isnt that easily done?

haughty mountain
#

unique requires sorting

fiery cosmos
#

sets remind me of haskell and i loath haskell shudders

#

ill just stick with my nice little arrays

#

also no dicts! only arrays.

haughty mountain
#

how is set haskelly?

#

I can solve this with only lists/arrays too, just use a ~N large boolean array to implement the set

#

one pass over the data, one (probably partial) pass over the bool array, done

rare dawn
#

@haughty mountain do you have a resource for simple help ?

fiery cosmos
rare dawn
#
#

i have done python 100% here

#

well its all i have

#

i am 100% at it

fiery cosmos
#

its also butts

rare dawn
#

for python

halcyon plankBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

rare dawn
#

well i am beginner programmer

#

but expert infosec

haughty mountain
#

I don't have any personal list of good resources, I'm mostly learning by doing and look up docs or random tutorials as I need them

rare dawn
#

same but now my use case if diffrent

haughty mountain
#

but knowing what to search for can also be difficult in the beginning

rare dawn
#

i normally use python to make web sockets

#

or games

haughty mountain
#

I think looking at relevant topics in the official tutorial can be helpful to know what exists in python https://docs.python.org/3/tutorial/

e.g. the parts about the basic built-in data structures

#

there are also other relevant standard modules, like collections and heapq

agile sundial
#

and itertools and functools

haughty mountain
#

tbh it's also hard to give specific recommendations since I would give very different advice to newbie programmers VS programmers new to python VS programmers new to python that has a good grasp of algos and data structures

#

or python programmers that are not used to reading and solving algorithm problems

rare dawn
#

i just feel so lost

#

i understand the theory of data structures

#

just struggle to program them

rare dawn
#

why

raven kraken
# rare dawn

Can you send the screenshot of the error message

rare dawn
#

list' object cannot be interpreted as an integer

raven kraken
#

This way it is hard to tell what could be the problem

haughty mountain
raven kraken
#

Also you are giving A = [1,2,3] and then looping inside the same list , why would the elif condition ever get satisfied?

haughty mountain
haughty mountain
raven kraken
# rare dawn

Try to dry run this code with all the suggested corrections

clear trail
#

Can anyone help me with this one?

The question is that "In a given chessboard with NxN dimensions we have to add all the values in black squares and values in the white squares"

I wrote a working code but it's not getting past through the test cases

    bsum=0
    wsum=0
    for i in range(n):
        for j in range(n):
            if ((i+j)%2==0):
                bsum+=arr[i][j]
            else:
                wsum+=arr[i][j]
    print(bsum)
    print(wsum)
 n=int(input())
arr=[]
for _ in range(n):
arr.append(list(map(int,input().rstrip().split())))
altmatsum(arr,n)```
#

Any ideas?

rare dawn
#

still doesn't work in demo test ide tho

#

but my editor work perfect

haughty mountain
#

doesn't work as in?

#

the solution you had would time out because you repeatedly check if something is in the list, which is slow

#

with a set you can make that lookup fast

rare dawn
#

THIS DONT WORK for test but in editor its perfect

haughty mountain
high pewter
#

Is anyone into physics?

haughty mountain
#

I mean, I studied it in uni

#

but it's been a bit

high pewter
#

what would i get

agile sundial
#

and this is not on topic for this channel

high pewter
#

Alright πŸ‘ thanks man

lean junco
#

what are some best research area in Deep Learning????

haughty mountain
lean junco
#

oh i thought it was this

#

sry

sleek cloak
hazy fossil
#

how do I get better at coming up with ds and algorithms? Is it just a lot of practice? My minds getting so boggled after drawing out a recursive function for a linked list..

shut breach
fiery cosmos
#

is there an easy way to WRITE, not use, write a simple 1d autoregressive algorithm for use with a moving average algorithm to create an ARMA model

#

i have a bunch of highly accelerated numba functions

#
@numba.jit(numba.float64[:](numba.float64[:]), nopython=True, parallel=True, nogil=True,cache=True)
def regressive_average(data):

    y = numpy.zeros_like(data)
    data_pad = numpy.zeros(data.size + 5)
    firstval = 2* data[0] - data[4:0:-1]
    data_pad[0:4] = firstval[:]
    data_pad[5:data.size] = data[0:data.size]
    x = numpy.zeros((data.size, 6))  # create array for outputs
    for i in numba.prange(data.size+5):
        x[i , 0] = data_pad[max(0,i -5)] * 0.2
        x[i , 1] = data_pad[max(0,i -4)] * 0.2
        x[i , 2] = data_pad[max(0,i -3)] * 0.2
        x[i , 3] = data_pad[max(0,i -2)] * 0.2
        x[i , 4] = data_pad[max(0,i -1)] * 0.2
        x[i , 5] = data_pad[i]


    for i in numba.prange(data.size):
        y[i+1] = numpy.sum(x[i,:])/2

    return y
opal oriole
# hazy fossil how do I get better at coming up with ds and algorithms? Is it just a lot of pra...

Have a real problem that can't be solved without new DSs and algorithms. Then check if anyone else has had the same or similar problem. (Also depending on what you are trying to make there will be a point at which you are forced to use some DS or algorithm you do not know yet, connecting DSs and algorithms to concrete problems really helps the idea stick in your mind and apply to other problems as you generalize from that concrete problem (specific -> general, other way around is hard without context))

marble girder
#

Hi, can someone help me... I'm having trouble installing PySimpleGUI

opal oriole
marble girder
#

thanks

merry scroll
#

Hi.
Please help me.
Limits:
1 <= n <= 10^5
1 <= a_i <= 10^9
Thanks in advance, and please ping me when you help

merry scroll
#

Mad because no one could answer

haughty mountain
# merry scroll Hi. Please help me. Limits: 1 <= n <= 10^5 1 <= a_i <= 10^9 Thanks in advance, ...

It's almost as if it's night for a lot of people. I guess after 3+ hours it's not worth it asking for a link to verify it's a public problem and not in some active hiring thing/contest.

The way of actually computing that is actually very straightforward, but coming up with the solution is not.

To begin with WLOG we can rearrange the array in descending order. This invariant will be maintained during operations.

Now we can make operations on prefixes on the array, we should note that operating on different prefix lengths are completely independent, so WLOG assume we do the shorter prefixes first.

When looking at a prefix we want to check how many times we can reduce everything in the prefix by 1. We can do this until the last element in the prefix is equal to the first element after the suffix. I.e.

[... last] [first ...]
```can be reduced `last - first` times. And including doing nothing it yields `last - first + 1` different arrays for that reduction.

These are actually all the puzzle pieces we need. We sort in decending order. For convenience we append a 1, which doesn't change the answer. Compute the difference between all adjacent elements plus 1. Multiply them all together (because the reductions for different prefix lengths are independent) mod `10**9 + 7`.
#

pythonesque pseudo-code

A = sort_descending(A) + [1]
D = adjacent_differences(A)
result = modded_product(d+1 for d in D)
```very straightforward, time complexity is dominated by the sorting
merry scroll
#

And in my understanding, if A = [1,2] then the answer should be 2, right?

A = sort_descending(A) + [1] = [2,1,1]
result = ((2-1+1) * (1-1+1)) % (10**9+7) = 2 * 1 = 2
#

@haughty mountain ?

haughty mountain
haughty mountain
merry scroll
haughty mountain
#

the problem is pretty badly specified, but I'm assuming that numbers need to stay positive

#

if you allow the numbers to become arbitrarily small there are infinte solutions

#

@merry scroll

merry scroll
# haughty mountain <@865551884861702165>

Can you explain for me if array items can get to 0, but can't be negative?

In that case the answer should be 4 ([0,0], [0,1], [1,1], [1,2])
Let me guess... Instead of adding 1 to A we will add 0 right?

haughty mountain
#

that should work, yeah

slim crest
rare dawn
#

hey i am doing bubble sort now

#

will this help me with my test ?

slim crest
#

whats your test

rare dawn
slim crest
#

you need help with bubble sort?

rare dawn
#

no

#

i am pro bubbler

#

but this will help me with this test yes ?

slim crest
#

i'm sorry idk what test you are talking about

rare dawn
merry scroll
#

!rule 8

halcyon plankBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

merry scroll
#

I guess we can't help you

rare dawn
slim crest
rare dawn
#

it say to help me

merry scroll
rare dawn
#

its not ongoing

merry scroll
#

anyway

rare dawn
#

i failed the second i enroll

slim crest
#

my ongoing exam is life

rare dawn
#

dood u put too many skill point into talk shit

#

can you help me ?

slim crest
merry scroll
#

You can just for all integers in range 1 - 1000000
But that is not "efficient".

rare dawn
#

yes i am doing bigO best practice

#

but will bubble sort help me ?

#

cuz i dont understand what they really asking me

rare dawn
slim crest
rare dawn
#

what algo help me with this ?

merry scroll
#

If you really want to do sort thing, then sort the list.
Then for each element a[i] in the sorted list, you need to check if a[i] > 0 and a[i] - a[i-1] > 1
If yes then the answer is a[i-1] + 1
I guess this is comprehensible

merry scroll
#

This is an example of a valid pyramid

     B
    B B
   W R W
  B R R B
 R W B W R
B W W R B W
wispy wren
#

would someone be able to help with this loud and rich problem? ive almost solved it, but theres a couple issues with my code and im not sure how to fix it

#
class Solution:
    def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:
        adjList = defaultdict(list)
        ans = [-1] * len(quiet)
        
        for i,j in richer:
            adjList[j].append(i)
                
        for i in range(len(quiet)):
            ans[i] = self.dfs(i, adjList, quiet)
            
        return ans
    
    def dfs(self, i, graph, quiet):
        if i in graph:
            j = i
            neighbors = graph[i]
            for next in neighbors:
                if min(quiet[i], quiet[self.dfs(next, graph, quiet)]) == quiet[i] and quiet[i] < quiet[j]:
                    j = i
                else:
                    j = next
                    
            return j
            
        else:
            return i
#

my approach is to just iterate through each node, search each node's path to completion and return the node that has the smallest value in quiet

#

i noticed that one problem with my code was that if it finds the correct node, it would just be overwritten when the next dfs search is performed

#

so i tried fixing that by only updating j if quiet[i] is smaller than quiet[j] and setting j = i

#

but it didnt work

haughty mountain
wispy wren
#

expected output: [5,5,2,5,4,5,6,7]
my output: [1,1,2,3,4,5,6,7]

#

the last 4 values are correct because those nodes either have no neighbors or just one

wispy wren
#

im just getting into graph theory

#

so my head hurts too

cyan berry
#

oo

#

good luck for it

wispy wren
#

thanks

#

ive been stuck on this problem all week

cyan berry
#

oof

#

I feel you

#

is leetcode a good way to start coding?

wispy wren
#

its great for practicing dsa

cyan berry
#

dsa?

wispy wren
#

idk so much about other stuff

#

data structures and algorithms

cyan berry
#

ohhh

#

do you think codingame would be better for me ?

wispy wren
#

you gotta know this stuff to pass the technical interview for jobs

#

im not familiar with it

wispy wren
#

have you learned a programming language?

cyan berry
wispy wren
#

then codecademy is great

#

there's a free python course

#

you can learn functions, classes, strings, lists, etc

cyan berry
#

ohh that's great

#

the hardest thing I did without watching a tutorial and stuff was making a guess game where you have to choose between 3 doors and one of them is a trap and makes you loose a life
then it gets harder, you can choose between 4 and 2 of them are traps
Can I show you the code really quick? I think i'd need an optimization

#

also thanks for the tip

wispy wren
#

sure

#

yeah

#

its a famous math problem

cyan berry
#

huh

wispy wren
#

i forgot the name

cyan berry
#

1/2

#

than 1/3?

wispy wren
#

actually

#

the original problem is 3 doors 2 traps

cyan berry
#

ohh

#

ye I did 3 doors 1 trap

merry scroll
wispy wren
#

yeah its similar to the monty hall problem

haughty mountain
wispy wren
#

oh

#

but i could

#

put the min value in ans

#

then compare that value to the next search

#

and just keep updating ans[i] accordingly

haughty mountain
#

wait, why is the constaint on n tiny?

wispy wren
#

because the runtime i think is quite large

#

im checking every node

#

and every node's neighbors

haughty mountain
#

I think this task can be solved in O(#edges + #nodes)

#

I guess it's intended to be able to brute force it

cyan berry
# wispy wren sure
from random import randint
score = 0
doors = None
answer = None
lives = 3
while lives != 0:
    doors = randint(1, 3)
    answer = int(input("You find yourself stuck in a dungeon. You have three doors in front of you. Which one will you take?: "))
    if answer > 3 or answer < 1:
        print("Warning, you must pick a door between 1 and 3")
    elif score == 5:
        break
    elif answer != doors:
        score = score + 1
        print(f"You passed! You have {score} points!")
    elif answer == doors:
        lives -= 1
        print(f"Only {lives} lives left!")

if score >= 5:
    while lives != 0:
        doors = randint(3, 4)
        another_door = randint(1, 2)
        answer = int(input("There are now 4 doors!! But two of them are traps! Beware!: "))
        if answer > 4 or answer < 1:
            print("Warning, you must choose a door between 1 and 4")
        elif answer != doors and answer != another_door:
            score = score + 1
            print(f"You passed! You have {score} points!")
        elif answer == doors or answer == another_door:
            lives -= 1
            print(f"Only {lives} lives left!")

    else:
        print(f"You lose! Your score was {score} !")
else:
    print(f"You lose! Your score was {score} !") 

sorry for sending it now, I didn't want to disturb your discussion but I couldn't find the right moment to send it

wispy wren
#

looks good

#

you dont have to initialize doors and answer to None though

cyan berry
#

ohh nice

haughty mountain
merry scroll
#

@haughty mountain

cyan berry
haughty mountain
# merry scroll Um I think the pattern is these following the exact rules But there is no proof ...

I thought I recognized the puzzle https://www.youtube.com/watch?v=9JN5f7_3YmQ

NEW (Christmas 2019). Two ways to support Mathologer
Mathologer Patreon: https://www.patreon.com/mathologer
Mathologer PayPal: paypal.me/mathologer
(see the Patreon page for details)

Today's video is about a recent chance discovery (2002) that provides a new beautiful visual key to some hidden self-similar patterns in Pascal's triangle and so...

β–Ά Play video
wispy wren
#

and its not exclusive to python

#

it can be done in any language

merry scroll
wispy wren
#

it just deals with how you organize, find, and compute data

#

to briefly summarize it

#

here is what google shows when you search it:
A data structure is a named location that can be used to store and organize data. And, an algorithm is a collection of steps to solve a particular problem. Learning data structures and algorithms allow us to write efficient and optimized computer programs.

#

a list is an example of a data structure

#

you organize data in such a way where you can call a particular data point from memory in O(1) time

haughty mountain
wispy wren
#

and you can search for a particular data point in O(n) time

#

where n is the number of data points in the list

#

there are also other types of data structures

#

such as hash maps and trees

#

ive gotten closer to solving this loud and rich problem

haughty mountain
#

data structures can range from super simple (e.g. arrays and lists, dicts) to intermediate (e.g. tries and other simple tree structures) to advanced (e.g. suffix trees)

wispy wren
#

just the first 2 indeces are wrong now

wispy wren
haughty mountain
#

hmm, thinking closer after toposort the problem actually becomes pretty trivial

wispy wren
#

its not hard conecptually

#

i can solve it conceptually

#

just start at each node

#

do a depth first search check every neighbor of every neighbor until i hit a dead end

#

and return the node that has the smallest value for quiet[node]

#

to do this i made an adjacency list

#

so for i, j in richer

#

j is the key

#

and i is stored at that key

#

i is richer than j so each node in the adjacency list points to nodes that are richer

#

if a node is not in the list

#

then there are no nodes that are definitively richer than that node

haughty mountain
#

you could just do the dfs and have it return the minimum value, right?

wispy wren
#

so what im doing is checking each neighbor that can be reached from the starting node

#

and i check if quiet[i] is less than quiet[self.dfs(next)] where next is a neighbor to i

haughty mountain
#

also, your dfs can end up doing O(#edgesΒ²) work since you don't make sure you visit a node only once, but that's separate from the correctness issue

wispy wren
#

yeah, i thought about that

#

but my first goal is correctness

#

then ill worry about optimization

#
class Solution:
    def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:
        adjList = defaultdict(list)
        ans = [-1] * len(quiet)
        
        for i,j in richer:
            adjList[j].append(i)
                
        for i in range(len(quiet)):
            ans[i] = self.dfs(i, adjList, quiet)
            
        return ans
    
    def dfs(self, i, graph, quiet):
        if i in graph:
            neighbors = graph[i]
            for next in neighbors:
                if min(quiet[i], quiet[self.dfs(next, graph, quiet)]) == quiet[i]:
                    if quiet[i] < quiet[next]:
                        j = i
                else:
                    j = next
                    
            return j
            
        else:
            return i
#

richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]

#

my code returns [1,1,2,3,4,5,6,7]

#

while the expected output is [5,5,2,5,4,5,6,7]

#

so my code is getting stuck on quiet[1]

#

it should check quiet[1] against quiet[2] which hits a dead end

#

so it should return 2

#

and compare quiet[1] and quiet[2]

#

then it should check quiet[1] and quiet[3]

#

3 points to 4, 5, and 6

#

quiet[3] < quiet[4] and quiet[6]

#

but > quiet[5]

#

ok so i see the issue

#

it correctly sets j = 5 when it checks quiet[5]

haughty mountain
#

would this work?

    def dfs(self, i, graph, quiet):
        minimum = quiet[i]
        if i in graph:
            neigh_min = min(self.dfs(neigh, graph, quiet) for neigh in graph[i])
            minimum = min(minimum, neigh_min)
        return minimum
wispy wren
#

but then it checks quiet[6]

#

quiet[3] < quiet[6]

#

so j is set to 6

#

sets it to 3 i mean

#

then thats compared to 1

#

and since quiet[1] < quiet[3] j becomes 1

cyan berry
wispy wren
#

i was thinking along the same lines but couldnt figure out how to do that lol

wispy wren
haughty mountain
wispy wren
#

i started dsa after learning python

haughty mountain
#

fiddling with the indices when you don't need to just adds fun ways in which the code can go wrong

wispy wren
#

@cyan berrywhat i'd do tbh is learn python, then learn dsa, which contains a lot of stuff, then pick a specialized field

wispy wren
#

my output is a list of people(nodes) where each value in ans[x] is the loudest person who is definitely richer than person x

#

but i like your idea of find all neighbors first

#

then comparing their values

#

so what i can do

#

is return quiet[i], i

#

for each search

haughty mountain
#

ah, it does ask for the index, I see

wispy wren
#

compare all the quiet[i]s

haughty mountain
#

this then?

    def dfs(self, i, graph, quiet):
        minimum = i
        if i in graph:
            neigh_min = min(self.dfs(neigh, graph, quiet) for neigh in graph[i], key=lambda x: quiet[x])
            minimum = min(minimum, neigh_min, key=lambda x: quiet[x])
        return minimum
#

actually...does min support key functions?

wispy wren
#

idk

haughty mountain
#

oh, it does

#

then it should work

cyan berry
#

maybe I'm too young to understand everything yet

wispy wren
cyan berry
#

o

fiery cosmos
#

i have been trying to solve this problem for two days with no luck :(. i found solutions online but still cant comprehend the logic behind the solutions. like how can i check every possible slice within the time limit

#

A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≀ P < Q < N, is called a slice of array A (notice that the slice contains at least two elements). The average of a slice (P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q] divided by the length of the slice. To be precise, the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q βˆ’ P + 1).

For example, array A such that:

A[0] = 4
A[1] = 2
A[2] = 2
A[3] = 5
A[4] = 1
A[5] = 5
A[6] = 8

contains the following example slices:

slice (1, 2), whose average is (2 + 2) / 2 = 2;
slice (3, 4), whose average is (5 + 1) / 2 = 3;
slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5.
The goal is to find the starting position of a slice whose average is minimal.

Write a function:

def solution(A)

that, given a non-empty array A consisting of N integers, returns the starting position of the slice with the minimal average. If there is more than one slice with a minimal average, you should return the smallest starting position of such a slice.

For example, given array A such that:

A[0] = 4
A[1] = 2
A[2] = 2
A[3] = 5
A[4] = 1
A[5] = 5
A[6] = 8

the function should return 1, as explained above.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [2..100,000];
each element of array A is an integer within the range [βˆ’10,000..10,000].

#

i would appreciate any explanation

polar gull
#

I know this is nothing about python, but my friend kicked me from his server, but when I try to rejoin it says I'm banned. I'm not on the banlist neither are any of my old accounts.

#

does anyone have a fix for this? Been trying for 1 hour+ and Tried clearing cache, vpn and a lot more.

haughty mountain
#

not the right server, very much not the right channel

haughty mountain
#

in this case, say you have a slice [a, b, c, d]

#

how will the average of it relate to e.g. the average of slices [a, b] and [c, d]?

fiery cosmos
#

they can be equal

fiery cosmos
#

if it is equal that means the average of those slices are duplicate

haughty mountain
#

how does avg([a,b,c,d]) and min(avg([a,b]), avg([c,d])) relate?

#

spoiler ||min(avg([a,b]), avg([c,d])) <= avg([a,b,c,d])||

#

what consequences does this kind of thing have?

polar gull
wispy wren
#

so this does something trippy
/run

def dfs(i, graph, quiet):
    loud, y = quiet[i], i
    if i in graph:
        loudest_neighbor = [dfs(neighbor, graph, quiet) for neighbor in graph[i]]
        #print(loudest_neighbor)
        for loudest in loudest_neighbor + [quiet[i], i]:
            print(loudest)
    return [loud, y]

dfs(0, {0: [1], 1: [2,3], 7: [3], 3: [4,5,6]}, [3,2,5,4,6,1,7,0])
haughty mountain
wispy wren
#

oh is there not a run command in this server?

fiery cosmos
wispy wren
#
[6, 4]
[1, 5]
[7, 6]
4
3
[5, 2]
[4, 3]
2
1
[2, 1]
3
0
[3, 0]
#

this is the output i get

haughty mountain
#

!e

def dfs(i, graph, quiet):
    loud, y = quiet[i], i
    if i in graph:
        loudest_neighbor = [dfs(neighbor, graph, quiet) for neighbor in graph[i]]
        #print(loudest_neighbor)
        for loudest in loudest_neighbor + [quiet[i], i]:
            print(loudest)
    return [loud, y]

dfs(0, {0: [1], 1: [2,3], 7: [3], 3: [4,5,6]}, [3,2,5,4,6,1,7,0])β€Š
halcyon plankBOT
#

@haughty mountain :white_check_mark: Your eval job has completed with return code 0.

001 | [6, 4]
002 | [1, 5]
003 | [7, 6]
004 | 4
005 | 3
006 | [5, 2]
007 | [4, 3]
008 | 2
009 | 1
010 | [2, 1]
011 | 3
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/awakesuhor.txt?noredirect

wispy wren
#

so for some reason

#

some "neighbors" dont return a list and instead return two integers

#

hmm

#

so here i should probably fix it so it doesnt visit already visited nodes

#

because its all there, just the nodes that are repeated mess it up

haughty mountain
haughty mountain
haughty mountain
maiden crown
#

I’m facing small problem while writing the json items in excel multiple json are there so it is creating different excel done in panda excel writer

#

I need to write in all json on same excel and need to use openpyxl if anything releted to this article please share

young merlin
fiery cosmos
young merlin
wispy wren
#

i keep running into bug after bug

#

so i finally found something that works as long as i check each node one at a time

#

but if i iterate through each node

#

rip

#

ok nvm

#

i figured out a way around it

maiden crown
maiden crown
haughty mountain
#

@wispy wren fwiw the code I posted earlier does work

    def dfs(self, i, graph, quiet):
        minimum = i
        if i in graph:
            neigh_min = min((self.dfs(neigh, graph, quiet) for neigh in graph[i]), key=lambda x: quiet[x])
            minimum = min(minimum, neigh_min, key=lambda x: quiet[x])
        return minimum
wispy wren
#

plus i dont fully understand lambda functions

#

maybe you can figure out why im getting a None type error though

haughty mountain
wispy wren
#
def dfs(i, graph, quiet, visited):
    if visited[i]:
        return
    visited[i] = True
    loud, y = quiet[i], i
    print(loud, y)
    if i in graph:
        loudest_neighbor = [dfs(neighbor, graph, quiet, visited) for neighbor in graph[i]]
        #print(loudest_neighbor)
        for loudest in loudest_neighbor:
            print(loudest)
            if loudest[0] < loud:
                loud, y = loudest[0], loudest[1]
    return [loud, y]
#for i in range(8):
    #visited = [False] * 8
dfs(0, {1: [0], 2: [0,1]}, [0,1,2], visited)[1]
wispy wren
#

hmm

haughty mountain
#

you can return [10**9, None] or similar

#

messed up the order at first

#

just some result that is basically infinity

wispy wren
#

how in tf

#

that doesnt happen for every test case though

#

so im trying to understand why

#

if i = 0

haughty mountain
#

yeah, it only happens in some graphs

wispy wren
#

it should skip the loudest_neighbor part entirely

#

and return [0, 0]

#

if i = 1

#

loudest_neighbor should be [[0, 0], [1, 1]]

haughty mountain
#

you know the kind of cases that mess things up, right?

wispy wren
#

no

#

my brain is about to pop

haughty mountain
#

this kind of graph causes you to do the same work multiple times

o-->o-->o-->o
|       ^
 -------
wispy wren
#

that still doesnt explain why it returns none

#

i should get [0, 0, 0] as my answer

haughty mountain
#

you return None in the beginning of your function

wispy wren
#

because of visited[i]?

#

oh

#

wait

haughty mountain
#

return some "infinite" value like [10**9, None] and it should work fine

wispy wren
#

visited should be set to [False] * len(quiet) each iteration

#

well i cant see the problem

#

im gonna take a break and try to figure this out later

#

thank you for your help

#

this is the closest ive gotten to solving this problem

haughty mountain
#

or do you want to know why what I proposed should work?

wispy wren
#

i dont even understand why your proposal works

#

its ok

#

i need a break

#

ill try to figure it out later

haughty mountain
#

you have a loop that picks the minimum of all options, adding an infinite value there won't matter, it will be immediately discarded

wispy wren
#

hmm

#

ok i see what you mean

#

what module is math.inf from again?

#

numpy

haughty mountain
#

a possibly cleaner solution would be to move the dfs call into your loop, and do the visited handling there

that way you don't need the inf value

haughty mountain
wispy wren
#

lol

#

it worked

#

i still dont really understand why

#

its super inefficient but it was accepted

#

faster than 5% of python submissions

#
class Solution:
    def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:
        adjList = defaultdict(list)
        ans = [-1] * len(quiet)
        
        for i,j in richer:
            adjList[j].append(i)
                
        for i in range(len(quiet)):
            visited = [False] * len(quiet)
            ans[i] = self.dfs(i, adjList, quiet, visited)[1]
            
        return ans
    
    def dfs(self, i, graph, quiet, visited):
        if visited[i]:
            return [math.inf, None]
        visited[i] = True
        loud, y = quiet[i], i
        if i in graph:
            loudest_neighbor = [self.dfs(neighbor, graph, quiet, visited) for neighbor in graph[i]]
            for loudest in loudest_neighbor:
                if loudest[0] < loud:
                    loud, y = loudest[0], loudest[1]
        return [loud, y]

the final product

#

oh i see why

#

so its hitting that visited[i] check after its already in the for loop

#

and then nothing is returned

#

so this fixes it by returning a list

#

@haughty mountainthanks

#

this problem was driving me insane

haughty mountain
#

np

merry scroll
haughty mountain
#

what are you actually doing in your solution to make use of the pattern?

merry scroll
haughty mountain
#

the pattern can be applied recursively

merry scroll
#

How can I do that?
Like creating a function?

haughty mountain
#

I mean, there is a pattern for the 4 large triangles

#

that collapses everything but the corners

#

what if we repeat that?

merry scroll
#

Yeah, I collapsed it.
And repeated it

haughty mountain
#

the pattern is true for (if I think correctly) lengths 4, 10, 28, 82, ...

merry scroll
#

Yeah, I know
After watching your video

gentle merlin
#

how to do in order traversal in binary tree

haughty mountain
#

so say you had n = 100, then you could make use of the 82 pattern to compute row...19 I think?

#

and then use the 10 to compute starting from row 19

#

and work your way down

#

runtime should end up as O(n) in total

#

for the example you posted earlier you can jump from row 6 to row 3

     -
    - -
   W R W
  - - - -
 - - - - -
B W W R B W
merry scroll
#

hmm...
Let me try

fiery cosmos
fiery cosmos
haughty mountain
#

it's not O(nΒ²)

merry scroll
#

OMG thank you so much for helping me twice today @haughty mountain
Thank you so much

haughty mountain
merry scroll
#

Your code looks good

fiery cosmos
fiery cosmos
haughty mountain
merry scroll
haughty mountain
#

similar speedup technique, pretty different problem

fiery cosmos
haughty mountain
#

replace it with manual code, i.e. add and divide by 2 and 3 respectively

#

it's like 30x slower

#

wtf

haughty mountain
#

it's optimized for accuracy and not speed

fiery cosmos
fiery cosmos
# haughty mountain it's optimized for accuracy and not speed

def solution(A):
all_avg = 10**10
p = 0
first_2_avg = sum(A[:2])/2
for i in range(3, len(A)+1):
avg_3 = sum(A[i-3:i])/3
avg_2 = sum(A[i-2:i])/2
c = avg_3 if avg_3 < avg_2 else avg_2
if c < all_avg:
all_avg = c
c_p = i-2 if avg_3 < avg_2 else i-1
p = c_p-1
return 0 if all_avg >= first_2_avg else p

#

got 100%. thank you very much @haughty mountain. i really appreciate your help

haughty mountain
#

np

halcyon plankBOT
rare dawn
#

it works

#

but its size of so messed up

#

please can someone help |?

barren ridge
#

Hello, I have read in a csv file via pandas which has 14 columns. I need to arrange the values of the columns under each other. I.e. append values from column 2 under 1 and so on. Can someone please help me with this?

fiery cosmos
#

I was Wondering if anyone knew the python equivalent of 'case' from C++

austere sparrow
#

If you want exactly switch-case from C, you can just have a chain of ifs

#

Or a dictionary, depending on why you need it

amber hedge
#

Hello here please I have a question to ask, I don't know if I can proceed

fiery cosmos
#

im noob at python who can help

amber hedge
#

TypeError: '<' not supported between instances of 'tuple' and 'int'

dark aurora
#

What is the fastest way to change the value of an item in a sorted list
is lst[inx] = newvalue; sorted(lst)
the fastest way?

#

if the max of a list is ten does it even matter performance wise?

keen hearth
#

@dark aurora If there are 10 items max, it probably won't matter a great deal how you do it.

#

If there were a lot of items, it might be better to del/pop the item, then do a binary search to find the index at which to insert the new item.

#

That would be something like this: ```py
del mylist[idx]
mylist.insert(bisect(mylist, newval), newval)

#

Where bisect is imported from the bisect module.

neon flax
#

A click counter is a small hand-held device that contains a push button and a count display. To increment the counter, the button is pushed and the new count shows in the display. Clicker counters also contain a button that can be pressed to reset the counter to zero. Design and implement the Counter ADT that functions as a hand-held clicker. in c++ anyone ??

haughty mountain
#

wrong server, wrong language, wrong channel

merry scroll
#

Help
I don't really understand this

haughty mountain
#

If I'm right about what the solution is the hard part is just making some observations about the problem

#

So, say we ignore the k operations you can do, do you get the basic setup?

#

You're given A and B (which presumably have non-negative elements?)

#

and you are (effectively) allowed to reorder the elements of A however you want to minimize f(P)

#

@merry scroll how would we minimize f(P), if we couldn't do any of the k operations?

merry scroll
haughty mountain
merry scroll
haughty mountain
#

say a<=b and c<=d, it's easy to show that

max(a*c, b*d) = b*d >= max(a*d, b*c)
#

so swapping never makes the maximum go up, but it might make it go down

#

this is a very typical argument for greedy problems like this, an exchange argument

#

so what's the consequence, what if we swap until we can't swap anymore?

#

@merry scroll

merry scroll
haughty mountain
#

well, yes, but what about the sequences A and B?

merry scroll
#

They will be sorted?

haughty mountain
#

yep

#

so, we've kinda solved the part of the problem that seemed hard

merry scroll
#

Yes...
And how about the k operations?

haughty mountain
#

I mean, we know the optimal configuration is. We don't have to worry that an operation will somehow make some completely different permutation be better. We can just focus on the permutation where things are sorted

#

Any ideas about what operation we want to do to bring the maximum down for that configuration?

#

Oh yeah, the operation is just that you're allowed to decrement an element in A by 1 (but you can't decrement it below 0)

#

@merry scroll

merry scroll
#

Maybe reduce the elements in A evenly?

#

To make A still sorted?

haughty mountain
#

not the maximum element in A

merry scroll
#

And I can decrease an element in A down to 0.
With enough operations, of course

haughty mountain
#

what is it that defines the maximum? i.e. what is f maximizing?

merry scroll
#

Maximizing?

#

When there is a pair of A_i and B_i (i is same for both) which A_i and B_i are maximum in the array they are in?

haughty mountain
#

i is the same for both if we consider A and B to be our re-ordered arrays, sure

merry scroll
#

yeah...

haughty mountain
#

f is maximizing the product of corresponding elements in A and B

#

how can we make that maximum go down with our operation?

merry scroll
#

Sort?

haughty mountain
#

with our operation, i.e. decrementing some element in A

merry scroll
haughty mountain
#

to ask a dumb question:
what is it that makes the maximum value what it is?

#

it's just ||the a*b pair(s) that have that value||

#

those are the pesky ones that keeps our maximum high...if only we could make them smaller somehow

merry scroll
#

yes.
Then we will use the operations to reduce it?

haughty mountain
#

my mental image is going around with a hammer and just bonking the largest thing around to make it smaller

#

and is there ever a reason to not bonk the thing with the largest product first?

merry scroll
#

oh okay

merry scroll
haughty mountain
#

are you repeatedly scanning the list for the largest product?

#

if so you want to avoid that

#

you want some kind of a priority queue

#

!d heapq see this

halcyon plankBOT
#

Source code: Lib/heapq.py

This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.

Heaps are binary trees for which every parent node has a value less than or equal to any of its children. This implementation uses arrays for which heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2] for all k, counting elements from zero. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that its smallest element is always the root, heap[0].

merry scroll
#

Sadly, I can't use heapq

haughty mountain
#

why?

wispy hare
#

I read that in US you can never be more than 115 miles from a McDonald, so I was wondering how we can compute this? Like given a set of 2D points representing the stores + the border of the map, how can we compute the maximum distance between a point in the map to one of the stores?

lean walrus
#
  1. calculate min distance to mc for every point in a grid (for example, with step = 1km)
  2. choose several points that have maximum distance ()
  3. try to optimize every point:
    3.1) move point a bit in some direction and look at how distance changes
    3.2) if distance increases - it is good, move this point again in same direction
    3.3) if distance decreases - it is bad, try move point in different direction
    3.4) if distance always decreases (for every direction) - you've found a local maximum - it is a solution
  4. you have several local maximums - choose biggest of them
#

Gradient descent (also often called steepest descent) is a first-order iterative optimization algorithm for finding a local minimum of a differentiable function. The idea is to take repeated steps in the opposite direction of the gradient (or approximate gradient) of the function at the current point, because this is the direction of steepest de...

#

@wispy hare

haughty mountain
haughty mountain
lean walrus
#

how to check that circles cover all shape?

haughty mountain
#

I guess the original problem can be solved by looking at all the "corners" of a voronoi diagram, but even that's annoying

glossy breach
#

Voronoi is the way ig

lean walrus
#

but building that diagrams is complicated task, i think

glossy breach
#

Binary search sounds easy at first sight but after thinking about it it is quite hard

haughty mountain
#

it's guaranteed not harder than the original question

glossy breach
#

Theres just no way to check if the circles cover the surface

#

Besides voronoi diagram already has a known algorithm to construct it

haughty mountain
#

the solution to the original problem gives you the answer for the covering question

#

for all radii

#

it might just be that some version of voronoi diagrams solves both

glossy breach
#

You are trying to solve the original problem tho lmao

haughty mountain
#

solving the simpler problem means we can solve the original problem

open moth
#

How to solve these

agile sundial
#

no one can read those

open moth
#

Is this could be read @agile sundial

agile sundial
#

is this a competition

open moth
#

yes

agile sundial
#

we can't help you with that

open moth
#

Thank you

fiery cosmos
#

hey , i need help , i have a project to do with python and HTML to create a website that asking you your password and username

#

then u can access to your own profile

#

how should i start?

keen hearth
merry scroll
#

@haughty mountain

haughty mountain
# merry scroll Hi What did I do wrong here? https://paste.pythondiscord.com/ewuwipomun.sql

I made a small fix to check (we can't allow negatives) and I rewrote the binary search to a form I'm more familiar with. Maybe only the check part was necessary, idk

from math import ceil

n,k = map(int,input().split())
a,b = [list(map(int,input().split())) for _ in range(2)]
a.sort()
b.sort(reverse=True)

def check(x):
    lk = 0
    for i in range(n):
        lk += max(ceil(a[i] - x/b[i]), 0)
    return lk <= k

low = -1
high = 10**12
while high - low > 1:
    mid = (low + high) // 2
    if check(mid):
        high = mid
    else:
        low = mid

print(high)
austere sparrow
#

isn't this... O(n * log(high - low))?

#

what is the problem about?

haughty mountain
#

k can be up to 10**18, values in A are <= 10**6

haughty mountain
south dragon
#

where i can find content to study about data structure and algorithm?

austere sparrow
south dragon
uncut oasis
haughty mountain
uncut oasis
#

I mean it has to exist on ALL the list of list and if it is called intersection then yeah

haughty mountain
#

unless you care about order and duplicates in masterlist, if so

isect = set.intersection(*map(set, individual_lists))
res = [x for x in masterlist if x in isect]
#

I ignored the fact that masterlist is a nested list, you probably didn't intend that

uncut oasis
#

I already did set on those duplicates

#

thanks, will try this later

native spoke
#

Hi when using polyfit it's giving me a very bad fit. Like pretttyyyy bad. I'm doing on a scale of 1-1000 (once every 10 it puts a point) and the ouputs are between ~35-50k but with a degree of three it screws up

#

my code is pretty normal there's nothing special

x = points[:,0]
y = points[:,1]

z = np.polyfit(x, y, 3).round(decimals=2)
f = np.poly1d(z)```
#

and I made sure x and y values are loaded properly

native spoke
haughty mountain
#

lol

chrome raven
#

I just spent all day developing an INI parser and I need some guidance on how to polish it into a nice software product. I learned about toml later, but fortunately, I found the thinnest excuse for justifying reinventing the wheel.

#

Anyway, long story short, it builds up a nice doctree, and that all seems to work fine according to the cursory "battery" of tests I've subjected it to. But the problem is, there really aren't any good methods for accessing the data in it. I've implemented the bare minimum to just see that the parser is working correctly.

#

So if you wanted to use an INI file, so you typed one out, fed it to this parser, and this parser handed you an object, how would you like to interact with that object?

#

Here's the constructor for the doctree node class that forms the basis of the doctree:

class Section():
    def __init__(self, name):
        if isinstance(name, str):
            self.name = name
        else:
            raise TypeError("'name' must be a string.")
        self.parent = None
        self.kwvals = {}
        self.sections = {}
        self.garbage = []
        self._name = name
#

There's a class called Doctree that derives from Section, has "" for a name, and doesn't have a parent. Otherwise, the rest of these Sections all get a name, and they get a parent. kwvals are key/val pairs associated with the section, sections contain other Sections, and garbage is a list of strings that weren't comments but didn't otherwise parse into anything recognizable.

#

Does anyone have any opinions? The vals in the key/val pairs are all strings. Should I make available a way to coerce them into the types they appear to be? Should I implement a jquery-like path parser for accessing elements? Utilities for dumping out pretty-printed trees?

merry scroll
edgy zealot
#

I am trying to find the derivative of a function using the limit definition (not via numpy/symby's differentiation method). I have a list of coefficiants (in order of degree) and am trying to create a numpy/sympy function using those coefficiants. I have included a picture of what I have tried (very bad, but i am very new to the sympy/numpy format), and I have gotten a 'expected non-empty vector for x' error. I am unsure of where to go to create this functon, and any help would be appreciated

#
coefficients = f.c[::-1]
    x_func = Symbol('x')
    y_func = (x_func * 0)

    print(type(y_func))

    for i in range(16, 0, -1):
        temp_x = Symbol('x')
        temp_y = temp_x
        temp_y += 0.001
        temp_y = temp_y**(i-1)
        temp_y *= coefficients[i-1]
        y_func += temp_y
haughty mountain
young merlin
#

I've just started leetcode, started with a medium problem, I get the desired output in python, yet:

native spoke
young merlin
#

yeah , somewhow the return doesnt give any output.

young merlin
young merlin
native spoke
#

np*

native spoke
#

so it's not exactly like it would be in console

young merlin
#

okay

#

so why doesnt return work in normal python?

fiery cosmos
young merlin
#

oh, return doesnt mean printing

#

now i get it

#

thats why print worked in normal python

#

thanks

fiery cosmos
#

Also while making functions we usually return values. Yeah. Because we want to use the values in our programme.

rare dawn
#

I failed

#

what is the answer ?

haughty mountain
#

do we really need to go through the same stuff a third time?

#

it was discussed in detail after the first time you asked

#

with code, even

slim crest
rare dawn
#

Guys wow

slim crest
#

what?

#

...

rare dawn
#

If you asked me for help on anything InfoSec you will look stupid

#

so stop being mean

#

i cant code but i cant inject binary into an application that will return it to the server and infect all users using that service

#

Obfuscation of binary injection type that i found out

#

most devs arent aware of this i even got award from my company

#

so shut up with being rude

#

im trying to learn

#

if you dont respect that you are a trash human

#

im not a programmer

#

im trying to learn

#

Im a Pentester

#

I know how to write bots

#

I dont know how to do math with code

#

im trying to learn

#

i can write a ruby script to crawl internet and look for SmexyCorny and all associated ip ,email ,other info

#

so stop being dick

#

you think you a smart dev but you and all the code you write can be hacked in 10 seconds @slim crest when i can program at least i wont be a child in security measures.

agile sundial
# rare dawn

do you remember what was discussed last time? what did you try, why did that not work

uneven geyser
#

!tempmute @rare dawn 4D We don't talk to people that way in this community. Telling people to shut up and stop being dicks or that they're trash humans is not welcome here. Take a few days to read our Code of Conduct, and the next time you get annoyed, step away from the computer instead of unloading a wall of ad hominem and petty bullshit.

halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied mute to @rare dawn until <t:1643287220:f> (3 days and 23 hours).

uneven geyser
#

I think people in here have been both patient and helpful. thanks for that.

halcyon plankBOT
uneven geyser
halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied warning to @slim crest.

uneven geyser
#

maybe you should read the CoC, too.

#

can we try to keep it a bit friendlier in here?

agile sundial
#

ask away I guess

uneven geyser
#

don't worry about me, just ask. that's what the channel is for.

agile sundial
#

using a class for that is kinda weird if you only doing it once

#

the code is pretty bad

jolly mortar
#

geeksforgeeks has... less than ideal code

agile sundial
#

does adding edges make sense?

#

wdym?

#

yeah?

austere sparrow
#

oh wait, it's a real website

#

huh

agile sundial
#

an edge is a connection between two nodes

#

this graph doesn't have the ability to have nodes with no edges πŸ˜”

haughty mountain
agile sundial
#

yes, exactly

haughty mountain
#

the graph is just an adjacency list, exactly what you would expect

austere sparrow
#

Conceptually, yes. In CPython it's a double ended linked list of small (64) arrays

kindred warren
#

looking for help with graph visualization. I'd like to be able to specify locations for certain nodes. Eg Node A in Top Right, Node B Mid Left, etc. it looks like this with NetworkX and matplotlib

#

hmm maybe pygraphviz

zealous kite
#

hi , i need help , i have this string and i need to take from this string only things behind ,name=(names), I know how to get extract nickname from that string , but i need o it multiple times how many times i have ,,name= ,,there

#

info1 is this ["[Player(index=0, name='Jura', score=0, duration=2818.6748046875), Player(index=0, name='Dajvi', score=0, duration=2632.51708984375), Player(index=0, name='TT LaserJetPro', score=0, duration=2628.998291015625), Player(index=0, name='Lahvon', score=0, duration=2194.8251953125), Player(index=0, name='TT You know who', score=0, duration=345.0632019042969)]"]

#

its getting info about player from server , but i need only Nicknames

lean walrus
#

why info1 = str(info1) ???

#

you lose data

#

dont convert it to str and use it as list of objects

keen hearth
fiery cosmos
#

How could i make a script to remember where he pressed a key. Then go back to that place to resume functions ?

upbeat charm
#

Develop Python code to show the application of both pivot()
function and pivot_table() function. how we do this

storm night
#

Probably a silly question but how do I return the string of a match object found via python's regex "re" library?

For example
re.search(r'\d{12}', filepath)
This only returns a re.Match object, but I'm not sure where to look to extract the match='somestring' part

night blaze
storm night
#

Welp that was straightforward lol, thank you

tough shoal
#
('hi')
harsh field
#

Hey,
I've never used classes before in python.
I want to make a tree where:
= each node has a score,
= each node has a list of child nodes,
= the name of each node is some string, and I can just look up any node if I input the matching string
Any ideas on how I can do this?

#
class Node:
    def __init__(self):
        self.children = []
        self.score = "u"

This is what I have, but I don't know what I'm doing

slender sandal
#

If each node has a name, it should be a property in the class

harsh field
#

Ah! That makes sense, i didn't know __name__ was a thing πŸ˜›
Thanks πŸ™‚

#

assuming that I use __name__ to accomplish what i want, which i'm not certain I do

slender sandal
#

I didn't mean that

#

Just like you have score

harsh field
#

Well, I've never used classes before. So I don't know what you mean

slender sandal
#

Have name

austere sparrow
#

@harsh field If you just want a data structure, you could just have a dictionary:

{
    "children": [],
    "score": "u",
}
``` and functions that operate on it
harsh field
prime merlin
#

I'm trying to randomly sample a 10 tuple (a1,...,a10) such that each ai is an integer from 0 to 100 and the ais sum to 100 in python

#

I cant seem to figure out how to do this

#

is there a numpy function for this?

#

cuz it seems like quite a natural problem

haughty mountain
#

If you had not had integers the problem is trivial since you can just rescale. If you care about uniformity and want integers this questions gets quite annoying

#

If you can write recursive code to count the number of ways to generate N integers summing to S then it wouldn't be so hard to modify that to generate tuples, I think

#

Like, there are X such tuples, let me generate an integer r in [0, X) and generate the rth one.

#

With the help of the counting function this can be made quick enough

prime merlin
#

yeah its a bit weird

#

problem is since they must sum to 100 thats quite a large number of possible partitions

fiery cosmos
# prime merlin I'm trying to randomly sample a 10 tuple (a1,...,a10) such that each ai is an in...

In the context of combinatorial mathematics, stars and bars (also called "sticks and stones", "balls and bars", and "dots and dividers") is a graphical aid for deriving certain combinatorial theorems. It was popularized by William Feller in his classic book on probability. It can be used to solve many simple counting problems, such as how many w...

fiery cosmos
polar gull
#

how do I make it so I can pip install my requirements.txt file?

runic tinsel
#

sort and find differences

#

something like that

#

no idea about distribution it makes

#

i guess 9 points

#

!e

from random import choices

def parts(sumto, n):
  x = [sumto] + choices(range(sumto+1), k = n-1)
  x.sort()

  return [y-x for x,y in zip([0, *x], x)]

print(parts(5,5))
  
halcyon plankBOT
#

@runic tinsel :white_check_mark: Your eval job has completed with return code 0.

[2, 0, 2, 0, 1]
plain rover
#

Hi, no idea where to post numerical things but:

Does anyone have an example implementation of a MUSCL scheme to solve 1d advection eq.?

prime merlin
#

thanks for the help everyone

haughty mountain
#

that matters a lot to what solution is ok

runic tinsel
#

oh you're right, it avoids large numbers

#

but

#

no, that's natural

#

you can't tell if it's not uniform

#

like, at a glance

haughty mountain
#

I'm more annoyed that the uniformity wasn't mentioned at all in the question. If you don't care about uniformity there are tons of ways. And if you ask about libraries that implement it I'll for sure assume you want a proper uniform solution 😩

runic tinsel
#

i think they care a lot

#

but trusted me 100%

#

you took it as "they don't care"

#

@prime merlin it's really really broken

haughty mountain
runic tinsel
#

fair enough

#

it's awful though

#

(3,6) β†’ (2, 0, 0, 0, 0, 1) rarely happens but other permutations of it with 0 on the ends happen a lot

runic tinsel
#
from random import sample
def parts(sumto, n):
  x = sample(range(1, sumto+n) , n-1)
  x.sort()

  return [y-x-1 for x,y in zip([0, *x], [*x, sumto+n])]
```working version of that idea
keen hearth
#

With the other solution, there's not a one-to-one correspondence, so some outcomes end up more likely than others.

high pewter
#

can someone help

raw anvil
# high pewter

you want ppl to give you code or tell you what to do ?

high pewter
high pewter
#

Not tell me what to do or give me the code

round glacier
#
    def bfs(self, start, end):
        queue = [[start]]
        while queue:
            path = queue.pop(0)
            node = path[-1]
            if node == end:
                return path
            for adj_vert in self.graph.get(node, []):
                new_path = list(path)
                new_path.append(adj_vert)
                queue.append(new_path)```
#

Can someone explain to me why I need to have:
new_path = list(path)

#

for finding a path with bfs?

#

path should always be a list...

#

why do i need to cast a list, to a list?

#
>>> x = ['1', '2', '3']
>>> list(x)
['1', '2', '3']
>>> x
['1', '2', '3']
>>> ```
#

i dont get it lol

#

its weird tho because if i dont do this, i do get different results

austere sparrow
#

@round glacier list(path) creates a copy of the list

#

!e

x = [1, 2, 3]
y = x
y.append(4)
print(x, y)
halcyon plankBOT
#

@austere sparrow :white_check_mark: Your eval job has completed with return code 0.

[1, 2, 3, 4] [1, 2, 3, 4]
austere sparrow
#

!e

x = [1, 2, 3]
y = list(x)
y.append(4)
print(x, y)
halcyon plankBOT
#

@austere sparrow :white_check_mark: Your eval job has completed with return code 0.

[1, 2, 3] [1, 2, 3, 4]
fiery cosmos
austere sparrow
#

?

fiery cosmos
#

Hlw

#

Can I talk with you ?

austere sparrow
austere sparrow
fiery cosmos
#

About programming ....

#

Ohh okay If you have problem then . it's okay

austere sparrow
#

@fiery cosmos If you have a question, you should see #β“ο½œhow-to-get-help and claim a help channel. Then just ask your question in the channel.
Or, if your question is about algorithms or data structures, you can ask here.

fiery cosmos
#

Can you tell about python arrays in details ....?

#

Or if you have any tips for me ?

#

Give me the tips for better learning ?

round glacier
#

ah i see

round glacier
# austere sparrow <@!745303696413425695> `list(path)` creates a copy of the list

Not sure why or how using list() in the code below would lead to two entirely different outputs

    def bfs(self, start, end):
        queue = [[start]]
        while queue:
            path = queue.pop(0)
            node = path[-1]
            if node == end:
                return path
            for adj_vert in self.graph.get(node, []):
                # creates a copy of the list
                new_path = list(path)
                new_path.append(adj_vert)
                queue.append(new_path)```
#

like why would not using list() add new values

#

i feel like it should be the opposite

#

if ur using it, u get values that u wouldnt

#

because ur popping the path, copying it, then adding to it

#

but when u dont copy, you get MORE values?

austere sparrow
# round glacier but when u dont copy, you get MORE values?

If you had just this:

    def bfs(self, start, end):
        queue = [[start]]
        while queue:
            path = queue.pop(0)
            node = path[-1]
            if node == end:
                return path
            for adj_vert in self.graph.get(node, []):
                path.append(adj_vert)
                queue.append(path)

All the lists in the queue would be the same list, not different lists

round glacier
#

oh ok

young merlin
#

guys in competitive programming competitions, are we usually allowed to use modules?

#

like itertools, etc

glossy breach
#

i dont think so

haughty mountain
#

any external dependencies, most often no

tame tundra
#

My code:

char = [['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
        ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' ]]

def check_password(string):
    char_number = 0
    char_lower = 0
    char_upper = 0
    
    for i in range(len(char)):
        for j in char[0]:
            char_number = char_number + string.count(j)
        for k in char[2]:
            char_upper = char_upper + string.count(k)
        for l in char[1]:
            char_lower = char_lower + string.count(l)
        break

    if char_number > 0:
        if char_lower > 0:
            if char_upper > 0:
                return 'YES'
            else:
                return 'NO'
        else:
            return 'NO'
    else:
        return 'NO'

if __name__ == '__main__':
    t = input()
    string = input()
    string_2 = input()
    print(check_password(string))
    print(check_password(string_2))
#

it produces correct output

#

but the website says its wrong

haughty mountain
# tame tundra

problem link so we know it's not some active contest or similar?

tame tundra
#

@haughty mountain

haughty mountain
#

you're only doing 2 passwords, rather than t passwords

tame tundra
#

how to get t passwords?

haughty mountain
#

read input and call check_password t times

#

currently you're doing it exactly 2 times

#

regardless of t

tame tundra
#
if __name__ == '__main__':
    t = int(input())
    for i in range(t):
        string = input()
        print(check_password(string))
#

something like this?

haughty mountain
#

yep

tame tundra
#

compilation is successful lets see the answer

#

its correct

#

Thanks a lot @haughty mountain

haughty mountain
#

the code for checking the password is a bit awkward, you can make it a lot simpler

if (any(c.islower() for c in string) and
    any(c.isupper() for c in string) and
    any(c.isdigit() for c in string)):
  return 'YES'
else:
  return 'NO'
nova sky
#

is the complexity for 2^(2^(n^2 + 4n)) * 2^7

#

or can we simplify it further

cloud wolf
#

can anyone suggest me the good source for learning data structures and algorithms?

slim crest
#

siuuu

patent isle
#

Any other good sources

#

Like is tutorialspoint pretty good

#

?

compact notch
#

Hi do you know how to convert a str to utf-8 who is usable in a web browser ?

vocal gorge
#

what do you mean by that?

compact notch
#

for example: Β¨ = %CC%88

#

when I encode to UTF-8 I get b'\xcc\x88'

haughty mountain
#

err

#

!d urllib.parse.quote

halcyon plankBOT
#

urllib.parse.quote(string, safe='/', encoding=None, errors=None)```
Replace special characters in *string* using the `%xx` escape. Letters, digits, and the characters `'_.-~'` are never quoted. By default, this function is intended for quoting the path section of a URL. The optional *safe* parameter specifies additional ASCII characters that should not be quoted β€” its default value is `'/'`.

*string* may be either a [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") or a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") object.

Changed in version 3.7: Moved from [**RFC 2396**](https://tools.ietf.org/html/rfc2396.html) to [**RFC 3986**](https://tools.ietf.org/html/rfc3986.html) for quoting URL strings. β€œ~” is now included in the set of unreserved characters.
compact notch
#

I will check this doc

haughty mountain
#

that's more like it

compact notch
#

yeah probably

#

It work !!
Thank you

patent isle
patent isle
#

And i dont wanna go through a project based course

#

Theres only three resources in pinned

#

Any suggestions?

patent isle
#

Or advice?

mental violet
#

Can someone help me with my linkedlist and tell me what I am doing wrong?

dark aurora
#

Can you sort a list by two attributes but that they are both equally important

#

so this (0,4) (1,2), (1,3) ,(2,8)

#

would be this descending (2,8), (1,3), (0,4), (1,2)

#

instead of this

#

(2,8),(1,3),(1,2),(0,4)

austere sparrow
#

And how should [(1, 10), (6, 7)] be ordered?

#

And what is your end goal with this sorting?

carmine wadi
#

Hello anyone is here willing to help me with the project? I got rejected. Need someone help please inbox me if you are willing to help me

thorn panther
#

and ur solution too

charred gull
#

Can anyone tell whether I should start learning how to analyze Algorithms (Time and Space Complexity) or should I learn Algorithms first? I thought it made more sense to first learn how to analyze these as that would help in understanding the difference but in the Analysis of Algorithms, people are constantly throwing around algorithm names and say that they're this and that (Like QuickSort's worst-case time complexity is O(n^2) but I yet have to see what QuickSort is) and I have trouble keeping up

(Ping if reply, Thanks)

fiery cosmos
charred gull
haughty mountain
#

learning one without the other is kinda silly

charred gull
#

I guess so, Thanks for responding

slim crest
#

hello I have a problem

#

i am currently making a program thats DFS to generate a random maze in pygame

#

but when I run the program(uncommenting maze.GENERATE()) I get a blank screen

#

I knew my code was wrong from the beginning

#

I am not looking for solutions but I will appreciate suggestions

#

My questions is why did the screen go blank

fiery cosmos
haughty mountain
slim crest
haughty mountain
haughty mountain
#

presumably, I have a hard time making sense of it

#

what is the thing meant to do?

slim crest
#

arghh hold on

#

what that program does @haughty mountain

haughty mountain
#

so they are writing their thing with a stack, so iterative, no recursion

#

it allows to easily do the execution step by step, i.e. their animation

#

if you want the step by step thing in python you have the option of either doing what he does, computing one step per function call, or making a recursive generator function

#

the latter is pretty cute, but maybe something you could revisit later

#

to do one step:

  1. let cur be the element on the top of the stack
  2. mark cur as visited
  3. find ok neighbors of cur
    3a. if such neighbors exist, pick one and add it to the stack (continue exploring)
    3b. otherwise pop the top element from the stack (this is the backtracking)
#

I never really write this kind of code with the intent of executing one step at a time, but I guess it's not much different pithink

#

normally this kind of logic would be in a while loop that executes until the stack is empty

slim crest
#

okay thanks i will do it iteratively

fiery cosmos
#

So, I took coursera course about data structures and alghoritms. I got an PDF that's about what to do to check if solution is correct. I don't understand one part about generating tests.

#

I don't understand what's here "model solution"

outer surge
#

Please, someone know opencv library ?

haughty mountain
fiery cosmos
haughty mountain
#

that's how I've used it in practice before

#

I suspect the "model solution" in your case might be a solution you're given though

vital valley
#

hey guys, I'm trying to understand topsort for disconnected graphs

#

in the example of 1->2->3 4->5->6

#

wouldn't it come out to be something like [4,5,6,1,2,3]?

#

6 isn't necessarily before 1, is it?

lean walrus
#

all correct results are correct Smart

vital valley
#

@lean walrus can you elaborate lol

ivory yacht
#

A topological sort isn't a total ordering, there's many valid orders. So that would be valid, so would [1, 2, 3, 4, 5, 6], or [1, 4, 2, 5, 6, 3]

vital valley
#

@ivory yacht ah, okay. I just thought the defintion was something like

#

it sorts it into an order where u->v implies that u is "before" v

#

or equal

ivory yacht
#

That's the definition yeah, but since you don't define the relationship between every pair of elements, multiple solutions are possible that satisfies all the constraints.

#

Usually you only care about having one of the solutions.

#

So if you had the constraint 1 -> 3 and 2 -> 3, both [1, 2, 3 and [2, 1, 3] would be valid.

vital valley
#

@ivory yacht ah, okay. thanks so much lol that cleared up everything

hybrid crystal
#

Can you not simply use input() in the appropriate cell?

hybrid crystal
#

I must be missing some context. Maybe I interpreted the question to generally; I thought you were simply asking how to incorporate user input into a project in Jupyter Notebook. Is there some specific project I am not aware of?

fiery cosmos
#

!rule 9

halcyon plankBOT
#

9. Do not offer or ask for paid work of any kind.

fierce sluice
#

I have a question
How can I write a class attribute that has the type of itself?

#
class Foo:
  all_foos: List[Foo]
  ...
jolly mortar
#

List["Foo"], or a from __future__ import annotations at the top
(we also have a #type-hinting for questions like these)

sick wyvern
#

I am tryin to debug a code in pycharm but its taking forever to do but its showing this any solutions?

open moth
open moth
lean walrus
#

!e print('2022-01-27')

halcyon plankBOT
#

@lean walrus :white_check_mark: Your eval job has completed with return code 0.

2022-01-27
outer mist
#

Hee guys πŸ™‚

I'm makinga telegram bot but i'm stuck on the interactive part

    if query.data == 'example':
        context.bot.answer_callback_query(callback_query_id=query.id, text=f'test example', show_alert=True)

Instead of only pop up an alert box, i want a interactive part

like give me your pet name > bot waits then go to next question what is your age > then prints the info. but it should start with the button

haughty mountain
#

wrong channel for this kind of question

novel trench
#
import json
import random

def main():
  def working():
    workvalue = random.randint(1, 5)
    print("You worked in your development job and gained $" + str(workvalue)
  with open('data.json') as f:
    data = json.load(f)
  moneyvalue = data['money']
  print('Money: $' + str(moneyvalue))
  print('')
  print('Actions:')
  print('[1] Work')
  print('[2] Exit')
  print('')
  action = input("> ")
  if action == "1":
    working()

why do i get syntax error

fiery cosmos
#

ah missing ) in print

#
 print("You worked in your development job and gained $" + str(workvalue) 

thats where it is

novel trench
#

oh ok thank you

novel trench
#
import json

print("Username:")
username = input("> ")
print("Password:")
password = input("> ")
if username == "crystalfur" and password == "root":
  print("Welcome " + username + "!")
  with open("cfc_bank.json") as f:
    cfc_value = json.load(f)
  print("Account Balance: " + cfc_value(str("crsystalfur")) + "CFC")

why wont the amount print

haughty mountain
#

cfc_value is a dict, you're calling it like a function

also this is not the right channel for this kind of question, this is for algorithms and data structures

novel trench
#

oh

fiery cosmos
#

anyone know why i get this error?

#

trying to run matlab script from python

fiery cosmos
#

can I ask what IDE you are running ?

trim obsidian
#

Guys i need a book which has hard to extreme level of ds algo problems

#

Any recommendations

austere sparrow
trim obsidian
#

Ahhh i ment for practice tbh

austere sparrow
#

ah

trim obsidian
#

Not like impossible ones but hard problems

#

So i grill my concept

#

I want depth

#

And pratcie like a ton of hard problems

austere sparrow
#

well, I'm a noob. so I don't have much advice for you