#algos-and-data-structs

1 messages Β· Page 91 of 1

wind idol
#

i'll report that racist one and delete the rest

fiery cosmos
#

Can functions be used in imperative programming ?

oblique panther
#

@fiery cosmos when people talk about "imperative programming", "object-oriented programming", etc, they're talking about general approaches to language design that can inform the design of a given language to varying extents.

wise fiber
#

I need help
finding the trailing zeros of a factorial

class Solution:
    def trailingZeroes(self, n: int) -> int:
        if n == 0 or n == 1:
            return 0
        curr = n
        sub = n
        for i in range(n):
            if sub == 0:
                break
            curr = curr*(sub-1)
            sub - 1
        print(curr)
        curr = str(curr)
        count = len(curr) - len(curr.rstrip('0'))
        return count
```when the test case is 7, the curr becomes some rlly big num idk why
wide prism
#

sub - 1
note that this doesn't change sub

#

other thoughts

for i in range(n):
if sub == 0:
break
better to just run the right number of times in the for loop
class Solution:
there's no real reason for this to be in a class imo (unless you're solving for some platform that requires it)

i think there's probably a more efficient way to do this than actually computing the factorial (although i guess whether that matters or not depends on how big your test cases are)

snow swift
#

looks like leetcode

fiery cosmos
#

Hello is there anyone available to help out with python

#

I need help with an assignment

agile sundial
#

it's possible to compute mathematically the amount of 0s without computing the factorial

wide prism
#

Just ask. People can't tell if they can or want to help with no info

brave oak
#

@wise fiber because factorials are huge.

#

10! is 3.6 million.

#

and it only grows faster from there

#

and yes, there is a way to calculate the number of zeroes without calculating the factorial

wide prism
#

Well they also weren't computing the factorial...

brave oak
#

Well they also weren't computing the factorial...
@wide prism they were trying to, though

#

anyway, the point is that you don't need to do that to know how many trailing zeroes there are

wide prism
#

Sure

brave oak
#

no matter how you optimise the factorial algorithm it will be way too slow for that purpose

tawdry urchin
#

can anyone explain how the code works

`def mergesort(a):
if len(a) == 1:
return a
elif len(a) == 2:
if a[0] > a[1]:
return [a[1], a[0]]
else:
return a

p = len(a)//2
m1 = mergesort(a[:p])
m2 = mergesort(a[p:])

ret = []
while 1:
if len(m1) > 0 and len(m2) > 0:
if m1[0] <= m2[0]:
ret.append(m1[0])
m1 = m1[1:]
else:
ret.append(m2[0])
m2 = m2[1:]
elif len(m1) > 0:
ret += m1
m1 = []
elif len(m2) > 0:
ret += m2
m2 = []
else:
break
return ret

a = [5,9,1,3,4,6,6,3,2]
print(mergesort(a))`

#

i get stuck at
m1 = mergesort(a[:p]) m2 = mergesort(a[p:])

wide prism
#

no matter how you optimise the factorial algorithm it will be way too slow for that purpose
i just threw together a totally naive loop at it feels instant for n 10,000
it's just linear in n no, it's not optimal but it's not an especially slow approach?

wise fiber
#

@wide prism thanks even though my problem was solved prior but thanks for the response

wide prism
#

np

wise fiber
#

so yes i changed from sub - 1 to sub = sub - 1 and also change if sub == 0 to if sub == 1

#

the time complexity of the program was bad tho lol

#

like 6482ms or something

wide prism
#

well if you're doing it for leetcode or something i guess they're looking for the constant time solution

wise fiber
#

is the 6482ms for all the 500 test cases or just the average for each?

#

i mean still proud of this one:
"Memory Usage: 14.2 MB, less than 100.00% of Python3 online submissions for Factorial Trailing Zeroes.
"

#

but my solution was shit

#

how could i improve it

#

any advise? im opened

brave oak
#

i just threw together a totally naive loop at it feels instant for n 10,000
it's just linear in n no, it's not optimal but it's not an especially slow approach?
@wide prism yup, it's linear, but with a relatively high constant?

wide prism
#

are you looking for a hint or a solution

brave oak
#

and, with small enough n and a fast enough computer...

#

I mean you're not wrong to say it's not that slow

#

but I'd say that such questions defo have at least one test case meant to weed out the naive approach (calculating factorial)

wise fiber
#

are you looking for a hint or a solution
@wide prism to me?

wide prism
#

yes

wise fiber
#

ok

#

yea a hint and also how i can improve it or chnage my habits

wide prism
#

yeah gm agreed that the 'intended' solution has got to be the faster one

wise fiber
#

intended?

#

sorry im new to problem solving and algos

brave oak
#

@wise fiber okay, hint: think of what prime factors any output of the factorial function has.

wise fiber
#

so go for the more math based approach?

brave oak
#

yup

wise fiber
#

ok

#

yea still havent got to more advanced math yet and i will look into them (not talking about prime factors)

brave oak
#

yeah so the thing is

#

some algorithms are more...computer sciencey

#

so like the trick is in optimising them by knowing specific programming things

wise fiber
#

ah ok

brave oak
#

whereas some are more about understanding the underlying math problem

#

and solving that

#

and this question is the latter

wise fiber
#

does it optimize it if i remove for loops?

brave oak
#

uh.

#

can you elaborate

wise fiber
#

whereas some are more about understanding the underlying math problem
@brave oak ok tysm for the adbise

#

can you elaborate
@brave oak if i avoid using loops, does it make it better?

#

i mean faster

brave oak
#

uh.

#

in vanilla Python

#

not really

#

but there are some libraries where loops are bad

#

because basically if you use a loop then you operate on one thing at a time

#

but if you use the library's APIs

#

you can operate on many at a time

wise fiber
#

ah ok

wide prism
#

you don't need to loop for this problem, you should be able to solve it with a single calcuation

brave oak
#

yup

#

in this specific case, calculating the factorial itself is unnecessary

wise fiber
#

you don't need to loop for this problem, you should be able to solve it with a single calcuation
@wide prism D: oh man

#

what is the equation/calculation

azure bobcat
#

hi i am new

wise fiber
#

wassup

wide prism
#

looping in itself isn't bad but you're doing approx n multiplications your way and you can do less work

azure bobcat
#

i am gr8

wise fiber
#

lol i still have so much to learn

#

any suggestions like articles or stuff for algos?

#

maybe not for college levels

brave oak
#

what is the equation/calculation
@wise fiber gave you a hint above about the prime factors

wise fiber
#

oh ok thx i will try to figure out by myself

wide prism
#

to be a little more explicit, you might think about what the factors of a number look like when it ends in zero vs when it doesn't (try a few examples) and note that if you're computing the factorial of n you know a list of its factors off the bat

fiery cosmos
#

I think the simplest way is to count how many two's are there in the prime factorization and five's in the prime factorization and taking the minimum of those is the number of zeros

#

and it turns out that the number of five's are always less than two's

#

so you just need to find the number of five's

#

this is the formula used which is applicable for any prime number besides 5

wide prism
#

yeah sorry i said 'a single calculation' but i guess that was overstating it
since this does vary with the number of summands

brave oak
#

yeah

#

there are multiple ways to implement that idea

#

mine was sum(i // (5 ** e) for e in range(1, floor(log(i, 5)) + 1))

wise fiber
#

oh thank u guys so much for the explanation

fleet token
#

you guys can help me in making a PC bot which will automatically join my classes according to my timetable

rough parcel
#

!rule 5

halcyon plankBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.

teal willow
#

Could someone tell me why i can't copy my nested lists which are in dict tmp = copy.deepcopy(dict_of_matrixes[aa])

slow glen
#

I would like to understand that too @teal willow

#

I looked online and found you need to import copy

#

I think it's enough to use tmp = copy.deepcopy(dict_of_matrixes)

teal willow
#

yeah i've imported copy

#

i still getting key error 1

slow glen
#

w/o the array at the end?

teal willow
#

I think it's enough to use tmp = copy.deepcopy(dict_of_matrixes)
@slow glen i want to copy not all dict i need to copy nested lists at specified index of dict

slow glen
#

you should then loop it

#

maybe in a for each

teal willow
#

Yeah i know but every time I deepcopy at specified index i get key eror 1

slow glen
#

i don't know if deepcopy does that automatically

#

wdym copy at a specific index of nested dict?

#

you want to extract a list of dicts from a dict?

teal willow
#

wait

slow glen
#

deepcopy at index 1 should do the trick and copy it all if i'm not mistaken.

#

doesn't matter about the index

teal willow
#

and there is a nested list or matrix how ever u want to name it

#

and I want to copy it

#

with deepcopy

slow glen
#

so, if i'm understanding correctly.

#

You want to deepcopy because you want one copy unchanged of the other?

teal willow
#

Yea

slow glen
#

did you nest a dict inside a dict?

#

I can't tell by that one you posted.

teal willow
#

no I have 1 dict and inside this dict i have matrixes

slow glen
#

in that case...

teal willow
#

it's simple app for competition programming

slow glen
#

you should be able to get something from this in stackoverflow:

#

you could have a syntax error, and something of a minor fix is needed.

vagrant condor
#

!code

halcyon plankBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

vagrant condor
#

hey guys...im a bit confused about the .get() in dictionaris

#
        for h in hours:
            f[h] = f.get(h,0) + 1

i want to make a account of how many times in each our

#

but my output its wrong

#

😦

fiery cosmos
#

.get gives the value f[h] if it is present in f else you get 0

lucid iris
#

@fiery cosmos Not zero but returns None

agile sundial
#

no? he wants a default value of 0 right?

fiery cosmos
#

I was saying acc to his code

fiery cosmos
#
def search(lst, x):
    if len(lst) <= 0:
        return "Doesnt exist"

    i = 0
    while i < len(lst):
        if lst[i] == xt:
            return "success"
        i += 1
    else:
        return "failure"
#

is this a okay way to do a search function in python for a binary search tree ?

snow swift
#

thats not binary search?

#

and we usually return bools instead of strs

fiery cosmos
#

How do I create a search function for bst ?

snow swift
#

first

#

thats not even a tree

#

its just a list

fiery cosmos
#

thats not my full program

snow swift
#

well that wont work on a tree anyway

fiery cosmos
#

what does a tree look like in python

snow swift
#

something like

#
In [13]: @dataclass
    ...: class Node:
    ...:     val:int
    ...:     left:Node = None
    ...:     right:Node = None
    ...:

In [14]: print(Node(val=5,left=Node(val=9,left=Node(10),right=Node(5)),right=Node(val=2,left=Node(3))))
Node(val=5, left=Node(val=9, left=Node(val=10, left=None, right=None), right=Node(val=5, left=None, right=None)), right=Node(val=2, left=Node(val=3, left=None, right=None), right=None))
fiery cosmos
#

@snow swift yeah ive got a list with tuples , but how I create a search function to search for something now .I have the insert function working

snow swift
#

that aint a binary search tree

stable pecan
#

if you do some clever __str__ methods you can get pretty trees:

    def __str__(self):
        first, *left_body = str(self.left).splitlines()
        second, *right_body = str(self.right).splitlines()
        return '\n'.join(
            (
                f"{type(self).__name__}(op='{self.op}')",
                f' β”œβ”€{first}',
                *prefix(left_body, ' β”‚ '),
                f' ╰─{second}',
                *prefix(right_body),
            )
        )

as an example

snow swift
#

do you have to write your own

#

lmao im doing this in ipython, im not fucking around with pretty printing

stable pecan
#

python best language to do pretty printing

fiery cosmos
#
(None, ('james', 'new york', '1'), (None, ('Donald', 'california', '2'), (None, ('mark', 'london', '3'), None)))
#

@snow swift this is bst

snow swift
#

so its (val,left,right)?

fiery cosmos
#

yes

snow swift
#

'new york' is a separate value from '1'?

#

because this tree seems kinda random in terms of types

fiery cosmos
#

no each entry has like name , address and id

snow swift
#

ok

fiery cosmos
#

so you search depending on certain element

#

so how do I do a search function

snow swift
#

you should probably make the values not-tuples

#

if the tree structure is already tuples

fiery cosmos
#

its done imperatively , cant use lists and objects

snow swift
#

wut

#

the code is going to be way messier

#

if you dont distinguish whats a value and whats a tree node

fiery cosmos
#

Its how it has be done

snow swift
#

is this for hw?

fiery cosmos
#

No

snow swift
#

then why is there a restriction on what you can use

fiery cosmos
#

I just need help doing search function , its a question im doing

#

How should I approach it ?

agile sundial
#

do binary search

fiery cosmos
#

@agile sundial that only works when the list is sorted

agile sundial
#

it's a binary search tree right?

fiery cosmos
#

yes

#
def search(root, val):
  if not root:
    return False
  if root.val == val:
    return True
  if root.val < val:
    return search(root.right, val)
  return search(root.left, val)
#

@fiery cosmos Thats helpful but my issue is that root is like -> (None , (name,address,id),None (etc..) etc...) So when I search for a val it doesnt exist

#

what are you searching for?

#

name right?

#

yes but it could be id or address

#

well implement search for each attribute then

#

How would I approach that ? use indexs ?

#

no just replace root.val with root.attribute and that attribute can be either name , address or id

#

but I cant use any objects

#

like classes with def init

#

I don't understand what you mean by that

snow swift
#

whatever

#

root[0]

#

root[1]

#

same thing

fiery cosmos
#

oh okay

snow swift
#

tho i still dont understand this "no objects" rule

#

tuples are technically classes with __init__

fiery cosmos
#

@fiery cosmos Could you explain what you mean again by replacing root.val

#

okay see this for example

#
def search_by_name(root, name):
  if not root:
    return False
  if root.name == name:
    return True
  if root.name < name:
    return search(root.right, name)
  return search(root.left, name)
#

ok

#
def search_by_id(root, id):
  if not root:
    return False
  if root.id == id:
    return True
  if root.id < id:
    return search(root.right, id)
  return search(root.left, id)
#

ok

#

the most useful function that makes sense is search_by_id because each one has a unique one

#

similary if you want to search by address you implement it tho it seems useless to me

#

But when im searching through the binary tree , how do I refer to what I want . If I wanted to return search_by_id(root,2) my root would still be (None , (a,aa,1) ,None (b,bb,2)etc....) how is id 2 going be found in the tuples ? I would like to return the tuple (b,bb,2)

agile sundial
#

return root?

fiery cosmos
#

root is the entire binary tree

agile sundial
#

no

#

when you recurse, root is then either root.right or root.left

fiery cosmos
#

wait, what do you want to return when searching for a element?

#

I want to return the entire entry so if searching for id 2 it should return (b,bb,2)

snow swift
#

this entire val ('james', 'new york', '1')

fiery cosmos
#

well instead of returning true of false return the root as java init said

#

hmm psvm is a nice nick

#

I will call you that from now on

agile sundial
#

if you really want to store it as a list, you would have to do math to calculate which nodes are children

fiery cosmos
#
if root.name == name:
agile sundial
#

you'd have some sentinel to make your list 1-indexed to make the math easier

fiery cosmos
#

tuple' object has no attribute 'name'

#

I cant create attributes , thats the problem

agile sundial
#

ok, but why

fiery cosmos
#

root is an object

#

not a tuple

#

thats the error i got

#

root is a tuple

agile sundial
#

then just use indexing to get the element you want

fiery cosmos
#

ok so every entry (which is a tuple) has a None to its left side , so is there a way to index this correctly . index [0] is None , index [1] is the first entry , but [2] is just the rest..

agile sundial
#

why does everything have None

fiery cosmos
#

Okay maybe another alternative would be to not insert the entire entry , just insert name , address or id .But then how I would return the entry when I my search function finds a specific insert.

dense citrus
#

hello, I have a python exercise to do where I have to write a simulation program on queues, I have written a program, the results are not good I think, if someone can help me please :3 I don't really see how to proceed

#

I can show you what i've already done if sb feels motivated for helping me

wraith valve
#

lmao i think i saw an indentical problem in my textbook

#

i think one way is to make a loop that runs 100 000 times where each cycle represents a clock tick

tall tusk
#

hey guys, what selection algorithms should i know?
im trying to self teach myself DS&A

oblique panther
#

@tall tusk do you know median of medians?

tall tusk
#

Nope-

#

Whats that?

eager hamlet
oblique panther
#

@eager hamlet why are all the questions about cows?

#

@tall tusk it's an algorithm for finding the median value of an unsorted list in linear time

void cliff
#

hello does anyone hear know about Matplotlib in python?

flat sorrel
fiery cosmos
#

@oblique panther its usaco, whose problems are based on the theme "bessie the cow" πŸ™‚

agile sundial
#

usacow

oblique panther
#

@fiery cosmos I see. Weird!

eager hamlet
#

seriously

#

i can't go to a farm without getting mild ptsd

eager hamlet
#

wait

#

i don't get the sample input

#

if there's 7, 7 and 5 in the first

#

that would contribute 14 to the last field

#

and the 5 in the 4th would contribute 4 to the last field

#

14 + 4 != 19

#

help

#

(ping)

#

wait nvm i got it

keen hearth
#

Maybe you should start by working out the un-carried-over volumes of the fields.

#

After that bit of pre-processing, I think it's a slightly simpler problem.

#

Then you can express the problem in matrix notation.

#

Say you have a vector x, where x[n] is the un-carried-over volume of the nth field, and a vector v, where v[b] is the volume of the bth breed of cow, and a matrix A, where A[n, b] is the number of cows of breed b in field n.

#

Then, using Numpy notation,

#

one sec... πŸ˜„

#

Then, using Numpy notation, x = A @ v

#

So, the goal is to find the matrix of non-negative integers, A, satisfying x = A @ v, for which A.sum() is minimised.

#

It becomes a fairly straightforward dynamic programming problem.

#

Because you can find the minimum cows for each field, independent of the rest.

fiery cosmos
#

Could someone help me with a minimax algorithm , I can explain more in dm

oblique panther
#

@fiery cosmos go ahead and ask your question here and someone will answer if they see it and know

floral nymph
#

guys

#

hello

#

i have a problem

oblique panther
#

@floral nymph go ahead and ask your question

eager hamlet
#

@keen hearth yeah i solved it that way

floral nymph
#

for the first question

fiery cosmos
#

a) is taking P and m as input and returning P[m] ig

#

I think there is no programming in it, just math

#

and I forgot the formulas πŸ₯΄

keen hearth
#

@floral nymph is this part of an ongoing assessment?

#

You have the joint distribution for X and Y. You can get the marginal distributions by summing along the rows and columns.

oak crow
#

Any free rss to learn algos and data structures?

#

I'm hearing that it's important to understand those for coding

#

And I'm just. Begginer still....

#

Feel free to ping me. Cuz I'm going to sleep now, as it's too late. Pls ping me wid the reply.

~tysm

mint jewel
#

@oak crow there is a nice course pinned

oak crow
#

Oh

#

Oh yeah, I wanted to learn djikstra specifically! It's there. Thanks @mint jewel

oblique panther
#

My program generates every combination of size two for a list of n items, and then does a linear time operation on that set of combinations

#

what would the big-O be?

#

would it be O(nC2) ? is that even allowed?

mint jewel
#

NC2 is just n**2 afaik. Since nC2 = n*(n-1)/2

oblique panther
#

oh good point

cerulean vapor
#

Where can I find algo. and data structs. exercises?

keen hearth
#

@cerulean vapor you could try solving problems on one of the many programming problem practice websites. E.g. https://www.hackerrank.com

#

For more academic exercises (which I think are also important) you could pick up an introductory algorithms textbook.

#

Also, you could try looking on sites like MIT OCW for problem sets.

eager hamlet
#

fool

#

everyone knows the best places are the usaco training pages

oblique panther
#

@keen hearth I believe that link is a pin for this channel

eager hamlet
#

yeah the bfs worked

hollow stratus
#

Who here is good with recursive algorithms

fiery cosmos
#

just ask what your doubt is and people will help

hollow stratus
#

Just questions on a recursive algorithm that rearranges numbers, not necessarily sorts them from least to greatest

wraith valve
#

the general tip is not to roll out the recursion

#

u prob need to define how you want to rearrange

hollow stratus
#

That’s what I’m confused about, i don’t understand how I’m instructed to rearrange these numbers πŸ˜‚

wide prism
#

show the instructions

#

how could anyone say something useful without seeing them?

hollow stratus
wide prism
#

i see
i agree with OUI OUI, i don't think recursion is the way to go here
i think you can just loop over lst.
here's what jumps to mind, although idk if it is optimal
i would run over lst and keep track of how many things of each type (less than x, equal to x, greater than x) i saw
this shows you the size of each "bucket" you're going to put things into
then i would loop over lst again and swap things as i see them so they're in the appropriate bucket in the first spot not yet confirmed to hold something right for that bucket

snow swift
#

ew c style calling conventions

wide prism
#

this means passing over lst twice, not sure if you can do it in one go

#

yeah the signature is unidiomatic for python isn't it

hollow stratus
#

Ya I’m required to recursively complete this code

wide prism
#

ig slightly better is to pass over once partitioning less than or equal to x from greater than x, and then a second time partitioning equal to from less than, since then you can end the second pass early

#

well i'm not sure what your prof is hoping for then. ig if i had to do it recursively i'd replace the loops with recursions
but, like, why

north cosmos
#

how do u apply a route in python?

brave oak
#

say I have a set of points (X) in a 2D space. how can I get the set of points (Y) for which the Manhattan distance of each point in X from that point is no larger than some value K?

#

there is the obvious quadratic time algorithm, but I'm sure that there's a faster way

raven kite
#

how to proove log(n^2+1) is O(N)

fiery cosmos
#

when you compare n^2 and n^2 + 1 for large values you can approximate that n^2 == n^2 + 1

#

so it reduces to log(n^2)
which again reduces to 2 * log(n)
when written in Big-O notation it is O(log n)

#

idk how it is O(n)

#

wait it actually makes sense to call it O(n) according to the definition of Big-O

#

but thats not the best way to tell the efficiency of algorithm

#

its like saying 1 < 2 * n ^ 100 instead of just saying 1 < 2 * n

half quarry
#

stock[input()] = input() is implementing backwards to my dictonary

#

any reason why?

#

{'apple': 8, 'strawberry': 35, 'orange': 8, 'beetroot': 18, 'carrot': 13, '23': 'bobby'}

#

input bobby

input 23

fast arch
#

can some suggest good resource for learning data structure & algorithms in python

#

stock[input()] = input() is implementing backwards to my dictonary
@half quarry i think because python executes command from right to left

half quarry
#

@fast arch ive been told to do this

#

Don't embed the input() calls in your assignment expression. As you have found, the right side evaluates before the left. Read them into variables first, then do the assignment to the dictionary.

fast arch
#

@half quarry here it's written clearly that you need to read them in to variables

#

So,

#

do ```py
key=input()
stock[key]=input()

half quarry
#

Thank you πŸ™‚

north cosmos
#

how would u square root something in python?

fiery cosmos
#

without using in-built sqrt?

north cosmos
#

there is a build in sqrt?

fiery cosmos
#

yeah math.sqrt()

north cosmos
#

ohh didn't know that

brave oak
#

** 0.5?

hot bobcat
#

hello! anybody know which algorithm filter() uses?

#

wait it actually makes sense to call it O(n) according to the definition of Big-O
@fiery cosmos yep, but it should be adjusted as any complexity bound

fiery cosmos
#

yes

fast arch
#

** 0.5?
@brave oak that would give a square & not square root

hot bobcat
#

@brave oak that would give a square & not square root
@fast arch whats the diff

fiery cosmos
#

no i ** 0.5 will give square root

brave oak
#

@brave oak that would give a square & not square root
@fast arch ** 2 would be square.

hot bobcat
#

@fast arch ** 2 would be square.
@brave oak haha yeah, i was kind of confused with that statement

#

anyways this channel is intended for algorithms and datastructure that should be asked on help or general

oblique panther
#

@fiery cosmos you'll want to check if there's a Haskell Discord.

#

Alright. This is Python Discord, though.

odd hare
#

Not sure if this is the right channel, but I am doing these little coding challenges and one of them stumped me. I'm trying to figure this out with out relying on google too much. I have to make a function that returns true if the values of two lists match (it is assumed they are the same length) and false if they are not the same. To make it easier for myself I copied the code into vsCode and made my own "test statemends" (not sure if that is what you would call them) Anyway here is my code:

def check_equals(lst1, lst2):
    for i in lst1:
        if lst1[i] != lst2[i]:
            return False
    return True

def print_value(boolin):
    if boolin==False:
        return "True"
    else:
        return "false"

print("Test 1 (False): " + print_value(check_equals([1, 2], [1, 3]))) #Should return false
print("Test 2 (True): " + print_value(check_equals([1, 2], [1, 2]))) #should return true
print("Test 3 (True): " + print_value(check_equals([4, 5, 6], [4, 5, 6]))) #should return true
print("Test 4 (False): " + print_value(check_equals([4, 7, 6], [4, 5, 6]))) #should return false

Ignore the second function, that is just to make the test statements work. The issue I am running into is that this just doesn't work and I'm struggling to figure out where I went wrong

ivory dirge
#

Python has the assert keyword which you can use like this

assert 1 + 1 == 2
#

it'll silently continue if the statement is true, but will throw an error if it isn't

fiery cosmos
#

for i in lst1:
means you are iterating over elements of lst1 not the indices

#

@odd hare

ivory dirge
#

yeah you'd want to iterate over range(len(lst1)) instead

#

for fruit in list_of_fruits will give you fruits

#

if you want their index you have to do the range(len( song and dance

odd hare
#

ooooh I see

ivory dirge
#

you could do

for item in lst1:
  for other in lst2:
    if item != other:
      return False
return True
odd hare
#

So just so I understand the logic, we iterate through each item in list 1, then iterating over each item in list 2, wouldn't that compare all the values of list two against the first value of list 1? Or am I misunderstanding

eager hamlet
bronze sail
agile sundial
#

clrs is great

bronze sail
#

clrs is great
@agile sundial is that to me? 🧐

ivory dirge
#

So just so I understand the logic, we iterate through each item in list 1, then iterating over each item in list 2, wouldn't that compare all the values of list two against the first value of list 1? Or am I misunderstanding
@odd hare you are completely right in that my code is wrong as hell yes lol

#

I didn't think it through at all

odd hare
#

XD though your first reply was the thing that fixed it for me, so at least there is that

ivory dirge
#

so assuming, as you said, both lists are the same length,

for i in range(len(lst1)):
  if lst1[i] != lst2[i]:
    return False
return True
#

aye

agile sundial
#

use zip instead

#

!zop

odd hare
#

thank you for the help, and a good chuckle XD

agile sundial
#

!zip

halcyon plankBOT
#

The zip function allows you to iterate through multiple iterables simultaneously. It joins the iterables together, almost like a zipper, so that each new element is a tuple with one element from each iterable.

letters = 'abc'
numbers = [1, 2, 3]
# zip(letters, numbers) --> [('a', 1), ('b', 2), ('c', 3)]
for letter, number in zip(letters, numbers):
    print(letter, number)

The zip() iterator is exhausted after the length of the shortest iterable is exceeded. If you would like to retain the other values, consider using itertools.zip_longest.

For more information on zip, please refer to the official documentation.

bronze sail
agile sundial
#

yep

ivory dirge
#

yes for something this simple you'd want to use a oneliner like zip

agile sundial
#

well, anytime you need to loop over multiple things at once you use zip

bronze sail
#

lolo I was lookin for that book, but could not find translated version in my shops, but I already got pdf πŸ˜‚

#

alto its only CLR without s πŸ€”

wide prism
#

it's an old edition

split grotto
#

so i had a question, cause i have an object and im adding functions to it with its decorators. but these functions im adding to it all have a common state, and was wondering how i should give them common resources

#

if that makes sense?

bronze sail
#

it's an old edition
@wide prism well it says its 4th , but its from 1994

wide prism
#

huh
mine says third edition and copyright 2009
so idk what's going on, i guess

bronze sail
fiery cosmos
#

hmm what year you are in?

bronze sail
#

2001

#

that book released at 2020 is actualy 7th here πŸ€”

fiery cosmos
#

lol I mean are you in college or school

eager hamlet
#

http://usaco.org/index.php?page=viewproblem2&cpid=836
so without thinking i did a floodfill and now i have an array called sizeRegions where each point indicates the size of the region that point is in
idk where to go from here, maybe for each point and its neighbors, if they're different, do another floodfill with the regions?
(ping 2 help plz)

#

i feel like that would tiem out tho

bronze sail
#

lol I mean are you in college or school
@fiery cosmos no, why you ask ?

molten sail
#

Hi guys, whats another way of sorting a list other than using .sort()/.sorted()?

agile sundial
#

you'd have to write your own sorting algo

#

or implement one

molten sail
#

bubble sort/ insertion sort?

agile sundial
#

sure

molten sail
#

i wrote like 2 but i dont get the right output

#

one doesnt even give 1

fiery cosmos
#

@bronze sail clrs is not recommended for high school students

#

It's a bit more formal book

next swallow
#

Hi everyone I got stucked on some basic method (> < )

#

Just for example list = ["ATCG","AAATTCCGC","TTCTTG"]

#

I want to count the first element (ATCG)

#

And then the output is 4

#

I dont know how to describe and reach the element in list

#

I would like to ask for your help (_ _ )

#

(οΌΏ οΌΏ )

#

I am a new learner of Python

#

( ; w ; )

lucid iris
#
words = ["ATCG","AAATTCCGC","TTCTTG"]
for word in words:
    print(len(word))
> Hi everyone I got stucked on some basic method (>  < )
@next swallow    
#

prints length of element in the list

next swallow
#

How about I want to compare the lengths of the elements?

#

As the list is actually containing many word actually...

#

Thanks Harsha

#

Like if I want to find the word that has i char
User than enters i

lucid iris
#

U can use if len (word)==length

next swallow
#

Thank you very much~ Harsha (๑‒̀ㅁ‒́ฅ)

lucid iris
#

You are welcome

fiery cosmos
#

Could someone help me with a remove function in a binary search tree ?

fiery cosmos
#

sure what part of it makes it hard for you?

narrow urchin
#

Guys, I need some help...I'm working now on the project of genetic algorithm at my studies...I have 20x8 array. I need to crossover each row and append it to new array. Each row should be a combine of first half first parent and second half second parent (next row second half of first parent and first half of second parent) etc. Could someone help me with it?

north cosmos
fiery cosmos
#
# the traditional way
S = (x2-x1)**2 + (y2-y1)**2
d = S**0.5
# using math module
import math
d = math.hypot(x2-x1, y2-y1)
#

Ok I will share something that will be useful in future
Do you know there is something called IPython?
It is really helpful when I want to check some documentation of something
Like this

#

I know all the methods of the module

#

see how helpful this is

#

Nice

#

all you need to do to install this is to do
pip install ipython

#

and type ipython in the command line

#

it looks like normal python intrepreter but is better

lucid iris
#

Thanks for sharing information

fiery cosmos
#

well I really liked this way of checking somethings before asking for help

north cosmos
#

wow

#

that's so cool

#

@fiery cosmos there is also syntax highliting which is super cool

#

and auto indentation

fiery cosmos
#

yep

#

I use it a lot to do some quick checking before helping someone πŸ™‚

narrow urchin
#

@fiery cosmos maybe you can help me a lil' bit? πŸ™‚

fiery cosmos
#

sure what's it about?

narrow urchin
#

that's my problem :/

fiery cosmos
#

to be honest I didnt understand what does that mean

narrow urchin
#

ok, maybe I wrote to complicated. I have an array:
matrix = np.array([[2, -5, 3, 2, 5, 9, -10, 1], [-6, 4, -4, -4, -1, 10, 1, -2], [-5, -6, -8, -9, 2, 2, 7, 10], [7, -5, -2, -4, -4, 7, 1, -1], [8, -10, 1, -9, 5, -7, 0, 9], [-3, -9, 5, 10, 2, 2, -9, -5], [-8, -3, 10, 2, 3, 7, -9, 1], [9, 7, -9, 1, 5, -6, -4, 5], [3, 10, 1, 4, 9, 5, -6, 1], [-9, 6, 8, 4, -10, 4, -3, 4], [7, -3, -5, 3, 9, 8, 0, 3], [-3, 0, 10, -2, -1, -8, 9, 8], [4, -1, 2, 0, -6, 6, -6, 3], [9, 3, 6, 6, 4, -4, 10, -1], [8, 8, 10, -3, -4, 0, -10, -5], [-8, 0, 10, 5, 2, 1, -3, -7], [5, -4, 9, -6, 0, -5, -9, -9], [6, -6, 0, 1, -1, 5, -9, 7], [-10, -2, -6, -9, 8, -9, 5, -6], [0, -5, 0, 2, 5, 9, -10, 1]])

#

Each row is a parent

#

I need to make a children_array from half of parents:

#

like

#

[2, -5, 3, 2, -1, 10, 1, -2], [-6, 4, -4, -4, 5, 9, -10, 1]
etc

#

@fiery cosmos Is that clear now for you?

#

I don't know how to loop it

fiery cosmos
#

so you need to get i and i+1 from that matrix?

narrow urchin
#

i need to get matrix[i][:4] and matrix[i+1][4:] and make of this children_array[0]

#

but

#

children_array[1] should be made of matrix[i+1][:4] and matrix[i][4:]

#

children_array[2] = matrix[i+2][:4] + matrix[i+3][4:] and children_array[3] = matrix[i+3][:4] + matrix[i+2][4:]

#

etc

#

@fiery cosmos I hope i didn't made a mistake in explaination

fiery cosmos
#

hmm I still dont know how to do this efficiently

narrow urchin
#

ok, I still try for my own πŸ™‚ btw thanks

fiery cosmos
#
Write a function that takes a positive integer n and returns the number of ten-pairs it contains. A ten-pair is a pair of digits within n that sums to 10. Do not use any assignment statements.

The number 7,823,952 has 3 ten-pairs. The first and fourth digits sum to 7+3=10, the second and third digits sum to 8+2=10, and the second and last digit sum to 8+2=10. Note that a digit can be part of more than one ten-pair.

Hint: Use a helper function to calculate how many times a digit appears in n.
#

can some one help me with this ?

#

plz?

lucid iris
#
l = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[-1,3,6,2]]
f = []
for x in range(0,len(l),len(l)//2):
    f.append(l[x][:2]+l[x+1][2:])
    f.append(l[x+1][:2]+l[x][2:])  
print(f)

@narrow urchin If you do have any optimizations to this problem please post it here, maybe with iterators we can do much more efficiently I think, but no idea how to go

narrow urchin
#

@lucid iris thx for interesting about my problem, I'm still working on it and I think I'm close to solve it.

#

but it is very simmilar to your's

#

@lucid iris @fiery cosmos this is my solution:

def cross():
    crossed = []
    for i in range(0, len(sorted_matrix)-1, 2):
        crossed.append(np.append(sorted_matrix[i][:cross_point],sorted_matrix[i+1][cross_point:]))
        crossed.append(np.append(sorted_matrix[i+1][:cross_point],sorted_matrix[i][cross_point:]))
    return np.array(crossed)
#

thanks for interesting

chilly junco
#

this channel looks like people are mining bitcoin in discord

fiery cosmos
#

Nope this channel is for algorithm and ds

bronze sail
#

mining bitcoint is in cryptology, so more like data science and only 20% in algost in my opinion πŸ€”

brave oak
#

say I have a set of points (X) in a 2D space. how can I get the set of points (Y) for which the Manhattan distance of each point in X from that point is no larger than some value K, in less than quadratic time?

brave oak
#

@lucid iris p sure that's not right

#

try "1919"

lucid iris
#

@brave oak answer is 3 only working

brave oak
#

it should be 4

#

Note that a digit can be part of more than one ten-pair.

lucid iris
#

(1,9),(1,9),(9,1)

brave oak
#

assuming you're counting permutations

#

otherwise, it should be 2 (but that's not what the question says).

#

first one with the two nines (2), second one with the two nines (2) = 4

lucid iris
#
l = list(map(int,input()))
r = list(filter(lambda x:10-l[x] in l,range(len(l))))
print(len(r))

@fiery cosmos once check this
@lucid iris
Now it's fine will work for any number of times for a digit to appear have edited the code

brave oak
#

@lucid iris what do you expect 19191 to give?

lucid iris
#

Sorry for that this is a very loose implementation I checked, but I have doubt that (5,5 ) can same number be counted two times in a pair

brave oak
#

Sorry for that this is a very loose implementation I checked, but I have doubt that (5,5 ) can same number be counted two times in a pair
@lucid iris see the question

#

the second and third digits sum to 8+2=10, and the second and last digit sum to 8+2=10. Note that a digit can be part of more than one ten-pair.

#

there's only one 8 in the example but it's counted twice

#

also

#

quite apart from that

#

your solution is quadratic in the length of the input

#

I'm p sure there's a linear time solution

lucid iris
#
from collections import Counter 
c = Counter(map(int,input())).most_common(5)
print(c)
r = sum(list(zip(*c))[1])
print(r-1)
``` @fiery cosmos Once verify this code if it is fine
empty trench
#

Hi guys. Which way is better to send exchange video frames between a server and client thru namedPipes, running on the same computer? The video frames are not that big 640x360 resolution. Right now Its exchanging image>numpy>bytearray>[send]>bytearray>numpy>image. It works but im wondering if its better to encode the images into a PNG? or does it really matter?

eager hamlet
#

probably wrong channel

empty trench
#

OH I thought that was part of data_structs discussion. thanks!

naive moss
#
a = input('Introduce A: ')
b = input ('Introduce B: ')
c = input ('Introduce C: ')

d = (int(a) + int(b))


if d == c:
    print('Ok')

else:
    print('It isn't ok...')```
#

Does anybody know why it might doesnt work?

#

I't always use else

fiery cosmos
#

c is a string

#

convert to to int

naive moss
#

Oh

#

I'll try

bronze sail
#

@bronze sail clrs is not recommended for high school students
@fiery cosmos ye I started reading it and its very formal, but I hope I will learn some algos and where to use them, I think I saw binary trees in table of contents

eager hamlet
fiery cosmos
#

hey there is a usaco discord server

#

there are lot of ppl practicing like you

#

the invite link ends with bessMBe

#

@eager hamlet

eager hamlet
#

yeah

prisma aspen
#

hi

eager hamlet
#

hi

oblique panther
#

@fiery cosmos go ahead and paste the link here and I'll white list it and pin it in this channel.

#

We're actually probably just going to whitelist it

fiery cosmos
#

Sure

oblique panther
#

the fixation on cows there is certainly odd.

fiery cosmos
#

lol πŸ™‚

#
class Dijkstra:
    def __init__(self, start, destination, length):
        self.start = start
        self.destination = destination
        self.length = length
        
    def find_route(self,start, destination):
        #e.g start = a , destination = e
        stack = []
        
    def make_diagram(self,start,end,length):
        pass
    
    
    
graph = [("a","b",7),("a","c",9),("a","d",11),("b","c",9),("b","e",4),("c","d",3),("d","e",5)]
Dijkstra('a', 'b', 7)
Dijkstra('a', 'c', 9)
Dijkstra('a', 'd', 11)
Dijkstra('b', 'c', 9)
Dijkstra('b', 'e', 4)
Dijkstra('c', 'd', 3)
Dijkstra('d', 'e', 5)
#

Hi guys , im trying make a Dijkstra's program ,but im stuck on how to exactly start.

#

okay so you have an weighted edge list

#

but the algorithm is too slow if you use this

#

Why is it called edge list ?

#

you are storing edges right?

#

Oh okay fair lol

#

have you heard of adjacency lists?

#

No

#

okay its nothing but a list of all nodes that are connected to a

#

more like a dictionary

#

in your example the adjacency list would look like this

#
a -> [(b, 7), (c, 9), (d, 11)]
b -> [(a, 7), (c, 9), (e, 4)]
.
.
.
#

I am assuming your graph is undirected

#

what does undirected mean

#

do you understand how we do this in python dictionary?

#

yes

#

oh it means if you can go from a to b

#

then you can also go from b to a

#

oh okay

#

where as in directed you need to follow the direction

#

there is a restriction

#

okay now that you have made your graph into the adjacency list format

#

you need to do dijkstra algo which finds the shortest path or length acc to your problem from a source to a target

#

right?

#

lets take the pseudocode from wikipedia

#

okay

#
function Dijkstra(Graph, source):
       dist[source]  := 0                    
       for each vertex v in Graph:            
           if v β‰  source
               dist[v]  := infinity           
           add v to Q                         
      while Q is not empty:                  
          v := vertex in Q with min dist[v]
          remove v from Q 

          for each neighbor u of v:          
              alt := dist[v] + length(v, u)
              if alt < dist[u]:               
                  dist[u]  := alt            
      return dist[]
  end function
#

hmm lemme remove comments

#

okay thats more good

#

now the graph in here is the adjacency list

#

since you stored it in that format

#

correct?

#

Whats source ?

#

from where you want to start

#

But why no end ?

#

and at the end of the function you will calculate all the shortest path lengths from source to all other nodes

#

not just for target but for all others too

#

so you can modify it like

function Dijkstra(Graph, source, target):
    blah blah blah
    return dist[target]
end function
#

dist represents the shortest lengths

#

Sorry im confused , I cant visulize this

#

hmm so I think you need to get strong in Graph theory basics

#

like how things work

#

hold up if you spend some time understanding these it will be helpful in future

#

So would knowing breadth first search and depth first search be useful for this ?

#

they are searching algorithms

#

not shortest path algorithms

#

I see

#

basically these are the foundations

#

to get to know more about graphs and how do algortihms work on them

#

you can watch dijkstra video if you want to before these

#

Btw I have done these algrothims before , just confused on how to code them.

#

do see other ppl implementations

#

I will watch that graph series tho

#

its hard to come up with some on your own

#

Yeah I would imagine

#

But I seen some online and just dont where to start on how to learn it

#

I suggest that series, it will help a lot

#

this for example

#

Yes im going to watch the series , thanks

#

you are scared seeing their implementation right?

#

Ye basically

#

its ok, you need to understand "how" the algorithms works

#

then seeing this code won't scare you

#

because you understand why something is written

#

Do you have any links , for websites that breakdown how the code works for Dijkstra's ?

#
Medium

From GPS navigation to network-layer link-state routing, Dijkstra’s Algorithm powers some of the most taken-for-granted modern services…

#

the first one is to visualising how an algorithm works and the second one is detailed just by looking at the implementation and the comments are the breakdown of the code

#

@oblique panther can you pin the visualgo site it will be a good resource πŸ™‚

oblique panther
#

@fiery cosmos I'll look into it πŸ‘

fiery cosmos
#

Thanks so much !!!

eager hamlet
#

i've been told this was really hard

#

my technique was to just simulate each of the meetings/barns until

#

and increment on the way

#

(ping 2 reply thx)

split obsidian
#

Is there a relationship between railway programming and monads? It seems to me like monads enable railway programming by letting you write a chained method that describes the "happy path"

fiery cosmos
#
# -1 represents infinity
#g = adjacency list of weighted graph
#n = the number of nodes in the graph
#s = the index of the starting node (0 <= s < n)
#e = the index of the end node (0 <= e < n)
def dijkstra(g, n, s, e):
    vis = [False] * n #size n
    prev = [None] * n 
    dist = [-1] * n #None = infinity
    dist[s] = 0
    pq = []#Empty priority queue
    pq.insert((s,0))
    while pq.size() != 0:
        index, minValue = pq.poll()
        vis[index] = True
        # if dist[index] < minValue:
        #     continue
        for edge in g[index]:
            if vis[edge.to]:
                continue
            newDist = dist[index] + edge.cost

            if newDist < dist[edge.to]:
                prev[edge.to] = index
                dist[edge.to] = newDist
                pq.insert((edge.to, newDist))
    if index == e:
        return dist[e]
    return -1 #infinity

def findShortestPath(g, n, s, e):
    dist, prev = dijkstra(g,n,s)
    path = []
    if (dist[e] == -1):
        return path
    at = e
    while at != None:
        at = prev[at]
        path.add(at)
    path.reverse()
    return path
dijkstra([(0,1,4),(0,2,1),(1,2,2),(1,3,1),(2,3,5),(3,4,3)],5,0,3)
#

Hi guys I read some pseudo code and try to re write it myself for the dijkstra algorithm , but I dont understand how to implement a adjacency matrix. Any help would be great

crude stump
#

I actually want to learn this topic in python , so which modules do I need to download?

fiery cosmos
#

can anyone help ?

agile sundial
#

an adjacency matrix is just a 2d list

fiery cosmos
#

yeah so is my list correct or do I need to change it ?

#

@agile sundial

agile sundial
#

sure, yeah

#

if there is an edge (i, j), then matrix[i][j] would have some value to tell you it's there

fiery cosmos
#

okay im assuming then my list is okay... but the insert function wont allow to take in a tuple . Im trying implement insert to use for my priority queue

agile sundial
#

instead of pq.insert((s, 0)), do pq.insert(s, 0)

crude stump
#

Could anyone tell , how to learn algorithms and data sciences in python?

#

I am a begginer in that sense

fiery cosmos
#

still having issues

bronze sail
#

Could anyone tell , how to learn algorithms and data sciences in python?
@crude stump books or tuts

#

do you know python or any other programmin language?

crude stump
#

Python

#

I was actually not able to find tuts so I asked , if you could link something it would be gr8

oblique panther
#

@fiery cosmos please don't dump images here

vagrant condor
#

!codehelp

#

!code

halcyon plankBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

vagrant condor
#

Hey guys i have a question. im using beautiful soap to look inside a html to find a link position and repeat 7 times.
i've already got the tag and i indexed the tag that i need.
But now i have to create a .get() to get the url.
i've got a hint that is the variable that stores the value of .get() the same as the variable that is read in the html line

html = urllib.request.urlopen(url, context=ctx).read()
#

which part is the varible? the whole ```py
(url, context=ctx) or urllib.request.urlopen(url, context=ctx)

snow swift
#

:thonk:

#

requests.get?

fiery cosmos
#

Im so confused, I have code to check if two strings are a permutation of each other. The code works perfectly but I am trying to understand how it works
I understand 90% of it but i dont understand the purpose of the last 2 lines can someone explain why these give me the correct results?

>>> def permu(str1, str2):
...     if len(str1) != len(str2):
...             return False
...     for c in str1:
...             if c in str2:
...                     str2 = str2.replace(c, "")
...     return len(str2) == 0
agile sundial
#

you're essentially "crossing out" characters you've found already

#

if at the end you crossed everything out, it's true

fiery cosmos
#

oooooh

#

thank you

#

is there a way to do this that involves arrays?

agile sundial
#

yes

fiery cosmos
#

okay I will try to tell you a dirty way
|| sort both and compare πŸ₯΄ ||

#

as ive gotten the problem from an arrays section in my cracking the code book

agile sundial
#

||sorting is faster right?||

fiery cosmos
#

im practicing sample interview questions but ill be using Python so im not sure if using arrays is necessary if python allows me to just use the code I already have

#

nope it takes n*log n to sort something but you can do this in O(n) using Counter in python

agile sundial
#

faster than the current solution i meant

fiery cosmos
#

yep

#

but the solution was incorrect

#

but it works?

#

I am sorry it indeed works

agile sundial
#

!docs collections.Counter

halcyon plankBOT
#
class collections.Counter([iterable-or-mapping])```
A [`Counter`](#collections.Counter "collections.Counter") is a [`dict`](stdtypes.html#dict "dict") subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The [`Counter`](#collections.Counter "collections.Counter") class is similar to bags or multisets in other languages.

Elements are counted from an *iterable* or initialized from another *mapping* (or counter):... [read more](https://docs.python.org/3/library/collections.html#collections.Counter)
fiery cosmos
#

im practicing some basic algos & ds for my upcoming technical assessment so im just trying to do all this using basic python, no additional packages or anything fancy, just the basics, so I can understand the logic behind it better rather than the code

#

well these are basics than other data structures you will encounter

#

using a dictionary, or Counter is not fancy imo

#

even the interviewer will understand this approach easily than that magical solution

#

i understand that im just trying to learn these things in perhaps a less pythonic way as the code in the book is done with I think java

#

so even though my code works I dont see it using arrays which concerns me

#

I don't understand why do you want to use arrays if it involves strings?

#

sorry my bad chapter is called arrays and strings

#

I just see lots of code involving arrays

#

probably not necessary to worry about arrays for now then

#

well if you dont want to do it in the pythonic way then it is fine

#

how would you do this in java?

#

im looking at the solution now its pretty lengthy

#
String sort(String s) {
2 char[] content = s.toCharArray();
3 java.util.Arrays.sort(content);
4 return new String(content);
5 }
6
7 boolean permutation(String s, String t) {
8 if (s.length() != t.length(Β» {
9 return false;
1a } 
return sort(s).equals(sort(tΒ» ;
12 } 
#

something like this sorry for numbers its copied from pdf

#

well then you see many ppl chose python because it makes the code shorter and faster to type

#

with the same logic

#

so you can't deny that

#

i just cant believe python is this much shorter

#

πŸ™‚ welcome to python discord

#

why do people bother with other languages Python has made all this so much easier

#

simple each language has its own pros and cons

#

I done a little bit of Java in university which put me off of coding for a while, I can see why now looking at the difference between this and Python

#

yeah if you were to ask me to chose python and java for interview I will def chose python

#

its easier for me and interviewer too

#

For my solution I posted earlier, I get that to work out the time complexity you count the number of loops or something, but how do you roughly estimate the space complexity or is this something I have to run tests on to find out?

#

To estimate space complexity you generally see what sequences you are declaring

#

if it were just normal variables like a = 6 its just O(1) space complexity

#

like this

frozen ermine
#

hello, friends. I have been tasked to do the following: Define the variable saying to contain the list ['After', 'all', 'is', 'said', 'and', 'done', ',', 'more', 'is', 'said', 'than', 'done', '.']. Process this list using a for loop, and store the length of each word in a new list lengths. Hint: begin by assigning the empty list to lengths, using lengths = []. Then each time through the loop, use append() to add another length value to the list.

here is what I have so far:
saying = ['After', 'all', 'is', 'said', 'and', 'done', ',', 'more', 'is', 'said', 'than', 'done', '.']
lengths = []

I am unsure of how to first start constructing the for loop. My attempts have been syntactically invalid

fiery cosmos
#

if you do something like this a = [] * n

#

it is O(n) space since you are allocating n values to the list

#

so if there is an array/list it is O(n) where n is the number of values in the list?

#

and if i have several lists would it still be O(n)

#

yep if you have lists of lists then it would be O(n^2)

#

lemme give you a link to these

#

thanks dude

#

check these

#

both are regarding time and space complexities

#

the first one is more detailed than second one

#

super helpful thank you gonna continue working on some practice problems now

#

where are you practicing?

#

im working through the interview questions on cracking the code 6th edition

#

and just using py in cmd

#

so i can learn better to write the code from memory rather than googling everything

#

i usually end up googling tho

#

Im currently working on this which im assuming should be easy:

URLify: Write a method to replace all spaces in a string with '%20: You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: If implementing in Java, please use a character array so that you can
perform this operation in place.) 
#

try leetcode practice problems

#

or most frequently asked interview problems if you are tight on time

#

I have to do a technical assessment using codility.com by next monday so im trying to get the grips of the first five lessons they offer

#

cool

#

I cant find what theyre going to ask me so i feel if i can understand this stuff well I can deal with any problem hopefully

#

gl!

#

thx

bronze sail
#

Hey, I want to solve problem that minimazes distance to some data, I got list of (hue, saturation and value)
and I want to find one object from that list that is closest to some target, 930, 200, 200) for example

#

is there some alg for that or I will iterate for all pictures?

frozen ermine
#

hi, everyone, I have a small question. the following code is meant to take the string contained in rawtext and return the string translated into pig latin. with how my code is written, it only returns the first word in the string. I'm unsure of what modifications I need to make so that pig_latin(list) runs on and returns the entire string

rawtext = "the empire strikes back"
list = rawtext.split()

print(list)

def pig_latin(list):
vowels = ['a', 'i', 'o', 'e', 'u']
for s in list:
if s[0] in vowels:
return string + 'ay'
elif s[1] in vowels:
return string[1:] + string[0] + 'ay'
elif s[2] in vowels:
return s[2:] + s[:2] + 'ay'
else:
return s[3:] + s[:3] + 'ay'

gilded torrent
bronze sail
lusty sand
#

i need assistance with hash tables

wraith valve
#

u prob need to be more discriptive

#

hash tables pretty general

lusty sand
#
HTcapacity = 99
HT = [None]*HTcapacity
multFactor = 137

file_name = 'C:/Users/Hello_World/Desktop/A6trans.txt'
fi = open(file_name, 'r')
a6input = fi.readlines()
fi.close()
print(len(a6input))

def Hash(inline, mFactor = 1123):
    instring = ''
    for n in range(1, len(inline)):
        instring = instring + str(inline[n])
    Hcode = 0
    for c in instring:
        Hcode += ord(c)
    return ((Hcode//3 * int(inline[3]) * mFactor) % HTcapacity)

def rehash(oldhash, mFactor = 10):
    return ((oldhash+1) * mFactor) % HTcapacity

HT = [None] * HTcapacity
for i in inlists:
    if i[0] == 'I':
        HC = Hash(i, mFactor = multFactor)
        if HT[HC] is None:
            HT[HC] = [i[1:-1]]
        else:
            HC = rehash(HC, mFactor = multFactor )
            HT[HC].append(i[:-1])
    elif i[0] == 'F':
        get_hash(HC, HT, HTcapacity)
    elif i[0] == 'R':
        continue
    else:
        continue
        raise ValueError('')
#
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-ee5bb67890d1> in <module>
      7         else:
      8             HC = rehash(HC, mFactor = multFactor )
----> 9             HT[HC].append(i[:-1])
     10     elif i[0] == 'F':
     11         get_hash(HC, HT, HTcapacity)

AttributeError: 'NoneType' object has no attribute 'append'
bright badger
#

@frozen ermine replace all ' return' with result +=
add result ="" to start of code

#

return result at the end

lusty sand
#

i'm trying to attempt collision avoidance but it won't permit me to do so

wraith valve
#

does the rehash function even go though ur list and rehash the values

#

or is that to get the new hash function?

lusty sand
#

the new hash function is supposed to rehash the hash value

#

is that not the proper way?

#

i know there's two types collision avoidance chaining/probing

wraith valve
#

ur supposed to go through the entire list and rehash each value

#

quite sure adding 1 to a list doesnt do a map of each value in the list by 1

#

imo i would make a class called hashtable that has a list to hold the elements, a constant alpha value

#

give it a method called insert

#

another method called generate hash value

#

and another method called rehash table

#

and also prob another variable(s) in the class to hold the hash functions parameters

brave oak
#

so, just checking

#

given an ordered collection of numbers, is there any way to find whether any three numbers in it sum to another given number in less than quadratic time?

pulsar lake
#

Sum of two can be found using hash map but three I have to see

fiery cosmos
#

Write a python program to print Armstrong numbers from 1 to 10

flat sorrel
#

!rules 5

halcyon plankBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.

oblique panther
#

@fiery cosmos what have you written so far?

flat sorrel
#

It's apparently for an exam, so we're not allowed to help (see #help-dumpling)

wraith valve
#

lmao who do u know

#

unless ur in the exam with him?

flat sorrel
#

Refer to the link to said channel

wraith valve
#

?

agile sundial
#

in help neon, he asked for help on his exam

brave oak
#

Sum of two can be found using hash map but three I have to see
@pulsar lake why do you need a map

pulsar lake
#

To make the searching for the other number O(1)

#

Suppose arr[0] is 1 and my target sum is 7 so I have to find if there is 6 in the array

#

Check this link 1st approach is O(n^2) the second approach uses hash map and brings it down to O(n)

brave oak
#

@pulsar lake I know a linear time solution for 2 numbers

#

and anyway that doesn't seem very Pythonic

#

but my original question

#

was about 3 or more numbers

pulsar lake
#

This is channel for algo and data structures so that's a generic approach

brave oak
#

which was my point

#

do you know of any solution that runs in less than quadratic time for 3 numbers?

pulsar lake
#

Python's list uses hash functions internally so when you use find() a hash function is referred

brave oak
#

Python's list does not use hashing...

#

are you thinking of dict

pulsar lake
#

do you know of any solution that runs in less than quadratic time for 3 numbers?
No, that I am trying to figure out as I stated at first

fiery cosmos
pulsar lake
#

are you thinking of dict
Yeah yeah

fiery cosmos
#

that is a cursed time complexity

pulsar lake
#

Mistake

fiery cosmos
#

idk the implementation details

brave oak
#

yeah, so

snow swift
#

doesn't gm want 4sum

brave oak
#

https://en.wikipedia.org/wiki/3SUM
@fiery cosmos thanks, somehow I could not find this by searching

In computational complexity theory, the 3SUM problem asks if a given set of

    n
  

{\displaystyle n}

real numbers contains three elements that sum to zero. A generalized version, k-SUM, asks the same question on k numbers. 3SUM can be eas...

#

nope, 3 is fine

#

because I was doing an interview and I got the linear time solution for 2 numbers but I couldn't come up with anything better than quadratic for 3

#

and I was thinking...is it possible?

snow swift
#

but this is 3 sum to 0

#

which is the same as 2 sum to another

pulsar lake
#

Yeah, this is not generic algorithm

brave oak
#

but this is 3 sum to 0
@snow swift no, they're equivalent problems

#

Instead of looking for numbers whose sum is 0, it is possible to look for numbers whose sum is any constant C in the following way:

Subtract C/3 from all elements of the input array.
In the modified array, find 3 elements whose sum is 0.

For e.g., if A=[1,2,3,4] and if you are asked to find 3sum for C=4, then subtract all the elements of A by 4/3 and solve it in the usual 3sum way, i.e., (a-C/3) + (b-C/3) + (c-C/3) = 0

Or you could simply modify the original algorithm to search the hash table for the integer (C -(S[i]+S[j])).

snow swift
#

oh wait you can just subtract the target

#

to get 0

brave oak
#

man so I was basically right 😑

#

interviewer wasted my time

#

Check this link 1st approach is O(n^2) the second approach uses hash map and brings it down to O(n)
@pulsar lake anyway, my point was that you can do it this way too:

bool({find_value - element for element in numbers} & numbers)
fiery cosmos
#

did the interviewer ask whether there is an algorithm faster than quadratic?

flat sorrel
#

When the elements are integers in the range [-N, ..., N], 3SUM can be solved in O(n + N log N) time by representing the input set S as a bit vector, computing the set S + S of all pairwise sums as a discrete convolution using the Fast Fourier transform, and finally comparing this set to -S.

#

Since you've mentioned that your collection is ordered, if your elements are all integers, you can obtain the range of the numbers and thus solve it this way

brave oak
#

did the interviewer ask whether there is an algorithm faster than quadratic?
@fiery cosmos no, but I came up with the obvious quadratic solution pretty fast and he just let me think out loud for like 10 min

#

Since you've mentioned that your collection is ordered, if your elements are all integers, you can obtain the range of the numbers and thus solve it this way
@flat sorrel it was originally unordered, but my hypothesis was that sorting would make it faster, so I started from there

#

and, yeah, I saw that...but that also is a bit too esoteric, I guess

#

thanks though

#

πŸ₯΄

#

another reason I think algorithm interview questions are just dodgy

fiery cosmos
#

@forest tinsel a^i b^j c^k where i >= 1, j >= 1, k >= 1 so abb, bbc, bc, ab, ac, a, c are rejected

forest tinsel
#

Ohhhh.... Got it! Thanks!

onyx current
#

not really sure if this is the right place to ask, im working on something like a blood type guesser which takes parents types and optional siblings, im thinking of how do i actually do it, i have the rules and i cant really implement it with if statements (it's some what complex)

agile sundial
#

wouldn't you just have a table with the inputs and map it to a list of outputs

#

like a punnet square

onyx current
#

not if you're taking account of siblings and maybe grand parents

agile sundial
#

you mean if you don't have your parents' blood types?

onyx current
#

no no

#

so most of the time by getting your parent's blood types you won't be able to get your blood type

agile sundial
#

of course not, the only way to get your blood type is by testing your blood

onyx current
#

yes, but taking account of siblings does increase the accuracy

agile sundial
#

no it doesn't

onyx current
#

yes it does?

agile sundial
#

flipping a coin and getting 10 heads in a row does not increase the chance of getting tails

#

it's independent

onyx current
#

and with the uncles/grandparents it's even more accurate

scarlet sleet
#

can anyone help me with integrating Dijkstra's algorithim with a doubly linked list?

onyx current
#

i studied about it

#

it's all synced up, i know that you mean it's not confirmed but it's still a high chance

agile sundial
#

πŸ€”

#

that's not how that works

fiery cosmos
#

hey i don't know what data structure is can somebody explain it to me?

agile sundial
#

it's a thing that stores data in a smart way

fiery cosmos
#

variables?

agile sundial
#

a variable could reference a data structure yeah

fiery cosmos
#

databases do that to?

onyx current
#

let's say your grand parents are one A and the other also A, and some of your uncles became O while your dad was A, and your mother was O, then that signs your chances of getting O are higher than usual no?

agile sundial
#

no?

#

it only depends on your parents

onyx current
#

but you can guess the A genetics if it's A0 or AA

#

im not sure if they're called A genetics but thats how they're called in my language at least

agile sundial
#

ok, i see what you mean now

onyx current
#

yeah

agile sundial
#

you don't have the genotypes

onyx current
#

yep

agile sundial
#

ok

onyx current
#

but i wanna guess them

#

so what would be the best approach

agile sundial
#

i'm not sure

foggy fable
#

i am watching a youtube video on data structures, and they are going through arrays and arraylists... they say arraylists aren't native to python... what do we use in python then? is an arraylist the same as a linkedlist?
the code they use for arraylist in the video is in c and java but dont provide a python example

agile sundial
#

python essentially has arraylists

#

python does have normal arrays, with the array module, but you'll probably never need them

foggy fable
#

is arraylist and linkedlist the same? since they store the reference to the location in memory

#

since they both*

agile sundial
#

no, they aren't the same

foggy fable
#

thanks homie @agile sundial

spice sparrow
#

Hey, so I'm doing a really simple password manager as a project for school and I've made this Use Case Diagram. I've been asked to make a UML Class Diagram but I have no idea how to go about this, would I just have 1 class named Password with some attributes and some methods like checkSecurity(), savePassword(), generatePassword() ?

#

I have this so far but I feel as if it's wrong because it's only 1 class

#

Anyone have experience with these UML class diagrams?

dusk estuary
#

Is anyone able to advice me on perlin noise, (is this even the correct channel?)?

#

I am unsure of what functions to use on the dot product, currently i am using the sigmoid function but that doesnt work for my data as the values produced are either really high or low 0.1 or 0.9 etc is there anything i can do about this?

#

Ideally i would divide the whole data set to bring them closer to the center of the sigmoid but doing this causes math.exp to cap out at around 750 with overflow error

fiery cosmos
#

I have a dice and I used an algorithm with OpenCV to find blobs of white in the area.
How would I make it only detect the top face?

snow swift
#

wrong channel

dusk estuary
#

@snow swift was that in reference to me, if so what would be more appropriate?

waxen cairn
#
# best algorythim in the world
print("Hello World!")
turbid pewter
#

True!

foggy fable
#

can someone help me understand the selection sort:

heights = [1,1,4,2,1,3]

for i in range(len(heights)):
    min_index = i 
    for j in range(i+1, len(heights)): 
        if heights[j] < heights[min_idx]: 
            min_idx = j
    heights[i], heights[min_idx] = heights[min_idx], heights[i] # swap 

the thing i dont understand is that: how is the list being accessed in both the for loops when range(len(heights)) returns 0,1,2,3,4 and not the elements inside the heights list? what am i not getting lol

snow swift
#

@dusk estuary that was for diamond, but ig it also applies to you

dusk estuary
#

well its graphics with data with perlin which is an alg so IDK?

covert scaffold
#

welp pressed enter before finishing the question

#

I:

#

Anyway I feel really confused, and I don't even know how to go about googling this

I have two pandas DataFrames and I want one of them to contain the same information as the other and then add a new column to the second DataFrame however when I do

A = Pd.DataFrame(data=DATA)
B = A
B[NewCol] = DATA1[NewCol]

A also ends up changing

#

Is there anything I can do to like 'lock' A to not change when B changes? I'm really new to programming and I'm doing things that are far beyond my level because of a class

brave oak
#

Anyway I feel really confused, and I don't even know how to go about googling this

I have two pandas DataFrames and I want one of them to contain the same information as the other and then add a new column to the second DataFrame however when I do

A = Pd.DataFrame(data=DATA)
B = A
B[NewCol] = DATA1[NewCol]

A also ends up changing
@covert scaffold look into the copy method

eager hamlet
#

if i'm given adjacent nodes of a tree and nothing else, is it possible to determine the parent node in something maybe less than linear? just curious

#

ik leaf nodes only have 1 edge

#

but like what about the ultimate node

brave oak
#

if i'm given adjacent nodes of a tree and nothing else, is it possible to determine the parent node in something maybe less than linear? just curious
@eager hamlet what kind of tree?

covert scaffold
#

@brave oak ty πŸ™‚

#

My questions are so dumb 😒

brave oak
#

My questions are so dumb 😒
@covert scaffold not really a dumb question but for future reference

#

for dataframe questions

alpine thorn
#

any good covid algos

eager hamlet
#

@brave oak like a normal graph tree

#

n nodes with n - 1 edges, only 1 path from a node to any other

brave oak
#

n nodes with n - 1 edges, only 1 path from a node to any other
@eager hamlet so no other constraints?

eager hamlet
#

uh yeah...?

brave oak
#

don't think so

eager hamlet
#

oh ok then

covert scaffold
#

Is this the right spot to ask about setting the arguments to a function? Or should I go to another channel

flat sorrel
#

If you're talking about a specific coding-related issue you are unsure of, it would be better to use a Python help channel

covert scaffold
#

Thank you

fiery cosmos
#

maybe you meant to print B.graph?

#

or diagram.graph

#

B(graph) is going to instantiate a new B

#

so you'll print out a class

fiery cosmos
#

@fiery cosmos type object 'B' has no attribute 'graph , this is what happens when print B.graph

#

because its not a class variable but an instance variable since you use self.graph

#

so use diagram.graph πŸ™‚

#

that will access the graph that is unique to diagrams instance

fallen helm
#

Hello! I'm looking for an algorithm that can calculate the following problem:
We want to travel a route of length D with the car. The vehicle has a tank of capacity G. N petrol stations with markings from 1 to N are arranged along the route. ) and the selling price pi per unit of fuel. Vehicle consumption is a unit of fuel per unit distance. The task is to determine at which gas stations we need to refuel if we want to drive all the way on the lowest. The restriction is to always fill the tank of the vehicle to the end when stopping at a petrol station. If several stopping sequences have an equivalent, select the one with the least stops.
I know how to do it with a brute force method but I'm looking for a more efficient way
All the help is greatly appreciated ❀️

fiery cosmos
#

@fiery cosmos Thank you !

vagrant condor
#

!code

halcyon plankBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

vagrant condor
#

Hey guys i have a question.
im using beautiful soup its for parsing html.
the thing that i have to do is to get a link in a position and with that position i have to follow that link and reply it 7 times.
ive made it to the while loop and i found the position.
my tag is a list.
my question is how to index throught that position?

from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
s = input("Enter position: ")
m = input("Enter count: ")

m = int(m)
while m > 0:
    html = urllib.request.urlopen(url, context=ctx).read()
    soup = BeautifulSoup(html, 'html.parser')
    tags = soup("a")
    m = m - 1
    #print(count)
    u = tags[18]
    print("Retrieving: ",u)
#

my position is tags[18] when i try to index the position for example f = u[1] i got a traceback

#

i know that tags is a list

oblique panther
#

@vagrant condor if you ever get a traceback, you'll want to post that as well. However this isn't an algos and data structs question.

vagrant condor
#

where should i post it?

oblique panther
#

@vagrant condor there isn't a topical channel for web scraping, really. The help system is described in #β“ο½œhow-to-get-help. Be sure to post the error message as well or people will skip your question.

vagrant condor
#

πŸ‘

royal elm
#

a good book recommendation for this subject.....?

#

for beginners

#

only

agile sundial
#

how new to programming are you?

#

@royal elm

royal elm
#

I know fundamentals can create command line apps

agile sundial
#

have you learned loops and control flow?

royal elm
#

Yea

agile sundial
#

algorithms illuminated is ok

bleak sparrow
#

web scraping is relatively simple

#

I watched keith galli's videos on youtube

#

he explains it really well

royal elm
#

πŸ‘

odd salmon
#

Hello I need some help regarding recurrsions

#

Develop two recursive functions keep(lst, num) and drop(lst, num) that each intake a list (lst) and a positive integer (num) such that:
keep(lst, num) keeps the first num elements of the list, if num is greater than the length of the list, then the whole list is returned, and
drop(lst, num) drops the first num elements of the list, if num is greater than the length of the list, then the empty list is returned.

NOTE: There should be no global variables declared AND no loops in your code!!

fiery cosmos
#

Has anyone ever done Dijkstra's algorithm using a dictionary as the graph ?

scenic mortar
#

bruh

fiery cosmos
#

bruh

halcyon plankBOT
#

Hey @wet blade!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

β€’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

β€’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

wet blade
#

Can anyone look out this problem once

#

t = int(input())
while(t):
n = int(input())
arr = list(map(int,input().split()))
tc = int(input())
while(tc):
chef=0
r = int(input())
for i in range(r):
tem = i%n
if arr[tem]%2!=0 and arr[tem]!=1 and tem!=n-1:
chef+=arr[tem]-1
elif tem==n-1 and arr[tem]%2==0:
chef+=arr[tem]-1
elif tem==n-1 and arr[tem]%2!=0:
chef+=arr[tem]
elif tem<n-1 and arr[tem]==1:
a = arr[:tem][::-1]
for element in a:
if element%2==0:
chef-=element
else:
chef = chef+1
break
else:
chef+=arr[tem]
print(chef)
tc-=1
t-=1

#

And tell where am I doing wrong

oblique panther
#

@wet blade what is this code meant to do?

#

The way the variables are named makes it hard to follow. Also arr can be defined as [int(n) for n in input().split()]

fiery cosmos
#

spaghetti code

#

πŸ™‚

#

if
elif
elif
elif

#

else

wet blade
#

@oblique panther could you see the problem

twin edge
#
Problem is not visible now. Please try again later.
silent bane
#

print(√9 * 2) why does this not work?

twin edge
#

My guess is that √9 is not defined

slow glen
#

Anyone else know about Abstract graph transformation to derived boolean logic?

agile sundial
#

that's not a valid operator in python

silent bane
#

how do i make this rectangle around my text in discord?

fiery cosmos
#

I have some code to determine the smallest common element of two arrays, but I dont actually know how it works can anyone explain?

def solution(A, B):
    A.sort()
    B.sort()
    i = 0
    for a in A:
        if i < len(B) - 1 and B[i] < a:
            i += 1
        if a == B[i]:
            return a
    return -1
#

@fiery cosmos do you understand the brute force approach?

#

trying every possible combination?

#

yeah it is O(n^2) right

#

ok

#

now if we sort those two sequences can we do any better?

#

if we sort them then we just find the first element to match?

#

yeah what would your time complexity be?

#

im not sure the time complexity of the sort function

#

lemme check

#

it is N log N

#

remember it

#

nlog2n

#

ok

#

yeah so you made the algo for N^2 to N log N

#

so it is an improvement

#

now imagine you are given sorted sequences A, B and you are to find smallest match

#

hmm ok

#

I am finding smallest match am I not with my counter?

#

yeah so you loop over each sequence and individual counter

#

and you loop over a sequence again to check if some element is present in both the counters

#

would changing the first if loop to a while loop improve time complexity?

#

actually I am not able to prove that your solution gives smallest match

#
cnt_1 = Counter(A)
cnt_2 = Counter(B)

for el in A:
  if cnt_1[el] > 0 and cnt_2[el] > 0:
    return el

return -1
#

im struggling to see how to improve the code in two lines as I only just understand how it works now

#

You can tell that this will def produce the correct result

#

But here you are using extra space, you notice that right?

#

by iterating over each sequence?

#
cnt_1 = Counter(A)
cnt_2 = Counter(B)
#

by these

#

they take some extra space

silent bane
#

in pycharm how do i exit a "project" i want to start a new one

fiery cosmos
#

many ppl don't talk here

#

you can ask in off-topic channels

#

@fiery cosmos do you understand the solution I gave?

#

I mean does it make sense

#

I can't really prove that the solution you gave always works

#

somewhat, you are using 2 different counters and for the first element that occurs in both that is greater than zero, return that element

#

is it true or not?

#

since A is sorted

#

the smallest element in A which occurs in B is the answer right?

#

yes

#

pretty much

#

yeah so the counter does the same thing

desert cedar
#

Why is a counter used here? what are you counting?

fiery cosmos
#

since A is sorted you check whether B has also this el

#

unfortunately i cant implement a counter im only allowed to modify 2 lines of the given solution

#

@fiery cosmos Oh so the soln is wrong?

#

I thought it was right

#

the solution works but contains bugs

#

yeah so I think the if else should be replaced with a while loop

#

then it would be correct