#algos-and-data-structs
1 messages Β· Page 95 of 1
I'll be back in 30min and I'll explain have to go sorry
Oh ok, so the rows where there are 1's stacked is ok?
ok waitin for ya ty
ahh ok!
yeah but in my case where i want to later convert it to emojis on discord having all tiles being defined as one value is easier
how did he manage to make it that fast... wow
He has wizarded up code for me before, it's amazing
so thats how this channel works? everyone sees what the person is trying to make and races to make it before everyone else? π€£
stuff i've never seen
damn
yeah xD It's good practice
yup
Alright how do I go from starting out to understanding this stuff?
hey m back
this type of problems (starting in a particular cell then traversing the grid by following some rules) is usually solved by using backtracking or BFS
ok
for example we have a grid where each cell has a cost, and we want to find the cheapest path to go from top-left cell to bottom-right cell
Aha
in that case we can use backtracking to traverse the possible paths and take the cheapest one
but in your problem
we are taking only one direction
so we don't need to go back to the previous cell and take another path
Owh ok
which means that we can do it without backtracking/BFS
Aha
we want to generate a path of length k, we can do it recursively, but we can just use a for loop that gonna be repeated k times
it's what I did
now that I've put them in an array, let's say ['top', 'left', 'right'] for example
I generate a random direction among them, and I take it
a direction is considered as valid if the next cell of that direction is not out of grid and is not visited yet
note that I assumed that we can't visit the same cell twice
Ye ofc
so I checked the four directions and appended the ones that are valid
so the direction has to be 0 (not visited) and can't be more than the len(layput[row]) which is offset
Layput*
Layout*
and not less than 0
Ye
then when I randomly generate a valid direction, I take it by updating x or y depending on the direction, and I put '1' in it
Aha
Full code:
||```import random
import numpy as np
def path(n, m, k):
grid = [['0']*m for i in range(n)]
grid[0][1] = '2'
x, y = 0, 1
for i in range(k):
directions = []
if x-1 >= 0 and grid[x-1][y] == '0':
directions.append('top')
if x+1 < n and grid[x+1][y] == '0':
directions.append('bottom')
if y-1 >= 0 and grid[x][y-1] == '0':
directions.append('left')
if y+1 < m and grid[x][y+1] == '0':
directions.append('right')
print(directions)
next_direction = directions[random.randrange(0, len(directions))]
if next_direction == 'top':
x -= 1
elif next_direction == 'bottom':
x += 1
elif next_direction == 'left':
y -= 1
elif next_direction == 'right':
y += 1
grid[x][y] = '1'
return grid
print(np.array(path(5, 10, 20)))```||
Ok this makes sense now but i am still kinda confused (code-wise)
Ok i'll try to implement it myself without looking at this code
x-1: previous row
x+1: next row
y-1: previous column
y+1: next column
What is the best way to understand these topics
Data struct and algo
solve coding problems
Do they start out easy
Cause itβs like normal python is one thing
This is another level
I'm actually posting a series on data structures and algorithms in Python on: https://www.instagram.com/inside.code/
I don't know if I'm allowed to put self links, tell me if I'm not
you're algorithm doesn't work every time btw.
sometimes it raises this error
raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0, 0, 0)
i'll try to fix it
i think it's blocking itself by like going throw circles
squares in this case
π
I think that's the case where there is no possible direction
it depends on how you want to handle it
Yeah
I'll make it so that doesn't happen ig since i am specifying how many tiles i need i have to get all of them
oh okay, then you'll need to backtrack to a point that has other directions
Ahaa
did you try?
Fixing a different problem now
For some reason my convert function wont work
converting the layout to discord emojis
Like that
wait are you sure that this is a valid path?
after 4th tile it's going from right and bottom xd
Ye
That can be done tho...
why
wait you agree that your manual example is not valid right?
this one
Ye its not valid
ye
I wrote it myself
do you know how to implement a backtracking algorithm?
okay basically backtracking is to try all possibilities while backtracking as soon as you find out that the actual possibility is not valid
backtracking means to go back to a previous point
in our case, a path represents a possibility, and we backtrack when we find out that the actual cell is out of grid or already visited
Mhm
yes we go back to the cell that still has possible directions to go from
I know how it works but i don't know how to implement it
do you know recursion?
that's gonna be a lil bit hard then xd
So recrusion is calling a function inside itself?
yes
it works because the same function but with different values for parameters can behave differently
async def createD():
layout = await createPath(5,8,15)
off = "β¬ "
path = "π« "
player = "π€ "
d = ""
for row in range(0,len(layout)):
if row == 0:
pass
else:
d += "\n"
for col in range(0,len(layout[row])):
if layout[row][col] == 0:
d += off
elif layout[row][col] == 2:
d += player
elif layout[row][col] == 1:
d += path
else:
pass
return (layout, dungeon)
``` why is thing returning `d` empty?
Does it work if its an async function?
I'm not familiar with async/await :c
but you have to know that when a function calls itself, it waits for that function call to end, then it continues its work
Hello! What is a good way to read fast millions of strings? I have a file with nearly 1.000.000.000 lines like this 123456789|word, and I am using this to get a line: ```py
from functools import partial
def readFile():
read= partial(file.read, 104857600)
for text in iter(read, ''):
if "123456789" in text:
textDiv = text.split("\n")
for x in textDiv:
if "123456789"in x:
print(x)
return
readFile()
read data in chunks
That is what I did, right? @fiery cosmos I am not reading 100gb to memory
idk if normal way of reading data is efficient in python
Use special library like pandas to speed up the process ig
okay, I am going to try it. Thanks
So I have a dictionary full of more dictionary's (I dont know what the right term for this is). Say for example {'0' = {'a':'2', 'b':'3'}}, {'1' = {'a':'4', 'b':'5'}}.
I have a value for 'b' and I want to get 'a' from the same record in the dictionary. how would I do this?
if d[key]['b'] == searched_value:
print(d[key]['a'])```
assuming that all your inner dicts have both 'a' and 'b' as keys
and, I don't know if it's a coincidence, but I noticed that your keys in the outer dict are 0, 1, ..., if it continues like that, I think that it's better to use a list
well thats just as my quick example but there are really much more keys and each is associated with a diffrent string
oh okay
I am still pretty new to this and I dont understand this for loop... whatever I did is now crashing it...
The thing is Im doing this in a discord bot and it doesnt tell me the error
the items of a dictionary are pairs of (key, value)
so this loop is traversing all the items of our dictionary (the outer one, the one that contains dictionaries inside it)
wait wait wait
my code is wrong
I got confused because your description doesn't match your example
let me re explain
it's more accurate to say a dictionary where the value of a key is a dictionary
so the right code would be this one:
if value['b'] == searched:
print(value['a'])```
what we're doing here is that we're traversing the pairs of key/value of the outer dictionary
and in this dictionary, the value of the pair is also a dictionary, the one that has 'a' and 'b' inside it
what's the error?
does it even have a console?
I put
for key, value in dictionary.items():
if value['owner'] == username:
print(value['players'])
it does
here username is a string
then use try/except and print the exception
'list' object has no attribute 'items'
then it's a list not a dictionary
I thought this creates a dictionary from a JSON: dictionary = json.loads(result)
print the whole thing and see
what would a list look like in comparison to a dictionary?
a list in Python is an array
can you show me what gets printed?
this is one section of it:
{'144': {'ip': '71.29.169.199', 'port': '34617', 'players': '1', 'maxplayers': '10', 'private': False, 'map': '/levels/west_coast_usa/info.json', 'pps': '-', 'sname': 'The Boys Server', 'time': 1608479054240, 'version': '1.13', 'location': 'US', 'playerslist': 'Flaboom;', 'cversion': '1.70', 'official': 0, 'owner': 'Flaboom#3416', 'sdesc': 'BeamMP Default Description', 'modlist': 'Resources/Client/AnyLevel.zip;Resources/Client/MidsizeDieselV8.zip;Resources/Client/Turbo_Everything_rk.zip;Resources/Client/ultrawide_aftermarket_transmission_package_mods.zip;', 'modstotal': '4', 'modstotalsize': '7503094'}}]
isn't it a list of one element?
wait
what do you mean
it counts all the way up to '144'
if thats what your asking but Im super confused
I asked if it wasn't a list of one element, like a list that contains one element which is the whole thing
I think yea
so based off the fact that we now know its a list, I changed d.items() to d[0].items() and its no longer giving me an error, but its not printing anything for value['players']
I think that it's because not all your values have the key 'owner'
you first need to check that value is a dict, and that it has the key 'owner' before checking if it's equal to username
if isinstance(value, dict) and 'owner' in value and value['owner'] == username:
print(value['players'])```
It still doesnt print anything...
you're using dictionary instead of d right?
yes
print this and tell me what it printed:
print([key for key, value in dictionary[0].items if (isinstance(value, dict) and 'owner' in value)])
btw
instead of always adding that [0], just add [0] where you loaded with json
write dictionary = json.loads(result)[0]
printed ['0']
so you have only one dictionary that has 'owner' in its keys
what
even this has an owner
here is where the json comes from: https://beammp.com/servers-info
I problably should have started with that
okay I'll try to work on it and see
Thanks
I figured it out, the initial list doesn't have only one element, it has 147
I just noticed that too, but the number of elements is can change.
do you know what the best way to iterate through these elements is?
for key, value in d.items():
if isinstance(value, dict) and 'owner' in value and value['owner'] == 'Titch#1689':
print(value['players'])```
this worked for me
remove the [0]
already did
titch is an example replace it by username
data is your dictionary right?
because I did:
for d in dictionary:
for key, value in d.items():
if isinstance(value, dict) and 'owner' in value and value['owner'] == username:
print(value['players'])
where username = perfectsquare150#8584 and it didnt print anything
yea sorry thats what I meant
its the same as my dictionary variable
it worked for me with perfectsquare
I am doing something very wrong then
this is my whole thing...
req = urllib.request.Request('https://beammp.com/servers-info')
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
data = urllib.request.urlopen(req)
result = data.read()
result = result.decode('utf-8')
dictionary = json.loads(result)
try:
for d in dictionary:
for key, value in d.items():
if isinstance(value, dict) and 'owner' in value and value['owner'] == username:
print(value['players'])
except Exception as e:
print(f"ERROR: {e}")
Is it to do with the way I created the list?
print the length of dictionary and tell me what did you get
got 146, weird xd
uhhhhhhhhhhh
btw I copied the whole page and saved the text as a json file they I opened it
didn't use requests
wait so is your data just the raw json?
I guess?
Thanks for the help, @wispy hare. Apparently that last problem was just me being dumb and not casting username as a string.
lmaooo okay okay
How do I find the most common prefixes in a big list of strings?
what do you mean by "most common"?
I don't know how long a prefix should be or how numerous (though I can set a minimum threshold)
Like, if I have ["abc", "abde", "cde", "cfg", "dfg"] it would give me ["ab", "c"]
I know that common means present in them all, but I didn't understand most common
Well, not all of them, but a lot of them
how much is a lot?
the most
There is no prefix in those strings that appear in more strings than "ab" and "c"
aah okay
I can set a minimum threshold like 30% if that helps
A trie works but will need to hold all strings
I suppose it is succinct enough to work
I have one more question that I think I should ask in this channel because I dont know which other channel would be the right one...
I want to remove any ^ in a string and the character after it. how would I go about doing this?
''.join([s[i] for i in range(len(s)) if s[i] != '^' and (i == 0 or s[i-1] != '^')])
you can also use regex if you want
Thank you!
I think I do
do you know about list comprehension?
its like when you take something like a sting and turn all the letters into elements of a list right
nope not that, wait lemme just write it with a loop and you'll understand what I did:
for i in range(len(s)):
if s[i] != '^' and (i == 0 or s[i-1] != '^'):
new_s.append(s[i])
new_s = ''.join(new_s)```
so your basically itertating through a string and if its not a ^ and the index before it is not, then you add the letter back into a list, then after its done you join the list into a string?
ok, thanks again!
you're welcome!
hello! is anyone working with data science/analysis with Python? I'm just starting and I don't know if I did this question right. some help would be appreciated. Thank you:)
lmao wrong channel
but anyways of all the 3 options
c looks the most right
if u were to guess
That person only has three messages in the server--"lmao wrong channel" isn't the way we want to approach correcting people.
this would be a question for #data-science-and-ml. The third answer is the correct one, though.
temp_str= "test string"
temp_dict = {}
for i in range(len(temp_str)):
if temp_str[i] not in temp_dict:
temp_dict[temp_str[i]] = 1
else :
temp_dict[temp_str[i]] += 1
for i,j in temp_dict.items():
if j > 1 :
print(f"{i}, count = {j}")
``` What is time comlexity of this code ?
what do you think
o(n)
why
first block of for loop is O(n) then appending in dict is constant time i suppose
again second block of for loop looks to be constant time for me...not sure tho
could u help me plz
bruhh
yes, the if statement in the loop runs in constant time
temp_dict[temp_str[i]] = 1 ...this line is O(n) isnt it since i am adding an item into my dict
thanks for the help
no, it's O(1)
yes it's O(n), and also, what you're doing here can be directly done with a counter
temp_str = "test string"
temp_dict = Counter(temp_str)```
now counter is a dictionary that contains each character and the number of its occurrences
@lyric bramble you also don't want to iterate over range len for this problem
!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.
ok thanks for the help guys will note them
you're welcome
I just listened to the first introductory lecture on Day 9 of Udemy 100 days of code, and my question is around the action of the python dictionary type:
If I have an existing dictionary with existing entries that look like -- leaving off the quotes on purpose:
pets = {
Dog: A friendly furry creature
Cat: An aloof furry creature
Python: One type of snake
}
and I want to ADD another entry, i programmatically write:
pets[Hamster] = Round Furry ball of fluff
which adds the key of Hamster, and sets it to have a value of "Round ..."
However, if I want to update the key of Cat: with the value "Warm furry vibrator" I use:
pets[Cat] = "Warm furry vibrator"
exactly the same syntax!
Why is adding an entry to the dictionary NOT differentiated from an update?
asks curious David -- hoping I am in the right channel for this question.
Well, since you access entries by keys, it's not possible to have duplicate keys. So assigning to the key overwrites the previous value, the same way assigning to a variable or list index or whatever does. There's not really a reason to make the two operations different, it'd just mean two almost identical syntaxes.
I was thinking that I as a programmer would want to be explicit for either operation. And then get an error if I tried to do the wrong thing -- such as:
pets[Hamster] += Round Furry ball of fluff <<< indicates that I INTEND to add an entry and fails if entry exists,
And then this syntax for an INTENDed update:
pets[Cat] = "Warm furry vibrator" <<< which fails if the key does not exist
surprised that for as much as python wants me to explicitly tell it what to do, and along comes this fuzzy syntax that "lets me get away with both"
You're viewing d[k] = v as being either adding or updating a key, and saying you would prefer those 2 operations to have different syntax. But that's not really what it does: it sets a key to a value. In both cases the state of the dictionary after d[k] = v is now that, if you get the item from the dict d with key k, you'll find value v.
You're not wrong, exactly, but you're looking at that operation from a different angle than the Python language looks at it. From the Python language's perspective, it is neither an "add" nor am "update", it is a "set"
It's not ridiculous to imagine that a language could exist where instead of a dictionary supporting one set operation, it supported separate insert and update operations, where it is an error to insert a key that already exists or update a key that doesn't exist. From the language designers' point of view, the question they would be asking themselves is if that decision would make it easier or harder to write correct code. And the designers of different languages could conceivably come to different conclusions than the designers of Python came to.
And, note in particular that your suggested syntax of py pets["Hamster"] += "Round furry ball of fluff" is already valid syntax for doing something different than what you propose: it looks up the value stored at pets["Hamster"] and adds to it. py d[k] += v is equivalent to ```py
d[k] = d[k] + v
Would this last operation fail if d[k] did not exist?
Yes
Because looking up the current value of the key is a part of it, and will fail if there is no current value to be found - in that case we don't know what to add the value v to.
Thanks for your thoughts and typing. Good night....
dag = input('dag?')
print(dag)
maand = [['Jan', 0], ['Feb', 3], ['Maa', 3], ['Apr', 6], ['Mei', 1], ['Jun', 4], ['Jul', 6], ['Aug', 2], ['Sep', 5], ['Okt', 0], ['Nov', 3], ['Dec', 5]]
i_maand = input("Type het overeenkomende getal met jouw maand\nJan=0\nFeb=1\nMaa=2\nApr=3\nMei=4\nJun=5\nJul=6\nAug=7\nSep=8\nOkt=9\nNov=10\nDec=11")
o_maand = [maand[[1][i]] for i in (i_maand)]
print(o_maand)
can you guys help me out here? Im trying to set o_maand to the value in maand
What you want to do exactly ?
Anything do inside the input() is the prompt message for the console.
I solved the problem already using a different way to code this. Thanks for the help though! How do I close this discussion?
oh mb Im new here. Posted it in the wrong channel
Hey Guys!
what does yield do?
I didn t understand it pretty good
it s like a return for loops?
it is return but it acts only when it is called
so much like you only answer when you are asked
so it only returns some value only when called
def yield_example():
a = [i * 10 for i in range(100)]
for el in a:
yield el
this will return values one by one
and when you call yield_example() it will step once and halts its execution
lol, that's a pretty bad example of yield, since you're still holding all the values in memory
ye much useful case is when you have some infinite stream of numbers
try a generator instead of list comprehension
anyone have a guide to understanding big o notation and code efficiency
I would say, go with https://www.geeksforgeeks.org/
Is it confusing to practice DS-Algo fundamentals using Python, rather than C, as I have no prior experience with C/C++.
Yeah, that is true
nope you can use the list
the list is implemented as a dynamic array
Yea, right
Actually, I have started my coding interview preparation for product-based companies, hence I was curious.
Anyways thanks
you can check this series of ig posts, check this one and the ones after it: https://www.instagram.com/p/CIdN2_NAxn4/
The biggest downside to learning data structures in Python is that you'll feel like you're reinventing the wheel a lot. You'll keep building your own, worse versions of things that exist in the standard library. That's not a bad thing, though. It's teaching you how the standard library works.
Just remember that what you're learning is not how to build these days structures in Python, because for the most part someone else has already made a high quality implementation you can reuse. Instead, you're learning how these days structures work internally, which allows you to reason about how they'll behave and perform in any language.
reinventing the wheel is fine when you know that it's just to understand how does it work imo
Yeah, exactly. To use an analogy, the purpose of the exercise isn't to build your radio, because you can buy excellent radios already made that do everything you're likely to want yours to do. The purpose of building your own radio is to learn how radios work, so that you can troubleshoot yours if it ever breaks, or understand what conditions will make it work worse, or understand why it can only pick up certain bands, etc.
As long as you understand that there's value in learning how these things work even though you'll throw away your implementations, Python is a perfectly fine language for it
exactly
don't focus on implementation, focus on knowing the time complexity of main operations and when to use a data structure instead of another
Yeah. Learning the implementation is mostly useful because it helps you understand why the time complexity is what it is.
"""
https://cses.fi/problemset/task/1662
5
3 1 2 7 4 should output 1
"""
divisor = int(input())
remainders_encountered = {}
total = 0
sum_so_far = 0
for i in input().split():
sum_so_far += int(i)
remainder = sum_so_far % divisor
total += remainders_encountered.get(remainder, 0)
if remainder not in remainders_encountered:
remainders_encountered[remainder] = 0
remainders_encountered[remainder] += 1
total += remainders_encountered.get(sum_so_far % divisor, 0)
print(total)
``` (problem in code) why doesn't this work lol
ping 2 reply thx
if anything's not cllear about the code i can explain
I need major help
This is my code
ideas = ""
num = 1
name = input("Employee first and last name:")
a = ""
b = ""
c = ""
slots = [a, b, c]
while num <= 3:
idea = input(f"Idea No. {num}:")
num = num + 1
if num == 1:
a = idea
elif num == 2:
b = idea
elif num == 3:
c = idea
if idea == "stop":
print(f"{name} is still thinking.")
break
print(f"List of collected ideas. Author: {name}.")
print(f"1. {a}\n2. {b}\n3. {c}\n")
but this is what it outputs
it misses the 1.
can someone help me?
wait, nvm, I figured it out
Cause you do num = num + 1 before the if statement checks if its 1, so you start with 2
Put it at the bottom of the second if statement, and there's an increment operator, so you can do num += 1
Yes, I feel the same.
Sure!
is this the place for square root code
Im writing one for computer science and im lost
@floral shell You initialize ur num to 1 and when u get into the while loop u add 1 to it before getting to the conditions instuctions
I suggest that u put that after the conditions
!eideas = "" num = 1 name = input("Employee first and last name:") a = "" b = "" c = "" slots = [a, b, c] while num <= 3: idea = input(f"Idea No. {num}:") if num == 1: a = idea elif num == 2: b = idea elif num == 3: c = idea num = num + 1 if idea == "stop": print(f"{name} is still thinking.") break print(f"List of collected ideas. Author: {name}.") print(f"1. {a}\n2. {b}\n3. {c}\n")
Yeh, I realized that lol
thx anyways
and by the way, slots will remain ['', '', ''], even after you update a b c, be careful
oh ok
I'm trying to parse a JSON file - one whose format I can not control - and it has both a list and an actual key : data pair named the same thing "listpicker_5". How can I get Python to look at JUST the key : data pair and ignore the list? (I'm trying to use python3 installed by Ubuntu 18.04.)
"listpicker_5": {
"selectedNames": [
"John"
],
"selectedScores": [
"0.000000"
],
"selectedValues": [
"John Smith"
]
}
[ more stuff ]
"listpicker_5": [
"John Smith"
],```
My simple code so far is this:
```python
#!/usr/bin/python3
import os,json
file = os.path.abspath('/some/path') + "/sample.json"
json_data = open(file).read()
json_obj = json.loads(json_data)
roObserverName = json_obj["listpicker_5"]
print(roObserverName)```
Any pointers or links to helpful articles is appreciated.
What is it?
"listpicker_5": {
"selectedNames": [
"John"
],
"selectedScores": [
"0.000000"
],
"selectedValues": [
"John Smith"
]
}
Is it your sample.json?
So it looks like?
{
...
"listpicker_5": {
"selectedNames": [
"John"
],
"selectedScores": [
"0.000000"
],
"selectedValues": [
"John Smith"
]
},
...
}
Sorry, I missed part of the copy/paste. I've corrected the post.
Basically in the sample.json, I have two "listpicker_5" entries - one is a list of values, the other is a single value (and the one I need) later in the file.
I need to ignore the list form and retrieve the single string version when parsing.
I think that you cannot create many keys in JSON object because next value overrides previous one
>>> import json
>>> with open("simple.json") as file:
... data = file.read()
...
>>> print(data)
{
"a": 0,
"b": 1,
"c": 2,
"a": 3
}
>>> json.loads(data)
{'a': 3, 'b': 1, 'c': 2}
As you can see, a is not 0 but 3 now because it's the last value assigned to key a
When I run my script, I get the following error:
Traceback (most recent call last):
File "./jsontest.py", line 59, in <module>
print("Observer Name: " + roObserverName)
TypeError: must be str, not list
And what is the error message? What can you read from sentence TypeError: must be str, not list?
I read it as "the data contained in 'roObserverName' is a list of things instead of a single string"
When I alter the print statement to:
print(roObserverName)
I get:
['John Smith']
instead of :
John Smith
So you are correct in that it's getting the last value in the file, but it's formatting it weirdly.
Right, it's not a str so you cannot make concatenation of str and list
Everything comes from your data
"listpicker_5": [
"John Smith"
],
so listpicker_5 is an array of strings (one in this case)
If you want to hold only one value just write
"listpicker_5": "John Smith",
Then you can execute print("Observer Name: " + roObserverName) because roObserverName is str
So str + str is stil str but str + list is unknown
So I just altered my script to contain:
roObserverName = json_obj["listpicker_5"].pop()
print("Observer Name: " + roObserverName)```
And it works.
Can you recommend a more elegant solution?
If you know that json_obj["listpicker_5"] contains only one element you can unpack it using
(roObserverName,) = json_obj["listpicker_5"]
Or call by index
roObserverName = json_obj["listpicker_5"][0]
I'll use the index route - it's more readable for me. Thank you!
Your welcome!
Hey guys, I wanted to know that as I am going to learn Data Structures and algorithms, do I need to learn C++ as well or python will do the job?
Python will do the job.
K thx
@quasi hinge ^ see this conversation from yesterday.
sorry to ping. but the first solution, (obviously im a bit inexperienved on data stuff) how does that work? and if you dont want to explain, what is that called? is that just a tuple with a second empty val in which you are assigning to his list...?
What exactly is a functor? From my perspective it seems to create functions (objects?) that share an interface?
Also has something to do with map?
in the programming context, there are two meanings
the first doesn't really exist in Python because functions are first-class
but in some other languages you'd need to turn functions into things that can be passed around like other objects (ints, floats, etc.)
those "things" are called functors.
on the other hand, there is also a more category theory-ish meaning of "functor"
basically, something that can be mapped over.
@brave oak Is there also a third case that looks something like functools.partial?
what do you mean
thx man . thats means i need to learn C++ which will hardly take 2 weeks
c++ has nice parts and also has parts that give big headaches
Ohk
No problem at all with your ping.
If you have a tuple with many values you can unpack it by writing
>>> x = (0, 1, 2)
>>> (a, b, c) = x
>>> print(a, b, c)
0 1 2
When you have tuple with only one element you can unpack it by writing
>>> x = ("a",)
>>> (a,) = x
>>> print(a)
a
When you write a = x you just assing tuple ("a",) to variable a but you want to unpack it so you need to add ,.
You can omit ( and ) so in short
>>> a, = x
>>> print(a)
a
It's very useful when you write with struct like struct.unpack("<Q", data) - it returns struct with only one element and to unpack it you can get value by index but by unpacking is better to read in my opinion
>>> import struct
>>> data = struct.pack("<Q", 2481632)
>>> num = struct.unpack("<Q", data)[0]
>>> print(num)
2481632
>>> num, = struct.unpack("<Q", data)
>>> print(num)
2481632
Hope that it's clear now @surreal ingot
Your welcome!
def shellSort(l):
interval = len(l)//2
while interval >= 1:
for i in range(interval, len(l)):
for j in range(interval, i+1, -interval):
if l[j] > l[j - interval]:
l[j], l[j - interval] = l[j - interval], l[j]
else:
break
interval //= 2
return l
this shell sort doesn't work
hi
class Node { public: int data; Node* next; };
can somebody explain whats "Node* next"
i totally have no clue
it represents the next node in that linked list
a linked list node must know where is the node after it located, so it needs a pointer next that points to the next node
int *p is a pointer
whats Node* ?
a pointer to an element of type Node
can u share any resource that explains this concept..
yes sure just search for linked list in C
what if i write Node *next instead of Node* next
It's the same
never saw a variable declared with class name..
It's similar to all the primitive datatypes
In what context would an adjacency matrix be favoured over an adjacency list?
Have a great coding day ahead guys !

if i have a function F(x,y,z) that outputs (a,b,c) is there a way to solve for F?
Could you share the code?
i dont have any yet, im just asking if its possible
Yes, you can define a function in the way just you want.
Yeah, it would be
Is this for a specific task or just an idea
just a idea
Well the context is obviously important
im asking if i can solve for a mathematical function F given its inputs and outputs
without doing numeric regression
Is f(), a complex function or just a simple coefficient?
you need to define it. I would say refer for resources that include constructing basic functions with some parameters.
Okay
Got it
then plotting the graph would be simpler technique, to solve the function that has dependent and independent variables, ie performing Regression and fitting it into straight line. Lol π
These seem equivalent to me:
class Thing:
def __init__(self, b):
self.b = b
def __call__(self, a):
return a + self.b
thing = Thing(b=1)
thing(5)
from functools import partial
def add(a, b):
return a + b
thing2 = partial(add, b=1)
thing2(5)
As you can read from docs functools.partial returns partial object which is very similar to your Thing class: https://github.com/python/cpython/blob/3.9/Lib/functools.py
But is Thing a functor? What about add?
Thing is not a function, it's callable object so it can work as a function
If our middle element is less than target, our low point becomes mid + 1 and if our mid element is greater than target, our high point becomes mid - 1.
do i have this correct?
for a binary search
i think i remember talking to to yesterday about binary search
basically if our target is less than mid
our high becomes mid - 1
and if our target is greater than mid
our low becomes mid + 1
u just flipped it around but otherwise its right
I just wrote a short en/decryption algorithm, can someone tell me, wether it (or the concept implemented) has some major flaws?
#!/usr/bin/env python3
import sys
import random
file_path = sys.argv[1]
plain_data = ""
with open(file_path,"r") as f:
plain_data = f.read()
password = input("Password: ")
random.seed(int("".join([str(ord(i)) for i in password])))
new_file = ""
for l in plain_data:
new_file += chr(ord(l)^random.randint(0,10000))
with open(file_path,"w") as f:
f.write(new_file)
print("[+] Program done!")
thank you! i had to write that down. hopefully ill remember it. π
i think the easiest way to remember it
is not what exactly it does
but rather the invariant (the thing that doesnt change)
ie in this case it is that the element u are looking for is at an index from low to high
and that ofc the array that u are looking though is ordered
Don't roll your own crypto, you rely on PRNG and it's not good idea
I couldn't find a seed() function in the crypto module
@split obsidian in that sense of "functor", there is no distinction between a function and a functor in Python
since functions are first-class objects
is there some method
so i can process 2 types of queries in a tree (each set to some random initial number)
- just xor sum of all nodes between 2 nodes
- update val of node
i found this link
but idk how to process part 2
(ping 2 help thx)
can someone help me convert this to numpy?
sum((min(dst(house, shop) for shop in shops) for house in houses))
a bit more readable:
running_total = 0
for house in houses:
value = min(dst(house, shop) for shop in shops)
running_total += value
return running_total
What is the most efficient way to built a large dataset for ML or DL? Break it up in pieces? Dicts? Tuples in dicts?
I've a dict with 10k entries, iterating through it isn't memory-wise cheap, any ideas?
Hi, do we consider Cross Entropy Method (RL) as an algorithm ?
Don't suppose anyone can help me with this, I can't seem to work out how to translate the solution to the input
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == []
def peak(self):
if not self.is_empty():
return self.items[-1]
def get_stack(self):
return self.items
is this good enough for a stack data structure? or am i missing something
@cloud bough peek is the proper spelling, .get_stack() is useless as you can just use .items. I would also make is_empty() __bool__, implement __len__ and __iter__.
you can also add more methods to train on stacks (sort, reverse...)
ahh got it, thank u both
how would sorting a stack even work
err, not how would it work, why would you do it
just to practice, because a real stack is more limited than a python list, so it's interesting to try sorting it by using push/pop/is_empty/peak only
sure
i feel being able to access all elements of a stack defeats its purpose
exactly
should asking for help in improving code for an algorithm asked here? or in a help channel?
yes you can do it here I think
for y in range(len(datarows)):
for x in range(len(datarows[0])):
gridindexes.append(list([y, x]))
for index in gridindexes:
digit2list = touching(datarows, [index], [index])
for digit2 in digit2list:
digit3list = touching(datarows, [digit2], [digit2] + [index])
for digit3 in digit3list:
if digitlength == 3:
final.append(str(datarows[index[0]][index[1]])
+
str(datarows[digit2[0]][digit2[1]])
+
str(datarows[digit3[0]][digit3[1]]))
else:
digit4list = touching(datarows, [digit3], [digit3] + [digit2] + [index])
for digit4 in digit4list:
if digitlength == 4:
final.append(str(datarows[index[0]][index[1]])
+
str(datarows[digit2[0]][digit2[1]])
+
str(datarows[digit3[0]][digit3[1]])
+
str(datarows[digit4[0]][digit4[1]]))
def touching(grid, cv, exc):
digits = []
leny = (len(grid) - 1)
lenx = (len(grid[0]) - 1)
for digit in cv:
digitlist = []
touchinglist = [[digit[0] - 1, digit[1] - 1], [digit[0] - 1, digit[1]], [digit[0] - 1, digit[1] + 1],
[digit[0], digit[1] - 1], [digit[0], digit[1] + 1],
[digit[0] + 1, digit[1] - 1], [digit[0] + 1, digit[1]], [digit[0] + 1, digit[1] + 1], ]
for t in touchinglist:
if 0 <= t[1] <= lenx and 0 <= t[0] <= leny and [t[0], t[1]] not in exc:
digitlist.append(t)
digits += digitlist
digitlist.clear()
return digits
here i use digitlength to determine if i want to use my function 3 times, or 4 times, but i want to be able to use about any user defined number, not just 3 or 4, but im having a hard time properly looping it to make it so dynamic
i udnerstand my variable names are bad, if you have any advice in that regard i would appreciate it
Made a Reddit post asking the same, but i described all the variables here :(https://www.reddit.com/r/learnpython/comments/kiyvbd/hello_i_want_to_make_my_code_more_dynamic_than_it/)
1 vote and 0 comments so far on Reddit
can you explain what is this algorithm supposed to do?
so it takes a 2D list, and returns every possible 3/4 digit length string of elements adjacent to each other
touching returns the indexes of the original grid, that are adjacent to the index in the arguments, so i loop through every index in the 2D list, get whats t adjacent, from the list returned from that, get whats adjacent, and repeat that till i have 4 digits, if that makes any sense?
an example of how to get 2 numbers, a 2x2 grid has 24 4digit results
Hey,
does anyone know of a good recourse to learn approximations?
Im specifically looking for ways to approximate functions to given sets of points such that the average distance of all the points to the function is minimized.
eg.: given 3 points, approximate a function of degree 1
I'm not sure but isn't it linear regression?
hey guys do u know how to open tor with selenium
@fiery cosmos that's a question for #web-development, assuming that what you wanted to do with Tor is ethical
Okay thanks bg
A linked list is essentially a stack, and linked lists can be sorted with O(n logn) complexity using mergesort, so that's a reasonable goal
hm. If you sort a stack, it's not a stack anymore. Or, to put that differently, "sort" isn't an operation that makes sense for the stack abstract data type. The stack abstract data type can only be mutated by pushing and popping, so the only way to sort a stack using the public interface of a stack would be to pop every item and push them back in sorted order.
That is what syph proposed to do though
To sort only by pushing/popping/checking if is_empty/peeking
The organizers of the children's holiday are planning to inflate m balloons for it. They invited n assistants, the i-th assistant inflates a balloon in ti minutes, but every time after zi balloons are inflated he gets tired and rests for yi minutes. Now the organizers of the holiday want to know after what time all the balloons will be inflated with the most optimal work of the assistants, and how many balloons each of them will inflate. (If the assistant has inflated the balloon and needs to rest, but he will not have to inflate more balloons, then it is considered that he finished the work immediately after the end of the last balloon inflation, and not after the rest).
Input
The first line of the input contains integers m and n (0β€mβ€15000,1β€nβ€1000). The next n lines contain three integers each, ti, zi, and yi, respectively (1β€ti,yiβ€100,1β€ziβ€1000).
Output
In the first line print the number T, the time it takes for all the balloons to be inflated. On the second line print n numbers, the number of balloons inflated by each of the invited assistants. If there are several optimal answers, output any of them.
Example
input
1 2
2 1 1
1 1 2
output
1
0 1 ```so i'm doing this problem
def inflated_amt(worker, time):
chunk_time = worker[0] * worker[2] + worker[1]
return (time // chunk_time) * worker[2] + min((time % chunk_time) // worker[0], worker[2])
def inflatable(workers, time, req):
return sum(inflated_amt(w, time) for w in workers) >= req
ballons, workerNum = [int(i) for i in input().split()]
# balloon inflation time, rest time, and balloons for rest time
workers = [[int(i) for i in input().split()] for _ in range(workerNum)]
lo = 0
hi = 10 ** 20
best_time = -1
while lo <= hi:
mid = (lo + hi) // 2
if inflatable(workers, mid, ballons):
best_time = mid
hi = mid - 1
else:
lo = mid + 1
each_inflated = []
alr_inflated = 0
for w in workers:
this_inflated = inflated_amt(w, best_time)
alr_inflated += this_inflated
if alr_inflated >= ballons:
this_inflated -= alr_inflated - ballons
each_inflated.append(this_inflated)
break
each_inflated.append(this_inflated)
while len(each_inflated) < len(workers):
each_inflated.append(0)
print(best_time)
print(' '.join(str(i) for i in each_inflated))
```and my code is as follows- however, it doesn't work- anyone know why?
Hey guys, I've just uploaded a video about the sieve of eratosthenes implementation in Python (in German language), and I would love to get your opinion about it. Surely I'm not a pro in video production, but I'd like to improve myself with time in that kind of activity. If demand is there, I will also post this kind of algorithm implementations in English language and for sure also other interesting topics about computer science on that channel. Please show me demand in terms of subs, likes or comments (:
My goal is to post a wide range of python basics, implementations, examples of complex projects and also highly theoretical fields of computer science, too. Surely I can only afford this time investion, if I see any kind of reaction to it.
Greetings,
Pio
βΊ Python Tutorial - Das Sieb des Eratosthenes
Heute implementieren wir einen Pseudocode zum Sieb des Eratosthenes in Python. Das Sieb des Erastothenes wird hΓ€ufig an deutschen Hochschulen vermittelt, um leicht und effizient eine Reihe von Primzahlen identifizieren zu kΓΆnnen. Du hast Fragen und/oder Anmerkungen zu dem Video? Ab in die Kommentare ...
(It's here in the algos-channel, because it is about algorithms) π
hey
find the sum of even fibonacci numbers with time complexity of log(log(n))
can anyone do it?
i cant figure it out
someone help
what does n represent?
just a sec wait
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
this is the problem
i can do it with log(N), N is 4 million
how about log(log(n))
so you mean n is smaller than 4 millions
wait forget everything let me rephrase the question
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
so this is the question
we can solve it
using some code
but that will provide time complexity of log(n)
i wanted to do it with Log(log(n))
did you get it no?
@wispy hare
The problem is find the sum of even fibonacci numbers that is fibonacci numbers that are even and is less than a given number N. We will present 3 insightful ideas to solve this efficiently.
I found this
thats the complexity?
whats*
A website dedicated to the fascinating world of mathematics and programming
here look at this post
someone made some big brain optimizations to work it in log(log(N))
@wispy hare
someone can recommend to me any videos about backtracking? I simply cannot understand this concept and the implementation of it. I want a general implementation, not a shitty maze/sudoku solving
Try to understand the concept instead of the general implementation, because backtracking can be applied to trees, graphs, 2D arrays, miscellaneous situations...
well i know the concept, if your next step is wrong you go back to the previous correct step
yes, this is why a backtracking algorithm usually has two base cases
a positive base case, that occurs when we've been able to find a valid solution to the problem, and a negative base case, that occurs when we notice that the actual solution is not valid
for example, we can have a collection of items, each one of them has a weight
and we want to find all combinations of items such that the total weight doesn't exceed maxWeight
the backtracking algorithm that we can use here is that at each index of weights, we try both possibilities, when we take the item i and when we don't
by doing so, we will be able to reach all possible combinations of the items
but here we want only those that respect the condition of having a total sum that doesn't exceed maxWeight
we can wait to generate all combinations, then filter, by writing something like this
return filter(lambda comb: sum(comb) <= maxWeight, combinations)```
but we can avoid having to generate them all, by subtracting weight[i] from maxWeight when we take an item
i think it s too much for what I really want to do on the generating subsets of a set problem
so if maxWeight become negative, we abondon the actual combination, because we already know that it exceeds maxWeight, so we backtrack
generating subsets of a set is easier, you have to use the take-or-leave method I explained here without caring about a particular condition
For example this is what happends when we want to generate subsequences of the string "abcd"
you can see that at each index, we have two new possibilities, one where we take the actual character and one where we don't
set = [10, 23, 42]
parts_set = []
def subsets(set, k):
if k == len(set):
print(parts_set)
else:
subsets(set, k + 1)
parts_set.append(set[k])
subsets(set, k + 1)
parts_set.pop()
i think i did it
nice!
now you can try now dealing with conditions
for example print only subsets whose sum is less than k
or those that have at most k elements
or those that have exactly k elements
you can also learn how to deal with cells problems in matrices
example: given a matrix, check if there is a path between (x1, y1) and (x2, y2)
by the way, the problem that I was explaining at the beginning (combinations that don't exceed maxWeight) comes from the course on recursion I released this week: https://bit.ly/recursioncourse (tell me if courses links are not allowed in this channel)
i follow on instagram inside code but idk if i can trust them with this recursion course
yes!
that s cool
The organizers of the children's holiday are planning to inflate m balloons for it. They invited n assistants, the i-th assistant inflates a balloon in ti minutes, but every time after zi balloons are inflated he gets tired and rests for yi minutes. Now the organizers of the holiday want to know after what time all the balloons will be inflated with the most optimal work of the assistants, and how many balloons each of them will inflate. (If the assistant has inflated the balloon and needs to rest, but he will not have to inflate more balloons, then it is considered that he finished the work immediately after the end of the last balloon inflation, and not after the rest).
Input
The first line of the input contains integers m and n (0β€mβ€15000,1β€nβ€1000). The next n lines contain three integers each, ti, zi, and yi, respectively (1β€ti,yiβ€100,1β€ziβ€1000).
Output
In the first line print the number T, the time it takes for all the balloons to be inflated. On the second line print n numbers, the number of balloons inflated by each of the invited assistants. If there are several optimal answers, output any of them.
Example
input
1 2
2 1 1
1 1 2
output
1
0 1 ```
so i'm doing this problem
def inflated_amt(worker, time):
chunk_time = worker[0] * worker[2] + worker[1]
return (time // chunk_time) * worker[2] + min((time % chunk_time) // worker[0], worker[2])
def inflatable(workers, time, req):
return sum(inflated_amt(w, time) for w in workers) >= req
ballons, workerNum = [int(i) for i in input().split()]
# balloon inflation time, rest time, and balloons for rest time
workers = [[int(i) for i in input().split()] for _ in range(workerNum)]
lo = 0
hi = 10 ** 20
best_time = -1
while lo <= hi:
mid = (lo + hi) // 2
if inflatable(workers, mid, ballons):
best_time = mid
hi = mid - 1
else:
lo = mid + 1
each_inflated = []
alr_inflated = 0
for w in workers:
this_inflated = inflated_amt(w, best_time)
alr_inflated += this_inflated
if alr_inflated >= ballons:
this_inflated -= alr_inflated - ballons
each_inflated.append(this_inflated)
break
each_inflated.append(this_inflated)
while len(each_inflated) < len(workers):
each_inflated.append(0)
print(best_time)
print(' '.join(str(i) for i in each_inflated))```
and my code is as follows- however, it doesn't work- anyone know why? (ping 2 help thx)
"i can't understand"
"just try to understand"
Can anyone suggest a data structure where I can store points and efficiently query all points within a particular radius, and also efficiently insert and remove points
Or, does something like this exist?
Also, if I can get support for toroidal space with that (assuming all points are within an aabb) it'd be amazing
(Sound too much like I'm making an order at a restaurant or something)
is that supposed to like
say my help request is bad?
i mean i fixed it in the end
was a small problem with array indices
although yeah, "it doesn't work" isn't the best
what is a problem
uh i fixed it already loll
We don't allow advertising your own paid resources, but you can share your open-source projects freely.
okay thanks for telling me!
does someone have a full implementation of a linked list coded?
all these websites have different implementations and its confusing me
if ur seeing the -> thats c
oh is that like a pointer
thats basically dereference then dot
ah
in python for a linked list, should i create a node class and a linked list class, or should it be all in one class?
you can have class inside class ig?
ive seen both ways
where there is a class to hold the variable to the start of the list and maybe a variable to the end of the list
and then u have a class for the nodes
this works, right?
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
that should work
would be better to do:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self, head=None):
self.head = head```
it gives more flexibility when creating a Node or a LinkedList
you could also have something to store the length of the list, but that's not required
ahh got it
so increment a value for every node created?
something like that
good idea, thanks
you can create an empty node: Node()
node by giving it a value: Node(5)
or creating many nodes at a time: Node(2, Node(3, Node(1, Node(8))))
same thing for the linked list
yes, because otherwise, you'd have to traverse it again to know the length
ahh
im learning all these data structures, but i have no idea when to use them when asked on a problem π
you would need to learn why to use one over another
for example, sets are nice when you need to do many membership tests
advantages vs disadvantages
oh
like there are always advantages and disadvantages with a choice
and u just pick the one that fits the best
i see. okay i need to look more into pros and cons of each data structures then
yes, focus more on that instead of implementation
like for example if u wanted an ordered list or sth
u can choose a linked list or an array
for example
and of the two each one has its advantages and disadvantages
like appending or prepending on a list is O(n) right?
cuz u have to move each index when adding an element
yeah
usually ur problem has constraints to it ie what types of operations u need to support
and once u took into consideration all the constraints, u try to pick one that suits it the best
ahh i see
although i will say when u go look into runtimes and such u might encounter some math
yes, excpet for appending an element at the end of a list which is O(1)
it's amortized O(1), O(n) worst case
occasionally when appending you need to copy the elements into a larger buffer
and i guess that math part can also be considered to be part of the "science" of computer science
yeah i got a lot to learn about that
im understanding time complexity right now
with lists stacks queues there isnt too much math
prob only thing is the asymptotic notation
ah
the runtimes are a bit intutitive as there isnt much proofs with theses
sets and dicts are quite magical though
most problems that i solved on leetcode happened thx to dictionarys
u can also look into hashing and looking at their ways of dealing with collisions if ur interested in dicts and such
yeah ill do that. those are all for hash tables aka dicts, right?
collisions and etc
ah
and ofc there are pros and cons to each
What's the algorithm for cubic interpolation with only one coordinate
like i want to transition from 1 to 8 for example with 60 iterations
x^2 + y^2 + z^2 = r^2 works mathematically
i would imagine with python u would simply evaluate this expression at ur desired radius at intervals that suits ur accuracy of what looks like a sphere
- How do I get the surface area of a sphere and cylinder (separately)
- How do I calculate the length of all edges of a cube or 3d rectangle
Once you understand time and space complexity, the advantages of one structure should become much more clear.
You can always implement a data structure in terms of another (e.g. impelment a list using a dict with integer keys), the only differences are convenience for certain problems and performance
ah that makes sense, I am going to really try and understand time/space complexity.
given a string i need to find a t so that s = t + t + ... + t
how can i do that?
if i have s = abcabc, t is abc and k = 2
s = "cicici"
chars = ""
t = ""
k = 1
for i in s:
chars += i
t += chars
while len(t) <= len(s):
t += t
k += 1
if t == s:
print(k)
break
else:
t = ""
k = 1
if i do this it repeats more than once
and if i debug it
when k = 3
this thing is cicicici
hmm, well the way i see it. we can incrementally split the string (first at 0 and 1, then at 0 and 2, 0 and 3, etc.) and then repeat that string until it matches the length of the original string. this explanation wasn't worded all that well, but here's a solution that works for that specific case
# string to find the substring of
s = "cicici"
i = 1
while i <= len(s):
substr = s[0:i]
newstr = substr * (len(s) // i)
if newstr == s:
print(f'found {substr} to be the correct sequence!')
break
i += 1
well i cannot see any difference
between your version and my version
but why len(s) // i
that's just to force integer division
since len(s) / i could potentially produce a float, and i can't multiply a string by a float
it repeats the string?
i have a number. I need to put 3 points so I can get all IP combinations:
1721601 -> 172.16.0.1 | 17.216. 0. 1 | 1.72.160.1
How can I do that? I have no idea
why not just generate the 4 numbers separately
it seems like the puzzle is to figure out every possible way to place three . into the string 1721601 to divide it into 4 legal octets. In which case, I'd go for a recursive solution: there's 3 legal places to put the first . (after the 1, after the 17, and after the 172), and then you have to figure out where it's legal to place 2 . inside 721601, 21601, or 1601 respectively. Inside 721601 it's only legal to put it after 7 or 72 (because 721 > 255), so then you recurse to put 1 . into 21601 or 1601 respectively.
though this seems to exclude 172.1.6.01 as a solution for some reason - I can't see why; that seems legal to me - it results in 4 octets, each with a value <= 255 (maybe there's an implied but not stated rule that an octet can't have any unnecessary leading zeroes?)
this is also a tiny enough input that the total brute force option is fine: the places where a . could be placed in 1721601 to divide it into 4 non-empty sections are after the 0th character, or after the 1st, or 2nd, or 3rd, or 4th, or 5th. Use something like itertools.combinations to generate all possible locations to insert the 3 dots, and then filter out the invalid ones like 1.7.2.1601 afterwards by splitting the string into 4 sections at those positions and making sure that 0 <= x < 255 for each section.
note that this solution is considered as a brute-force solution, it runs on O(nΒ²) time complexity, where n is the length of s
I've read about an O(n) solution where you try to find s in (s+s) at an index that is different from 0 or something like this
good point! i wrote it up pretty quickly haha. i had actually thought about this earlier and how there might be a better solution
yes, it's possible in O(n) by ||creating a suffix tree and finding the deepest node||
actually, i may have read the problem wrogn
i think we could assume that the input is always gonna be something like abcabcabc
so i think we could optimize around that :p
ok, it is possible in O(n)
i don't get it, as a developer, is it necessary to understand time-space complexity. Do developers actually check this stuff in live code ?
i doubt most developers are thinking too heavily about it. most stuff that really benefits from complexity analysis, like searching, sorting, etc. are either built-in or established in the environment. but i'm not a developer, so don't take it from me :p
also, that O(n) solution looks something like
def get_generating_substring(string):
repeated = string * 2
index = repeated.find(string, 1)
if index != len(string):
return string[:index]
return string
get_generating_substring('abcabcabc') spits out abc
and get_generating_substring('hello') gives us hello
@stray geode is recursion better than loops. I heard recursion is better in performance too.
do you have any comment
iteration is almost always the best way to go haha. recursion is really cool, but it rarely ends up being the most efficient solution
What exactly does this do text = a[i].text with i being the number looping in a for loop
i cant wrap my head around it
@stray geode how do you actually calculate the performance of the code. i meant doesn't it vary per hardware
you usually don't calculate the performance of code, just the performance of it relative to other code that does the same thing
but uh
i shouldn't say that because, i mean maybe you do often calculate the performance of code?
i never see anyone saying "this code should run in approximately this time" though :p
@stray geode i just code sub consiconusly
you determine time complexity, which is how your runtime scales as input size increases
but that's really the question that complexity analysis solves. if one solution works in O(n), while the other works in O(log n), then it's pretty clear which one to use if you plan to scale
yes, you want to pick the data structures and algorithms best suited for your task
for production code, the wrong data structure may lead to huge slowdowns
Technically no. O notation hides the hidden constants. Fibonacci heaps are amortised O(1) for a bunch of operations, but they have such a high constant factor that you just don't want to use it unless you have huge inputs
10n is better than 10000000000logn for a large range of inputs
right, of course
he said if you plan to scale lol
wat santa said
relevant reading lmfao https://en.wikipedia.org/wiki/Galactic_algorithm
A galactic algorithm is one that outperforms any other algorithm for problems that are sufficiently large, but where "sufficiently large" is so big that the algorithm is never used in practice. Galactic algorithms were so named by Richard Lipton and Ken Regan, as they will never be used on any of the merely terrestrial data sets we find here on...
Even if you plan to scale. My aforementioned fiboancci heaps example, I tested. Binary heaps were the fastest even for graphs of 2500nodes and 0.8VΒ² edges. Fibonacci just wasn't worth it
bogosort be like
Ackermann function be like
i heard about ackermann, what is it actually used in realworld though
It's mostly theoretical afaik, but the inverse Ackerman function comes up in the time complexity of disjoint set union data structure implemented with pointers and path compression
but there is no pointers in python, as per my knowledge
basically if u have a disjoint set implementation
and u want to do path compression
and disjoint sets can also be implemented as an array
or use an array to hold the connections instead of using pointers
like the value is the index of the parent
@wraith valve oh. i am just a noob though
its one possible implementation
and pointers can be just thought of as a variable in python
lots of times ppl use c++ for writing an algorithm
and thats when there is a pointer
interesting
but u can do the same thing in python
does anyone know about back-propogation algol
Yeah pointers are not necessarily "pointers", just some sort of reference. Index arrays are the same thing, and probably more efficient than linked list trees
You definitely need to understand time complexity in order to write real world code. Unless you understand why a linked list performs better than a Python array for insertions in the middle, or why checking if an element is in a dict is much faster than checking if an element is in a list, you'll forever be choosing the wrong data structure to represent your code, and making it run much slower on real life data sets as a result.
it's true that most developers will never need to write a sorting algorithm, or build a dynamic array or a hash table in real world code - language's standard libraries give those things to developers out of the box, and it almost never makes sense to reinvent them yourself. But, if you don't understand time complexity, and to some extent space complexity, you'll never know when choosing one of them is the wrong option.
@lean dome guess i need to start following in my codes now.
Probably a dumb question... how exactly do i encrypt a large video/any file without slowing down the device. For example. suppose i have a video file of 50gb, how exactly should data be read for encryption process. A) Do i read & perform encryption operation on raw bytes of particular fixed length (like chunks) from original source B) Convert entire file to raw bytes and then do procedure A. c) any better solution, please suggest.
ur talking about compression right?
regardless of whether you're talking about encryption or compression, the answer is the same: read bytes from the file in fixed-size blocks, and feed those blocks to the encryption or compression library. The library may have a method for doing this for you.
from talking to someone who made a decompressor
u definately want to use threads to split up the work
if you've written it in Python, that will only make it slower.
@wraith valve but threads run pretty much random, how exactly do i know which thread completed which and which has not
use synchronisation
threads in Python cannot be used to parallelize Python code running in multiple threads.
mutex semaphore take ur pick
interesting...
i have a feeling with decoding or whatnot there is no shared data access
im not sure about the exact algorithm on how the video is chopped up
they can be used to parallelize IO bound code, but not CPU-bound code, because only one thread can be holding the GIL at a time, and only the thread with the GIL can modify Python data structures or execute Python bytecode. If the function running in the thread spends most of its time crunching numbers - like a decompression algorithm would - and that algorithm is written in Python (as opposed to in C, let's say), adding threads to the mix will only slow it down
but what if, i want the first-encrypted blocks hash needs to act as the key for second-block to be encryption key
i guess i should say the person that made a decompressor wrote it in c++
right - in that case threads could help much more than they could in Python.
then it sounds like you're trying to invent your own encryption algorithm, which is A Very Bad Idea
just learning,not re-inventing wheel
i mean how u would approach it depends on how u chop up the video?
like frame by frame or sth
you can do frame by frame? how isn't mp4 like properiatry code
idk for sure thats why i said depends on how u handle the vid
getting encryption right, in a way that makes it difficult to break and unable to leak information about the encrypted contents to someone who doesn't have the key, is very, very difficult. People spend their entire careers working on just that one problem. You really want to use an existing encryption algorithm. If your goal is to learn, you should look up how some existing encryption algorithm works and study it.
i mean things that are independent from each other can be easily parallelized
dont need to worry about synchronisation in those cases
The Cormen book? It's good. It's pretty much the standard algorithms textbook.
Quite mathy though, if that's not your thing.
from numbers import Real
from collections.abc import Iterable
def maximum(it: Iterable[int]) -> Real:
try:
maxi = it[0]
except IndexError:
return None
for i in range(len(it)):
if it[i] > maxi:
maxi = it[i]
return maxi
def minimum(it: Iterable[int]) -> Real:
try:
mini = it[0]
except IndexError:
return None
for i in range(len(it)):
if it[i] < mini:
mini = it[i]
return mini
``` Can I get some feedback on these max and min algorithms? is there any way to find the max and min without iterating?
there isn't, every item needs to be compared to find the min or max, but you can iterate through the items directly, without having to index:
def maximum(it):
mx = -float("inf") # Everything is greater than negative infinity, no need to prime the first value
for item in it:
if item > mx:
mx = item
return mx
would you return mx?
np
need someone to try my game dm .py
can anyone help me with genetic algorithm in python ? have to use it to solve a maze
with open(problem_set, "r") as stageFile :
I have a txt file named probem_set
and its in the same file with python file
so when I use open
It doesnt open my file
Anyone help ?
Found it nvm
I need to store a bunch of points in 2D space. Ordinarily, I would do this with a quadtree. However, I need to be able to handle toroidal space. What kind of data structure can I use for toroidal aabb queries?
if I have a list of tuples, where each tuple has 3 elements, can I create a key function for the sorted function so that the t[1] is ascending and if t1[1] == t2[1], the t[2] is descending?
[('a', 2, 100), ('b', 1, 19), ('c', 2, 27), ('d', 1, 25), ('e', 3, 15)] to become [('d', 1, 25), ('b', 1, 19), ('a', 2, 100), ('c', 2, 27), ('e', 3, 15)]
oh, okay lmao i m dumb
just needed to put a -
def for_sorting_tuples(t):
return t[1], -t[2], t[0]
tup = sorted(tup, key=for_sorting_tuples)
you can use a lambda function btw
I'm trying to print a graph (vertices, edges) using pyplot but it doesn't seem to work, for example:
x, y, z = node.get_pos()
circle1 = plt.Circle((x, y), .2, color='r')
plt.gcf().gca().add_artist(circle1)
throws an error matplotlib.units.ConversionError: Failed to convert value(s) to axis units: '35.212217299435025'
how do I plot properly for some (x,y) positions?
x and y are str?
how do i use a list of strings as a key for a dictionary/
the dicitonary is going into a pandas array if there is a better way to do this
you can convert it to a string or a tuple
you're welcome!
how do I append data to a column instead of a row
df["COLUMN INDEX"] = tempdf.iloc[:,3].tolist()
this puts it in a row
I followed what w3 schools did, but thier put it in a row and not a column
oh i see, its making itself a series
can i make the thing stay as a 1d dataframe?
So i'm doing this if first:
first = False
df = pd.DataFrame([stock, tempdf.iloc[:,3]])
else:
print(stock)
df[stock] = tempdf.iloc[:,3].tolist()
think i figured it out
stock and the tempdf thing needed to be swapperd
never mind
it didn't work
@sonic night #data-science-and-ml would be better, probably
since that's pandas-specfic
ok thanks
Hi, I would like to learn data structures and algorithms, can someone recommend me a good (free) resource?
Check the pins
Thanks π
Hi, I'm having trouble doing a question
The question is basically -
We have to put gears on every peg. Each gear will touch the gear to its right. Find the radius of the FIRST gear such that the speed of rotation of the last gear is half that of the first gear. If this is not possible return -1, -1.```
ping me if you respond please
hello. This is probably a stupid question, but Im trying to wrtie a summation function. I have a coefficent array, C, of size n and want to write the function:
sum (from i to n) C[i]*x**(2/2**i)
Instead of writing C[0]*x**2+C[1]*x**1+(C[2]*x**(1/2))+(C[3]*x**(1/4))+(C[4]*x**(1/8))+(C[5]*x**(1/16))
I could do this in a for loop, but there is probably a one line way of doing this, right?
you can use list comprehension + sum() function: sum([C[i]*x**(2/2**i) for i in range(len(C))])
Great, that works! Thanks!
you're welcome!
Hola, I want to learn data structure suggest in
can anyone suggest me good stuff to learn π
There is a link to an MIT course in the pins
tysm
http://www.usaco.org/index.php?page=viewproblem2&cpid=921 so i'm doing this problem
and i found this pretty helpful link: https://cp-algorithms.com/graph/tree_painting.html
however, this one is for painting edges- i have no idea how to paint the vertices in something like O(log n) as is in the problem
that's because even though each edge occurs only once, each vertex can occur multiple times
any help? (ping plz)
I just started with data structures and algorithms, in the first lesson of the MIT course a binary search algorithm is explained to find a peak in an array of positive integers, I understand why the algorithm works, but I can't explain it "formally", can someone help me?
Look up "heavy light decomposition"
i mean there's nothing other than hld here
you're most likely to not find too many CPers here, you might wanna join a cp server for that
oh ok then
What's the algorithm, specifically?
binary searches belong to a class of algorithms commonly called "divide-and-conquer algorithms". https://en.wikipedia.org/wiki/Divide-and-conquer_algorithm
For a divide-and-conquer algorithm, a formal proof that the algorithm works is generally done using proof by induction: first prove that it works correctly on an empty list, then prove that if it works correctly on a list of size N it will work correctly on a list of size N+1. https://www.comp.nus.edu.sg/~sma5503/recitations/01-crct.pdf walks through this proof for a typical binary search.
Hey all, does anyone have good resources for preparing for technical ML interviews? Currently an ML eng at big tech co. I've been using leetcode.com for coding prep for traditional data structures & algorithms, and datascienceprep.com for ML/stats questions, was wondering if anyone knew of others.
join kaggle
thats the main site for all ml competitions, it has a lot of datasets, some courses and communities too
so in the case of a binary search I'm just breaking down the problem by taking part of the array that will definitely contain a peak, and I can prove that the algorithm works by simply testing it on various inputs, right?
Hey so I am having problem understanding Space complexity
def avg(n):
sum = 0
for i in n:
sum += i
return sum / len(n)
print(avg([1,2,3,4]))
```What would the the Space Complexity in this and why?
what kind of formula would give this kind of graph (x can't be negative)
btw is there a tool where I could just draw a line and it would give me the formula for the graph? I know TI-Nspire has that sort of function but that's paid
I believe there's "regular" space, and then there's "auxiliary" space.
if you're taking the average of n numbers, you have to have at least n numbers in memory.
But what other memory do you need? It looks like there are only other two other numbers you need to keep track of: the running total (which you named sum) and the total number of numbers, which is given by the len(n) expression.
Note that it's always two extra numbers, no matter how many numbers n is.
It doesn't scale relative to the size of n.
So my guess is that avg has either an O(n) or O(1) space complexity. Because the amount of auxiliary space is a constant.
I was learning Big O : I understand that the time complexity is O(n) but I don't get why the space complexity is O(1)
for what algorithm?
the average of a list?
yea
alright, so I guess the space complexity is O(1) because the number of extra memories you need to solve the problem is a constant.
cosinus function from 0 to pi/2
ty
Or -x^2 + 1 where x is from 0 to 1
I don't know what "peak" means in this context, and you haven't linked to the algorithm you're asking about, so I can't say.
Not "is a constant" but "does not increase with the length of the input", to be precise.
isn't that what is usually meant by "constant" in the context of discussing complexity?
Yeah, O(1) is referred to as "constant time" commonly, but what it means isn't that it takes the exact same amount of time for all possible inputs, but that the time it takes is not correlated with the length of the input.
Imagine you've got an algorithm like:
def sleepy(lst):
time.sleep(lst[-1])
That doesn't always sleep for the same amount of time, but its time complexity is still O(1), because the amount of time it takes is not correlated to the length of the input list.
Same argument goes for space complexity. O(1) there doesn't necessarily mean that all possible inputs need exactly the same amount of space, just that the space required isn't greater for longer inputs.
it's O(last_item_in_list) though
Sure, but when we use O() we generally define N to be the length of the input, and that's what I'm using here.
sure
You're right that the time it takes varies with something, but that something isn't the sequence length, and so it is "constant time" with respect to the sequence length, even though it doesn't always take the same amount of time
Wikipedia phrases it this way:
the amount of time taken and the number of elementary operations performed by the algorithm are taken to differ by at most a constant factor.
Not that the time is literally constant, but that any difference in time is bounded by some constant
How would I go about sorting nested lists based on min() of say the 2nd element in the list, example [ ['id1',29]['id2', 36]['id3', 22] ] -> [ ['id3',22]['id1', 29]['id3', 36] ]
sorted([['id1', 29], ['id2', 36], ['id3', 22]], key=lambda x: x[1])
comparison-based functions like sorted, min, max, etc. have a key argument where you pass a function that will get called on each element. And that function needs to return what value can be used to sort the object it came from.
Often it's going to be a lambda, like in sumedhbala's example.
though it can really be any function.
!e
strings = ['Hi!', 'Apple', 'abcd', 'bOb']
strings.sort(key=str.lower)
print(strings)
@oblique panther :white_check_mark: Your eval job has completed with return code 0.
['abcd', 'Apple', 'bOb', 'Hi!']
The strings get sorted in terms of their lower-case form, so 'Apple' doesn't go before 'abcd'.
What you want to do is to sort by first attribute (AACG, NWS...) then by second attribute (date)
For example, if we have this array: [(4, 5), (4, 2), (6, 8), (1, 2), (1, 9)] and we want to sort it by first element then by second element, we would write: sorted(arr, key=lambda x: (x[0], -x[1]))
the minus is to sort in descending order, which is what you want to do with your dates
and this is what we get [(1, 9), (1, 2), (4, 5), (4, 2), (6, 8)]
now try to find a way to do the same thing with your problem
you can do that ye
with open('data.csv', "r") as file:
lines = file.read().splitlines(True)
data = lines[1:]
data.sort(key=lambda x: (x.split(", ")[0], datetime.datetime.strptime(x.split(", ")[1],"%m/%d/%Y"), float(x.split(", ")[2].replace("$",""))))
with open('data.csv', 'w') as fout:
fout.write('Symbol, Date, Close/Last\n') # adding csv header
with open('data.csv', 'a') as fout2:
fout2.writelines(data[1:])```
is there a way to print it, export it to csv just so i could look at it's content easily
What's a good book for learning about algorithms
well you can just google it but
a) clrs is the bible . The book if you want to learn everything. It has pseudocode
b)sedgewick's book (the C++ one) is also very interesting . The C one is outdated but again both books aren't in not in python so headsup there.
Knuth if you want to learn really really everything
For pseudocode -> code , you can always look up python implementations of the said algorithms !
It doesn't have anything regarding IDA*, BFS or DFS
Ah, thanks
can someone help me in solving this problem with Python 3.8? I'm beginner so i can't solve but i want to know solution of this
Hey @tawdry shard, is that a graded exam?
it's like an exercise from my course, and as i said i'm beginner, couldn't solve it so i thought if i asked you guys for help then you can help me
yeah i know, but the problem is i don't know how can i solve it in python
Aside from the already mentioned CLRS, another good book is The Algorithm Design Manual by Skiena. The thing I like about it is that it's filled with "real world" examples & applications. Depending on where you're located, you might be able to check it out as an eBook from your local library.
isn't skiena hard tho
i haven't used it but from what i have seen it is more into the design logic etc
it is good book , yes
It's not any harder than CLRS, imo.
Can you describe some example?
aren't you talking about an n-ary tree?
adding a character to a string creates a whole new string because strings are immutable in Python
right but like someone benchmarked it and it doesn't behave like that
unpredicatable basically
For understanding: that would make the above code snippet quadratic in time and linear in space?
better use an array then join
yes
How do i get the index of an element in a pandas series if i have the value, like mySeries.index(myVal)
You would be better served in #data-science-and-ml, #algos-and-data-structs is generally for CS stuff
would someone please help me with a problem? I started learning python 2 days ago and i'm stuck on a homework problem
does anyone know about the vigenere cipher?
Did you check this https://www.youtube.com/watch?v=SkJcmCaHqS0 ?
This video is part of the Udacity course "Intro to Information Security". Watch the full course at https://www.udacity.com/course/ud459
Python noob here, can anyone lend me a hand in trying to get a simple program I am working on working?
I'm creating a shopping list generator. I want it to randomly select X number of meals, get the ingredients for making each meal, append them to a list. I have done this part, but now I want the program to sort the shopping list items by category (produce, meat, dairy, etc.). this is where I'm stuck
shopping_list = sorted(shopping_list, key=lambda item: item.product)
and I assume I'd need to define what category items belong to, which I am currently trying to do in a JSON file, right?
or is there a better way?
I can share a snippet if it helps
yes show please
sure
this is my JSON file that I am using to outline the ingredients for each meal, while also assigning the ingredients to categories
{
"grilled chicken caesar salad": {
"produce": ["romaine lettuce", "tomatoes"],
"meat": ["chicken breast"],
"dairy": [],
"grocery": ["caesar dressing", "garlic and herb croutons"],
"deli": [],
"bakery": [],
"frozen foods": []
},
"reubens": {
"produce": ["pumpernickel bread"],
"meat": [],
"dairy": [],
"grocery": ["thousand island dressing", "sauerkraut"],
"deli": ["swiss cheese", "pastrami"],
"bakery": [],
"frozen foods": []
},```
and this is my .py file, the area where I am stuck I suppose
# determines number of meals to make a shopping list for
number_of_meals = int(input("Enter how many meals: "))
# reads from the JSON file. Creates a Python dict object.
with open('meal ingredients2.json', 'r') as json_file:
data = json.load(json_file)
# selects a random assortment of meals. The # of meals depends on value of number_of_meals variable above.
meals_selected = random.sample(data.keys(), number_of_meals)
print(meals_selected)
# for every selected meal, this loop grabs the ingredients needed and compiles a list. The list contains all the ingredients needed for all selected meals to be prepared.
ingredients = []
for item in meals_selected:
ing = data.get(item)
ingredients.extend(ing)
print(ingredients)```
yes so you need something to know the category of a product
does the structure of my JSON file accomplish that, or no? would this be a good use for classes?
wait I didn't fully get what do you mean by sort the shopping list, can you give me an example?
sure
so instead of an unorganized list of things like:
apples
chicken breast
peanuts
toothpaste
dental floss
bottled water
milk
eggs
it's sorted depending on the area of the grocery store they're found in, so:
PRODUCE
apples
DAIRY
milk eggs
PERSONAL HYGIENE
toothpaste
dental floss
so on and so forth
yes so you need a dict that contains each product and its category
like in general, not necessary of one specific recipe
then when you have a shopping list, you can organize it by transforming it into a map where the key is the category and the value is a list of ingredients
Example:
category_map = {"apples": "produce", "toothpaste": "personal hygiene", "dental floss": "personal hygiene", "milk": "dairy"}
now if you have shopping_list = ["apples", "milk", "dental floss", "toothpaste"]
you can organize it by writing:
for product in shopping_list:
organized[category_map[product]].append(product)```