#algos-and-data-structs
1 messages Β· Page 97 of 1
@austere sparrow :white_check_mark: Your eval job has completed with return code 0.
12586269025
(If you're not familiar with decorator syntax)
def _fib(n):
if n <= 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
fib = cache(_fib)
and in fact, that thing already exists in Python:
import functools
# python3.9+
@functools.cache
def fib(n):
if n <= 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
# before 3.9
@functools.lru_cache(maxsize=None)
def fib(n):
if n <= 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
@feral wadi
umm @functools.cache a syntax?
What's wrong with it?
i've never used that one
If you're not familiar with decorators:
@decorator
def f(x):
...
is the same as:
def _f(x):
...
f = decorator(_f)
@feral wadi
yeah i get that now
i wanna get good in algos but most of the time i fail to recognize a problem
I find that a little confusing. Could you explain what the code does?
Well, that's not a piece of working code, just an explanation of syntax. You can read this if you want more info: https://realpython.com/primer-on-python-decorators/
hello guys is there anybody using Leetcode for problem solving
Hello everybody, I was wondering how to create a matrix of 24 rows and 6 columns in Python , cuz as much as I look on google or books are simple arrays
yeah you'd know how to do it if you knew how to do it @mystic basin
the simplest way would be to use two nested for loops. range of 24 for the row and range of 6 for the column
I agree lol
Thanks guys, I solved it, I come from programming in C , Java and JS, and I do not like that a matrix is something not incorporated in pure python .
is [[0 for i in range(24)] for j in range(6)] OK?
does C have a matrix structure?
or you could use numpy
no, neither C nor C++ has one.
I've attended Olympiad in Informatics and had to use C++ in such contests......
When I have to use matrices, I need to write a class on my own...
C and C++ and Java have two-dimensional arrays, which you could use as a matrix
and what is "mtx[rows][cols]" then ?
in C
a two dimensional array.
there are indeed multi-dimensional arrays
but there are no algorithms related to that
such as matrix multiplication, fast power and stuff.
right. A two dimensional array is one potential way to represent a matrix's data, but it is not itself a matrix.
A one dimensional array is also a way to represent a matrix's data.
I wonder why don't they use python instead of C++ in OI contests(
is there a "Graph" structure in python's standard library?
or in any libraries I could download with pip
(the Graph in graph theory
networkx
speed, mainly
Oh, Thx!
there's also https://docs.python.org/3/library/graphlib.html in 3.9 now.
which is limited, but can traverse a DAG in dependency order.
I guess u'r right(
importing numpy takes something like 2.77s
and a common OI problem has a time limit of at most 1s.
that doesn't matter as long as everyone's using the same language - they can just adjust the limits accordingly.
but in competitive programming situations where you can choose the language you use, you probably shouldn't choose Python if your competitors can use C++
yeah
it's pretty common for a bad C++ algorithm to run faster than a good Python one.
and #include <bits/stdc++.h> is pretty close to from * import *, heh - handy for reducing typing when time is on the line
C++ even has optimise(2) or optimise(3) to increase its speed
#include command does the import operation when compiling
(while python does no compiling work
yeah u can tell the complier to optimize ur code
a = [[0] * 6] * 24
EDIT: oops. i was too late apparently.
yep. what's up?
How difficult is a monte carlo tree search and does anyone have any good resources on them?
I guess "Monte Carlo" is a sort of random algorithm
and I'm pretty bad at random algorithms, so maybe I can't help you (sad
Hello, I have a stupid question about arrays, can i ask it here ? ^^
yes
it's almost exclusively what we do here. ask away π
I have a question about json.loads(). I guess everyone has experienced once, but I can't find a solution...
import json
jsonString = '{"employees": [{"name": "John Watson", "dateOfJoin": "01/01/2018", "active2": True, "awards": None}]}'
_json = json.loads(jsonString)
print(_json["employees"][0]["name"])
```raises```arm
JSONDecodeError("Expecting value", s, err.value) from None
I have no idea what wrong.
Thanks in advance!
What are True and None values in your JSON?
JSON notation uses rather true and null
lol thanks so much
Your welcome
hi
hi guys , my recursion with memoization was working fine but suddenly it broke and it raises an error like " RecursionError: maximum recursion depth exceeded in comparison " , i dont understand what did change before the last time because in last time it worked fine , with same input and same func .. Can anybody tell me what happened
Hello guys
for dictionary in db_list:
for key, value in dictionary.items():
print(key, value)
what is a better way to do this?
i have a list of dicts in my db
id like to iterate through them and get the key and value of each dict
this code works, but is there a... nicer? way to do it?
@sleek shale We don't allow recruitment here
https://leetcode.com/problems/serialize-and-deserialize-bst/
guys need help
cant make my preorder recursion
https://leetcode.com/playground/g4DmCxEb
need help understand recursion in python i am screwing up my return statements
how do i send a mail to HackerRank support regarding a correction?
hey guys
i want to find number of "x" in my output
the output is like :
x
x
y
x
now there are three x's here
but i want dont want to count them manually
maybe you can save it as a file and read the file, and
f = open("file.out", r) # assume file.out as the file name
print(f.read().count("x"))
f.close()
or simply use Word
would that be what you want
Could someone tell me if this is an optimal or near-optimal solution for finding if two words are anagrams? ```python
def map_word(word):
words_letters = {}
for letter in word:
if letter not in words_letters:
words_letters[letter] = 1
else:
words_letters[letter] += 1
return words_letters
def are_anagrams(word_one, word_two):
if len(word_one) != len(word_two):
return False
mapped_one, mapped_two = map_word(word_one), map_word(word_two)
for char in mapped_one:
if char not in mapped_one or mapped_one.get(char) != mapped_two.get(char):
return False
return True
if name == "main":
word_one = "racecar"
word_two = "carcear"
print(are_anagrams(word_one, word_two))```
I understand there are good solutions which involve sorting a list of the letters for each word but this feels like it would be more efficient. Would love to hear someone's take though
if the word is only English words with English alphabet, then you could use a list of length 26
which I think would be faster
the solution that involves sorting that you're talking about is something like
sorted(word1) == sorted(word2)
it sorts twice, so it's O(n log n + m log m)
I guess you could judge whether the words have the same length
before sorting them
and the list version is only O(n)
in your solution, you loop over each character in a string and use in to check if it's in another string, which is O(n^2)
I don't know what I was up to with that statement geez. What if I change this line from if char not in mapped_one or mapped_one.get(char) != mapped_two.get(char): to if mapped_one.get(char) != mapped_two.get(char):
your solution is also not guaranteed to work, i believe
def areAnagrams(a: str, b: str) -> bool:
if len(a) != len(b):
return False
length = len(a)
lsta = [0 for _ in range(26)]
lstb = [0 for _ in range(26)]
for i in range(length):
lsta[ord(a[i]) - 97] += 1
lstb[ord(b[i]) - 97] += 1
return lsta == lstb
Assume they use ASCII
def are_anagrams(first_word: str, second_word: str) -> bool:
return sorted(first_word) == sorted(second_word)
``` lol
This is not as fast as the list version, I believe
since this is O(n log n) and the list is just O(n)
it's probably just as fast for strings under 1000 chars or so, but i'm just guessing
Feels like cheating lol. Just taking a data structs and algorithms course so I'm trying to dip my toes in the proverbial water
yeah, I know the interviewer wouldn't accept this anyways
44 ms, faster than 78.81% of Python3 online submissions for Valid Anagram.
that's kind of sad
well, as an OIer, I think the faster the better lol.
well yeah, but
but I guess using numpy.array will even increase its speed(
probably not
Runtime: 52 ms, faster than 50.39% of Python3 online submissions for Valid Anagram.
Guess I have a lot to learn this semster π Thanks everyone for the input
!e
def areAnagrams(a: str, b: str) -> bool:
if len(a) != len(b):
return False
length = len(a)
lsta = [0 for _ in range(26)]
lstb = [0 for _ in range(26)]
for i in range(length):
lsta[ord(a[i]) - 97] += 1
lstb[ord(b[i]) - 97] += 1
return lsta == lstb
print(areAnagrams("abc", "cba"))
You are not allowed to use that command here. Please use the #bot-commands channel instead.
you should ignore these messages from leet. the interviewer only cares about the theoretical time complexity
Runtime: 40 ms, faster than 88.91% of Python3 online submissions for Valid Anagram. it's a stupid question to be honest. you can't handicap people from using the built in tools of their language of choice
that was the runtime for your counter solution
well it was the same speed as my solution using sorted, so i just assume their test cases weren't large enough to make a difference
I guess anyway the words are pretty short
longest common words are something like 20 or 30 letters.
they didn't have to be actual words though, could just have been long strings
yes
not the most efficient way but clever indeed
Counter is linear
indeed
dm @fallow ginkgo to report @dense mauve
could anyone here help me solve a recursion problem in #help-popcorn ?
You're asking in the wrong channel, but write pass inside login
this is kind of unclear to me, but does anyone know, in ant colony optimization algos, is the pheromone matrix initialized to 0, or some non-zero positive value?
having it be all 0's at the start would require some sort of special case for picking the next vertex for the ant, no?
and it would mean that whatever paths the first ants choose and then deposit the pheromones on, if there are any edges with 0 pheromones left after that, they will always have 0% probability to get chosen compared to any other edges with any amount of pheromone on them
or am i misunderstanding something
hello just wondering if anyone knows how to implement a functional recursive merge sort in python?
i'm sure a few people do
i'm tying to make one right now but there's always an error when I try to use the len() function on the arrays that i pass in the parameters
Hey @valid coral
Perhaps they are iterables (can be iterated with a for loop), but not sequences (can be accessed by index with [] and have a defined length)?
Do you get an error message like this? ```
TypeError: object of type 'generator' has no len()
yeaaa object of type 'NoneType' has no len()
your functions need to return something
I am guessing you have something like
def fun():
if ...:
...
fun()
``` where you need
```py
def fun():
if ...:
...
return fun()
Can someone explain why we need to use gradient descent, for example for linear regression, when we can just take the derivative of the function and see where it = 0?
because there is no easy way to compute the derivative of the function.
so if our error function was only, say 3D, then would that be a feasible solution?
in other words, if we only had 2 features in our data set
because the derivative function would be a single variable equation..?
oop nvm im wrong about that
remember that the function you use gradient descent to take the derivative of takes all of your network parameters as arguments and outputs the error over some slice of the dataset.
ok...what do you mean some slice? doesnt it use the whole dataset for its parameters?
not always, it can often yield better results if you descend after only going through part of the dataset, or even only one datapoint since it much more performant, though this is more a topic for #data-science-and-ml
let's say I wanted to search if a phrase (string/rope/...) is a subsequence of several other stored phrases (subsequence in the can you remove elements to get the sequence). I know of the dynamic programming algo for this, but that is for 1:1, but here I have 1 phrase which may be a subsequence of several other phrases, so I wonder if there is some e.g. tree I could build to not have to do
phrases = ["pricey orange grafter"]
for phrase in phrases:
if issubsequence("peter", phrase):
print(phrase)
```. It may turn out fast enough this way, didn't write it yet, but this more of a let's practice algorithms project than a let's get something useful done project
does heapify do heapsort on the array? I am trying to get the next smallest element from heap by interatign thru the heapified array, will go in heapsorted way or do i have to heappop everytime?
generally heapify creates a heap
and i think if u actually want the sorted values u need to pop them all out
yeah, you have to iteratively pop, though I think that is what heapsort does
there is no heap iterator builtin, so you can make your own
def iter_heap(heap):
heapq.heapify(heap) # optional
while heap:
yield heapq.heappop(heap)
you may want to copy the heap as well before depending on your usecase
though why not just use sorted() instead?
Can someone explain why we need to use gradient descent, for example for linear regression, when we can just take the derivative of the function and see where it = 0?
@small drift remember that the equation is overdetermined in the general case
therefore it has no exact solutions
ok thank you!!
Hi! i was actually able to do the merge sort but I need to have the out put where I print the elements of the array after each sort and I'm not really sure where to place the prints :< can anyone help out?
def merge(a, b):
out = []
while (len(a) > 0 and len(b) > 0):
if (a[0] <= b[0]):
out.append(a[0])
a.pop(0)
else:
out.append(b[0])
b.pop(0)
while(len(a) > 0 ):
out.append(a[0])
a.pop(0)
while(len(b) > 0 ):
out.append(b[0])
b.pop(0)
print(out)
return out
def half(arr):
mid = len(arr) // 2
return arr[:int(mid)], arr[int(mid):] # array colon python
def mergesort(arr):
if (len(arr) <= 1):
return arr
left, right = half(arr)
L = mergesort(left)
R = mergesort(right)
#print (merge(L, R))
return merge(L, R)
def inputList(size):
arr = []
for n in range (0, size):
arr.append(int(input()))
return arr
i have this so far with the print in the merge function but it doesn't print everything out
ans = max(helper(k, k), helper(k, k + 1), ans, key=len)
how and why did we use "key=len"?
Whose length is key storing ?how and why did we use "key=len"?
Whose length is key storing ?
we use key=len when we want to compare elements by their length
for example, if we have a list of lists and we want to get the longest one, we write max(lists, key=len)
your code means max(len(helper(k,k)), len(helper(k,k+1)), len(ans))
Thanks for your helpπ
you're welcome!
How does string slicing work in this example s[i + 1 : j] ??
s[i+1:j] returns the substring in s between indexes i+1 (inclusive) and j (exclusive), so it returns {s[i+1], s[i+2], ..., s[j-1]}
so its same for s[i : j+1]?
how do u format it like this or is it the backticks `
nope s[i:j+1] returns {s[i], s[i+1, ..., s[j]}
yep backticks
ah
Example:
>>> s = "inside code"
>>> i = 1
>>> j = 5
>>> s[i+1:j]
<<< "sid"
>>> s[i:j+1]
<<< "nside"
the second one?
The second one looks cleaner
How coarse should a lexer be? Should every operator get its own token or should they be grouped e.g. a token encompassing all binary operators?
hello everyone , i just start to learn data-struct
i install a repo to record my study
can someone help me to do code review?
thanks a lot
csv = """AACG, 01/02/2015, $4.7
AACG, 01/02/2018, $5.43
AACG, 01/02/2019, $0.94
AACG, 01/02/2020, $1.35
AACG, 01/31/2017, $3.04
AACG, 01/31/2018, $5
AACG, 01/31/2019, $1.08
AACG, 01/31/2020, $1.1569
NWS, 01/20/2017, $12.35
NWS, 01/21/2014, $16.76
NWS, 01/21/2015, $14.45
NWS, 01/21/2016, $12.72
NWS, 09/27/2019, $14.17
NWS, 09/28/2015, $12.44
NWS, 09/28/2016, $14.27
NWS, 09/28/2017, $13.65""".split('\n')
csv.sort(key=lambda x: datetime.datetime.strptime(x.split(', ')[1], '%m/%d/%Y'))```
Are there any Python packages or other software/tools that will return the discrete form of a differential equation?
how do I write the label for a matplotlib chart? I have r"$a_y$ in $\frac{m}{s^2}$" but i want the m ans s to be straight up (not like a variable) because they are units
r"$a_y$ in $\frac{\mathregular{m}}{mathregular {s^2}}$" worked.
(if i should delete my messages pls tell me)
mynumbers = [15, 12, 2, 6, 10, 20, 1, 4, 21, 18, 5, 14, 3]
for i in range(len(mynumbers) - 1):
minindex = i
j = i + 1
for j in range(j, len(mynumbers)):
if mynumbers[j] < mynumbers[minindex]:
minindex = j
if not minindex == i:
temp = mynumbers[i]
mynumbers[i] = mynumbers[minindex]
mynumbers[minindex] = temp
print(f"The sorted list is {mynumbers}")
My attempt at selection sort...
Is there a more efficient way to do this?
def selection_sort(numbers: list):
for sorted_index, _ in enumerate(numbers):
# get index of smallest element
min_element, min_index = numbers[sorted_index], sorted_index
for index in range(sorted_index, len(numbers)):
min_element, min_index = (numbers[index], index) if numbers[index] < min_element \
else (min_element, min_index)
numbers[sorted_index], numbers[min_index] = numbers[min_index], numbers[sorted_index]
hi, any king of string slicing?
look into the slice() command
formatting: teststring.slice("what to slice by")
Hey guys. I've been stuck on this problem for more than a day now..
hot
how do i create a simple program that calculate the mode of a given number list?
Loop over the list to find how many times each number occurs in it, then loop over the counts to find which number has the most occurrences
from collections import Counter
nums = [5,5,9,6,9,2,7,0,3,3,4,7,5,3,2,1,5,43,7,8]
c = Counter(nums)
mode = c.most_common()[0][0]
print(mode)
Thanks so much
the simplest and probably least algorithmic way is to use mode from the statistics module
Yep but that one was the one in looking for
Does someone know how to turn a set of integeres in a matrix ?
A set? Into a matrix? What order would you arrange them in, and why?
Hi, I've got a question.
Suppose I'm looking at multiple stocks all in the format of [initial price, end price] and given that I have a limited amount of money to buy said stocks once, what is the best way i can calculate which stocks i should buy to maximize profits.
Take note that just doing (end price - initial price) and choosing the most profitable may not necessarily work in all cases
This seems like precisely the https://en.wikipedia.org/wiki/Knapsack_problem.
With profit being the value and initial price being the weight.
wow yeah looks really similar! how did you find out about this knapsack thingy
it's a classic well known problem
My mom wants me to code a program to help her in packaging for exports:
Given a list of items of different weights in grams (example, [6.5, 6,7, 6,7, 7, 7, 8]), pack them into boxes of 100g. The criteria is to pack as many full boxes with exactly 100g (or other weight), and return the list of boxes.
I'm not quite sure how to tackle this problem other than just filling the boxes with the heaviest items first and try every possible combination.
https://en.wikipedia.org/wiki/Bin_packing_problem might help you
In the bin packing problem, items of different volumes must be packed into a finite number of bins or containers each of a fixed given volume in a way that minimizes the number of bins used. In computational complexity theory, it is a combinatorial NP-hard problem. The decision problem (deciding if items will fit into a specified number of bins...
thank you, I will have a read. I see that it seems like an NP-complete problem
you're welcome!
hmmm the heuristic algorithms don't guarantee (unless I misread) filling up most boxes to max weight though, it's more like minimizing the boxes used but not filling them up to the brim
I feel like my problem is slightly different
need help
why do we have so many sorting methods. Just do bogosort and be lucky like me and it'll sort in O(1)
def sorted(L):
return L
Timsort - Python's default sorting algorithm - basically does that. If the data is already sorted, Timsort is O(n)
How should i seperate the items in this list so that i can print each out individually
Anyone help?
this thread is cool! i'm learning so much. thanks π
@shrewd solar u looking kinda cute ngl
thanks grapes
How long did y'all take to get a decent grasp on DSA ??
A list that you can append into a 3 x 3 matrix.
Data structures didn't take me much work. I understood most of them the first time I was taught them, including what operations were efficient and what operations weren't on each. Learning algorithms was much harder for me. It took a year or two of different classes discussing big o notation before I really was comfortable with it and could reason about it.
In retrospect, the more theoretical aspects of computer science were always much harder for me to grasp and internalize than the more practical aspects, so it's not surprising that algos was tougher for me than data structures.
can this be condensed into a single line list comprehension?
tempsls.append(file_io.read_cpu(i))```
Where templs is an empty list and file_io.read_cpu(i) returns a floating point value
yeah if u loop and append u can list comp
i think it would be templs = [file_io.read_cpu(i) for i in [8,12,16,20]]
need some help
I would love to try to help :D
its going in a infinite loop
can some one help me with this problem
it goes to infinte loop
I would suggest adding whitespace, makes code a lot easier to read.
What exactly are you trying to do here?
im just thinking
if none of the if and elif work
like the first if evaluates to false
and the elif also evaluates to false
the whole thing is a while true loop
Exactly, there's no default else case.
oh i just saw the dude's question in general
he wants to sort the squares of the numbers
i personally would first square the numbers ie doing a map using lambda x: x**2 on the list
and then doing ur sort on the newly created list
@lyric bramble just to ping u about the question u had
yes but its going to an infinite loop
how is that an infinate loop
the output section is blank
and make a new list
ok
by squaring each value in the list
ok
oh wait ur code actually isnt totally wrong
but buddy i need a linear solution
sorting will never be linear
with squaring and then sorting i would get o(nlogn)
ur just implementing the sorting wrong
but im not sorting
like ur quicksort that u made is wrong
im just comparing the values, which is bigger gets appended first
How does that sort the array?
so ur basically trying to find the biggest value
and append that first
and doing that for the entire array
well thats getting u quadratic
not linear
^
yessss
dude
ur not getting linear runtime by doing that
and sorting will never be linear
if u do comparision
You can't get a linear comparative sort
If you do something like radix you can get close
so my code will go quadratic??
n + n-1 + n-2 + ... + 2 + 1
is what ur code is doing
if ur finding max
and appending to list
until the initial list is empty
oh damn and that is o(n^2)
It's called selection sort
lmao facts
(Technical Interview Study Guide Available)
Patreon - https://www.patreon.com/nick_white?al...
Discord - https://discord.gg/2f2Tgy3
Twitch - https://www.twitch.tv/nickwhitettv
Twitter - https://twitter.com/nicholaswwhite
Instagram - https://instagram.com/nickwwhite
LinkedIn - https://bit.ly/37AEo5j
Github - https://github.com/white105
Beco...
see this video
he says its o(n)
lmaooooo
You're getting a sorted input, so the largest square at any point in time is at either end
exactly
Yeah so you didn't tell the entire question till now lmao
The fact that the input is sorted makes a huge difference
yea ur righr
okay ur code now makes more sense
oh so u werent aware it was sorted?
I mean, you didn't mention it so we couldn't have known
Cool
ur idea is right
u compare the ends with each other
and keep on doing it till u meet
also i noticed
y dont u use append
ur repeatedly inserting into the first index
with insert(0, value)
bocz im sorting from desceding to ascending
actually it makes it much faster, since insert(0, val) is very slow
compared to append
but then it would get sorted in reverse manner
well im not sure about its exact implementation
either it does a backwards iteration and appends
ok
list.reverse is linear time
and not really worried about actual running time in terms of seconds
u know whats the actual issue with ur code
its the inequalites
what if the two numbers at the ends are equal
omgggggg
def sort_sq(arr):
n = []
low,high = 0,len(arr)-1
while low <= high :
if arr[low]**2 >= arr[high]**2:
n.append(arr[low]**2)
low += 1
elif arr[low]**2 <= arr[high]**2:
n.append(arr[high]**2)
high -= 1
n.reverse()
print(n)
this is my code now
im appending both
and the second = in the elif is unneccessary
order doesnt matter
bc the first if would capture the equals
yes
i mean u can still do a insert(0,val)
no ill dothe reverse
yeah either have the equal in the if or elif
and the elif can be turned into an else
bc its either less than or equal which is captured in the if
or its greater than
changed it
def sort_sq(arr):
n = []
low,high = 0,len(arr)-1
while low <= high :
if arr[low]2 >= arr[high]**2:
n.append(arr[low]**2)
low += 1
else:
n.append(arr[high]**2)
high -= 1
n.reverse()
print(n)
this is my version
which is basically what u did
correct
thanks
could u help me w one more problem
Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
look into itertools.groupby
i want to implement it on my own
use a for loop while recording the current character and the number of instances you've seen
A good way would be to use nested loops
And u can speed it up by skipping indexes
Is what I feel
Hello guys. There's this piece of code:
def productSum(array, multiplier = 1):
sum = 0
for element in array:
if type(element) is list:
sum += productSum(element, multiplier + 1)
else:
sum += element
return sum * multiplier
That I'd like to turn into this:
def productSum(array):
currentSum
productSumHelper(array, 1, 0)
return currentSum
def productSumHelper(array, multiplier, currentSum):
for i in range(len(array) - 1):
if type(i) is list:
sum+= productSumHelper(array, multiplier + 1, currentSum)
else:
currentSum += i
return currentSum * multiplier
Right now I'm getting compilation errors of currentSum not being defined. But if I set it to zero then the entire thing returns 0. What's the correct way of doing it?
Please ping me
def selection_sort(arr):
start = 0
while start < len(arr):
min_item = min(arr[start:])
index = arr.index(min_item)
arr[start],arr[index] = arr[index],arr[start]
start+= 1
return arr
what is the time complexitiy of this program??
O(1) space since you're not storing anything extra and O(n) time since you're just going through the input without anything crazy
is this the correct method of implementation of insertion sort
bcoz traditionaly its o(n^2)
Oh yeah I'm sorry, it's n^2 actually, you're right
could u explain how is it o(n^2)
I don't know about your implementation specifically, I'm not very well versed in python
It's 0(1) Space because you're not storing anything. And O(N^2) time. N is the size of your input. And it's N^2 because you keep re iterating through the unsorted part of the list
ok
I'm pretty sure your implementation is wrong because there has to be a double for loop which is also an indicator that the complexity is n^2
this uses .index to find elements inside the inner loop, so it's O(n) for each iteration, for a total of O(n^2)
(don't have input on whether it's correct, mind, but it's O(n^2))
@stiff pewter Its O(n^2) time because you get a sum 1 + 2 + ... + n = n(n-1)/2 = O(n^2)
@lyric bramble
Oh wait, yeah ConfusedReptile is correct. However, properly implamented you get a sum as described above.
Do u guys have any website/video/book suggestions to learn about algorithm, data structure, the inside and out of cs?
so im doing quick sort right now, and this is the part i dont understand
p = partition(array, start, end)
quick_sort(array, start, p-1)
quick_sort(array, p+1, end)
Quick sort is what's known as a divide and conquer algorithm.
It choses a pivot element and creates two arrays to hold numbers less than and greater than the pivot.
It then uses recursion to sort the two arrays.
so it sorts before the pivot and after the pivot in this case it seems
but what does it return when it is sorting before/after and also how does it combine everything
every time you call the partition function, it places the pivot in the correct location of the array. in other words, it takes the pivot point and places it in the correct sorted order.
hey can someone help me with understand a hash func from an ctf. i have the answer and it is not sitll happening
plz
Hey, is https://realpython.com/python-matplotlib-guide/ a good place to learn matploit or do you guys advice another ??
Hi guys.I'm new here. I've been learning python for more than a month. Is it right time to start learning data structure and algorithms. If yes, how should I study?
Hey #data-science-and-ml is probably a better place to ask this.
It might be worthwhile learning a bit about algorithms. Certainly it would help to understand what the different data structures python provides do.
For example, when and why you might use a dictionary or set instead of a list.
I cant able to solve a single problem easy in hanckerank
hey lx, where would I go with my qestion
I have to refer solutions everytime
Erm, maybe open a help channel. Be sure to post the question rather than 'asking to ask', as you'll get more responses that way.
kk
See #βο½how-to-get-help if you don't know how to claim a channel.
That's fairly normal starting out. Solving even the 'easy' questions might require some knowledge of things like 'asymptotic runtime' and some data-structures.
You might not be quite ready to dive into algorithms if you've only been programming for a month, but it depends.
What resources have you been using to learn?
Book - automating the boring stuff with python(only theory)
Oh right. That book is often recommended.
ofc sorry
Are you making much progress?
I would maybe work all the way through that book before moving on to programming challenge websites like HackerRank.
And maybe do a couple of small projects.
After that, Khan Academy have a nice introduction to algorithms course online. Unfortunately the programming challenges are in Javascript, but you can skip those (or try doing them in python on your own computer and posting your answers here for feedback).
just to clarify this is O(n^2) due to having N loops through the list and then inside the loop having another pass through the same list (min and index)
Thanks, I'll try to do that
guys how do I make this more efficient so that I can find the sum of all prime number till 2 million
[10:32 PM]
num_l=[]
y = int(input("enter till what number do you want the sum"))
for count in range(0,y):
num_l.append(count)
total = 0
for counter in range(0,y):
num = num_l[counter]
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
total = total + num
print(total)
rip no one is answerin
so the reason why this:
list1 = [1, 3]
list2 = list1
list1[1] = 4
print(list2)```
returns
[1,4]
instead of
[1,3]
is bc python is a dynamic language or something else?
= never copies, it just makes list2 refer to the same list as list1 does
you need to redefine one of them so that they don't have the same reference anymore
makes sense
or use list2 = list1.copy()
its more just trying to understand the limits than a specific purpose
but good to know
that i can also do that
thanks
you're welcome

related to the topic: don't use * operator with a mutable element (e.g.: list)
[[]*10] for example is just creating a list of 10 lists that have the same reference
write [[] for i in range(10)] instead
mutable my bad
oh gotcha
got it
yeah it gets messy when you throw arrays in there

but numpy has some cool functions
So I'm trying to do something interesting
My class played a bunch of games w/ each other and recorded down who beat who
for example person A beat C, person C beat B, A beat B, etc
I was trying to see who was best/worst using a topological sort but it seems to not actually possible to write it that way in this case
so then does anyone know if there's some way I can take these relationships and extract a few cycles sorta like a circular topological sort
so in this case A -> C -> B -> A ...
i thought about this a bit and i'm not even sure whether an ordering like that would be well defined but ummm
if anyone has any ideas please lmk
Can someone help me better understand how to implement BFS?
Like problems with explained code
i mean one way is have a queue
u start at a vertex
and u append all the neighboring vertex to the queue
and u loop though till queue is empty
Hey, do you know about how chess players are ranked? You could try something similar to that maybe.
Hey, what is it you're having trouble with? I can show you a really simple way to implement a BFS, if you like?
The pagerank algorithm may even provide an interesting metric.
I find the simplest way to implement bfs is to go level-by-level: ```python
def bfs(start: T, goal: T, successor_fn: Callable[[T], Set[T]]):
level = {start}
visited = {start}
depth = 0
while level:
if goal in level:
return depth
level = set.union(*map(successor_fn, level)) - visited
visited |= level
depth += 1
can anyone suggest me some good resources to learn algorithms and data structures
I don't know any courses, but Introduction to Algorithms (Cormen, Leiserson, Rivest, Stein) is a popular book.
Though one problem in learning DSA in Python is that manually implementing DSes (like many courses involve) in Python will result in very inefficient ones. It's not really a big problem, though.
can someone PLEASE help me with hash funktiosns
i have one from a ctf last year with answer but id ont understa
ply
What's your question?
I posted it a while back want me to ss you what i posted
a possible implementation is by using a heap, and there exists the module heapq for that
I'm sorry, but what is start : T. What object is T? And what is Callable[[T], Set[T]]. Sorry im a bit new to algos and stuff
append does not return the list, so remove ts2 =
oh okay thanks
quick question. why code in the photo outputs this?
I wanted the output to be [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]]
Can anyone help me for the right output?
add print(cols) after
never use * operator with mutable element
I don't get it. why do we add print(cols)? it will be just 5
then what should I use without using numpy?
[[0]*cols for i in range(rows)]
isn't that the same thing?
nope because * operator will give the same reference to all the lists
but list comprehension will create rows distinct lists
I don't think so
got it. Thanks let me try it if it has all different references
then can you persuade me?
'a'*n will create a string of length n, so it probably has a time complexity of O(n)
so you are saying that list multiplication is O(n)
I think it makes sense if each list should be aligned in a list. that could be O(n). Thanks
maybe O(nm), where m is the length of the multiplied element
like if you're doing s*n where s is a string of length m and n the number of repetitions, you get an O(nm) time complexity
Check out the linked course in the channel pin. I also quite like Khan Academy's intro to algorithms course; the exercises are in Javascript, but you can skip them.
Ah, sorry, those are type hints. The T is a type variable. What it says is that start and goal have the same type, T, and that successor_fn is a function which takes an object of type T and returns a set of objects of type T.
So, start and goal are the starting node, and the goal node.
And successor_fn is a function that takes a node and returns a set containing its 'successors' (these could be e.g. neighbours, in a maze problem).
Hey, any good sites or recources for learning/practicing algorithms? I wanna get into AI and I dont know any good place to start
algoexpert?
y would u go to algoexpert
its literally paying for a service that u can get free else where
i dont know bro its just the only one i can think of off the top of my head
those yt ads indoctrinating u
yeah but those are coding challenges, isnt algosexpert specifically for data structures and algos
i mean
When doing gradient descent for categorical cross entropy, is the loss function summed up over all samples or is it just per sample? I am kind of confused on how to calculate loss with multiple inputs..can someone explain?
Please do not use this server to advertise for your business. It is against our rules here.
Hi everyone, I am stuck on a activity. I 250 for the area walls apparently there is more to it. I don't know how to correctly get the 2nd answer I tried substituting the 250 gotten a totally different answer.
remove line 4 in your code
@smoky chasm
and line 6
4 is the one causing error, but 6 is not needed in the code
np
Hey, youβre more likely to get a response in #databases
Does someone know how can I print out the process a memory address belongs to?
I don't even know if it's possible but would be great if it is
You want to know how virtual memory maps to physical memory?
That might be more suitable for #unix, assuming you're talking about Linux. I'm not sure this is really the right forum to ask this though, as python programming mostly deals with higher-level stuff.
??
oh, i'm on windows
There is a module called pymem which is an wrapping for the ctypes module, allows reading and writing to memory addresses
but i'd like to figure out how to print out what process module a mem address belongs to
I'm not sure if this fits here, but I have a program that automatically adds a stat (it's user count and current UTC timestamp) to a csv file. I then want to display the user count over time using matplotlib.
My problem is I now have more than 1300 samples, and the matplotlib graph is fairly long to generate. How could I "reduce the resolution" of the list by taking 500 elements that are representative of the list ?
I could remove half of the list by keeping only the values that have an even index for example, but this will get an issue again when I will hit 2600 samples...
How could I get a number of samples always between 500 and 1000 ?
you can for example generate x indices between where x is between 500 and 1000
I finally found a solution
step_size = len(base_list) // 500
usercount = usercount[::step_size]
or
>>> random.sample(range(1, 100), 3)
[77, 52, 45]```
replace 100 by the length of your data and 3 by how many numbers you want to generate
I think random sampling will not necessarily always be the best solution to get an accurate representation of the list
I would like the list to reduce it's resolution but keep the same space between samples
Δ±'m stuck when Δ± try to create a tree with my inputs can anyone help me
[('bike', {'wheel': 2, 'frame': 1}), ('wheel', {'rim': 1, 'spoke': 1, 'hub': 1}), ('rim', 60.0), ('spoke', 120.0), ('hub', {'gear': 2, 'axle': 1}), ('gear', 25.0), ('axle', {'bolt': 5, 'nut': 7}), ('bolt', 0.1), ('nut', 0.15), ('frame', {'rearframe': 1, 'frontframe': 1}), ('rearframe', 175.0), ('frontframe', {'fork': 1, 'handle': 2}), ('fork', 22.5), ('handle', 10.0)]
what should I do
wheel and frame are the children of bike right?
yes
what does 22.5 mean in fork?
their cost when Δ± have to calculate the complete bike cost
using tree is mandatory for this problem
okay so you want to actually build the tree right?
your tuples can either be (str,float) or (str,dict) where dict contins the children right?
this is sample input input are depend on user
yep
do anyone have suggest?
I recommend using a dictionary here.
tree_dict={'bike': {'wheel': 2, 'frame': 1}, 'wheel': {'rim': 1, 'spoke': 1, 'hub': 1}, 'rim': 60.0, 'spoke': 120.0, 'hub': {'gear': 2, 'axle': 1}, 'gear': 25.0, 'axle': {'bolt': 5, 'nut': 7}, 'bolt': 0.1, 'nut': 0.15, 'frame': {'rearframe': 1, 'frontframe': 1}, 'rearframe': 175.0, 'frontframe': {'fork': 1, 'handle': 2}, 'fork': 22.5, 'handle': 10.0}
Access it by:
Example: tree_dict["bike"]
Not sure if I am going in the right direction :)
can someone here help with a quick question, its about stacks
yes then
tree = Tree(root_name)
if isinstance(tree_dict[root_name], dict):
for key in dict.keys():
tree.children.append(build_tree(key, tree_dict)
return tree
I do not understand your question. what do you mean by create a tree? there is no such data structure as tree in python
you can have a nested dictionary, probably:
{'bike': {
'wheel': {
'tyre': 'value',
...,
},
'frame': {
'child': 'value',
...,
},
...,
}
I want to do exactly like that
Δ°t is my actual input list
I have to convert it to tree
First Δ± tried to make children dictionary but Δ± confused
hey, so i am trying to learn some sorting algorithms right now, and i learned selection sort and bubble sort. i was told that the advantage of bubble sort over selection sort is that in the best case, bubble sort will be more efficient because you have the ability stop the alg whenever you don't need to sort it anymore. my question is why can't you implement this in selection sort?
In bubble sort, you can detect the "already sorted" condition by noticing that you made it through a full iteration over the container without performing any swaps. There's no efficient way to detect that condition for selection sort.
For bubble sort, if the inner loop performs no swaps, the list is sorted. For selection sort, if the inner loop performs no swap, the i'th element was already in the right position
That doesn't imply anything about whether the (i+1)th element is in the right position
I see a pattern here, so try using it in a loop
I use other languages han python ... can someone let me know why this doesn't work?
def climb_stairs(n):
dp[0] = 1
dp[1] = 1
for i in range(2,n):
dp[n] = dp[n-1] + dp[n-2]
return dp
I get a NameError ... I would like to be able to write code like this with lists
pretty sure that wouldn't work in other languages either
you have to define dp before you can use it
your list only contains 2 items, but you are trying to use 3
yes, and the name is not defined, of course
it would certainly work in Matlab ...
[dp] = function climb_stairs(n)
dp(1) = 1; dp(2) = 1;
for i = 3:n
dp(n) = dp(n-1) + dp(n-2);
end
that's basically what I'd like to do
well, i'm not very familiar with matlab
where is this line [dp] = function climb_stairs(n) in your python snippet ?
oh, this is a function signature π
if you can explain what that matlab code does, I may try to make a python of it
you basically have a vector that you make within your function for the first two cases of dp
In Go it would be "dp := make([]int, n+1)
dp[0] = 1
dp[1] = 1" ...
u just want to say ok i know the base value
for dp[0] and dp[1] are equal to zero
and then just run a loop that takes the value of n
so, you also need to define dp in python, which you did not do
in you case it would probably, be dp = []
gotcha
I actually get:
"---> 16 dp[0] = 1
17 dp[1] = 1
18 for i in range(2,n):
IndexError: list assignment index out of range
"
because you only have 2 items in your list, but you are trying to use 3
yes, because you onl have 2 items in your list
well actually, he has zero items
so trying dp[0] will error
you could do dp = [0] * n for a list with length n
adding items to a list you need to use append
i understand now, what you are trying to do
just use append - should work
but initailly you can just do dp = [0, 1]
or whatever your values are
yes
perfect, thanks
also wrote i instead of n
works fine
just out of curiousity why can't you just do:
"dp[n] = (dp[n-1] + dp[n-2])"? why do you need to do append?
because doing dp[n] you are getting an existing element with index n
anyone know how to solve this
In this exercise, you are going to count by 2, starting at 2 and ending with the provided number.
You should return the numbers as a space seperated string.
Example:
count_by_two(10) --> "2 4 6 8 10 "
count_by_two(4) --> "2 4 "
What do you mean
For example
each of the internal lists has a name as a first item and some tuples as the other items.
so, the tuples are, probably, the children π
= [["rearframe", 175.0], ["bike", (2, "wheel"), (1, "frame")],
["frontframe", (1, "fork"), (2, "handle")], ["hub", (2, "gear"), (1, "axle")],
["fork", 22.5], ["nut", 0.15], ["rim", 60.0], ["axle", (5, "bolt"), (7, "nut")],
["handle", 10.0], ["frame", (1, "rearframe"), (1, "frontframe")], ["bolt", 0.1],
["spoke", 120.0], ["gear", 25.0], ["wheel", (1, "rim"), (1, "spoke"), (1, "hub")]] the list is not ordered is it problem
So you say Δ± donβt have to use dictionary
no, you, probably, have to use dictionaries, but there is an easy way to create a function, which will do this for you for this data structure
i guess all that effectively means is you always have to pre-allocate if you want to do that ... which is fine I guess, it's good practice.
hey guys
and gals, hey people, ok here goes my question:
So, let's say that we have a system that count resources needed for tasks, let's say ovens, i distribute the work in 15 minutes buckets, but i need to identify which ovens are made available in the middle of the 15 minute bucket. So I have oven tasks finishing withing the 15 minute time range and others starting within, so by looping through the list i can see which ovens i can reutilize hence minimizing the total ovens needed
is there a good algo based way to do this?
currently I looped through the ones that finish before others start and then store in a list the "reused oens" that way I dont assign a nnon existen new oven task to the 3rd oven in this example
Hmm, it sounds like an easier variant of https://en.wikipedia.org/wiki/Job_shop_scheduling, but I'm not sure.
I need some help who can help me to solve about data structure
part_lisr= [["bike", (2, "wheel"), (1, "frame")],["wheel", (1, "rim"), (1, "spoke"),
(1, "hub")],["rim", 60.],["spoke", 120.],["hub", (2, "gear"), (1, "axle")],
["gear", 25.],["axle", (5, "bolt"), (7, "nut")],["bolt", 0.1],["nut", 0.15],
["frame", (1, "rearframe"), (1, "frontframe")],["rearframe", 175.],
["frontframe", (1, "fork"), (2, "handle")],["fork", 22.5],["handle", 10.]]
this is input
but output have to be like this
formatted=["bike",[2,"wheel",[1,"rim",[60.0]],[1,"spoke"[120.]],[1,"hub",[2,"gear",[25.]],[1,"axle",[5,"bolt"[0.1]],[7,"nut",[0.15]]]]], [1,"frame",[1,"rearframe",[175.]],[1,"frontframe",[1,"fork",[22.5]],[2,"handle",[10.]]]]]
how can I write this algorithm
Ummm... What
I have a question for people who learn programming in schools, as someone who just read books in spare time.
Why do you so often see people ask questions like, "Does anyone know a good course to study algorithms and data structures in Python that is beginner friendly?"
What does this mean? Why do they always specify these two things together. If they just learn python, they'll learn lists, dicts, etc.
Do they want to know sorting algorithms? If so, why dont they say that instead of "algos and data structs"
I have to assume this is something that is common for a university course to be called.
I was learning Python for four months plus, and had my fundies down before I ever tackled a recursion. Whatever it is, I doubt I'll ever find a use case for it as a freelancer or on my own project.
I think the algs are really for those looking to get into traditional work with start-ups and such, because they use them to filter applicants in interviews.
After doing some reading in seems like "algos and data structs" is what people say when they mean "mathematical computer science"
So yeah.
I think that recursion is more than just a function calling itself, it's a way of thinking, it gives you the ability to decompose a problem into multiple instances of the same problem, which is useful sometimes
Oh yeah. I'm glad I studied it. It def forces you to think in a non-traditional way. I like any structure/problem that allows you to have an epiphany, when you finally "get it". Unlike syntax rules, which erodes through lack of use, once you really understand recursion, or something similar, you usually don't forget it.
Just today I came upon a Singleton method using a new-type object in some open source code. I didn't even know WTH a singleton was, really. One thing about coding, is if you love learning, you are going to love coding.
!range
Iterating over range(len(...)) is a common approach to accessing each item in an ordered collection.
for i in range(len(my_list)):
do_something(my_list[i])
The pythonic syntax is much simpler, and is guaranteed to produce elements in the same order:
for item in my_list:
do_something(item)
Python has other solutions for cases when the index itself might be needed. To get the element at the same index from two or more lists, use zip. To get both the index and the element at that index, use enumerate.
sometimes it's a shorthand for "mathematical computer science", but it's more than just that. If you just learn Python, yes, you'll learn lists and dicts, but you won't learn how lists and dicts work. At most, you'll learn that dicts require keys to be hashable, and that immutable objects like strings and ints and tuples are hashable. You won't learn what a hash table is, or how it works, or which operations are fast on a hash table and which are slow, or why hashability is useful and why dicts require it. Likewise, you won't learn that a list is a dynamic array, and that each time it needs to grow it grows itself by some factor (50% larger on each resize, or 100% larger, or whatever) in order to achieve amortized constant time appends to the end of a list. Or that removing things from the start of a large list is very slow.
when someone says that they want to learn Python data structures, they might mean that they want to learn how to use Python's builtin data structures, but when someone says that they want to learn data structures and algorithms, it always refers to how the data structures themselves work, and what algorithms they use internally, and what algorithms can be efficiently applied to them.
That fully clears it up. I would say even I dont really know that. I know how to use it, not so much why and how it was designed that way
Hi, I'm looking for some books / video / info or introductions to Data Science or similar. I have a project in mind regarding string manipulation and matching using FuzzyWuzzy. Project is quite huge (lets say over 5k individual strings needs matching against a huge library (> 100k strings), but I need some reading to understand fundamentals. Any recommendations?
what is the time complexity of string concatenation in python
check pdfdrive for e-books
udemy for courses
O(n + m)
, because of which joining N strings of length n is a total of 2n + 3n + ... + N n = O(n N^2). That's why one should use join instead.
(there's an optimization that makes += work in O(m) in some circumstances, but it only works when there's a single reference to the string)
For details on all this, see https://blog.mclemon.io/python-efficient-string-concatenation-in-python-2016-edition.
EDIT: oh damn, the blog got deleted. Thankfully, the Internet remembers: https://web.archive.org/web/20190715231220/http://blog.mclemon.io:80/python-efficient-string-concatenation-in-python-2016-edition
do we have a java channel?
Nope, this is a Python server. There's the offtopic channels, but also, well, there's Java discords.
Is it possible to get the arbitrary precision functionality from decimal module in python to work with GPU using pyCUDA without losing the benefit of a GPU speedup? I do not need to vary the precision across the runs, but I need significantly larger than double precision floats. (Not sure of the appropriate channel)
I'm not expert in this area, but I wouldn't have thought so.
GPUs work mostly on single and double floats.
Are you sure you need that much precision?
I am assuming it must be technically possible to divide a higher precision decimal operation in terms of lower precision floats? Perhaps the decimal module internally does something similar?
But implementing it in C++ from scratch looks like a lot of work. So was wondering if it is possible to avoid that.
Would Numba be any good instead of pyCUDA?
(N3, C, RES) ~ (NI + N2, 0~0);
while (min(Nl, N2) # 0) V (C ~ 0)
do NEXTBIT; (NI, N2) ~ ([N1/2], iN2/21) od;
RLINK[RES] *-- if NI ~ 0 then R1 else R2 fi;
R3 *-- RLINK[0]
endproc UNION
Cam somebody explain me this algorithm
Pls
uhhhhh
idk
also
Curious Folk problem
https://codeforces.com/problemset/problem/1263/D
I don't see how it woudl be possible to solve this in N log(N)
cause don't you need to first make the n^2 connections?
or am I missing something?
It's a bit hard to see the way it is written here.
Can you re-write the pseudocode in a code block?
!code
@keen hearth explain me pls
Sorry, the command didn't work π
I don't understand what some of the symbols in this pseudocode mean, and I'm assuming there's some missing indentation.
Can I send you pics?
Alright π
you do be missing a point, its never N^2 if you only calculate(roughly) equivalence subsets, they're 26(one for each letter) so you have at most 26 passwords that actually matter and at most 26*N checks to make, so basically linear time :D
the data structure needed to proceed after that is DSU, i'm guessing not actually solved the problem yet but i'm pretty sure that a DSU will give the answer :D
I am assuming it must be technically possible to divide a higher precision decimal operation in terms of lower precision floats? Perhaps the decimal module internally does something similar?
But implementing it in C++ from scratch looks like a lot of work. So was wondering if it is possible to avoid that.
@languid onyx I donβt think so...?
because of the bit layout of floats
like I donβt think you would lose the parallelism but youβd need to write a lot of custom code, it seems?
Iβm not a CUDA expert though
ohhh I seee i'm stupid ty so much I really appreciate it! π
no me!
That's not at all how the decimal module works. float is a base 2 floating point number. decimal.Decimal is an base 10 floating point number. You cannot losslessly convert even small Decimal objects, like Decimal("0.3"), to a float.
And GPUs have no facilities for manipulating base 10 floating point numbers, as far as I know.
!e ```py
import decimal
print(decimal.Decimal("0.3") == 0.3)
@lean dome :white_check_mark: Your eval job has completed with return code 0.
False
how would I do this problem:
Hey @kindred coyote!
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:
ping if answer
Can someone explain me why this error comes when I try pickle.loads(f) (I had already created f with a context manager)
_pickle.UnpicklingError: invalid load key, '\x0a
Ping to answer btw
So \x0a is a linefeed character. is the file local? Can you verify the file actually exist and is readable? Able to reproduce on another system?
@fiery cosmos
Base 10 might be how it represents the number but I meant that ultimately the actual calculations must involve integer/float manipulation being done by the CPU, right? And I don't need to convert it into the regular floats at any time. Something like breaking up the significant digits into smaller integer/float chunks based on the prec and then piecewise adding/subtracting/multiplying and then combining the result? No clue how the internals of the Decimal module work though, all is guesswork.
Yes. It appears so. But a related question, unless I am mistaken, Mandelbrot set renders also need higher precision than floats. Don't some of them use GPU? I think I have not seen python versions accelerated by GPU though.
I meant that ultimately the actual calculations must involve integer/float manipulation being done by the CPU, right?
Integer, yes, float, no.
And I don't need to convert it into the regular floats at any time. Something like breaking up the significant digits into smaller integer/float chunks
If you can't losslessly represent a number like 0.3 as a single float, how could you hope to losslessly represent it as the product of multiple floats?
Check out https://en.wikipedia.org/wiki/Decimal_floating_point - it explains how Decimal works.
@lean dome
Thanks! Will check it out.
For my GPU purposes, based on the downstream analysis, the high precision decimal object will give a tiny integer which is the actual output. And that is all I want. Hence if decimal like calculation can be broken into 32-bit ints, I was hoping to do it on a GPU (Nvidia ones can handle 32-bit ints?). But it looks like the decimal module has a lot of padding code surrounding this decimal -> int breakdown on piece-together.
for there to be any hope of accomplishing what you want, you're gonna need to read and internalize that wiki page, and understand how Decimal works. Just like a regular float, it has a sign bit, exponent bits, and significand bits. They're just interpreted in a different way.
And CPUs and GPUs are really fast at working in base 2, and not at working in base 10.
how much higher precision do they need than floats? Note that Python floats are double precision (like C's double, not like C's float).
from what I can find from a quick google, Mandelbrot set renders typically use doubles...
and others use fixed point, instead of floating point.
and CPUs typically have 80 bit floating point registers, which might be able to be used in some cases.
Need around 1.5 times the precision of doubles actually.
On a deeper Mandelbrot zoom, I am sure the doubles would fall short. The 80bit CPU registers is interesting. I'll look more into it. Thanks!
Hey guys can anyone tell my what sort of data this is and point me in the right direction to go learn about it?
-3.200000 -0.480000 -3.040000 -0.480000 -2.720000 c\n-0.320000 -2.560000 -0.160000 -2.400000 0.160000 -2.240000 c\n0.480000 -2.240000 0.800000 -2.080000 1.440000 -1.920000 c\n1.920000 -1.760000 2.240000 -1.600000 2.400000 -1.600000 c\n2.560000 -1.440000 2.720000 -1.280000 2.720000 -1.120000 c\n2.720000 -0.800000 2.560000 -0.640000 2.400000 -0.480000 c\n2.240000 -0.320000 1.920000 -0.320000 1.440000 -0.320000 c\n1.120000 -0.320000 0.800000 -0.320000 0.480000
-0.480000 c\n0.320000 -0.800000
well, where did you get it from?
it's decompressed flatedecode but it doesn't look the same as other decompressed flatedecode
it's normally straight up bytes
mayb u parsed them as floats instead of bytes by accident
guys Δ± have data mining final exam its really important for me to get higer result can sombody help me after 4-5 hour its not long
actually Δ± fucked up in yhe first time
now its make-up exam
!rule 5 @ruby mortar
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.
We will not help with ongoing exams.
In [7]: from random import randrange, choices
In [8]: NODES = list(range(20))
...: my_graph = {node: choices(NODES, k=randrange(2, 6)) for node in NODES}
In [9]: my_graph
Out[9]:
{0: [9, 18],
1: [2, 19, 1],
2: [16, 8, 19, 15],
3: [12, 15, 1, 9, 14],
4: [4, 0, 15, 1, 8],
5: [16, 4, 0, 11],
6: [18, 18],
7: [9, 6],
8: [7, 6, 7],
9: [4, 17, 5, 3],
10: [6, 10, 14, 9, 11],
11: [3, 18, 6, 17],
12: [11, 2, 3],
13: [11, 7, 3, 18],
14: [6, 9, 15, 6],
15: [16, 13],
16: [10, 9, 16],
17: [17, 10, 5, 11, 15],
18: [16, 4, 19, 12],
19: [15, 7]}
note choices needs a sequence so you can't use dictionary keys
In [10]: choices(dict.fromkeys("abcdef"), k=3)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-10-9203d8559d44> in <module>
----> 1 choices(dict.fromkeys("abcdef"), k=3)
...
though you can just use a range object directly, don't need to make a list first
In [14]: range(20)[3]
Out[14]: 3
one doesn't see too many examples of indexing ranges
range objects have some useful features that are a bit esoteric
or at least less used
huh. I always assumed random.choice has a special case for handling range objects, but if they are like this, it might as well just work with them like lists... cool.
I think this is actually a fairly subtle problem.
One sec while I do some research...
Is the desired graph directed or undirected?
Actually, I think I just forgot the meaning of the term 'simple graph' π
it's equivalent to generating a random symmetric matrix with 2-5 nonzero entries in each ro- oh, has to be simple too, yikes.
The thing is, there are probably many different such distributions, with different properties.
Alright, so, I did some reading, and found this algorithm:
- Randomly generate the degree sequence.
- Generate a simple (not necessarily connected) graph with that degree sequence:
2.1) Give each vertex a number of 'stubs' (two stubs connect to make an edge) matching its degree.
2.2) Repeatedly select any vertex, and bind all of its stubs to other vertices' stubs to form edges (always choosing the other vertex with the most stubs left). - Connect the graph, without changing the degree sequence.
- Shuffle the edges to make it random, while keeping it simple and connected.
Here's where I got it from: http://complexnetworks.fr/wp-content/uploads/2011/01/random.pdf
It's the algorithm under the heading "Markov chain Monte-Carlo algorithm"
Generating the degree sequence is just a matter of doing: ```python
degree_sequence = sorted(
random.choices(range(2, 6), k=num_nodes),
reverse=True
)
Then step 2 is the 'Havel-Hakimi algorithm', which is an algorithm to generate a simple graph with the given degree-sequence or prove that one does not exist: https://en.wikipedia.org/wiki/HavelβHakimi_algorithm
I was having a go at implementing it but got distracted sorry π
Yep. I think that's the desired behaviour in this case.
random.sample selects without replacement.
It's generating the degree sequence, which is like the number of edges out of each node.
It's presumably fine for two nodes to have the same degree.
Sorry for mixing the terms node/vertex and edge/arc π
Not sure what you mean. π€
Ah no, this isn't generating the edges themselves, just the number of edges (the degree) of each node.
So it's a random choice from range(2, 6) because each node should have at least 2 edges, and at most 5 edges.
It's just the first step in the algorithm.
Oh, are you talking about the code Salt posted earlier?
The code I posted only generates the degree sequence, which is the degrees of the nodes sorted in reverse order.
For example, this graph has degree sequence [3, 3, 3, 2, 2, 1]
Alright π
Np
Hey, so I was just watching some youtube videos and they mentioned binary search and I had previously heard about it and wanted to make an implementation of it. So I gave it a go. Is this a good implementation or is it bad and hard to read? ```py
#tVal: Target Value
#l: List
#sVal: Smallest Value
#lVal: Largest Value
def binarySearch1(l, tVal, sVal=0, lVal=0, index=0):
if index == 0 and lVal == 0: index, lVal = math.floor((len(l))/2), len(l)
if l[index] == tVal: return index
elif l[index] > tVal: lVal, index = index, math.floor(index/2)
elif l[index] < tVal: sVal, index = index, math.floor((index+lVal)/2)
return binarySearch1(l, tVal, sVal, lVal, index)
Haha yeah, idk as I don't work with other people and I myself just for some reason think it's easier to read I usually condense it like that
Instead of math.floor(a/b), you can do a//b.
Oh okay, thank you. Is it like a to-integer division sign or something?
it's floor division
def binarySearch1(l, tVal, sVal=0, lVal=0, index=0, comp=0):
if index == 0 and lVal == 0: index, lVal = (len(l))//2, len(l)
if l[index] == tVal: return comp
elif l[index] > tVal:
lVal = index+1
elif l[index] < tVal:
sVal = index-1
return binarySearch1(l, tVal, sVal, lVal, (sVal + lVal) // 2, comp+1)
``` Why would the change in the index declaring make such a big difference in the search? It went from averaging about 45 comparisons to 13. The new index declaration is the (sVal + lVal) // 2
Binary search is often a little bit trickier to implement in practice than you would think.
They key thing is to think in terms of an invariant, which is just a property that is guaranteed not to change throughout the execution of the algorithm.
Although you seem to have implemented it recursively.
Oh okay, thanks. Is it bad to use it recursively or would it have any effect?
Hey
Hey
in this case, recursion is slower than iterative
Why would that be?
calling a function is slower than doing another iteration
Then why would someone ever use recursion if they can just use iteration and it would be faster?
recursion is sometime easier to use
readability/maintenance but that's partially subjective
some algorithms break down nicely recursively
Oh okay that makes sense
like tree traversal algorithms
Yeah
hey, is there an algo/data structure that can get all the points (x, y) that are strictly greater than a given point (a, b)?
(ping 2 help thx)
how do you count "strictly greater"
in other words how do you order points
my first impression is Euclidean distance from origin but it could be any metric
uh
oh yeah
(a, b) is strictly greater than (c, d) if a >= c and b >= d
wait sorry
i shouldn't have said strictly greater
just greater than or equal to
hm
okay I just woke up but
it seems to me like a basic BST would work?
you don't really have a total ordering but
you can treat (a, b) and (c, d) where a >= c and d >= b as equal
...does that make sense?
π€
actually
if it's greater than or equal to
that wouldn't work
or
you could have two trees
one for each coordinate
but that would be a lot slower
hm there's probably a better solution
the problem is the ordering
what do you mean by "all the points"? do you have some collection of points and you're trying to find which of them are greater than some reference point?
yeah
here's some context: http://usaco.org/index.php?page=viewproblem2&cpid=995 - don't wanna be asking an XY problem
off the top of my head, two binary search trees - one that is point-by-x, one that is point-by-y. Search the first tree to find all of the points with high enough X, search the second tree to find all of the points with high enough Y, and then take the intersection of the two sets.
hm. isn't this just a graph traversal problem with weighted edges? The only points that are interesting are the start location, the target location, and the start and endpoint of each springboard. There's a cost for getting from each interesting location to each other interesting location, there's some locations that cannot ever reach other locations (since you can't walk or spring backwards), and your goal is to find the path with the lowest cost from the start location to the target location
so that's a directed, acyclic graph, and the weight of any given edge is the amount of moves it takes to reach the latter vertex from the former - either by springing for one action or by walking for (x2-x1 + y2-y1) actions.
granted that's still a graph with up to 20,002 vertices, though - I'm sure it can be simplified further than that...
Ah, you can start building it up from the origin, and then you only need to keep a running tally of the cheapest path from the origin to each other vertex...
Hi, I have a list of times, and I need to calculate the difference between each time, anyone know an easy way to do this that is not too complicated?
[t2 - t1 for t1, t2 in zip(lst[:-1], lst[1:])] perhaps?
!e ```py
lst = [1,2,3,5,7,10]
print([t2 - t1 for t1, t2 in zip(lst[:-1], lst[1:])])
@lean dome :white_check_mark: Your eval job has completed with return code 0.
[1, 1, 2, 2, 3]
also, I just wanted to check if my implementation of building a graph is correct (I know that there isn't a "correct" way of implementing a graph as it is based on a problem, but I am wanting to make sure if my implementation is rarely used or if it can be improved)
social_strucutre = [[1,2],[2,3],[1,4],[5,6],[7,6]]
social_strucutre.sort()
graph = {}
for element in social_strucutre:
if element[0] in graph:
graph[element[0]].append(element[1])
else:
graph[element[0]] = [element[1]]
print(graph)
and that implementation is for the below problem
looks like a typical adjacency list implementation to me @wicked coyote
Bruh use formatted code blocks
hello idk if Im in the right channel but I'm a beginner, and I wanted to make a simple algorithm that generates a password.. and I'm not sure if my method is the most efficient but its kind of well randomized
it looked pretty neat and simple but I'm very sure that it can be easily cracked
by the way, you can use a defaultdict to avoid checking key existence
social_strucutre = [[1,2],[2,3],[1,4],[5,6],[7,6]]
social_strucutre.sort()
graph = defaultdict(lambda: [])
for element in social_strucutre:
graph[element[0]].append(element[1])
print(graph)```
I'm playing around with the mandelbrot set, but I'm not sure how I to do the "zooming" at a specific point? I basically start from -2-2i to 2+2i - I suppose I need to shrink that area for each zoom, right?
hey, super beginner here, is it possible to use python to create a gui that then fill an excel file ? I got a student job and at this place they use a computer with an open excel sheet as a checkout. It's long and boring when people pay because I have to write the type and sub type of item, the price, the amount, et weight, all that manually x)
So I'm wondering if it is possible to easily make a GUI with like dynamic box for the type and subtype and that can calculate the price instead of me
Not #algos-and-data-structs, but yeah, that's possible. The GUI will probably be the most annoying part, as you'll have to learn the basics of some GUI library.
oky, thanks !
Hey, I need some help for a math exercise, and i need Python, but I don't understand how to do it. It's for a square matrix "M" order 2, we note s(M) the sum of the coefficients of M. We consider the matrix A=(1 2)
(3 4)
- Determine s(A^k) for k belonging {1, 2, 3}.
2)Write a python function "seuil (M)" which take for argument a real number superior or equalt to 10 and return the smallest natural number k =>1 as s(A^k)=>M
With the help of this function, determine the smallest natural number k =>1 as s(A^k)=>2021
If someone can help me? It will be super nice
It doesn't sounds like an algorithm problem, really, you just calculate higher and higher powers of A.
numpy will make this trivial. The @ operator is how you do matrix multiplication in it.
But the probleme is, i don't know how to use an Ide Python and i don't know how to write a python functions π
!e
import numpy as np
A = np.array([[1,2],[3,4]])
tot = A
for i in range(5):
print(f"s(A^{i}) = {np.sum(tot)}")
tot @= A
You are not allowed to use that command here. Please use the #bot-commands channel instead.
ah. Yes, that would make things complicated.
!resources, I suppose, but it's hard to learn programming from scratch quickly.
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
!resources, I suppose, but it's hard to learn programming from scratch quickly.
this?
s(A^1) = 10
s(A^2) = 54
s(A^3) = 290
s(A^4) = 1558
is the output
in the function we don't need any return ?
That's not a function, and it's not doing what the second question asks either.
ah
okay
Thanks a lot for the first question π
and for the sencond, do you have any idea ?
I mean, yes, but you're supposed to write it yourself.
The idea is simple though - calculate higher and higher powers of A until you get one with a sum that's >= the number you were passed; return what power that is.
i don't know all the function,
It will help me so much
or anybody else ?
so @vocal gorge do you know how to make the function ?
Hey. It's not a python question, but I'm wondering, how did you understand dynamic programming?
How would I find a path in a tree that involves a specific set of nodes
Let's say this is the tree. How would i find a path that includes [0,6,2,4,3,7]. You can go back from a path as long as you get the nodes
The answer is 6 β 1 β 0 β 2 β 3 β 7 β 3 β 4 but I was curious how they got that answer.
There could be multiple answers ^ but they need to be the shortest path. It could also be 7 > 3 > 4 > 3 > 2 > 0 > 1 > 6, 4 > 3 > 7 > 3 > 2 > 0 > 1 > 6
Forgot to add (yes that's an alt)
I'd just use recursion
Like
- Choose a random node (from list of wanted nodes)
- Run dfs or sth like that
For every instance of dfs, pass an array or sth like that where you can check if node v (from wanted nodes) was visited
Also
always start on a leaf and know that other leaves will add an extra step
Pass a list/vector/array whatever which will keep the path
When you Reach a point where all wanted nodes were visited then just stop and retrive values from that vector
One solution i saw is thst you could eliminate all nodes that aren't in the list
But that might lead to no paths
Well, yeah
I am trying to fit a neural network to a sin wave..Can someone check my derivative code and tell me what i am doing wrong?
https://colab.research.google.com/drive/1D8Uw_S0cv9T79ewy__C2obcUJFFVl8zi?usp=sharing
SciPy's solve_ivp documentation and examples use time t as the independent variable such as dy/dt = f(t, y). But as far as I can tell, the solver can be used to solve ODE systems for space/position such as dy/dx = f(x, y). Is this true or is the solver restricted to ODEs in the time domain? Here's a link to Scipy's docs: https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html
can anyone help me out in a call ?
N = 7
#Keeping track which nodes are visited
visited = [False for i in range(N)]
#Edges in list
social_structure = [[1,2],[2,3],[1,4],[5,6],[7,6]]
#Converting edges into a graph
#Extending the reversed version of the edges so it isn't directed
social_structure.extend([element[::-1] for element in social_structure])
social_structure.sort()
graph = [[] for i in range (N)]
for element in social_structure:
graph[element[0]-1].append(element[1])
#Finding the Subsets
def dfs(index, father):
global visited
visited[index] = father
for path in graph[index]:
if visited[path-1] != father:
dfs(path - 1, father)
for i in range(len(visited)):
if visited[i] == False:
dfs(i, i)
print(visited)
Is this the most effecient way to find all of the different connected components in a graph ?
Running DFS or BFS (doesn't matter) on every non-visited node in order is the common way, yeah.
Node that you can even number them by component:
next_component = 0
for i in range(len(visited)):
if visited[i] is False:
dfs(i, next_component)
next_component += 1
print(f"Total components found: {next_component}")
Oh, and note how I used is False instead of == False. 0 is equal to False, but is False only detects Falsees. I think using comparison in your code might produce bugs in which the component with a father of 0 will be considered nonvisited, and recalculated each time.
(for context, a is b means id(a) == id(b), and id gives the memory address of an object. So only a few things should be compared using is - mainly, you use is to do checks like is True/is False/is None when you want to not accidentally detects ones/zeros as such.)
okay, ty! π
at worst, however many neurons there are in the typical 5-year-old's brain, so 10-100 billion or so, times however many you need to represent a neuron (though an actual neuron network would be a better choice).
.code
can anyone help me out with recursion ?? i dont get the logic of this question

