#algos-and-data-structs
1 messages Β· Page 91 of 1
Can functions be used in imperative programming ?
@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.
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
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)
looks like leetcode
Hello is there anyone available to help out with python
I need help with an assignment
it's possible to compute mathematically the amount of 0s without computing the factorial
Just ask. People can't tell if they can or want to help with no info
@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
Well they also weren't computing the factorial...
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
Sure
no matter how you optimise the factorial algorithm it will be way too slow for that purpose
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:])
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?
@wide prism thanks even though my problem was solved prior but thanks for the response
np
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
well if you're doing it for leetcode or something i guess they're looking for the constant time solution
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
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?
are you looking for a hint or a solution
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)
are you looking for a hint or a solution
@wide prism to me?
yes
yeah gm agreed that the 'intended' solution has got to be the faster one
@wise fiber okay, hint: think of what prime factors any output of the factorial function has.
so go for the more math based approach?
yup
ok
yea still havent got to more advanced math yet and i will look into them (not talking about prime factors)
yeah so the thing is
some algorithms are more...computer sciencey
so like the trick is in optimising them by knowing specific programming things
ah ok
whereas some are more about understanding the underlying math problem
and solving that
and this question is the latter
does it optimize it if i remove for loops?
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
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
ah ok
you don't need to loop for this problem, you should be able to solve it with a single calcuation
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
hi i am new
wassup
looping in itself isn't bad but you're doing approx n multiplications your way and you can do less work
i am gr8
lol i still have so much to learn
any suggestions like articles or stuff for algos?
maybe not for college levels
what is the equation/calculation
@wise fiber gave you a hint above about the prime factors
oh ok thx i will try to figure out by myself
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
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
yeah sorry i said 'a single calculation' but i guess that was overstating it
since this does vary with the number of summands
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))
oh thank u guys so much for the explanation
you guys can help me in making a PC bot which will automatically join my classes according to my timetable
!rule 5
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.
Could someone tell me why i can't copy my nested lists which are in dict tmp = copy.deepcopy(dict_of_matrixes[aa])
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)
w/o the array at the end?
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
Yeah i know but every time I deepcopy at specified index i get key eror 1
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?
wait
deepcopy at index 1 should do the trick and copy it all if i'm not mistaken.
doesn't matter about the index
that's how my dict looks like
and there is a nested list or matrix how ever u want to name it
and I want to copy it
with deepcopy
so, if i'm understanding correctly.
You want to deepcopy because you want one copy unchanged of the other?
Yea
no I have 1 dict and inside this dict i have matrixes
in that case...
it's simple app for competition programming
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.
!code
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.
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
π¦
.get gives the value f[h] if it is present in f else you get 0
@fiery cosmos Not zero but returns None
no? he wants a default value of 0 right?
I was saying acc to his code
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 ?
How do I create a search function for bst ?
thats not my full program
well that wont work on a tree anyway
what does a tree look like in python
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))
@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
that aint a binary search tree
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
do you have to write your own
lmao im doing this in ipython, im not fucking around with pretty printing
python best language to do pretty printing
(None, ('james', 'new york', '1'), (None, ('Donald', 'california', '2'), (None, ('mark', 'london', '3'), None)))
@snow swift this is bst
so its (val,left,right)?
yes
'new york' is a separate value from '1'?
because this tree seems kinda random in terms of types
no each entry has like name , address and id
ok
you should probably make the values not-tuples
if the tree structure is already tuples
its done imperatively , cant use lists and objects
wut
the code is going to be way messier
if you dont distinguish whats a value and whats a tree node
Its how it has be done
is this for hw?
No
then why is there a restriction on what you can use
I just need help doing search function , its a question im doing
How should I approach it ?
do binary search
@agile sundial that only works when the list is sorted
it's a binary search tree right?
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
oh okay
tho i still dont understand this "no objects" rule
tuples are technically classes with __init__
@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)
return root?
root is the entire binary tree
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)
this entire val ('james', 'new york', '1')
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
if you really want to store it as a list, you would have to do math to calculate which nodes are children
if root.name == name:
you'd have some sentinel to make your list 1-indexed to make the math easier
ok, but why
then just use indexing to get the element you want
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..
why does everything have None
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.
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
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
hey guys, what selection algorithms should i know?
im trying to self teach myself DS&A
@tall tusk do you know median of medians?
http://usaco.org/index.php?page=viewproblem2&cpid=417 would like a greedy method work for this problem?
or do i have to do a sort of bfs with all the diff types of cows?
@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
hello does anyone hear know about Matplotlib in python?
You will be well-served in #data-science-and-ml
@oblique panther its usaco, whose problems are based on the theme "bessie the cow" π
usacow
@fiery cosmos I see. Weird!
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
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.
Could someone help me with a minimax algorithm , I can explain more in dm
@fiery cosmos go ahead and ask your question here and someone will answer if they see it and know
@floral nymph go ahead and ask your question
@keen hearth yeah i solved it that way
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 π₯΄
@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.
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
@oak crow there is a nice course pinned
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?
NC2 is just n**2 afaik. Since nC2 = n*(n-1)/2
oh good point
Where can I find algo. and data structs. exercises?
@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.
fool
everyone knows the best places are the usaco training pages
http://usaco.org/index.php?page=viewproblem2&cpid=513
anyways, doing this problem
would like a bfs without a visited set work? (bc a. it's directed and there's only max 100 nodes and b. we have to find all possible times)
@keen hearth I believe that link is a pin for this channel
yeah the bfs worked
Who here is good with recursive algorithms
just ask what your doubt is and people will help
Just questions on a recursive algorithm that rearranges numbers, not necessarily sorts them from least to greatest
the general tip is not to roll out the recursion
u prob need to define how you want to rearrange
Thatβs what Iβm confused about, i donβt understand how Iβm instructed to rearrange these numbers π
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
ew c style calling conventions
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
Ya Iβm required to recursively complete this code
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
how do u apply a route in python?
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
how to proove log(n^2+1) is O(N)
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
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
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
@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.
@half quarry here it's written clearly that you need to read them in to variables
So,
do ```py
key=input()
stock[key]=input()
Thank you π
how would u square root something in python?
without using in-built sqrt?
there is a build in sqrt?
yeah math.sqrt()
ohh didn't know that
** 0.5?
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
yes
** 0.5?
@brave oak that would give a square & not square root
@brave oak that would give a square & not square root
@fast arch whats the diff
no i ** 0.5 will give square root
@brave oak that would give a square & not square root
@fast arch** 2would be square.
@fast arch
** 2would 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
@fiery cosmos you'll want to check if there's a Haskell Discord.
Alright. This is Python Discord, though.
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
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
for i in lst1:
means you are iterating over elements of lst1 not the indices
@odd hare
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
ooooh I see
you could do
for item in lst1:
for other in lst2:
if item != other:
return False
return True
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
http://usaco.org/index.php?page=viewproblem2&cpid=836
so clearly floodfill
but how should i maintain references to the neighboring regions
clrs is great
clrs is great
@agile sundial is that to me? π§
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
XD though your first reply was the thing that fixed it for me, so at least there is that
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
thank you for the help, and a good chuckle XD
!zip
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.
this si clrs? xd
yep
yes for something this simple you'd want to use a oneliner like zip
well, anytime you need to loop over multiple things at once you use zip
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 π€
it's an old edition
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?
it's an old edition
@wide prism well it says its 4th , but its from 1994
huh
mine says third edition and copyright 2009
so idk what's going on, i guess
I guess the translated version is 4th? cause they say thats the original book
hmm what year you are in?
lol I mean are you in college or school
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
lol I mean are you in college or school
@fiery cosmos no, why you ask ?
Hi guys, whats another way of sorting a list other than using .sort()/.sorted()?
bubble sort/ insertion sort?
sure
@bronze sail clrs is not recommended for high school students
It's a bit more formal book
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 ; )
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
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
U can use if len (word)==length
It works nowοΌοΌ I set word as 0 before. It is not necessary. I got it nowοΌοΌ
Thank you very muchο½ Harsha (ΰΉβ’Μγ β’ΜΰΈ )
You are welcome
Could someone help me with a remove function in a binary search tree ?
sure what part of it makes it hard for you?
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?
how would I apply this formula using python,ik the (x1, x2, y1, y2)
# 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
now how do I know how to use an individual method?
Like this
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
Thanks for sharing information
well I really liked this way of checking somethings before asking for help
wow
that's so cool
@fiery cosmos there is also syntax highliting which is super cool
and auto indentation
@fiery cosmos maybe you can help me a lil' bit? π
sure what's it about?
to be honest I didnt understand what does that mean
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
so you need to get i and i+1 from that matrix?
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
hmm I still dont know how to do this efficiently
ok, I still try for my own π btw thanks
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?
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
@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
this channel looks like people are mining bitcoin in discord
Nope this channel is for algorithm and ds
mining bitcoint is in cryptology, so more like data science and only 20% in algost in my opinion π€
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 answer is 3 only working
(1,9),(1,9),(9,1)
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
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
@lucid iris what do you expect 19191 to give?
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
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
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
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?
probably wrong channel
OH I thought that was part of data_structs discussion. thanks!
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
@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
http://usaco.org/index.php?page=viewproblem2&cpid=918
clearly a bfs would time out
what would be an optimal strategy? to get the maximum, you'd probably place one cow as close to the opposite end as possible, but idk about the minium (ping 2 help plz)
hey there is a usaco discord server
there are lot of ppl practicing like you
the invite link ends with bessMBe
@eager hamlet
yeah
hi
hi
@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
the fixation on cows there is certainly odd.
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
Graph Theory algorithms video series
Support me by purchasing the full graph theory playlist on Udemy. This version offers additional problems, exercises and quizzes not available on YouTube:
https://www.udemy.com/course/graph-theory-algorithms
Discount coupon (Expires 07/07...
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 ?
https://visualgo.net/en
https://medium.com/cantors-paradise/dijkstras-shortest-path-algorithm-in-python-d955744c7064
VisuAlgo was conceptualised in 2011 by Dr Steven Halim as a tool to help his students better understand data structures and algorithms, by allowing them to learn the basics on their own and at their own pace. Together with his students from the National University of Singapore...
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 π
@fiery cosmos I'll look into it π
Thanks so much !!!
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)
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"
# -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
I actually want to learn this topic in python , so which modules do I need to download?
can anyone help ?
an adjacency matrix is just a 2d list
sure, yeah
if there is an edge (i, j), then matrix[i][j] would have some value to tell you it's there
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
instead of pq.insert((s, 0)), do pq.insert(s, 0)
Could anyone tell , how to learn algorithms and data sciences in python?
I am a begginer in that sense
still having issues
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?
Python
I was actually not able to find tuts so I asked , if you could link something it would be gr8
@fiery cosmos please don't dump images here
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.
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)
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
you're essentially "crossing out" characters you've found already
if at the end you crossed everything out, it's true
yes
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
||sorting is faster right?||
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
faster than the current solution i meant
!docs collections.Counter
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)
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
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
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
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?
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'
i need assistance with hash tables
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'
@frozen ermine replace all ' return' with result +=
add result ="" to start of code
return result at the end
i'm trying to attempt collision avoidance but it won't permit me to do so
does the rehash function even go though ur list and rehash the values
or is that to get the new hash function?
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
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
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?
Sum of two can be found using hash map but three I have to see
Write a python program to print Armstrong numbers from 1 to 10
!rules 5
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.
@fiery cosmos what have you written so far?
It's apparently for an exam, so we're not allowed to help (see #help-dumpling)
Refer to the link to said channel
?
in help neon, he asked for help on his exam
Sum of two can be found using hash map but three I have to see
@pulsar lake why do you need a map
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)
@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
This is channel for algo and data structures so that's a generic approach
which was my point
do you know of any solution that runs in less than quadratic time for 3 numbers?
Python's list uses hash functions internally so when you use find() a hash function is referred
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
are you thinking of
dict
Yeah yeah
that is a cursed time complexity
Mistake
idk the implementation details
yeah, so
doesn't gm want 4sum
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?
Yeah, this is not generic algorithm
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])).
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)
did the interviewer ask whether there is an algorithm faster than quadratic?
When the elements are integers in the range
[-N, ..., N], 3SUM can be solved inO(n + N log N)time by representing the input setSas a bit vector, computing the setS + Sof 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
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
@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
Ohhhh.... Got it! Thanks!
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)
wouldn't you just have a table with the inputs and map it to a list of outputs
like a punnet square
not if you're taking account of siblings and maybe grand parents
you mean if you don't have your parents' blood types?
no no
so most of the time by getting your parent's blood types you won't be able to get your blood type
of course not, the only way to get your blood type is by testing your blood
yes, but taking account of siblings does increase the accuracy
no it doesn't
yes it does?
flipping a coin and getting 10 heads in a row does not increase the chance of getting tails
it's independent
and with the uncles/grandparents it's even more accurate
can anyone help me with integrating Dijkstra's algorithim with a doubly linked list?
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
hey i don't know what data structure is can somebody explain it to me?
it's a thing that stores data in a smart way
variables?
a variable could reference a data structure yeah
databases do that to?
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?
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
ok, i see what you mean now
yeah
you don't have the genotypes
yep
ok
i'm not sure
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
python essentially has arraylists
python does have normal arrays, with the array module, but you'll probably never need them
is arraylist and linkedlist the same? since they store the reference to the location in memory
since they both*
no, they aren't the same
thanks homie @agile sundial
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?
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
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?
wrong channel
@snow swift was that in reference to me, if so what would be more appropriate?
# best algorythim in the world
print("Hello World!")
True!
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
@dusk estuary that was for diamond, but ig it also applies to you
#data-science-and-ml maybe
well its graphics with data with perlin which is an alg so IDK?
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
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
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
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?
My questions are so dumb π’
@covert scaffold not really a dumb question but for future reference
#data-science-and-ml will probably be better
for dataframe questions
any good covid algos
@brave oak like a normal graph tree
n nodes with n - 1 edges, only 1 path from a node to any other
n nodes with n - 1 edges, only 1 path from a node to any other
@eager hamlet so no other constraints?
uh yeah...?
don't think so
Is this the right spot to ask about setting the arguments to a function? Or should I go to another channel
If you're talking about a specific coding-related issue you are unsure of, it would be better to use a Python help channel
(See #βο½how-to-get-help)
Thank you
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 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
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 Thank you !
!code
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.
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
@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.
where should i post it?
@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.
π
I know fundamentals can create command line apps
have you learned loops and control flow?
Yea
algorithms illuminated is ok
web scraping is relatively simple
I watched keith galli's videos on youtube
he explains it really well
π
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!!
Has anyone ever done Dijkstra's algorithm using a dictionary as the graph ?
bruh
bruh
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:
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
@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()]
Problem is not visible now. Please try again later.
print(β9 * 2) why does this not work?
My guess is that β9 is not defined
Anyone else know about Abstract graph transformation to derived boolean logic?
that's not a valid operator in python
how do i make this rectangle around my text in discord?
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
in pycharm how do i exit a "project" i want to start a new one
uhh go to #ot0-psvmβs-eternal-disapproval
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
Why is a counter used here? what are you counting?
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