#algos-and-data-structs

1 messages · Page 22 of 1

opal oriole
#

Python can return as many values as you want, and I would take advantage of that.

fiery cosmos
#

this sounds correct

opal oriole
#

You can then have separate file IO code that can take the failure list and write it out.

#

In general, try to keep IO separate, as its own chunk.

#

So you can have a nice input -> processing -> output flow in the code.

#

Like 3 paragraphs / ideas one after another, rather than mixed.

fiery cosmos
#

right right. ok! let me try

opal oriole
# fiery cosmos right right. ok! let me try

Note that with this method the user of the data_read function can ignore the return values (the failure list) and not report it. If you want the user of a function to not ignore it then exceptions can be used. They now must not ignore it or it will abort the program with the exception message. So using an exception can be a way to avoid the user making the mistake of ignoring the errors. But sometimes you don't mind if they ignore the errors (soft errors), so it depends.

fiery cosmos
#

so it's a bit wonky but here is my strategy:

#

then i'll return both lists for processing in the main function

opal oriole
#

That works.

#

A validation phase that separates into categories is common.

fiery cosmos
#

hmm

#

i also have an interesting problem that was a problem my dad had to solve in engineering school that im curious about

fiery cosmos
exotic nexus
#

Does anyone know how to install leafy?

#

I keep getting an error

opal oriole
#

Is that a problem? You have to iterate over all of the inputs.

#

Or do you mean it's generating the wrong valid list with duplicates?

fiery cosmos
#

Because my if condition is within the loop which checks every char

#

I guess I just have to dedent my append statement but it wasn’t immediately obvious how to do such a thing

opal oriole
#

Examples include checking if a list contains something / meets some boolean condition, computing a summation, product, min, max, or other function that involves a sequence and ends up as one value as the result (stored in the variable created before the loop starts, and used after).

#

And if it's a boolean and that controls whether you append or skip something in some way, it's a "filter".

fiery cosmos
#

I don’t want to break out early though, I just want to append a given item of a list to another list if one of the characters of a string is found to be not in the language

#

Else if an invalid character is not found, append to ‘valid’

opal oriole
#

Ok, so you have two appends going on.

fiery cosmos
#

Right but the issue is that the appends are nested as far in as the doubly nested loop which checks each char in a string for each string in my input set

#

So naturally there are too many appends occurring

opal oriole
#

The valid append feels like what I just described.

#

The other appends in that internal loop, but I don't have the code so IDK.

fiery cosmos
#

Yeah I’ll give an explicit example tomorrow. Thank you for your help

brittle moat
#

I need help with this algo. It's running infinitely but I Need it to stop once banana is less than 1 b 2ns or 3as

#
def solution(S):
    S = S.lower()
    a = ["a", "a", "a"]
    b = ["b"]
    n = ["n", "n"]

    less_than = 0
    counter = 0

    if S.count("a") < 3 or S.count("b") < 1 or S.count("n") < 2:
        return less_than


    while not less_than:
        for x in range(len(a)):
            S.replace("a", "")
        for x in range(len(b)):
            S.replace("b", "")
        for x in range(len(n)):
            S.replace("n", "")

        counter += 1

    return S```
lean walrus
#

There are a lot of issues in this code

brazen needle
#

hi how do i make it so a python script will run when a specific url is opened in chrom

#

chrome

dusky canyon
#

Hello everyone, can anyone help me to solve this problem?
Any algorithm I write cannot do the processing quickly. My record for 1,200,000 is 5 minutes.
I am also attaching the code file.
https://www.codewars.com/kata/56a1c63f3bc6827e13000006

Codewars

This is a hard version of How many are smaller than me?. If you have troubles solving this one, have a look at the easier kata first.
Write
function smaller(arr)

that given an array arr, you...

halcyon plankBOT
agile sundial
#

you need a flag variable to know if you should append or not. check after the inner loop so you append outside the loop

fiery cosmos
#

ok i think it just clicked thanks. the flag goes off when an invalid char is detected and then after each inner loop iteration i can check the flag for append or not append status

#

hmm do i have to abandon my exception i was trying to use to return the invalid char?

#

can i append the error string as the exception?

agile sundial
#

because i is an element not an index

fiery cosmos
#

ooh

#

?

#

but only got 1 where it expected 2 error

limpid smelt
#

did you print both d and e?

fiery cosmos
#

i'm not printing them i'm using them to build strings

limpid smelt
#

no like print them and see what the values are

#

for debugging

fiery cosmos
#

yeah i see what you're saying. according to what i wrote above, one of them doesn't exist. i need to go back and confirm every element of this list is indeed a tuple

limpid smelt
#

brb lemme switch OS

agile sundial
#

because now i is an index. show your loop again?

fiery cosmos
#

so there is a second error string i'm never adding to my invalid list and i don't know why

limpid smelt
#

Oh I got it, use d[:] to get the strings

#

or d[0] + d[1]

#

cuz d is a list now

#

and e should be 'string'

fiery cosmos
#

it's adding 1 when there are 2 in the input

#

both with the same error, actually

limpid smelt
#

kinda what youre tryna do?

fiery cosmos
#

well index i should be looking at each tuple, so not quite

limpid smelt
#

I didnt try to fix the space in there

#

what is in prevalid?

fiery cosmos
#

its a list compiled from my input of potentially valid strings to process or invalid strings to reject

agile sundial
fiery cosmos
agile sundial
#

char will not be the char that is invalid here

agile sundial
fiery cosmos
#

not publically, can i PM you

limpid smelt
#

can you share like the structure of prevalid?

#

like [([int, float], string), ([int, float], string)] or something?

agile sundial
limpid smelt
#

it might not be taking a string as true if the last character is in AGCT

#

is that intentional?

agile sundial
#

it just doesn't log the correct char in invalid

#

can you show a sample input and output

#

that is representative of the error

limpid smelt
#

SMELL should be valid and SMALL should be invalid?

agile sundial
limpid smelt
#

but isnt he checking AGCT?

agile sundial
limpid smelt
#

ah right, my bad

agile sundial
#

are you parsing it properly? is prevalid what you expect?

fiery cosmos
#

yes

#

wait a tick

#

oh wow, its failing to get the final char of the final string for some reason...

#

printed prevalid and it's cleaved off

#

so weird. i missed bc it happens to not successfully get the final char of the final string, and that's where i happened to put an error

#

let me put it internal to see if it teases out

limpid smelt
#

is this the correct expected output?

fiery cosmos
#

yes but could you please delete this

#

i don't want personally identifying information

agile sundial
#

how is that PII lmao

lean walrus
#

It cant find wrong char in any string. Try to put Q inside string

#

Deleting messages is bad

limpid smelt
#

I didnt change your code at all btw

fiery cosmos
#

i know its weird

agile sundial
#

that's still not PII though, unless someone has a database of every person's DNA and that is enough to uniquely identify them

fiery cosmos
#

i think its bc of one of my strip statements

agile sundial
#

show your parsing code

fiery cosmos
#

these were randomly generated

limpid smelt
#

do plagiarism sites check discord as well now? lmao when I was in college they only checked research papers and stuff from google xD

fiery cosmos
#

🤷‍♂️

agile sundial
#

just generate new ones?

fiery cosmos
#

yeah i'll have to

agile sundial
#

also, yeah. Google doesn't index discord and I highly doubt anything would

fiery cosmos
#

extra work

lean walrus
#

You mean these sequences?

limpid smelt
#

you could just use something like passgen to generate alphabetical strings randomly?

agile sundial
#

it's highly likely you need to show more sample data, so just generate some data to submit and some to show

haughty mountain
#

!e

from random import choice
print(''.join(choice('ATCG') for _ in range(20)))
agile sundial
#

imagine if that was the same sequence

halcyon plankBOT
#

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

ACGTACGATCATCGCCGACA
agile sundial
#

lol

#

then wouldn't they see the context? are you not allowed to get help or something lol

#

¯_(ツ)_/¯ ok

show your parsing code?

limpid smelt
#

Its okay man, we can just let him be. literally no need to ask for info if they arent comfortable with it xD

agile sundial
limpid smelt
#

if hes not comfortable with it, it doesnt really matter 🙂

#

thats why I instead asked for the structure of the datatype

fiery cosmos
#

so the existing issue is that i'm failing to parse every single char, specifically the last char of the last string is being neglected somehow

limpid smelt
#

try maybe just line[:]?

fiery cosmos
#

yeah why is it -1?

limpid smelt
#

idk xD

haughty mountain
#

just line.strip()...

fiery cosmos
#

what would fail every string for the same reason though would it not

limpid smelt
#

also I dont think you need to do line[]?

haughty mountain
#

[:] is a noop here

limpid smelt
#

shouldnt line.split() be enough?

#

yeah like fiery said

#

line[].split is not needed

#

cuz line[:] == line

radiant belfry
#

this line just gets you everything except the last character in the line, you can just use strip() to get rid of \n

haughty mountain
#

the split is needed

#

though you could split on ' = '

lean walrus
limpid smelt
#

?

#

Modified Universe is their name?

fiery cosmos
#

yep. on my birth cert. thats me

haughty mountain
#

you could easily just regenerate the random dataset pithink

limpid smelt
#

now someone in this server has had their name leaked xD

#

okay anyways, line.strip().split('=')

lean walrus
haughty mountain
#
varname, seq = map(str.strip, line.split('='))
limpid smelt
#

aah with map

haughty mountain
#

map or equivalent, yeah

limpid smelt
#

but idk if they want to handle two different vars or just keep it in a single var

#

no dont use that

haughty mountain
#

or unpack in the first loop as well

limpid smelt
#

so i = (['S2', 'AGAAATTAGAQ'], 'Q') and i[0] = ['S2', 'AGAAATTAGAQ']

#

yeah could do that as well

haughty mountain
#

that way you can give sensible names

fiery cosmos
#

unpack in first loop?

#

woah. @haughty mountain and @agile sundial were helping me 6 months ago. crazy

#

can't believe i've been doing this stuff for so long already

limpid smelt
#

time sure flies when youre doing something you like or are forced to like xD

#

unpacking inside first loop

fiery cosmos
#

i'm not able to see how to purpose it for what i'm trying to do

limpid smelt
#

you want to output a sentence with S<num> and the randString and the invalid char?

#

or something like that?

fiery cosmos
#

i'm going to rebuild in the input sequence from the list and then add some statement like this sequence was not processed because of the following character: then print e in my d, e scheme

limpid smelt
#

since you know there will only be two elements in the i[0]

#

idk what output format you want though so

#

also today I realised .strip() only removes the whitespaces from the end and beginning..

#

I am stupid

#

.replace() is so much better xD

fiery cosmos
#

uh oh

limpid smelt
#

?

fiery cosmos
#

so just tried a new error, putting a # into one of the strings, and it reported that it was invalid because of the final character (a valid one) and not because of the symbol

#

wait let me look

#

probably can figure this out before writing about it on discord 🤦‍♂️

limpid smelt
#

maybe just break the for loop as soon as the string is invalid?

#

or are you storing all the invalid chars?

fiery cosmos
#

i'm not, i just added an extra variable to store the invalid char and append that one to my invalid list, should have fixed it up let me test

#

yep

limpid smelt
#

which invalid_flag state is the correct one if a string is invalid?

limpid smelt
fiery cosmos
#

right its fixed up now

limpid smelt
#

cuz youre checking invalidity at end of loop

fiery cosmos
#

now i just have to test with a bunch of valid inputs and make sure it's running as expected

limpid smelt
#

Niceu! Good luck!

fiery cosmos
#

thanks. i think i've botched the usual runtime with doubly nested loops, but w.e

#

where n and m are the length of the input strings

limpid smelt
#

there are two input strings? I thought input string was 'S1= HABHNDJKMD' ?

fiery cosmos
#

it compares and finds the longest common subsequence between each pair

limpid smelt
#

true. I still dont get how you would have multiple input strings, but maybe I missed something

fiery cosmos
#

do you have CLRS text?

#

let me just get you the pseudocode

#

this is the core of the program, not including the print algo

#

as you can see, it only operates on two input strings at a time

#

but you can build out a python program to run it pairwise on every pair of strings in an input file

limpid smelt
#

maybe its the difference between our different countries xD no idea what those arrow symbols are xD

#

but as far as time complexity I got the point you were making

#

might just be that its 1:30AM

fiery cosmos
#

The arrows just indicate where to look in the dp table

limpid smelt
#

is that like a truth table?

fiery cosmos
#

different from truth table. a dp table stores pre-computed subproblems so that they can be looked up, rather than continuously recomputed

#

this particular problem is highly amenable to such an approach, because in two sequences of length 500, the number of combinations of possible subsequences to check is greater than the number of atoms in the known universe

agile sundial
fiery cosmos
#

yes, the arrow is just a string which points somewhere

#

this is a dp table - "dynamic programming" table

limpid smelt
#

oh you mean this is pseudocode for the strings code you were doing with filter?

fiery cosmos
#

that pseudocode is the core of my algo

limpid smelt
#

I've been thinking you were trying to show me pseudocode for how to find time complexity lmao

fiery cosmos
#

noo

#

its the pseudocode for LCS, the longest common subsequence algo

limpid smelt
#

I was like we were taught to use math to find complexity xD

fiery cosmos
#

there are other famous DP problems/algos, eg rod-cutting probem

limpid smelt
#

idk about the algo, we were always just made to use math to figure it out and make our own algos so we werent taught like this in college haha

#

but thats cool!

limpid smelt
#

true, but like we weren't told that this is the LCS algorithm or this is the blah blah algorithm etc

fiery cosmos
#

well, if you took an algos course they likely would have

limpid smelt
#

as I said different countries have different flavours of teaching ig xD

fiery cosmos
#

did you take algos?

limpid smelt
#

there is no course called algos per se

#

but like DSA course had various algos for like searching splitting etc

#

but we had to figure out the pseudocodes ourselves

fiery cosmos
#

yeah thats just a combined data structures and algos course

limpid smelt
#

we were just taught theory

fiery cosmos
#

largely the same

limpid smelt
#

yeah

fiery cosmos
#

what text did you use?

limpid smelt
#

um, I dont even remember now its been over 6 years

#

might have to find it

fiery cosmos
#

its ok i was just curious

limpid smelt
#

I think it was some book by a professor ig within the college

fiery cosmos
#

makes sense

limpid smelt
#

or maybe some text copied from IITs or BITS (tier 1 colleges)

fiery cosmos
#

Indian Institute of Tech?

limpid smelt
#

we usually never even used the books. the professor would just explain on the board, we would copy that and then go back to the room and relearn from youtube

#

Yeah

#

basically rote-learning

fiery cosmos
#

thats a good way to do it

limpid smelt
#

lol no way xD

#

I mean atleast for me

#

I cant memorise stuff to save my life. I need to understand it completely and after that its fine

#

but people here do have a talent for memorising stuff

fiery cosmos
#

i'm good at both concepts and memorization. but i shied away from math early on in life and i've been paying for it ever since

#

just now getting my shit together

limpid smelt
#

we had people memorising questions and answers from 800+ page guide books..

fiery cosmos
#

there are strategies, for example memory palace and others

limpid smelt
#

aah yeah math was my favourite subject apart from cs

fiery cosmos
#

its not difficult to memorize. putting all the memorized concepts into theory and mechanism is where the real comprehension comes from

#

theres nothing important about memorization anymore in the age of google

limpid smelt
#

nah I do better by understanding concepts. even though it takes more time, it will benefit you in the long run

#

like I still remember stuff from math in school but I dont remember a single thing from chem during college

#

chem is the worst for me.. its just so much of stuffing random tidbits of knowledge and then regurgitating them onto your answer sheet

fiery cosmos
#

i love chem its one of my favorite subjects and some of the concepts are unique and fascinating eg enantiomerism

limpid smelt
#

so I would get like 90+ in English, Math, Physics, CS, German and then like 60 in chem xD

#

enantiomerism?

fiery cosmos
#

sterioisomerism

limpid smelt
#

oh, I only remember isomers faintly, no idea what they were

#

are you doing UG or PG?

fiery cosmos
#

basically, because we exist in 3 dimensions, two molecules can have the exact same molecular formula, same weight, same everything, but nevertheless be biologically different

#

and the only way to tell them apart is using plane polarized light

limpid smelt
#

wait but then wouldnt there be multiple versions of lets say the CO2 or H2O molecules?

fiery cosmos
#

no, in order to be a stereoisomer it must have a chiral center, eg a chiral carbon, which requires 4 different types of atoms

#

well, 3 not including the chiral carbon

#

it forms a pyramid shape with the chiral carbon at the center

limpid smelt
#

aah okay so a specific shape, gotcha

fiery cosmos
#

its not the shape that is important, but that there are 3 different atoms attached to the carbon. if two of the 3 are the same, you cannot have chirality

haughty mountain
#

I hated basically any subject that was just memorization

#

thankfully math, physics and cs is more about concepts than "just remember these random pieces of fact"

#

of course it's some memorization, but a lot of stuff you can reason yourself to from other facts

fiery cosmos
#

chemistry is much more concepts than memorization as well

#

bio used to be all about memorization, but now with google the best biologists are the best with concepts, biochem, immuno, etc, eg, the people who simply memorize, their days are limited

#

its more now about uncovering mechanisms and understanding signalling cascades, and whathaveyou

fiery cosmos
#

@haughty mountain are you curious about this problem my dad had to solve in 4tran a million years ago? kind of a neat problem

haughty mountain
fiery cosmos
#

so basically you are given 3 points in an x,y,z coord system and have to find the area of the resultant triangle

agile sundial
#

isn't there just a formula for that

fiery cosmos
#

probably. i'm curious about the algo and how it is solved

agile sundial
#

pretty sure it's just "plug it into the formula"

fiery cosmos
#

i'll google

haughty mountain
#

there is a simple cross product formula for this

haughty mountain
#

you don't want heron here

agile sundial
#

there's a simpler one where you don't need distances first

lean walrus
#

Ah, you can do cosine theorem

haughty mountain
#

iirc correctly this works
|(A - B) x (C - B)|/2

lean walrus
#

Idk how it is actually called

haughty mountain
#

where x is the 2d cross product

agile sundial
#

it's like, abs(x0(y1-y2) + x1(y2-y1) + x2(y0-y1))/2

lean walrus
agile sundial
#

what is vector area

haughty mountain
#

area with a sign

#

basically

agile sundial
#

but why 😔

haughty mountain
#

because that's what cross product describes

#

it pops up naturally

lean walrus
agile sundial
#

ah

lean walrus
#

It is useful in physics, for example

#

If you have pressure and you want to calculate pressure force, you can do: F = S*p, where S and F are vectors

haughty mountain
#

there is also fun generalizations of cross product that I never bothered to learn

#

wedge product and something else I think

fiery cosmos
haughty mountain
haughty mountain
lean walrus
haughty mountain
#

and
(x1, y1) x (x2, y2) = x1*y2 - x2*y1

#

(I think that's the correct sign at least)

fiery cosmos
#

i thought each point will have 3 coords?

haughty mountain
#

ok, are we in 2d or 3d?

fiery cosmos
#

3

#

x,y,z coord system

haughty mountain
#

the formula still works, you just need to do the full 3d cross product

fiery cosmos
#

ok i'm gonna write all this out and try to solve it

#

its a cool problem

agile sundial
#

ig i don't remember as much linalg as i should 😔

fiery cosmos
#

i need to learn linear

haughty mountain
#

does anyone have 3 points with a known area?

fiery cosmos
#

wolfram alpha does

fiery cosmos
haughty mountain
#

!e second time's the charm?

def cross(a, b):
  return (
    a[1]*b[2] - a[2]*b[1],
    a[2]*b[0] - a[0]*b[2],
    a[0]*b[1] - a[1]*b[0],
  )
def sub(a, b):
  return (
    a[0] - b[0],
    a[1] - b[1],
    a[2] - b[2],
  )
def add(a, b):
  return (
    a[0] + b[0],
    a[1] + b[1],
    a[2] + b[2],
  )
def magnitude(a):
  return sum(x**2 for x in a)**.5

A = (1, 2, 3)
B = (4, 1, 5)
C = (2, 5, 3)

area = magnitude(cross(sub(A, B), sub(C, B)))/2
print(f'{area = }, {area**2 = }')
halcyon plankBOT
#

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

area = 3.0413812651491097, area**2 = 9.249999999999998
haughty mountain
#

err...

#

not quite

#

it doesn't let me re-run :<

#

!e

def cross(a, b):
  return (
    a[1]*b[2] - a[2]*b[1],
    a[2]*b[0] - a[0]*b[2],
    a[0]*b[1] - a[1]*b[0],
  )
def sub(a, b):
  return (
    a[0] - b[0],
    a[1] - b[1],
    a[2] - b[2],
  )
def add(a, b):
  return (
    a[0] + b[0],
    a[1] + b[1],
    a[2] + b[2],
  )
def magnitude(a):
  return sum(x**2 for x in a)**.5

A = (1, 2, 3)
B = (4, 1, 5)
C = (2, 5, 3)

area = magnitude(cross(sub(A, B), sub(C, B)))/2
print(f'{area = }, {area**2 = }')
halcyon plankBOT
#

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

area = 5.916079783099616, area**2 = 35.0
haughty mountain
#

cool

#

that's correct

#

had dumb typo

agile sundial
#

it's cause the syntax highlighting

fiery cosmos
#

wow i guess its a lot simpler than a bunch of undergrads found it to be like 40 yrs ago

haughty mountain
#

in any case, the cross product formulation is quite typical

fiery cosmos
#

i wonder how long their code was

haughty mountain
#

cross products are signed areas of parallelograms

lean walrus
fiery cosmos
#

ugh i just found a bug in my code, f***

haughty mountain
#

cross products sadly don't generalize well

#

(exterior algebra does)

#

without the || you get a signed area depending how u and v are pointing relative to each other

fiery cosmos
#

signed area 😵‍💫

#

nope.mp4

#

that video about newtons fractals was really cool

#

and then i understood what those images you shared were

#

they were the limit approaching the boundary between each of the zones where the points of a grid collapse to one point or another using newtons method

#

of approximating when polynomials = 0

opal oriole
#

If want all this stuff to make sense and no seem to come out of nowhere I recommend Geometric Algebra.

#

Then you also don't need all the other stuff like quaternions, etc.

#

Simplifies all formulas when used.

fiery cosmos
#

rn i need to find out why my code is erroring 😦

#

i just don't want to post the entire thing publically

haughty mountain
opal oriole
fiery cosmos
#

i'm gonna learn stats, R, linear alg. in due time

#

not straight away

#

got other fish to fry

opal oriole
#

The "geometric product": ab = a.b + a^b

#

Where . is inner, ^ is wedge/exterior.

#

From this lots of things come naturally, like complex numbers.

#

Quaternions, spinors, cross product, etc (all of those are hacks added as needed, this cleans it all up into one thing).

fiery cosmos
#

trivia: who coined the term imaginary number

haughty mountain
#

guess euler or gauss in math trivia and you're right 90% of the time

fiery cosmos
#

not in this case

#

give up?

haughty mountain
#

Descartes, huh?

fiery cosmos
#

👍

opal oriole
#

(He was being mean)

haughty mountain
#

"coined as a derogatory term"

fiery cosmos
#

oh lol i didn't realize that

opal oriole
#

Gauss had the right name, "lateral numbers".

haughty mountain
#

complex numbers are the real real numbers

#

so much stuff that's ugly in real math is very beautiful in complex math

opal oriole
#

In regular algebra*

#

I always find it really cool how the algebra was basically saying to the writer that it needed another channel for the information, one was not enough.

haughty mountain
#

closed path integrals are zero unless they surround singularities

#

and if they surround singularites we can evaluate the value just by looking at the values related to the singularities

opal oriole
#

In geometric algebra, complex numbers make even more sense.

haughty mountain
#

the residue theorem is so nice

opal oriole
#

And are just a part of it, just one case.

haughty mountain
#

in unrelated news, I'm debugging checksum code written in this god awful language

agile sundial
#

exapunks 👀

#

i've been wanting to try that

fiery cosmos
#

when you are done can i share my code

#

/ error

haughty mountain
#

exapunks is a nice game, very constrained programming

fiery cosmos
#

wth is exapunks

agile sundial
#

fenix have you played nandgame

haughty mountain
#

you basically have 1 maybe 2 registers to work with per bot

#

no pithink

agile sundial
haughty mountain
haughty mountain
agile sundial
#

it's fun lol

haughty mountain
#

more than normal?

#

I think it was more confusion about why you didn't seem to care about having posted your name in some screenshots but then being concerned about randomly generated data pithink

#

this was random data you generated, no?

#

which you could easily regenerate

haughty mountain
#

so you're indexing a list with a tuple somewhere

#

is this the line that causes the error?

fiery cosmos
#

this is my input into a function which takes two input sequences

#

mylist is a list of lists

haughty mountain
#

put a print(i, j) just before

#

I'm assuming one of them is a tuple

fiery cosmos
#

yes, but i thought tuples only existed in my invalid list. i must be erroneously appending an invalid tuple into my valid list

#

mylist should only be valid sequences, and none should be tuples

#

let me print it

haughty mountain
#

right, track the tuple backwards through the code

fiery cosmos
#

hmm there's something weird going at the end of my append statements in getdata

#

no, that's just i and j printing

#

huh

brittle moat
#

hey, I have a leetcode question that's asking to rotate a matrix by 90*. I can hardcode it, or I can do it dynamically - but would harcoding it be a bad solution?

#

like I'm thinking of just adding each index by the respective amount for the rotation (so if index 2 has to move to 8, index index 2 + 6 % len(matrix)) instead of running a double loop. would companies care about that?

brittle moat
#

yeah I figured they would

fiery cosmos
#

im still stuck if anyone doesn't mind me DMing them

haughty mountain
#

if so where did the one that was a tuple come from

#

if in a list or similar, when and how was a tuple added?

#

(printing stuff will help a lot with figuring out that)

fiery cosmos
#

it's saying that the list index itself is a tuple, which i don't get. i printed each individually and it was fine

#

also, the indices are just integers running in simple loops

#

i do have tuples in a different list that isn't being indexed here

#

and that's intentional

haughty mountain
#

is either i or j a tuple or no?

fiery cosmos
#

no they're strings

#

wait 1s

#

no, they are lists

haughty mountain
#

could you post the stack trace here?

#

you're probably using i for something else

fiery cosmos
#

oh yeah, there is another loop within this loop that uses i

#

let me test

#

fixed thank you

#

hmm

#

i guess i should be able to detect empty input strings

haughty mountain
#

empty input should be valid

fiery cosmos
#

big oof

haughty mountain
#

it shouldn't really be a special case if the code is sensible

fiery cosmos
#

its SO COOL it'll run and the output file echoes the input, gives the LCS of each pair, and then returns which input strings were removed and why

#

fricken sweet

#

one thing i'm not doing is returning both/all errors if there happen to be multiple invalid chars in a single string

#

could easily be implemented, however

cinder cedar
#

Anyone can help, Time complexity for this algorithm?

cinder cedar
#

Nvm I understood it

fiery cosmos
#

can someone help me w my algo? it's erroring when there is whitespace beyond the input strings

#

also i want to implement error handling to detect duplicate string names

fiery cosmos
#

nevermind, i'm just going to make sure the input files are formatted properly. i implemented duplicate name detection

haughty mountain
#

I'm just curious what extra whitespace is causing problema

#

end of line?

#

extra stuff after the last proper line?

fiery cosmos
#

causes a list index out of range error

haughty mountain
#

I would just read the whole file and strip it

#

f.read().strip().splitlines()

#

and then you have sensible lines

#

ignoring the case of empty lines in the middle of the file

polar current
#

help me pls
How do I add the creation date of this post to the footer in discord.py?

haughty mountain
#
for line in f.read().strip().splitlines():
  y = [s.strip() for s in line.split('=')]
polar current
#

?

fiery cosmos
#

😂

haughty mountain
bronze sail
#

algorithmic problem

haughty mountain
fiery cosmos
#

what about my file = f.readlines() line

haughty mountain
#

my code would replace this

#
        file = f.readlines()
        for line in file:
            y = line.strip().split('=')
            y[0] = y[0].strip()
            y[1] = y[1].strip()
fiery cosmos
#

the other weird thing i'm doing is, instead of detecting and removing strings with duplicate names in the input, i instead detect them later and just close the program. this is in contrast with detecting error strings where i remove them and allow the program to execute. so i'm going to now try to implement handling and removing duplicate string names and allowing the valid ones with unique names to run

haughty mountain
#

stripping the leading/trailing whitespace of the file removes a bunch of issues

fiery cosmos
#

actually this brings up another potential error: where the two strings are exactly the same to begin with in the input

#

ehh im running up against having not made this modular enough to begin with

#

currently the only error strings printed to out are because they had disallowed chars

#

so i can't handle strings with duplicate names in the same way 🤦‍♂️

#

oh. i can just make different folders for why each are invalid

haughty mountain
#

modularity is helpful yes

#

e.g. you can easily to things one step at a time

  • read (name, string) pairs
  • filter out ones with disallowed characters
  • handle duplicates
fiery cosmos
#

oh god. what if there are duplicate names and each one has disallowed chars

#

i guess it doesn't matter, it'll get filtered out one way or another

haughty mountain
#

decide what behavior you want

#

imo just raising an exception and exiting the program on bad input is sensible

#

rather than trying to salvage something from the broken input

#

i.e. detect error and bail the program with a message

haughty mountain
#

do the easy thing, if users give you bad input you scream at them

fiery cosmos
#

lmao

#

yeah i was trying to implement a custom exception but it got too complicated handling every different error possibility

#

and i am not going down that road now as i do not have the time

haughty mountain
#

rather than accept bad input

fiery cosmos
#

you're probably right

tight wind
#

May I get some help with this problem please?

glossy breach
#

this is quite literally minimum spanning tree

#

with 0-1 weights you could use 2 dfs to solve it in O(V+E)

fiery cosmos
#

AWS just started their own genomics platform

sonic basin
#

anyone online?

#

Anyone got any suggestions regarding what a beginner python programmer should be doing? I started self-learning python three days ago.

steel matrix
#

hello am complete beginner i found an article with a program that i was interested in for automatic microsoft rewards points with python. Pero I don’t know what to do for running it or whatever. would appreciate guidance .

fiery cosmos
fiery cosmos
lunar jacinth
#

guys

halcyon plankBOT
#

Hey @lunar jacinth!

It looks like you tried to attach file type(s) that we do not allow (.tiff). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

lunar jacinth
#

What algo is this?

#

Can someone point me in the correct direction

agile sundial
#

prim's

fiery cosmos
#

can someone remind me how to do a batch file

#

open a text doc, save all the python commands, save as something.bat, run from command line?

#

i remember this being annoying because it wants to exist as a text file on windows

#

ah i got it. open notepad > save as type "all files" > somename.bat and you're good

fiery cosmos
#

yeah i got it. just had to remember to open notepad and save as type 'all files' and name it .bat. i don't think right clicking somewhere and hitting create new text file would work, as it already has type .txt

#

you can right click and create a .txt and just change the extension to .bat

#

does that work on windows? feel like i've tried that. as an aside: i want to run this bat but have all the outputs go elsewhere (not my current directory), how do?

#

yeah, and you can use cd on a line in the bat file to change the current working directory, like bat cd ../some/other/folder python -c "import os;print(os.getcwd())"

fiery cosmos
#

eg the powershell cwd

#

when you run the bat file from powershell the cwd is wherever you are in powershell, so yes? The python script will see that as the cwd already

#

yeah i'm just wondering how changing the cwd within the .bat doesn't throw python's ability to see the input files

fiery cosmos
agile sundial
#

is there only one algorithm with 4 russian authors

fiery cosmos
#

lmao idk

hybrid epoch
fiery cosmos
#

Hi I am searching for help

jolly mortar
crystal tundra
#

oh my bad i didn't see

fiery cosmos
#

guys i have a really basic algorithm question:

Suppose you have n items and you iterate through them all - this would be known as an O(n) time complexity.

If you used nested for loops iterating through n - this would be known as O(n^2) time complexity.

But, what if you have two separate for loops (not nested) what would the time complexity be.

Also, if we only iterated through half of n what would the time complexity be?

agile sundial
#

n, n

languid heron
fiery cosmos
agile sundial
#

answers for your two questions. O(n) and O(n)

fiery cosmos
#

oh, but what if you only iterate through half of n how would it be O(n)?

agile sundial
#

because the definition of O(n). n/2 is only a constant factor different from n

fiery cosmos
#

its better to just say O(n)

agile sundial
#

yes. most people would say O(n/2) is incorrect

keen hearth
#

Whether the exact runtime in seconds is given by the formula n or 2*n (or k*n for any k > 0), if you double the size of n then you double the runtime.

#

O(n^2) means if you double the size of the input you quadruple the runtime.

#

O(n^3) means double input size -> multiply runtime by eight.

#

And so on.

#

O(2^n) means if you add 1 to n, then you double the runtime.

keen hearth
exotic nexus
#

Hey guys, im trying to create a face detection algorithm

#
import cv2

# step1: read the image
image = cv2.imread(r"C:\Users\awais\OneDrive\Documents\pythonProject\test1.jpg")

# step2: converts to gray image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# step3: get HOG face detector and faces
hogFaceDetector = dlib.get_frontal_face_detector()
faces = hogFaceDetector(gray, 1)

# step4: loop through each face and draw a rect around it
for (i, rect) in enumerate(faces):
    x = rect.left()
    y = rect.top()
    w = rect.right() - x
    h = rect.bottom() - y
    # draw a rectangle
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

# step5: display the resulted image
cv2.imshow("Image", image)```
#

when i run this code the image doesnt load and a window opens and closes for half a second

#

any reason why?

gentle loom
#
dict = {
   k: {i: {j: {} for j in range(26)} for i in range(26)} for k in range (26)
}

word = "bat"

def index(word):
    indices = []
    for i in word:
        letter_index = ord(i) - ord("a")
        indices.append(letter_index)
    return indices


def searchDict(dict, word):
    indices = index(word)

    found = False

    if dict[0][indices[0]] == word[0]:
        if dict[0][1][indices[1]] == word[1]:
            if dict[0][1][2][indices[2]] == word[2]:
                found = True

    return found

def insertDict(dict, word):

    indices = index(word)
    print(indices)

    dict[0][indices[0]] = word[0]
    dict[0][1][indices[1]] = word[1]
    dict[0][1][2][indices[2]] = word[2]

    return 

def deleteDict(dict, word):
    indices = index(word)

    dict[0][indices[0]] = -1
    dict[0][1][indices[1]] = -1
    dict[0][1][2][indices[2]] = -1

    return 


insertDict(dict, word)
#

hey guys, im trying to implement a 3 layered dictionary in python, and im trying to use my insert function. my friends say it looks right but i get this error:
TypeError: 'str' object does not support item assignment
for the line
dict[0][1][indices[1]] = word[1]
i should also mention that this is a program for 3 letter words only

#

i am so stumped, if someoe could help i would appreciate it

lusty swallow
#

regex no work me sad

haughty mountain
#

the first + is a repeat for the character class before

#

the rest is just nonsense as it's written now

lusty swallow
#

so I'm applying + for the previous term and the next one

haughty mountain
#

the same thing before, one or more times yes, but it applies to things like characters or groups

haughty mountain
#

so you have 3 "repeat this thing" in a row

lusty swallow
#

I was practicing regex for this question

lusty swallow
haughty mountain
#

e.g. [ab]{2,3} would match things like ab, aaa, bab

#

but not a or baba

haughty mountain
#

I wouldn't try to encode that as a regex

lusty swallow
haughty mountain
#

I wouldn't even do this with regex tbh

#

of course you could do it with a few regexes though

#

but feels like a roundabout way of doing things

lusty swallow
#

so I just use 5 nested ifs

#

with regex

versed charm
#

i want to iterate over a random integer sequence of lenght N based on a seed, and do the same iteration in reverse at the same time... is that possible without consuming O(N) memory?

#

the way i am currently doing this: ... is there a way to do this with generators smh?
`from random import randint, seed
seed("No Generator")
N = 10
g = [randint(1, 21) for i in range(N)]

for i in range(N):
at_forward_number = g[i]
at_reversed_number = g[-i-1]
print(at_forward_number, at_reversed_number)`

haughty mountain
#

technically, but not without digging into the actual random number generation

#

at least that's my best guess

#

of course you could be silly and re-generate the sequence a lot to accomplish O(1) memory, but the time complexity would be terrible if you did that

versed charm
agile sundial
#

yes, by saving the seed at one point in time. then generate a bunch of numbers, then set the seed back to the start

haughty mountain
#

I'm doubtful rngs are reversible in general

versed charm
haughty mountain
#

that's the very terrible time complexity one I mentioned

#

basically O(n) to get the element at index n

agile sundial
#

yeah. is memory really that big of a problem

versed charm
#

yeah .. I am doing "premature optimization" again. if the seed is not that important, this here works:

SEED = "SOLUTION"
N = 10

for i in range(N):
    seed(SEED+str(i))
    at_forward_number = randint(1, 21)
    seed(SEED+str(N-1-i))
    at_reversed_number = randint(1, 21)
    print(at_forward_number, at_reversed_number)```
haughty mountain
#

wait, why would that work?

#

the seed isn't a way to jump to some point in the sequence

versed charm
haughty mountain
#

oh wait, I'm dumb

#

you're only generating one thing per seed

#

at this point you could just do hashes or something and it would probably work comparably well

fiery cosmos
#

How do I learn to understand algorithms and read them from code when prompted in exams or quizzes?

Usually I defer to running the code and testing various things in a interpreter, but exams ask for a breakdown on paper with no access to a interpreter. Sometimes they can be very complex (modifying sets of sets etc).

How could I learn to think algorithmically?

versed charm
#

isnt that basically how minecraft can generate chunks independently from another? with a base seed? so you can teleport to different spots on the map, without having to generate the whole map?

haughty mountain
#

idk how minecraft rng works pithink

fiery cosmos
#

Even if you teleport halfway accross the map, anyone accross time would see the same chunks you find there

haughty mountain
#

but it needs to be more complicated than that if you want things to line up at chunk borders, no?

versed charm
haughty mountain
#

that doesn't really explain things either, what if I start at two faraway points and generate chunks inwards, then when they meet things there will be some significant clashing going on

#

or maybe they generate things far enough away for this not to matter and the smoothing actually to kick in pithink

#

feels like this is at risk of making worlds dependent on exploration order though

#

I'm assuming that's not the case in reality?

versed charm
toxic dome
#

im trying to do a selector in python, i mean i have a school project using a raspberry

haughty mountain
oak lintel
#

can someone explain linear probing??

opal oriole
#

There are several seed reverse engineering tricks. Most use specific structure locations to simplify the problem.

#

Same idea also used for infinite tiling of textures in graphics in general. Pretty much all comes from Perlin Noise originally made for Tron to texture their models (giving the unique "Tron look" where everything has these infinite random patterns that are clearly generated looking).

cunning mirage
fiery cosmos
#

hi, can anyone help me with any counterexample that would prove that the algorithm is wrong?

fiery cosmos
#

Dijkstra's algorithm fails in graphs with negative edge weights.

#

the algorithm never ends if the graph contains at least one negative cycle. By a negative cycle, I mean a cycle that has a negative total weight for its edges.

#

The Floyd-Warshall algorithm is used to detect the presence of negative cycles.

#

minimum = -10 , new_edge_weights = a-b= -5, a-c = -8, b->c -20

#

I think dijkstra's algorithm wont work with this example.

halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied mute to @fiery cosmos until <t:1669981256:f> (10 minutes) (reason: duplicates rule: sent 4 duplicated messages in 10s).

The <@&831776746206265384> have been alerted for review.

somber raft
#

hello

#

How is this expected to be false?
abbzzca
babzzcz
switch first A with second B
babzzca
replace last a with the first z
babzzcz

#

same concept as this image except with 2 operations instead of 3

#

this is a leetcode problem btw

hybrid epoch
#

For LC 1657, operation 2 states: transform every occurrence of one existing character into ANOTHER existing character, and do the same with the other character.

Meaning that you can't apply operation 2 on a single letter, e.g.:

babzzca -> babzzcz

Instead you must choose at least two letters to do the transformation, e.g.:

babzzca -> babzzac

vocal gorge
#

but also, I think it just doesn't produce the same results in general. Adding x to each edge means a path's length gets increased by its number of edges. This can lead to different paths becoming best, e.g.

a-b-(2)-c
|       |
d - e - f
# Shortest path from a to c is a-b-c, of length 3. Subtract 1 from each length, and then the path a-b-c has length 1 (because the b-c edge is length-1 now), whereas the other path has length 0.
paper tapir
#

Hello
Here my problem

x = 1
y = 3
z = 1

while (x != 1 or x!= 3) and (y != 1 or y != 3) and (z != 1 or z != 3):
    print("ok!")
#

This code loops as it is not supposed to. How to exit the loop with those values ? However, this code doesn't work because it create a infinite loop...

vocal gorge
#
(x != 1 or x!= 3)

this is always True for any x. same for the other two.

lusty swallow
#

REGEX bulli me:

import re
inp=input()x`
tup=tuple(map(str,inp.split(',')))
i=0
while i<len(tup):
    x=tup[i]
    a=re.search("[0-9a-zA-Z\$#@",x)
    if a!="None":
        break
    else:
        i=i+1
if a!="None" and len(tup[i])>=6 and len(tup[i])<=12:
    print(tup[i])
else:
    print("invalid")
INPUT:
ABd1234@1,a F1#,2w3E*,2We3345

ERROR:

fiery cosmos
#

that regex character group has no matching ]

lusty swallow
#

oo ty

raven crag
#

how do i find the shortest path between two nodes in an undirected tree

#

what is the fastest solution in python

#

does anyone have any idea

foggy lynx
#

Hi there--can someone help me with a cvxpy objective function formulation?

#

I'm trying to do the following: compute the tax impact of a portfolio transaction. That is, my x variable is my final portfolio allocation. If x is lower than my current holding (a vector), I want to incur a tax penalty or benefit (another vector). But apparently, cp.max(data['pct_portfolio'] - x, 0) * data['tax_benefit'] doesn't work

#

How exactly should I formulate this?

raven crag
#

i need some help with this proble,m

haughty mountain
#

if there are more it's not a tree

agile sundial
#

oh tree, yeah

exotic nexus
#

@hexed gust i missed your answer regarding a question previously, can i ask here?

fiery cosmos
#

also will increasing the edge weights have an effect on Dijkstra's algorithm when finding the optimal route?

hexed gust
limpid smelt
#

ax.plot(x, y, **{'linestyle': 'None','color': 'lightsteelblue', 'marker': 'o'}) for just dots

#

not sure about the line through the middle is that the regression line?

#

you can try this

visual zephyr
#

m strting

#

to learn python

limpid smelt
#

okay, nice!

hexed gust
limpid smelt
exotic nexus
exotic nexus
# hexed gust Sure if you still have the question. I don't really recall what it was.
import PIL.ImageDraw
import face_recognition

# load the image and convert it into numpy array
image =face_recognition.load_image_file("images/sample_image.jpg")

#find all the faces in the image
face_locations = face_recognition.face_locations(image)
no_of_faces = len(face_locations)
print(no_of_faces)

#draw the rectangular image on the face

pil_image = PIL.Image.fromarray(image)

for face_location in face_locations:
    top,right,bottom,left =face_location
    draw_shape = PIL.ImageDraw.Draw(pil_image)
    draw_shape.rectangle([left, top, right, bottom],outline="red")

#displat the image
pil_image.save("images/output_image.jpg")
pil_image.show() ```
#

yeah i was asking if this was a hog algorithm or not and you said the code is imported from 'face_recognition'

#

but when i run it on my pc the code works

urban kiln
#

I tried doing something with binary search and math.factorial but i think calculating the factorial wasnt even necessary since n could be up to 10^12 and calculating 10^12! would take way too long

fiery cosmos
#

I think the solution for N is the highest prime factor of K, since then N! will be a multiple of that factor and every other factor below it, times some other stuff but that doesn't change it being a multiple.

#

So look into factor finding I think discre3Hmm

jade mountain
#

I made like a simple 11 line python encryption software without modules challenge to decrypt it without the key password

#

Dm me to get the encryptor code

#

And the challenge text

sharp junco
#

Hi guys

#

How do i get my python code to linear time

#

I have my problem solution already

#

But it really isn’t that efficient

#

If anyones willing to help, would really appreciate it

haughty mountain
#

e.g. let k be some power of 2

#

but for sure the prime factorization is the critical thing to solving this in reasonable time

#

you would need to check for every unique prime factor, how far do I need to go to get that many factors

#

but that's fairly easy

sharp junco
haughty mountain
#

on what?

#

I see no code

fiery cosmos
haughty mountain
#

N=4

#

2 from 2
2*2 from 4

#

similary K=16 would be N=6

#

because 2 from 6

sharp junco
#

I’ll post it rn

#

Or can I PM it?

haughty mountain
urban kiln
#

wait ill read it

#

ah oh

#

ty

sharp junco
#

And the problem

hexed gust
fiery cosmos
#

Is it worth learning how to implement more complex data structures like graphs or how/when to use them?

haughty mountain
sharp junco
haughty mountain
#

why?

sharp junco
#

if you dont wanna help its fine

haughty mountain
#

I'm fine with helping, but I don't want to help over dm

sharp junco
#

interesting

#

ill make a help channel then

#

are you fine with that

#

or is that a problem

haughty mountain
#

fwiw you're missing a big insight about the problem

#

is it ever useful to check longer sublists?

sharp junco
#

so you read the problem already

haughty mountain
#

yes

sharp junco
#

why wouldnt it

#

is that making my code slower

haughty mountain
# sharp junco why wouldnt it

say I have a sublist L with some min and max, can adding an element make the minimum larger or the maximum smaller?

sharp junco
#

minimum larger

haughty mountain
#

how?

#

give me an example

sharp junco
#

if the sublist L's max has a given limit, adding the element would automatically have to go the min

#

or vice versa

#

but then that wouldnt make sense thinking about it again

haughty mountain
#

the task is to minimize max - min

#

so we want to have max small and min large

sharp junco
#

Yeah

haughty mountain
#

if I add another element to a list I could only make the minimum smaller

#

similar for maximum

sharp junco
#

True

haughty mountain
#

so I want the smallest possible list

sharp junco
#

Yea\

haughty mountain
#

in this case length 2 is the smallest allowed

#

checking anything larger is useless

sharp junco
#

then 500000 is the max

#

yeah

#

so how can i optimize

#

this to be more efficient

#

time limit is 3 seconds

#

for any input given

#

i get this when doing a large input

#

11 seconds is way to much

#

right

haughty mountain
#

what about implementing the thing we just talked about?

sharp junco
#

So we should eliminate checking anything bigger then 2 here? And have the max smaller while the min being larger?

haughty mountain
#

just the first part

#

just check all sublists of length 2

#

not all sublists like you're doing now

sharp junco
#

Seems like it’s just a matter of removing a line

#

Or multiple for that matter

#

Not really sure which ones

#

Would removing the second if statement be sufficient?

sharp junco
#

is this better? @haughty mountain

haughty mountain
#

no

#

you're still processing way more stuff than you need

#

you aren't checking only the length 2 sublists

#

the thing you have there is also just wrong

#

it always answers 0 afaict

sharp junco
#

mind helping me with this? ive been at it for awhile but its not clicking

#

like i get the objective

#

here

#

but like i dont rlly see how i should execute

#

or go about it

sharp junco
#

i kinda get it ig

haughty mountain
#

start by iterating over all sublists of length 2, then the rest should be trivial

sharp junco
sharp junco
#

@snow arch here it is

#

if you can, or anyone else can

#

would really appreiciate the help

snow arch
#

im not sure about it but if im u i will take a look at threading or multiprocessing

haughty mountain
#

there is a very simple O(n) solution

agile sundial
#

there is?

#

oh there is

thorn sable
#

``que = []
front = 0
rear = 0
arr = []
ajmat = [[0 for i in range(20)] for j in range(20)]
b = []
p = 0

def display():
print("BFS of Graph: ")
for i in range(n):
print(arr[i])

def insert(val):
x = front
que[x] = val
front += 1

def Del():
rear += 1
return que[rear-1]

def unVisit(val):
for i in range(front):
if(val==que[i]):
return 0

return 1

def bfs(i):
j = 0
if(front==0):
insert(b[i])
for j in range(n):
if(ajmat[i][j]=='Y'):
if(unVisit(b[j])):
insert(b[j])
m = Del()
arr[p] = m
p += 1
return 0
if name == "main":
n = int(input("Enter the number of nodes in a graph: "))
for i in range(n):
b1 = input("Enter vlaue for node "+str(i+1)+" :")
b.append(b1)
print("Enter the value in adjancency matrix in from of 'Y' or 'N'\n")
print("If there exits an edge between two vertices than 'Y' otherwise 'N'\n")
for i in range(n):
print("\n")
print(b[i])
for j in range(n):
v = input()
ajmat[i][j] = v

print("\n\n")
for i in range(n):
    bfs(i)
display()''

I have declared front = 0 gloally but why is it showing UnboundLocalError: local variable 'front' referenced before assignment

haughty mountain
#

because of how globals work in python

#

in insert you reassign front, which means python will ignore the global front in that function

#

you could use the global keyword in this case, but having mutable globals isn't great design

stuck nebula
#

Write a function named get_first_name that asks the user to enter his or her first name, and returns it.

method 1

def get_first_name():
first_name = input('Enter your first name: ')
return(first_name)

print("Your first name is: ", get_first_name())

method 2

def get_first_name():
first_name = input('Enter your first name: ')
return(first_name)
get_first_name()

#

Which method would work i tried both it works and counts towards my HW assignment i think but i wrote it different way twice to get my brain from thinking more.

sharp junco
#

mind helping me out with it?

#

like ive been trying for hours

#

but im just stuck

#

please would really appreciate it

haughty mountain
#

I'm not going to write code for you

#

the idea is just to iterate over all sublists of length 2 and get the difference

#

smallest difference is the answer

sharp junco
#

was just wondering like

#

would I have to remove any of my existing code? or

#

.

#

here it is

haughty mountain
#

I would scrap it and start new, write code to iterate over all adjacent pairs

#

a = [...]
n = len(a)
iterate over
a[0], a[1]
a[1], a[2]
a[2], a[3]
...
a[n-2], a[n-1]

stone cipher
#

would calling the max function on a segment tree if l was 0 and r was equal to N have the same time complexity as calling the max function on an array normally?

sharp junco
#

this isnt any better

#

the efficiency still sucks

#

please help

#

i feel like i was close with

#

my code here

#

the run time was just bad

haughty mountain
sharp junco
#

it doesnt fit the time contraints

#

of 3 seconds

#

for any input

haughty mountain
#

for what size input?

sharp junco
#

key word

#

in the problem

#

for any input

halcyon plankBOT
#

Hey @sharp junco!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

haughty mountain
#

500000

sharp junco
#

yeah

haughty mountain
#

!e

import time
import random

n = 500000
a = [random.randint(0, 1000000000) for _ in range(n)]

start = time.time()

ls=[]
for i in range(len(a)-1):
    x = a[i] - a[i+1]
    ls.append(abs(x))
print(min(ls))

end = time.time()
execution_time = end - start
print(f'Elapsed: {execution_time}')
halcyon plankBOT
#

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

001 | 292
002 | Elapsed: 0.1945819854736328
haughty mountain
#

see, easily fast enough

#

for the largest valid input array size

sharp junco
#

what was that command

#

and the program your using to

#

calculate the time

haughty mountain
#

program?

#

I'm just using the statements you had in your code

#

to time it

hexed gust
#

They are including the input() into the time elapsed. Hence the longer time.

haughty mountain
#

(+ some code to generate random data to run on)

sharp junco
hexed gust
#

If you are just timing the for loop, it's near instant on smaller input*.

haughty mountain
#

but sure, you can include parsing time as well

hexed gust
#

No, I mean it's including the time it takes for you to type the input in lol

haughty mountain
#

!e

import time
import random

n = 500000
a = [random.randint(0, 1000000000) for _ in range(n)]
s = ' '.join(map(str, a))

start = time.time()
a = [int(x) for x in s.split()]

ls=[]
for i in range(len(a)-1):
    x = a[i] - a[i+1]
    ls.append(abs(x))
print(min(ls))

end = time.time()
execution_time = end - start
print(f'Elapsed: {execution_time}')
halcyon plankBOT
#

@haughty mountain :warning: Your 3.11 eval job timed out or ran out of memory.

[No output]
sharp junco
#

interesting

haughty mountain
#

lol, too much memory I'm guessing

sharp junco
#

also can you check if this alternative sol works as well

#
import time # import time module

arr = list(map(int, input().split(" ")))

# sort the list in ascending order
arr.sort()

# initialize the minimum and maximum elements we have seen so far
min_ele = arr[0]
max_ele = arr[1]

# initialize the smallest difference between the maximum and minimum element
# in any sublist of length at least 2
diff = max_ele - min_ele

# iterate through the list, starting from the second element
for i in range(1, len(arr)):
  # update the minimum and maximum elements
  min_ele = min(min_ele, arr[i])
  max_ele = max(max_ele, arr[i])

  # update the smallest difference
  diff = min(diff, max_ele - min_ele)

# print the smallest difference
print(diff)```
#

has to run within 3 sec

#

largest input 500000

haughty mountain
#

that will give the wrong answer

sharp junco
#

im trying to figure out the bug with it

#

mind pointing out why

haughty mountain
sharp junco
#

because of the sorting?

#

how could i fix it

haughty mountain
#

it's computing totally the wrong thing

hexed gust
#

I was just stating that to clarify any confusion with timeit

haughty mountain
#

you can just send a file to stdin

sharp junco
#

like

#

the bug with it

haughty mountain
#

it's not like a single bug, the whole thing there is just wrong

#

this thing computes the right result

#

and it should easily run fast enough

halcyon plankBOT
#

Hey @sharp junco!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

sharp junco
#

alright, makes sense. also how do i use a txt.file , such as this one as input in pycharm

#

i want to use it to test this problem

halcyon plankBOT
#

Hey @sharp junco!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

haughty mountain
#

you could read the file from python

sharp junco
#

yeah was wondering how id do that

haughty mountain
#

or send it to stdin, though idk how to do that in pycharm

sharp junco
#

mind if i share screen quickly

haughty mountain
sharp junco
#

i have the IDE open

haughty mountain
#

what's wrong with just sharing code or (maybe) screenshots

sharp junco
#

so we can step by step approach the testing of the file?

#

i mean sure

#

but idk i thought sharing my screen would be faster

#

if ur not comfortable with that its fine

haughty mountain
#

instead of using input()

sharp junco
#

OH SHOOT

#

bro remember the original code that i had, from the very beginning

#

i added one line and i think its linear time now

#

wanna see

haughty mountain
#

I'm assuming it's close to equivalent to this

sharp junco
#

i added the min line after defining the array

#

that would make it linear time right

sharp junco
haughty mountain
#

that one line is equivalent to the code I mentioned

#

idk why you have the rest there still

#

the loops and stuff

sharp junco
#

what should i remove

#

can you use the e! command one more time with the code

#

just wanna see if how fast it is

#

with 500000

haughty mountain
#

do you not see that the loop part is still quadratic?

#

I'm saying this is a complete solution

import time # import time module
arr = list(map(int, input().split(" ")))
result = min([abs(a-b) for a,b in zip(arr[1:],arr[:-1])])
print(result)
#

that second line is the same logic as this

sharp junco
#

i get an error with the sample inputs

haughty mountain
#

!e

import time # import time module
s = "10 6 9 1"
arr = list(map(int, s.split(" ")))
result = min([abs(a-b) for a,b in zip(arr[1:],arr[:-1])])
print(result)
halcyon plankBOT
#

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

3
haughty mountain
#

yes it does

halcyon plankBOT
#

@sharp junco :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | EOFError: EOF when reading a line
sharp junco
#

bruh

#

i literally just want to

#

test this

#

with 500000

haughty mountain
#

your loops are quadratic time

sharp junco
#

i thought you said

#

that the line i added

#

helps

haughty mountain
#

where?

sharp junco
#

min([abs(a-b) for a,b in zip(arr[1:],arr[:-1])])

haughty mountain
#

I said that one line is a solution to the problem

#

everything after it, the loops and stuff, is still quadratic and doesn't need to be there

haughty mountain
sharp junco
#

so this is all i need

haughty mountain
#

as is this

#

both linear

#

that snippet you just posted and the code I replied to just above are essentially the same

sharp junco
#

how similar, because i got it as an example solution, and my solution cant be exactly same, otherwise the code will be flagged

haughty mountain
#

oh, is none of this your code? or is some of it yours?

sharp junco
#

the very first was mine

haughty mountain
#

so neither this

#

or this is yours?

sharp junco
#

this is not

#

the rest is mine

#

this was mine

fiery cosmos
#

anyone can help

sharp junco
#

one sec

#

we almost done

haughty mountain
#

I didn't say exactly the same

#

but they do basically the same thing in the end

sharp junco
#

Are you familiar with MOSS

fiery cosmos
#
            if x>283 & y>200 & x+w<356 & y+h<280 :  #x+w<<420 & y+h<<330
                print("x değeri:",x," y değeri:",y," x+w degerı:",x+w , " y+h değeri:",y+h)                
                color="undefined"
                if hue_value <9:
                    color="red"
                elif hue_value<85:
                    color="green"
                elif hue_value<120  :
                       color="blue"
                print("deger:",pixel_center)

but but i get value when it doesn't enter the loop

x değeri: 538  y değeri: 61  x+w degerı: 575  y+h değeri: 115
deger: [ 13  25 145]
haughty mountain
sharp junco
#

We almost done

fiery cosmos
#

oh

sharp junco
#

Want to run my code through it

#

Or itself, if possible

haughty mountain
#

why? just submit your own code and you should be fine

sharp junco
#

I hope so

#

Should be fine

fiery cosmos
#

help_

haughty mountain
fiery cosmos
#

what type of this question

haughty mountain
sharp junco
#

or even here too, im open to it

#

seems like u did !e

#

but idk how it works

#

just to see use it for this code here

haughty mountain
#

it just executes code

sharp junco
#

so what do i do

#

to test the max test case

#

for my code here

haughty mountain
#

generate the test case

#

and then test using it

#

no magic there

sharp junco
#

with my code here

#

i understand it just executes the test case

sharp junco
#

Alright

limpid smelt
#

No problem!

sharp junco
haughty mountain
#

what is there to explain?

#

you have my code for generating the test case right there

sharp junco
#

im a lost cause

#

clearly this was complicated

#

but seems simple

#

my bad

haughty mountain
#

!e

import time
import random

n = 500000
a = [random.randint(0, 1000000000) for _ in range(n)]
s = " ".join(map(str, a))

start = time.time()


arr = list(map(int, s.split(" ")))
result = min([abs(a-b) for a,b in zip(arr[1:],arr[:-1])])
print(result)


end = time.time()
execution_time = end - start
print(f'Elapsed: {execution_time}')
#

oh right, memory issues

sharp junco
#

i can do it in my ide

#

if thats possible

#

but idk how

halcyon plankBOT
#

@haughty mountain :warning: Your 3.10 eval job timed out or ran out of memory.

[No output]
haughty mountain
#

like literally just put the code above in a file and run it

sharp junco
#

idk why its a decimal

#

should be in seconds right

haughty mountain
#

it is

#

0.21 seconds

sharp junco
#

that is fast

#

linear time is

#

wow

#

So lines 1-8 and 16-18 are calculating how fast it is

#

and the rest is my actual code