#algos-and-data-structs
1 messages ยท Page 23 of 1
Hi below is code which has puzzled me about dictionaries:
Love it, if anyone could explain why this behavior is for dictionary and not for other variables.
def count_char(text, count={}, num=0):
for t in text:
count[t] = 1 + count.get(t,0)
num += 1
print("dict - inside function =",count)
print("var - inside function", num)
return count
count_char('abc')
count_char('efg')
count_char('hij')
Output :
dict - inside function = {'a': 1, 'b': 1, 'c': 1}
var - inside function 1
dict - inside function = {'a': 1, 'b': 1, 'c': 1, 'e': 1, 'f': 1, 'g': 1}
var - inside function 1
dict - inside function = {'a': 1, 'b': 1, 'c': 1, 'e': 1, 'f': 1, 'g': 1, 'h': 1, 'i': 1, 'j': 1}
var - inside function 1
Why when i change text in file it still prints old information ?
# Using readline()
lines = [0,1,2,3,4,5,6,7]
i = 0
result = []
while True:
with open("myfile.txt", "r+") as fp:
# access each line
for line in fp:
# check line number
if i in lines:
result.append(line.strip())
i = i + 1
testas1 = result[0]
testas2 = result[1]
testas3 = result[2]
testas4 = result[3]
testas5 = result[4]
testas6 = result[5]
testas7 = result[6]
testas8 = result[7]
print(testas1)
print(testas2)
print(testas3)
print(testas4)
print(testas5)
print(testas6)
print(testas7)
It happens with every object as a default value for a parameter in Python. It's just that with mutable objects, operations performed on them don't result in a new one, so you're left with an edited version of the original object (that's what mutating an object means). Python dictionaries are mutable objects, so the object in each call with the default value is the mutated dictionary throughout the program's runtime (Python assigns the parameter the same object as a default value, so if it is mutated, you get to keep the changes).
how to keep counter for number nodes for doubly linked lists
!dictionary
you just want the answer directly?
no help or suggestions at all?
would this sol work as well
import time
arr = list(map(int, input().split(" ")))
st = time.time()
diff = 10**9
for i in range(len(arr)-1):
curr_diff = abs(arr[i] - arr[i+1])
if curr_diff < diff:
diff = curr_diff
print(diff)```
(as in being linear time)
guys for be developer advanced in python what i need to know?
shouldn't you be able to verify that yourself by looking at the code? 
how many times does the inner part of the loop run?
the inner part of the loop will run once for each element in the list, except for the last element.
wait what
npnp
so?
correct
thanks fr
so when testing this and any other code i have, with the max input and time contraints
was just curious how id do that
i have my code already
just wanna see if it satisfies the contraints
which is 10000
and then 9 seconds
have my code already
generate a hard case
you know the constraints, you should have some idea of what case would make your code run slow, generate the worst case you can within the constraints
in the previous thing only the array size matters, in other problems the worst case might be harder to know
wouldnt he need to make a program to calculate the time
and test the constraints?
you can't test the constraints without having some inputs close to the worst case 
You have two python range objects, xs and ys. Assume they are normalised so that xs.step > 0 and ys.step > 0. How would you go about finding the smallest integer z such that z in xs and z in ys? Also, how would you find out if they intersect at all (that is, set(xs) & set(ys) != {})? I know it has something to do with modular arithmetic ๐
sorry, you're right
so what would the inputs be
im curious now
I'm not sure, seems like you would want to maximize the number of overall neighbors within 2 steps
aren't you just checking the bounds? i don't think modular arithmetic comes in. if they intersect the bounds will overlap (one will start before the other ends)
I think connecting a bunch of nodes with 70 connections each together is the best you can do
but not entirely sure
different steps
ah
so gcd ends up mattering
E.g. if xs = range(0, 10, 2) and ys = range(1, 10, 2), then they don't share any numbers in common at all ๐ค
it's a diophantine equation
Oh no
start1 + step1*x = start2 + step2*y
In mathematics, a Diophantine equation is a polynomial equation, usually involving two or more unknowns, such that the only solutions of interest are the integer ones. A linear Diophantine equation equates to a constant the sum of two or more monomials, each of degree one. An exponential Diophantine equation is one in which unknowns can appear ...
Ah right ok ๐ค How would I go about solving for x and y?
allowing for arbitrary x and y, there generally are either 0 or โ solutions
(iirc)
what you tend to do is find one solution, and then solve a related equation to get all solutions
specific and homogenous solutions, I think the terms are
but yeah, read the wiki section
Looks like the solution is right there. Thanks!
that will give you the family of all solutions, you might need to do some small work to get the one you are interested in
picking the appropriate k
what is the best way to calculate operations of graph/path finding algorithms
i wanted to know what is the most efficient data structure for this
then i can code
in general we can use dictionary
but is there any better way
Just to check my understanding of time complexity, this thing is time complexity O(n), right?
https://wiki.python.org/moin/TimeComplexity
it should be.
iteration is obviously O(n), but set/dict membership detection can be, in the worst case, O(n) as well (otherwise O(1)). This means the worst-case is O(n^2), with average case of O(n)
the reason for this is that it's technically possible for a hash algorithm to produce the same hash for all of some number of inputs, and that means linear search is required, which is O(n)
although if you found a series of inputs that hashed to the same value, thus making set/dict detection O(n), you could probably submit them as a bug, and the hash algorithm might get changed
Thanks
it would depend on the elements in array, but probably O(n)
it's trivial to make this happen for ints, because the hash function is basically identity
but for some reason int hashes weren't randomized like str hashes were
the reasoning is that it's less common irl to have a lot of ints like you would strings
plus like, the periodicity is like 2^61 or something
2^61 - 1
that's the most trivial way of causing collisions, but there are others
that doesn't need as huge numbers
idk why they didn't just do a sane hash for ints as well
and that's not true for string hashing?
i don't think you can apply the idea of periodicity to strings, though. sure if you got 2^61 strings at least 2 would have the same hash
so why was string hashing an issue?
I'm sure it must have been pretty easy to construct collisions
otherwise no-one would have cared
they said it was more common than ints, i think
strings are probably more common as a type in general
but that doesn't really justify leaving int with a bad default hash
yeah tbh it's a little strange. i think the reasoning is because it's really fast, but like, how much benefit does that give a program?
I don't think modern hash algos have that much overhead
in fact python already has siphash for strings, you could easily use that for ints as well
just hash the bytes that makes up the int digits
rust also uses siphash
is it worth getting https://cses.fi/book/index.php for learning more abt dsa or is the pdf version enogh?
can someone explain this please
i dont understand the step size part of this
from my understanding, if we had string = "Hello World"
then string = [0:6] would output only World, correct?
but then i dont really undertsand the step size digit here
(hw problem)
D i think
i wanna understand it
its empty
what
uhh
i think D bcs without -1 it would output a string but with its doing steps of -1 and idk how to say it
wheres the -5 string
ahhhhhhh
okok makes sense
so -5 in the string xs = "0123456789"
would be 5, since counting backwards from the end of the given string is how we index negative numbers
thanks
i think its none of the above actually ๐
if you're on ur pc try using an IDE to see for yourself
this seems like a trick q ngl
nvm it is D
bruh this is weird
im thinking of learning C++ for algos, since its the best language for competitions, what do you guys think? or python is a viable option
python
so i appended these random email adresses from .txt file to a list of strings, when i print the entire list, all the adresses have a \n at the end, however when i print them individually this \n doesn't appear, can someone tell me why?
\n is a newline, and you do see them
print prints space separates, but you get a newline then a space
you can use .strip() to remove surrounding whitespace from the string
thx
from discord.ext import commands
bot = commands.Bot(command_prefix='.')
@bot.command(name='spam', help='Spams the input message for x number of times')
async def spam(ctx, amount:int, *, message):
for i in range(amount): # Do the next thing amount times
await ctx.send(message)
bot.run('TOKEN HERE')
what is wrong in it?
Hi guys, I got a problem on my loss function:
def loss(G: nx.Graph, output):
_loss = 0
choices = torch.argmax(output)
for u, v in G.edges:
if choices[u] and choices[v]:
_loss += 1
return _loss
output is from my torch model, and I want to minimize this loss function. unfortunately, var loss is not derivative with output. Is there any way to replace my for loop using torch operations?
should I change this wide format to long ? say add a column with wine,beer,vodka,champagne,brandy
Hello, stupid me has a question, at my university they want to host a poker bot battle.
I don't think i'm anymore capable enough to participate but the idea still intrigues me
What would be the smartest approach ?
Mine would be to refer look up tables but it seems not efficient at all, a bit dawning
lookup tables are the best. you can precompute chances of all the possibilities

Anyone know an Algo to compare the data of two non binary trees. For example compare the following two trees
Hey guys do you have any resources to practices recursion questions
Does anyone know of any program where you can find the Big O notation of a function? I have a set I'm working on and would like to check my answers (professor refuses to give answers even though its a practice :/ )
How are you wanting to compare them? Take a value from each node and find the greater one, replacing elements, etc
Can't you check the elements of the list on the left to see if they are in the list on the right ?
Yep. Starting from 1 those are possible BFS and DFS sequences. Obviously it depends on how you go about choosing at each step if you have several nodes to choose from.
For example, if you always choose the successor with the smallest label, then the DFS sequence would be 1, 2, 5, 4, 9, 7, 10, 3.
I see. Interesting, thank you
is it bad to get there warnings everytime i install a new package?
Can someone help me do a really simple mvvm javascript code?
I can't find any simple one that can run online
Can you show what command or package youโre getting this with?
i was getting tensorflow, but this happens with every package i ever downloaded, i used pip install tensorflow --user
bcs with just pip install tensorflow it wouldn't work
Are you installing in an env or through vscode terminal or through cmd?
negative indexes start from the end, step is the last digit [start: end :step]. indexing starts with 0 (number 0 is at index 0).
negative step goes from left to right ex. 'hello world'[::-1] would return 'dlrow olleh' ('hello world' spelled backwards)
How can I loop through my dictionary to find values > 1?
use dict.values()
sorry for the late reply i went to sleep, i install through vs code
Is there a way to get a hashing algorithm by a string value?
by "to get" do you mean use or do you mean get a list of the available hashing algos?
If the former, you can use hashlib.new(algo_name)
if the latter, you can use hashlib.algorithms_available
this is documented here => https://docs.python.org/3/library/hashlib.html
Ok thanks this was my question
are you installing it in a virtual env? If not, try installing through cmd
Guys I have a question
the question isthis - "calculate the length of python string without any inbuilt functions or using for loop or changing the given string's value and without exception handling"
I bet noone can solve this
so simple yet irritating
I solved it
but took me 6hours to do it
what about||```py
s = "pineapple"
l = 0
while s[l:]:
l += 1
print(l)
this was my solution
||```py
x=str(input())
i = 0
while True:
if x[-1:i:-1] == x[-1]:
i+=1
break
else:
i+=1
print(i+1)
ctypes isn't builtins 
aww, I think I would need id though
!e
import ctypes
len = ctypes.cast(id('this is 26 characters long')+16, ctypes.POINTER(ctypes.c_size_t)).contents
print(len)
@haughty mountain :white_check_mark: Your 3.11 eval job has completed with return code 0.
c_ulong(26)
guys what does null value do in database?
Hi Everyone,
Question!
If I have a Series which contains something similar to this:
2021-12-12 True
2021-12-19 True
2021-12-26 False
2022-01-02 False
2022-01-09 True
2022-01-16 True
2022-01-23 False
How could I ask Python to extract only the dates of the first occurences of True?
Meaning, my expected result would be:
2021-12-12
2022-01-09
Thanks!
divide by total
Is there a better way to write this?
def time_taken(self) -> timedelta:
value = timedelta()
last_date = None
for curr_date in self.timestamps:
if last_date and curr_date.flag == TimestampFlag.stopped:
value += abs(curr_date.timestamp - last_date.timestamp)
last_date = None
if curr_date.flag == TimestampFlag.start:
last_date = curr_date
if last_date:
value += abs(datetime.now() - last_date.timestamp)
return value
TimestampFlag is an enum and self.timestamps is a list of objects. The object only has a timestamp (datetime) and flag properties.
I've been playing with this for a bit, a better way is to improve readability
first I had the logic for calculating the time taken moved into a separate function
def calculate_time_taken(start_date: datetime, end_date: datetime) -> timedelta:
return abs(end_date - start_date)
function will be triggered everytime TimestampFlag.start is in the self.timestamps list, and the time taken will be added to the value variable.
this would help you avoid the same logic multiple times
here's the full code from my end
from datetime import datetime, timedelta
from enum import Enum
class TimestampFlag(Enum):
start = 1
stopped = 2
class Timestamp:
def __init__(self, timestamp: datetime, flag: TimestampFlag):
self.timestamp = timestamp
self.flag = flag
class Timestamps:
def __init__(self, timestamps: list[Timestamp]):
self.timestamps = timestamps
def time_taken(self) -> timedelta:
value = timedelta()
def calculate_time_taken(start_date: datetime, end_date: datetime) -> timedelta:
return abs(end_date - start_date)
last_start_date = None
for curr_date in self.timestamps:
if curr_date.flag == TimestampFlag.start:
last_start_date = curr_date
elif curr_date.flag == TimestampFlag.stopped and last_start_date:
value += calculate_time_taken(
last_start_date.timestamp, curr_date.timestamp
)
last_start_date = None
if last_start_date:
value += calculate_time_taken(last_start_date.timestamp, datetime.now())
return value
def test_timestamps():
# Define a list of timestamps with associated flags
timestamps = [
Timestamp(datetime(2022, 10, 1, 8, 0, 0), TimestampFlag.start),
Timestamp(datetime(2022, 10, 1, 8, 30, 0), TimestampFlag.stopped),
Timestamp(datetime(2022, 10, 1, 9, 0, 0), TimestampFlag.start),
Timestamp(datetime(2022, 10, 1, 10, 0, 0), TimestampFlag.stopped),
]
# Create a Timestamps object with the defined timestamps
t = Timestamps(timestamps)
# Calculate the time taken for the timestamps
time_taken = t.time_taken()
# Print the time taken
print(time_taken)
# Expected output: 1:30:00
test_timestamps()
Hello,
A functional approach could be to use itertools.groupby (https://docs.python.org/3/library/itertools.html#itertools.groupby) on the second field (boolean) and get the first result of each group (and this first field i.e datetime)
Not a difficult implementation/solution, i let you try first ^^
Hi Guys!
i need help to flatten JSON inside Pandas DF cell and turn it into a new DataFrame.
i tried, among other things, pd.json_normalize(df['col_name'] but i get an error string indices must be integers
when i check cell's type with type(df['col']), i get Series
any ideas on how to unpack the cell's values that look like a JSON and create a new DF?
figures it out
all good
I have question Can we really add valiable after object, models.___ , if i get parameter and add after obeject Or should i make if else?
I ended up using a for loop and copied the initial list twice each time using an incremented shift but I'm curious about the group by approach so I'll try that out!
Thank you!
Heyo! So I've been learning stacks, and part of the applications is conversion of expressions, and this is where I got stuck. The algorithm to convert an infix expression to postfix is quite straightforward. However, infix to prefix is not.
The algorithm taught to us to convert infix to prefix is -
1) Reverse the infix expression, taking care of parantheses
2) Convert the reversed infix expression to postfix
3) Reverse the result of step 2 to get the prefix
However, when I convert the given infix expression manually, the result is vastly different. For example, for the expression A+B*C/D+E the manual conversion led to ++A/*BCDE whereas the result of the algorithm is +A+*B/CDE
Now I'd like to know where I'm going wrong with this concept. Any help is greatly appreciated.
Here a very simple/naive implementation with itertools.groupby tool :
>>> series = [
... ("2021-12-12", True),
... ("2021-12-19", True),
... ("2021-12-26", False),
... ("2022-01-02", False),
... ("2022-01-09", True),
... ("2022-01-16", True),
... ("2022-01-23", False),
... ]
>>> from itertools import groupby
>>> [next(g)[0] for k, g in groupby(series, key=lambda t: t[1]) if k]
['2021-12-12', '2022-01-09']
Enjoy ^^
ps: i'm in love with functional programming and short one-line code ๐
I will probably have more questions like this!
Thanks for your help!
for i in range(1, 3):
data = createList(i)
file.write(str(data))
Hello. I am trying to implement a function that writes in a file a list of lists that i create with createList function.
However this function does something like [[1, 2], [3, 4]] [[6, 7], [8, 9]].... And I want something like
[[1, 2], [3, 4], [6, 7], [8, 9].....]
Is there any way to concatenate those newly created lists in the for loop?
when you don't know when to take a break from typing, your compiler will let you know :v
Step 1:
Reversing one level at a time, starting from the outer layer and working inwards:
(A + ((B * C) / D)) + E
E + (A + ((B * C) / D))
E + (((B * C) / D) + A)
E + ((D / (B * C)) + A)
E + ((D / (C * B)) + A)
Step 2:
Again, one layer at a time from outer to inner
E + ((D / (C * B)) + A)
E((D / (C * B)) + A)+
E((D / (C * B))A+)+
E((D(C * B)/)A+)+
E((D(CB*)/)A+)+
Step 3:
Should be obvious to see that reversing the result of step 2 gives +(+A(/(*BC)D))E, which is indeed the correct prefix version of the expression.
I wanted to ask if anyone knew Solana blockchain development in python
Thanks for the detailed explanation. I think I get where I went wrong. I didn't handle operator precedence in step 1, leading to confusion in step 2 since the precedence is not the same as that in step 1. This helped a lot :)
No problem. Glad it helped
you dont need ( and ) here
++A/*BCDE is also valid
I know. But it's easier to see precedence with them.
Is there a built-in Mapping type in Python that can hold arbitrary objects as keys including impossible to hash types? I don't really care if lookups are O(n) and identity can be compared naively with __eq__ but I just want to know if I should make one for myself or one already exists in the stdlib.
isn't that just a list, then
if you just have __eq__ (not even __lt__), then you pretty much can only use a list
Yeah, I would just build it as a list of tuples, I just wanted to know if something that already implements the Mapping protocol already exists. Guess not.
yeah or just 2 lists
Hey guys, so I have a doubt...
I've got this huge dataset and it contains 30 parameters which result/affect one target parameter.
I'm supposed to find out the pattern or the logic in which the other parameters affect the target parameter.
Is there any library or package available for it or is there any way I could do it in simple steps? ๐
tensorflow?
im having a preety strange problem
def updatesensor(self):
#Variables so it soesn't call the same sensor data more than once
#Increases speed reduces error
acc = self.accelerometer.acceleration
#print(acc)
ambient_pressure = self.bmp.pressure
self.sensordict = {
'time': time.time(),
'acc_x': acc[0],
'acc_y;': acc[1],
'acc_y;': acc[2],
'acc_resultant': (acc[0] ** 2 + acc[1] ** 2 + acc[2] ** 2) ** 0.5,
'solenoid1': self.solenoid1.value,
'solenoid2': self.solenoid2.value,
'solenoid3': self.solenoid3.value,
'solenoid4': self.solenoid4.value,
'solenoid5': self.solenoid5.value,
'gps_alt': self.gps.altitude_m,
'gps_latitude': self.gps.latitude,
'gps_longitude': self.gps.longitude,
'gps_speed': self.gps.speed_knots,
#'bmp_temp': self.bmp.temperature,
'bmp_altitude': 44307.7 * (1 - (ambient_pressure / self.bmp.sea_level_pressure) ** 0.190284),
'bmp_pressure': ambient_pressure
}
and it returns this
{'time': 1670799768, 'gps_latitude': None, 'gps_longitude': None, 'acc_x': -5.64863, 'bmp_pressure': 1013.99, 'bmp_altitude': 46.8398, 'gps_alt': None, 'solenoid4': False, 'acc_y;': 7.33537, 'acc_resultant': 9.86718, 'solenoid5': False, 'gps_speed': None, 'solenoid1': False, 'solenoid2': False, 'solenoid3': False}
why is it mixing my dictionary up?
Because dict are not ordered on old python versions
What version are you using?
Dict are ordered after 3.7 iirc
You can use list of 2-tuples for unhashable keys and dict for hashable keys
It will be faster if you have a lot of hashable keys and only several unhashable
Hello, I was wondering if there is an algorithm that given a list of numbers and a target number, the algorithm finds the smallest sum of a list of numbers that is greater than or equal to the target number:
numbers = [2, 4, 5, 3, 1]
target_number = 12
print(find_lowest_sum_numbers(numbers, target_number))
Output:
(2,4,5,1)
Thanks in advance!
Hello!
How do you write a for loop in list comprehension where the result depends on an external variable?
cwd = Path()
level = 0
result = []
for row in rows:
cwd = adjust_cwd(cwd, level, row.level)
if row.is_row():
result.append({path: cwd / f"{row.name}.md"})
else:
cwd = cwd / row.path
result.append({path:cwd})
level = row.level
hi guys.
I need some tips before practicing OOP design patterns.
I am a developer for around 5 years - I know OOP in a "general" way, i mean... I don't know what's a "factory" pattern, but will definitely know when and how to use it (i think, and that's why i want to practice).
- Is it recommended to know all patterns names and common uses?
- How is it best to practice these kind of stuff (not a beginner). Just build an "vanilla" python OOP based app?
I would like some kind of a pro review of my app. how do people write code today and make sure that they are doing it "the right way"๐ค
py```
def format_name(f_name, l_name):
if f_name == "" or l_name == "":
return "You didn't provide valid inputs."
formated_f_name = f_name.title()
formated_l_name = l_name.title()
return f"Result: {formated_f_name} {formated_l_name}"
#Storing output in a variable
formatted_name = format_name(input("Your first name: "), input("Your last name: "))
print(formatted_name)
why does this work as intended but when I swap it to py
if f_name or l_name == "":
do SAS plats like AWS utilize parallel processing?
it's hard to imagine why they wouldn't
whats the point of talking about data structures and algoritmes, in one of the slowest languages known to man
whatever you write, an amateur in a language like rust, c++ or golang, can prob make it a few 100 times faster, and prob despite an expontial time complexity
and the other problem is that even if you have a time complexity of say O(n) for an algorithm instead of O(50*n), that doesent mean that O(n) is faster,
if you have terible cache locality or the problem cant be processed in paralel, it could still be allot slower
i mean, switching languages is just a constant factor speed increase :P
so whats your point?
the point of learning DSA is not so that you go out and implement them on your own everywhere. your goal is to learn the concepts. in some cases, the language you're writing it in does matter (but not for the reasons you mentioned) in my opinion, but concepts can be learned in any languuage
also, i don't really get your last two sentences, they don't connect with the first part
whats dsa?
but whats the point of learning these concepts, if your not gonne implement them?
so every time you need to sort a list you just write your own mergesort implementation?
the goal is to get exposure to algorithms and learn what tools to use in each situation
no you just use the builtin sort in python
data structures and algorithms
im pretty sure almost any tool you can imagin already exists in a module in python so why spend the effort to learn all of em, if your not gonne go out of your way to try to implement something faster
sure
you can just black box them, and just learn how to use them, not how they work, that would save time
my terible english
and in the case that you do want to make something faster, your prob just gonne hand that fast algorithm you made, to someone who can implement it as a module instead of doing it yourself
hello! I was wondering if anybody had any ideas for using combinations/itertools to get all possible combinations of "event outcomes?" Currently I am putting each outcome into a big list and getting the combinations of those, but it contains tons of invalid combinations with multiple outcomes for the same event.
And filtering them post-hoc is taking way longer than I suspect a native itertools function call would take
if working around the math formula for combinations takes too long, look intro libraries such as asyncio and numpy, they improve the performance by a lot
getting the combinations themselves is pretty quick its more filtering out the invalid ones thats a problem
but I guess just getting the combination iterator isnt the slow part anyway
its more actually iterating through them all
the point is knowing what kind at algos and data structures are available and how they work
if you don't know they are available you can't use them to solve a problem
if you don't know roughly how they work you won't know why and when something is applicable
And the considerations that goes into picking the right algorithms for a problem.
I see learning about ds&a as adding tools into your toolbox, and familiarizing yourself with how to use those tools
Hey! Is there any way to filter a list of lists by lists with a specific column value without using Pandas?
I've looked up on the internet but didn't find anything that satisfies my needs.
Thanks in advance :)
I was able to do what I was trying by using Cartesian product rather than combinations. Put the outcomes of each event into a list and then those lists into another list, then get product(*listOfLists)
But it still makes my computer crash. I think there are just too many combinations
HEX_FILTER = ''.join(
[(len(repr(chr(i))) == 3) and chr(i) or '.' for i in range(256)])
print(HEX_FILTER)
word = 'Error\t'
map = '..eror'
map2 = 'omk'
print("with hex filter:", word.translate(HEX_FILTER))
print("with map:", word.translate(map))
print("with map2:", word.translate(map2))
# output:
#
# with hex filter: Error.
# with map: Error
# with map2: Error
pls help me understand this :/
Hello I'm trying to type an algorithm that basically finds the number of different ways square shapes can fill a random given XY Grid
For example there is only 1 way to fill 1x1 grid and that's by puting a 1x1 square, there are 2 ways to fill a 2x2 grid first is 4 1x1 squares and second is 1 2x2 square, how can i approach this problem without brute force?
when you fill a square, do you need to use squares that are all the same size? or does this count as a filling:
##...
##...
@@...
##@##
##@##
(1 3x3, 3 2x2, 4 1x1)
is that a 5x5 grid?
yeah
yeah that fits what i need
like that would be a way to fill 5x5
they just have to be squares
makes it tougher, but i suppose there's probably some smart way to break it into smaller pieces
i already did find a way
by brute forcing every 4x4
way to fill
which is finding combinations of position each XxY size has to fit
but still working on it
I've written this little code but for some weird reason, when I execute it, the print(Fore.GREEN + "[+] Writing bytes into \"" + file + "\"", end="") gets outprinted after the writing is done
print(Fore.GREEN + "[+] Writing bytes into \"" + file + "\"", end="")
start_time = get_current_time()
with open(file, "wb") as f:
f.write(bytes("1".encode("utf-8") * size))
time_taken = get_current_time() - start_time
print(" Done(" + format_time(time_taken) + ")")
Have you tried an f-string?
How do you mean this?
This didn't fix my problem
Ok I found out that this is because of I print it with end=""
But why? I need to stay in the same line
What should I do
I did ANOVA two-way hypothesis testing and made this mistake : ValueWarning: covariance of constraints does not have full rank. The number of constraints is 9, but rank is 1
I have no null value in my data, but I don't know how to fix it
@codeine#1240
did you find the solution?
Yes. You have to set flush=True, because normally the buffer is only flushed after a new line or longer string
Hi guys--I have an operations research question
Is there any Python library, that given a convex set of constraints, can just generate N random feasible solutions?
I.E. I have a non-convex objective, and do not wish to use mixed integer programming due to computational costs in general, so instead, would like to simply enumerate 1000 random feasible solutions, and take, say, the top 20 or so in order to feed into a convex optimization problem.
Is there some exiting Python library that'd allow me to do this?
Pyomo is pretty good for optimization problems
What do u guys think about 4/6/8 month-1 year data science bootcamp? Especially for undergraduate IT student
class Solution:
def maxProfit(self, prices: List[int]) -> int:
l, r = 0, 1 #left is buying, right is selling
maxP = 0
while r < len(prices):
if prices[l] < prices[r]:
profit = prices[r] - prices[l]
maxP = max(maxP, profit)
else:
l = r
r += 1
return maxP
i don't understand the point of l = r
as opposed to l += 1
Best Time to Buy and Sell Stock - You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot ac...
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
hashset = set()
for n in nums:
if n in hashset:
return True
hashset.add(n)
return False
what's the advantage of using a set instead of a list?
and also, don't sets contain only unique items?
Contains Duplicate - Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
Input: nums = [1,2,3,4]
Output: false
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Constraints:
...
actually it works because sets only store unique items
i think i figured it out
well this solution doesn't depend on sets only having unique items. it uses a set because it's fast at checking if it contains an element or not
yea
weird, bc a list doesnโt work for the test cases
but it is correct
Wait
Lists times out?
That is strange
N only goes up to 1e5 and the solution is O(nlogn)
it's n^2
I have a begineers problem here with python and pandas. Trying to get the example running. Heres all I've done in the dir.
mkdir pandas; cd pandas;
python -m venv .
bin/activate
pip3 install -r requirements.txt
python3 pandas.py
This is where I get the error
ModuleNotFoundError: No module named 'pandas.core'; 'pandas' is not a package
My requirements file is pretty simple
yfinance
numpy
pandas_ta
Any idea what I'm doing wrong here?
I want to dynamically split up a task into n threads. How can I get n depending on how much the hardware of the pc can take
A bit of googling of python cpu count later, looks like there's a builtin for that, https://docs.python.org/3/library/multiprocessing.html#multiprocessing.cpu_count
also i think ThreadPoolExecutor uses that as the default
processpoolexecutor, presumably
yeah something like that
Wait am i missing something
The sol with lists sorts the lists
Which is O(nlogn)
not his solution with lists
And the linear checks the list for duplicates
Oh
I thought u were saying that lists are too slow for this problem
My mistake
I misunderstood
hello guys i want to learn data structure via python, i want complete topics like linked list, trees, dijkstra algo and everything please suggest me any course or youtube channel
Im making a script with which you can create files with a given size, I add the bytes together with size * '000000000000000000\n but this takes way to long. What can I do about it?
Do the contents need to be ASCII '0' characters, or is anything that takes up space good enough? If you just need to take up space, open the file in binary mode ("wb"), seek to the desired size with seek, and then close the file
Does it have to be a python script?
You can use fallocate (at least on unix)
https://unix.stackexchange.com/a/381339
do trees appear often in contests(not leetcode)
im thinking about skipping trees for now since i havent seen any tree problem except in leetcode contests
How can I make a hash function that's around as fast as the inbuilt hash function?
Also without using any other libraries
You might not see trees directly but for many problems on there it's helpful to think of it like a tree and do recursive traversals on it
I'd assume the inbuilt one is implemented in C for all the primitive types, so if you wish to do so in Python that would always have extra overhead
I see, so what would be the best hash function even if it's not as fast as the inbuilt one?
This is hard to answer generally tbh. What's your use case? You can have a simple but fast hash function which might work well for certain types of data but not others
If you want a good general purpose hash function there's a few common ones you can find, I don't know about their performance in python
okey so i am reading https://runestone.academy/ns/books/published/pythonds3/Introduction/ObjectOrientedProgramminginPythonDefiningClasses.html tthis and i have trouble understanding concept of Connector implementation
so basically this ```
g1 = AndGate("G1")
g2 = AndGate("G2")
g3 = OrGate("G3")
g4 = NotGate("G4")
c1 = Connector(g1, g3)
c2 = Connector(g2, g3)
c3 = Connector(g3, g4)
print(g4.get_output())
Enter pin A input for gate G1: 1
Enter pin B input for gate G1: 1
Enter pin A input for gate G2: 1
Enter pin B input for gate G2: 1
0
``` this is output
how is there only 2 and gates involved?
I need a hash function for a hashset implementation and it only really needs to do strings
nvm got it
Even for strings it depends. Here's some you can look at:
XOR hashing
DJB2 hash
Murmur Hash
Superfast hash
Jenkins hash
Try them out, see which one works faster / better. They're all mostly straightforward to implement
Is there a reason you're not just using the built-in hash function though?
What do you think of this code?
def fast_hash(string):
h = 0
for c in string:
h = (h * 31 + ord(c)) & 0xffffffff
return h
Cuz I'm required to build my own for the project
Might work ๐คทโโ๏ธ again you gotta remember how good a hash function is depends very much on the input
I don't know what sort of strings you have. You should just implement a couple and see how many collisions you're getting with each
Also one thing to note is that this has way better distribution compared to the inbuilt function?
How is that possible
For your particular input, perhaps
I see
It's hard to talk about absolutes without doing some mathematical analysis on what the distribution would actually be like
Well I'm gonna be using a really huge txt file with words to test it
Like around 15 million words
Just normal English words
Just try it out, if it works it works
If there's something more specific you're looking for we can talk, but I can't tell you what is "better" without context
I see
I cannot run it on the main test file
But I got a smaller sample
Which I can test using my phone
First run uses the inbuilt while the second uses the code I showed
2000 is not a lot of words, you probably want to do more precise timing with something like timeit module to see actual performance comparison
The file has 13k words, it just shows the amount of unique words
Ah I see
I've never used the time it module so I'll try it
can someone explain this algorithm to me
def encrypt(plaintext, key):
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
ciphertext = ""
for i in range(0,len(plaintext)):
print('1.',ciphertext)
character = plaintext[i]
print('i = ', i)
ciphertext = ciphertext + character
for j in range (0,key):
ciphertext = ciphertext + random.choice(alphabet)
print('2.',ciphertext)
return ciphertext
i dont understand how to decrypt it
oh ok i guee ill practice them more
why is inserting after a Node in a linked list O(1) and not O(n)?
dont u have to get to the given node before you can make given_node.next = ...
inserting after a node is O(1). inserting into a linked list when you don't have a pointer to a node is O(n)
i've never seen that before
i hope ill never see it again
it looks terrible
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
Sounds like a binary tree sideways to me
it's not a tree it's directed
yea
im trying the second rn
i was able to implement a way to solve some cases
but now i have to figure out how to solve the rest
omfg i cant solve ot
and time is running
damn i was so close to solving it
That for https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/? It's a neat challenge but not really a data structure to worry about in the real world
ok
any youtube playlist recommendations for into to dsa with python?
anyone wanna help me debug some pytorch code
I think this would more appropriately fit #data-science-and-ml
Can anyone here help me with a discrete problem really stuck on it?
hey, short question due to lack of my knowledge (started coding yesterday)... Trying to implement an automatic option to open an app on mac... but i have no clue how to input the app correctly...
Currently stuck on: subprocess.popen (/application/xxx.app)... Not a single clue how to do it correctly...
Hi everyone, does any one know any function that print each permutation of a list without saving all of them
I find some functions but have problems with memory
itertools.permutations?
what is the formula for load factor in hash table
Hey @quaint perch!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
thanks, i will try
help me please
I'm interested in learning to optimize sql.
Do leetcode sql questions deal with sql optimization?
Anyone know of any more efficient versions of the diffusion library?
There are a few issues like it not being very good at smartly allocating VRAM
mid=(len(a))//2 #+1
start=0
while start!=mid:
if a[start]>a[mid]:
a.insert(start,a[mid])
a.pop(mid+1)
mid+=1
start+=1
return a```
Time complexity of this (dependent of number of items in list a would be O(n), right?
No, it is O(N^2)
I was just browsing through some website with explanation of big O notation and I think it's actually O(n). Mid variable starts at the the middle of array a. Then in a/2 iterations, it can get up to len(a). a/2 iterations will also boost start to a/2. Then only a/2 iterations left, for start to get to mid, where the loop ends. Sorry, I've probably explained the script wrong. I will try to run few checks to confirm the O(n)
It seems to have linear time complexity. Sorry for the confusion. There were also few bugs so the code I sent was wrong
insert is not constant time
pop is also not
Oh :/ Thanks for letting me know
Anyone here familiar with numba prange that can help?
I'm wondering in variables defined inside a prange are independent between loops.
https://discordapp.com/channels/267624335836053506/1055466095085109248/1055466095085109248
im having some trouble with a bit of code,
assuming I have 6 points how can I find 2 triangles such that the sum of their area is maximized?
I need this to be moderately fast as I plan to loop over this n^2 times so going over all combinations/ permutations is to slow do to repeated triangles like ((0,0)(0,1)(1,0)) and ((0,0)(1,0)(0,1)) that use the same points in different orders
You should just loop over the combinations not all the permutations
so โถCโ is 20 which should be small enough?
then take the largest two elements. You could either use sorted or heapq.nlargest if you wanna be fancy, not sure what would be faster at such small scales
Can anyone explain what Im doing wrong in this post order traversal code
Practice, practice, practice. There's really no substitute.
it was bothering me that is was going over ther same triangles twice or more, so I ended up "pining" the first point to triangle_A and looping over combinations of length 2 in the remaining 5 points, thanks for the help ๐
class Queue:
def __init__(self):
self._list = [None] * 10
self._size = 0
self._front = 0
def enqueue(self, element):
if self._size == len(self._list):
self._resize(2 * len(self._list))
end = (self._front + self._size) % len(self._list)
self._list[end] = element
self._size += 1
def dequeue(self):
answer = self._list[self._front]
self._list[self._front] = None
self._front = (self._front + 1) % len(self._list)
self._size -= 1
if 0 < self._size < len(self._list)//4:
self._resize(len(self._list)//2)
return answer
def print(self):
for i in range(self._front, self._size + 1):
print(self._list[i])
def _empty(self):
return self._size
def _resize(self, size):
new = self._list
self._list = [None] * size
walk = 0
for i in range(len(new)):
self._list[i] = new[walk]
walk = (walk + 1) % len(new)
self._front = 0
qq = Queue()
qq.enqueue(5)
qq.enqueue(5)
qq.enqueue(5)
qq.enqueue(5)
qq.enqueue(5)
qq.enqueue(5)
qq.print()
qq.dequeue()
qq.print()
The dequeue() function is returning None But it should return 5.Why it is that ?
5 5 5 5 5 5
None
5 5 5 5 5
Not sure what you mean, iterating over the combinations will ensure you don't go over the same triangle twice.
yes but I have 6 points, so for each 3 I iterate over I also need the other 3 points to create a triangle
ie - 1,2,3,4,5,6
iterate over 1,2,3
second triangle will be 4,5,6
and then when I iterate over 4,5,6 the second triangle is 1,2,3
and the order is irrelevant so I avoided these computations
If you hold the state you'll avoid having to iterate over triangles you've already seen
what do you mean by that?
does anyone know altair python?
Let's say that the triangles are stored in a list[tuple[int,int,int]] and let's call it points and let's say you have an area function that has a signature (tuple[tuple[int, int], tuple[int, int], tuple[int, int]]) -> int.
Now I am saying that the following code will only go through 20 triangles without revisiting ones already seen.
max_area = sum(heapq.nlargest(2, map(area, combinations(points, 3)))
I am not looking for the 2 largest triangles, im looking for the pair with largest sum
The pair with the largest sum will be the two largest triangles from all possible triangles.
*matching pair
from 1,2,3,4,5,6
I pick 1,2,3
then 4,5,6 are not picked
sum(area(1,2,3),area(4,5,6)) is what im trying to maximize
1,2,3
1,4,5
are not valid as 1 appeared in both triangles
or because 6 is not used
depending how you look at it
You didn't mention this initially
yea, this was unclear sry
my current code looks like this
best = []
size = -1
for i in itertools.combinations(range(5), 2):
trigA = [points[i[0]], points[i[1]],points[5]]
trigB = [points[ii] for ii in range(5) if not ii in i]
if (tmp := triangle_list_area([trigA,trigB]) > size):
best = [trigA,trigB]
size = tmp
return best
where points is a list of 6 Tuples(int,int)
You've precomputed the areas?
sry im having trouble copy pasting as the code is indented
triangle_list_area is computing the area itself
triangle_list_area computes the area of two triangles?
any amount but for our case yes
try using tuples where you know the data is immutable
points_id = set(range(6))
max(map(lambda c: (triangle_area(*c), triangle_area(*(points_id - set(c)))), combinations(range(6), 3)))
try something like this
I thought about using sets, but if I have the same points twice this method breaks
and a dictionary is getting a bit ugly
although I might come back to that as I need to make a version for 9 points
but if I have the same points twice this method breaks
In that case try using distinct_combinations from the more_itertools lib.
https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.distinct_combinations
this would actually also break
When you use distinct_combinations you'll iterate over points rather than indicies.
it just means all triangles with a duplicate in them would count as 0, but there are some options where I split the duplicate across the two triangles
I always iterate over points as calculating indicies is slower
You're bringing in new constrains as we speak.
I think at this point see what works best for you ๐
not a constraint, just what I did in my code
if it can be done with indicies it's also good
for example the points (0,0,0,0,1,2) would still have a valid option in 0,1,2 0,0,0
well first up the points will be tuple[int, int] not int
and that's exactly what distinct_combinations would do
anywho, as I said before do what works best for you
I see, I thought it was tossing out similar values where it is tossing out permutations that contain the same variables, thenks ๐
ayo can anyone suggest a website that teaches dsa courses for free
kinda urgent...
Can anyone explain to me the difference between LOESS and MARS algorithms? From what I understand they both split up datasets and run regression techniques on the subsets of data to get a more accurate measure.
why not normalize the triangle points, e.g. sort them
how would that help tho?
I nums is a list of strings, you need to change it into a list of ints
nums = [int(i) for i in nums]
or
for i in range(len(nums)):
nums[i] = int(nums[i])
first one is better, but second one uses more basic syntax
where should i add this
you're welcome
nums = list(map(int, input().split()))
i think just mapping the input would be even better
I know of the other ways but considure your target audiance
also this is nicer I think:
[int(i) for i in input().split()]```
imo not but ig its just preference
i just use map bcs it can be used without lists too
for example when knowing that u will get 3 ints as input, u could do:
int1, int2, int3 = map(int, input().split())
nvm
that could be done with list too
ig there is no big advantage
but typing () is faster than []
oh but you could just do tuple too
ig there are no advantages
nums = list(map(int, input().split())) -> 38 chars
nums = [int(i) for i in input().split()] -> 40 chars
nums = sorted(map(int, input().split())) -> 40 chars
nums = sorted([int(i) for i in input().split()]) -> 48 chars
a,b,c = [int(i) for i in input().split()]
would also work
the reason I prefer the comprehension is that it is one tool to do the work of both map and filter as well as the existence of one line generators, set comprehensions and dictionary comprehensions
people prefer it as it is one tool to do all of these rather then like 10 tools
https://leetcode.com/problems/reward-top-k-students/
can someone with leetcode premium send me a writeup of this question
cant check what i did wrong since it is a premium question
im prefer a website
you cant go to the discussion/solution section of the sectoon
atleast that was the case when i asked
and it said that i needed premium to access the question
(i tried viewing the solution page 3minutes after biweekly ended)
but ty
why are you converting the pos and neg list to sets
i thought the list is already not containing duplicates
og
oh
my bad
how can i measure an angle, knowing the coords of points which are connected to each other
i think you forgot an indentation block
just put a space before the red marked line
this is python pseudocode, i wanna ask what property of OOP is in the Pink shape image?
They are just calling Class methods
this is a leetcode question , in the example 1 , why is the answer not 10 , as we can start from index 0 , and pay 10 to climb 2 steps as allowed , and reach third , so according to me the answer should be 10.
I am not able to understand the problem statement , i guess , completely?
please help
the top of the stairs is not the last element of the list, but right after. i'm not sure that i agree with that interpretation of the definition of steps, though, and they probably should be more clear
ok , i am also not comfortable with interpretation , thanks for help
100-element array/list of integer type
how do you test the output
easiest way is to port the pseudocode into a language of your choice (python, for example) and run it
other way is to recognize what the algorithm is doing and do it all in your head
also how to port X[100] to python
I know some conversion like
N = int
K = int
N = 4
K = 1
while K <= N:
probably X = [0 for _ in range(100)]
the first two line of the pseudocode, declaring variable types, are irrelevant to python. ignore them.
it's a symbol commonly used for when you don't care about a variable's actual value
what about X[N/2], will it becomes X = [0 for _ in range(N/2)]
?
no, that's accessing the value within X with the index N/2. although you would have to ensure N/2 stays an integer, so you would need X[int(N/2)] or X[N//2]
!e
l = ['a', 'b', 'c', 'd']
print(l[3])
@covert thorn :white_check_mark: Your 3.11 eval job has completed with return code 0.
d
k imma try to convert them all
!e
N = int
K = int
X = int
X = [0 for _ in range(100)]
N = 4
K = 1
while K <= N:
X[int(K)] = K**2
K = K + 1
print(X[int(N/2)])
print(X[1], " ", X[int(N-1)])
@rare moss :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 4
002 | 1 9
is this correct?
almost:
it's not clear why the intended behavior of Write is, but judging by the single answer line, i'm assuming it's referring to a language with no implicit line breaks on print calls. It's also not clear if the second Write call contains a space in the middle or not (" " or ""). With the space would probably be 41 9 and without 419.
If it does use implicit newlines, then
4
1 9
``` or
4
19
tl;dr maybe `41 9`?
it's kinda of a terrible question, tbh
how is it 41 9
print(X[int(N/2)])should be in the first line
I mean how 4 and 1 be concatenated
many languages do not automatically add a newline in their print statement. python does, but, for example, C/C+++ and Java don't, so ```c
printf("a");
printf("b");
would result in `ab` instead of
a
b
The problem is that it's not clear what `Write`'s expected behavior is
both write output to screen, yes. Exactly how they do that may differ
This is a, what, homework assignment? I would suggest asking the professor or such how Write is expected to behave with regard to newlines
Prepare the program that will do the following for the y value to be entered from the keyboard. 1ยฒ+2ยฒ+3ยฒ+4ยฒ+โฆโฆ. +yยฒ
how can I do it
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
countS, countT = {}, {}
for i in range(len(s)):
countS[s[i]] = 1 + countS.get(s[i], 0)
countT[t[i]] = 1 + countT.get(t[i], 0)
for c in countS:
if countS[c] != countT.get(c,0):
return False
return True
i don't understand countS.get(s[i],0)
.get gives the value for a key
0 is the default value
i've just never seen it written like that
also, why can't we write if countS[c] != countT[c]?
neetcode says it's to avoid a key error
because if the key doesn't exist in countT, then it would give a key error
Am looking for a one teammate or two by max so we can learn together and solve ex. From leetcode everyday by choose a specific hour. I just start to attend udacity course for algorithms and data. Anyone interested DM me
Ok add me, yes i need just a few people so we can have a voice chat while we are solving the exercises
def is_anagram(a, b):
return sorted(a) == sorted(b)
any python developers here? need help! i am using nsetools library to fetch top gainers and losers. i wanto fetch the data for every 5 minutes. how can i do that?
that works too
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
res = defaultdict(list) #mapping character count of each string to the list of anagrams
for s in strs:
count = [0] * 26 #a ... z
for c in s:
count[ord(c) - ord("a")] += 1
res[tuple(count)].append(s)
return res.values()
Group Anagrams - Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [...
so count is a list of 26 numbers?
what's the point of using ascii values?
it's a bit iffy to call it O(1)
I would add in another parameter, alphabet size
otherwise you can do...very silly stuff
Is this the channel to ask about leetcode?
I see there is no leetcode channel here
leetcode doesn't even have a discord server
if we changed the alphabet to be unicode or even bigger the thing would technically still be constant, but it's a bit misleading since that constant is now huge
so whenever an alphabet size is involved I much prefer adding it as a parameter
e.g. there are a bunch of algos that are O(n+k) or O(n*k) where n is size of input and k is alphabet size
yes, my point is you're missing a scaling that exists in the problem, it scales with alphabet size
your n will easily fit in an 64 bit int, so the input is O(1), clearly
also there's such thing as +=, instead of x = x + y, x += y
kk just doing pascal work in python to see the answer
lol
I had an argument that by extension said that "there are only a constant number of floating point numbers", so O(1)
how come
my point is just that if you don't include the relevant parameters in your complexity it's kinda garbage
if i ever feel the need to i would
if channel not dedicated for it then no point
e.g. how fast is looking up a string in a hash table?
no, O(length of string) is correct, and I see people all too often completely gloss that fact over
i.e. to make the lookup you need to hash the object, which is linear in the size of the object
I mean, I do have the role
so yes. I finished on the 25th
algorithmically easier, more impl focused a lot of the time
let's say codeforces, but really any competitive programming thing
advent of code is just a different style of task, a lot of the time the algos involved aren't too interesting
(though a handful of problems per year ends up being interesting on that front as well)
it would be quite boring to me if I didn't spice it up somehow, so I don't do it in python or C++ that I'm really used to
hahaha after looking at two sum for four days i think i finally understand the solution
and it was all about figuring out what my dictionary had, because the dictionary had integers mapped to indices
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
res = defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
count[ord(c) - ord("a")] += 1
res[tuple(count)].append(s)
return res.values()
IndentationError: unindent does not match any outer indentation level
^
res[tuple(count)].append(s)
Line 11 (Solution.py)
is it because the res[tuple(count)].append(s) isn't perfectly in line with the for?
yes, and bc the return isn't completely inline with the default dict
leetcode was being weird there
i don't understand what the keys of my dictionary would look like tho
the key would be a list of 26 ints
i'm confused
count[ord(c) - ord("a")] += 1
``` i think that's what i don't understand
like how does the string "eat" end up [1, 1, 0, 0, ..., 0] ?
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
res = defaultdict(list)
for s in strs: #iterates through strings
count = [0] * 26
for c in s: #characters of strings
count[ord(c) - ord("a")] += 1
res[tuple(count)].append(s)
print(res.keys())
return res.values()
i put a print(res.keys()) here
dict_keys([(1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0), (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0), (1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0)])
got this output
["eat","tea","tan","ate","nat","bat"]
leetcode used that input
i notice how the keys are different tuples
but it doesn't help me figure out how it's being calculated
how the keys of the dictionary are being formed
sure, but how does that build it?
it calculates the ascii values and then what
what type of knowledge is usually required for heuristic(i think thats how its spelled) contests
i feel like the problems are completely different from ABCs or codeforces contests
So I have an numpy Poly1D which returns complex numbers. The real part represents X and the Imaginary part represents Y. How do I sample points on the resulting graph?
i'm doing the blind 75
oh i see what you're saying
but after two sum comes group anagrams anyways so
well i need to practice anyways
?
at least i knew to use a dictionary for group anagrams
hey, i think i'm able to understand group anagrams now
i took the test case of "eat"
for example, the letter "e" is the fifth letter of the alphabet
so that's why the fifth position in the list is 1
the letter "a" is the first letter of the alphabet, so that's why the first position in the list is also 1
and t is 20th, so the 20th position in that list is 1
so i have a small problem with json files, if i can ask here idk really, i want to get a data called with a name in the json file and just load it into my python file, so i can use it or just for example print it,
heres the json file :
{
"SwitchKey": "p", // this is what i want to get from the json file
"ExitKey": "y",
"ReloadKey": "i"
}
so how do i get that into my python file and print it
from what i gathered it has to be something from json.load()
!d json.load
json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *fp* (a `.read()`-supporting [text file](https://docs.python.org/3/glossary.html#term-text-file) or [binary file](https://docs.python.org/3/glossary.html#term-binary-file) containing a JSON document) to a Python object using this [conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).
*object\_hook* is an optional function that will be called with the result of any object literal decoded (a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict")). The return value of *object\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders (e.g. [JSON-RPC](https://www.jsonrpc.org) class hinting).
*object\_pairs\_hook* is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of *object\_pairs\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders. If *object\_hook* is also defined, the *object\_pairs\_hook* takes priority.
or json.loads
i still didnt get how to get my data out of that
am i looking at it not right
cuz i am not new to python i have been working with python for 3 years
d = json.loads(...)
print(d["SwitchKey"])
OHHHH
im so stupid
i thought you do like json.load("SwitchKey")
its 2 AM im tired sorry
!e ```py
import json
data = """
{
"a": "b",
"c": "d"
}
"""
parsed = json.loads(data)
print(parsed["c"])
@tepid needle :white_check_mark: Your 3.11 eval job has completed with return code 0.
d
!d json
Source code: Lib/json/__init__.py
JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript 1 ).
Warning
Be cautious when parsing JSON data from untrusted sources. A malicious JSON string may cause the decoder to consume considerable CPU and memory resources. Limiting the size of data to be parsed is recommended.
json exposes an API familiar to users of the standard library marshal and pickle modules.
Encoding basic Python object hierarchies:
i got it, thanks lad
for now, fair winds my friend
since version 2.6
- Two Sum II - Input Array Is Sorted
can i just do the same hashmap approach like in part 1?
they want you to only use constant extra space
it is
is this a good channel to talk automation? or which channel is best
I'm not 100% sure if this is the right channel to talk about big O notation but i can't see a better one
if I know the time complexity of a function and i know how long it takes for a certain input n
can i work out how long it will take for a bigger input
for example if an O(2^n) function takes 2 seconds to run at n=2, does that mean it will take 512 seconds to run at n=10?
or is that not how that works
2pointer exceeded time limit so i just did hashmap approach:
class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
pairs = 0
time = [i%60 for i in time]
hashy = {}
for i in time:
if i == 0:
if 0 not in hashy: hashy[0] = 0
pairs += hashy[0]
hashy[0] += 1
else:
if 60-i not in hashy: hashy[60-i] = 0
if i not in hashy: hashy[i] = 0
pairs += hashy[i]
hashy[60-i] += 1
return pairs
it can be improved i think
i did i==0 since 60-0 is an edge case
and i did the list comprehension to not do modulo in every loop
oh
i used hashmap
all the times%60
i thought thats what i was supposed to do
isnt that the same
i mean the only difference is that you do modulo in every loop
ur solution is way shorter
oh
ok
ty
ill try
but idk how to solve sliding window problems(this ones seems to be one)
ill have to look up some concepts for that
ill finish this https://leetcode.com/problems/zigzag-conversion/ first
no, i havent finished school yet(idk if my school would be called high school in us)
you?
i wanted to do it but i havent started yetz
is it difficult?
isnt numRows==len(s) also just return s
hi ๐ guys, i want to build a search for my website, it has many articles, every article has json file that includes {url of the page, title, article, keywords, date_created, tags โฆ..} how can i make a text search that can get me the article which is most similar to the text search?
1- how can i build it with tensor flow, nltkโฆ ?
2- how can i return the result of the search as url and article title?
3- how should my data be before processing, in one big json file or multiple ones ?
4-how can i match the text search to the article ?
thx in advanced and plz ๐๐ป mention me in the reply
since if len(s) == numRows:
example: s="abcde", numRows=5
converted should be:
a
b
c
d
e
solution=abcde
damn
i thought ill just simulate each step and then return some "".join(simulated)
ig
yea
doing usaco training too
but im too lazy to think about a way to convert basex num to basey num
nah im pretty bad at coding i think
cant solve most problems
im doing the simulation section rn
i think i am at the lost cow
im able to solve them
but im not fast at solving
i think bronze problems can be solved fast
https://codeforces.com/problemset/problem/1765/E this one is great
1.1k i think
i did 4 contests so far
nah
i think 1.2k can be reached by just doing div3 problem a-c
there isnt much math in easier problems
what rank is 1.1k again?
i want to reach 1.6 or 1.8 next year
CM isn't amazingly high
depends on how good you are ๐
I was at 1599 after 3 contests, but that was before div3, div4 and everything existed
damn
a mix of math, physics and engineering
I did a bunch outside codeforces before
I'm also better at long form contests like the ones hackerrank and codechef had
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1 or numRows == len(s): return s
simulated = ['' for _ in range(numRows)]
section = (numRows-1)*2
for index, i in enumerate(s):
if index % section < numRows:
simulated[index % section] += i
else:
simulated[(section - (index % section)) % numRows] += i
return ''.join(simulated)
```section is just the num of chars per section(picture)
but this isnt constant space right?
since it is creating a seperate aarray
heuristic ones?
What's the command for formatting code in chat? Is it backticks?
` 3times on each side
Thanks ๐
code
Ok, so I'm working with a coworker's code. It's really something. I'm trying to figure out the Big O on it because it's so slow. Using pseudo code:
function
for (A)
for (B)
for (C)
for (D)
for (E)
for (F)
for (G)
while (H)
for (I)
And we call that function twice on a specific operation.
Is that Big O(2n^9)?
there are some ~week long contests
not heuristic ones
other than practice and pick up new stuff, not much
depends on what the loops are
without knowing ranges for loops you can't say much
and the while loop could be a lot of different things
Good point, I haven't had to calculate Big O since school. They're not all For (A).
big O is just about counting the number of overall operations and how it scales with parameters
were there like 100 problems or extremely hard ones?
you likely have a bunch of parameters, unless all loops are over the same range
Yeah. In practice, this thing is very slow. But I can't give an accurate Big O based on the loops alone
problems ranging from not too hard to really hard, e.g. an old codechef one:
https://www.codechef.com/JUNE18A/
is popping the last element of an array O(n) or O(1)?
last element is O(1)
first element is O(n) right?
yes, you need to shift everything after the deleted element
oh ok
what is balanced bst and why do we use it for dynamic lists?
we don't
sets, maps
reptile already explained it to you
did you not understand the explanation?
i kinda did but i had some follow up questions and wanted some more clarity
ask those then
but please explain it again because i didnt 100% understand it
what parts did you not understand
basically what it actually does and why we use it
what does the algorithm do on a technical level.
what is its purpuse and how does it do that
there are multiple ways to implement a BBST. i'm most familiar with the red-black tree. another common one is the AVL tree
could you explain what those two things are?
they're implementations of BBST. i'm not familiar with the AVL tree, but the red black tree essentially "rotates" nodes so that the heights of subtrees are within 1 of each other
This video is part of the Udacity course "Technical Interview". Watch the full course at https://www.udacity.com/course/ud513
should be english
about red black
can someone please explain the very basics of balanced bst to me?
Am looking for a study buddy, anyone interested?
what problems were greed<?
forgot it
damn
i hate question which are edging me
what type of questions are being used in university exams?
are uni exams just some leetcode like questions?
do you have to describe how you solved it and explain it
or is it just like some leetcode weekly contest where you have to answer 4 questions
how do i convertz a num to base n where n>10
```py
def to_base(num: int, base: int):
if num < base: return str(num)
return to_base(num // base) + str(num % base)
this works for base<10
str(num % base) needs to be refactored: every num possible between 0 and base-1 (both inclusive) should have a unique character to represent them
you could for example, store a list of those (in base 16 for example:
digits = ['0', '1', ... , '9', 'A', 'B', 'C', 'D', 'E', 'F']
and then you modify str(num%base) by something like digits[num%base]
(I let you code it at your best convenience)
ah
yea ty
yea it worked
ty
digits = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J'] # (first 20 digits)
def to_base(num):
if base == 10:
return num
if num < base: return digits[num]
return to_base(num // base) + digits[num % base]
base isnt given as a parameter because it is read from a file a few lines above
base = int(fin.read())
@cobalt mirage https://leetcode.com/problems/keys-and-rooms/ this one is good
it was the daily a few days ago and it was fun solving it
oh
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
visited = set()
keys = set([0])
while keys:
temp = []
for i in keys:
temp.append(i)
visited.add(i)
for i in temp:
for o in rooms[i]:
if o not in visited:
keys.add(o)
keys.remove(i)
return len(visited) == len(rooms)
a lot of loops
yea
simulation
simulating everything
i am not good at graph problems
and simulation worked
0 <= rooms[i].length <= 1000
nvm
time was pretty good
O(nm)?
n is number of rooms
anyone have time to explain to me the logic behind a codeforce problem?
and m the num of keys in a room
idk
probably
this one is easy
yea
bu mean the new problem i send?
fr easy
get a paper and write down the first 5 stairs with possible ways
you will notice a pattern
from functools import cache
class Solution:
@cache
def climbStairs(self, n: int) -> int:
if n in (1, 2, 3):
return n
return self.climbStairs(n-1) + self.climbStairs(n-2)```
just fibonacci sequence
i hate making my own cache#
im too lazy#
idk
because i did alot of easies to understand linked lists and basic data structures
and i started dsa by doing leetcode
and i wasnt able to solve medium problems
have you solved todays daily?
i think
icpc was the university competition right>?
uni version of ioi i think
im too bad for ioi
i would have to practice way more
and for a long time
whats quant interview?
first round tho
14/15 points
i did
?
ill also do it later
I was stuck with a problem for some time, thought it could be useful to ask here ,
Would there be an ideal way to find the minimal set of Inputs (I's) for which every alphabet (A,b,c,d... it can be more than 26) is present.
for example for I0 + I2 + I3, alphabets A,B,C,D,E,F, are all present as 1 atleast once so I0I2I3 is a "minimal set". Im probably not doing a good job at explaining it but thanks for the time in advance.
edit: apparently this is called a set cover problem which is NP-hard
yeah, that's minimal set cover
soo how would you recommend approaching the problem, is it more of a machine learning problem? sorry if I''m asking stupid questions ๐
I would check whether your underlying problem is really this problem or not
if it is really this problem we don't know of good optimal approaches
how large is your input?
for small enough input you could just brute force it
How can I check if in an iterable, any object contains a specific attribute in O(1)? i.e how can I check if this list of objects contains an object with id of 1 in O(1)?
I know I can use any but that still goes through the whole list whereas ids should be unique
from dataclasses import dataclass
@dataclass
class Person:
age: int
id: int
name: str
john = Person(10, 1, 'john')
brad = Person(11, 2, 'Brad')
people = [john, brad]
I assume using a dictionary with the id as the key is the best bet but I've already got my schema like this and don't really wanna change it if I don't have to
there might be 2^20 ish rows and thousands of columns
Hi, anyone happy to discuss sorting points by polar angle?
I've got a way to do it using a key function & the atan2 method, but would it be more efficient to use a custom comparison function (to avoid using a trig function) and then use the cmp_to_key function
Like, by comparing their y/x ratios? That might work, but I wouldn't be sure if it actually would be faster, since math functions are written in C, so the time for calculating the arctangent is likely negligible compared to the rest of the code.
hello! i was learning about vEB trees when i found this:
u^(1/2) - site array v.cluster[0], ....., v.cluster[u^(1/2) - 1]
Im confused as to why v.cluster[u^(1/2) - 1] is the maximum number the tree can store. someone please explain this to me
if it wasn't python I would for sure recommend doing the non trig way, not only because of performance but because of accuracy
one non-trig compator is to get the quadrant for both points, if they are different then we can immediately tell which is smaller, if they are the same compute the 2d cross product of the vectors and check the sign
i'd say O(nk/2)
each loop is len(days_of_week) and 2 is subtracted from k each time
ahh no, it's O(infinity), this code won't stop
did you run that code?
it does stop
there's a return statement
Your K never changes
but that condition is always False
because days_of_week[i] is a string
and can't be equal to 5
so it's O(n)
It's O(nk) - because we should take worst case
When S is "Sun" and K substracts by 1 on each loop
so it's quadractic time complexity
ye
you think it's possible to make it linear or not
like is this the most effecient way to do it
No, i mean, can you tell in words what you want to do? I don't really understand what you try to get here
given days of the week when entering a number return that day
so enter wed, 2 return fri
ye, i see
So, i am really sorry, i was wrong again and your code was O(n + k). ๐
But you can do it better if you get k % 7 - result will be same, but faster on big k - O(n + k % 7), which is just n really
Also it can be written much simpler :
days_of_week = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
return days_of_week[(days_of_week.index(S) + K) % 7]
can you explain how it's n + k and not n*k
First your code goes until it finds S, in worst case it will be last element, n iterations
Then it substracts 1 from k until it become 0, k steps
Other operations are just coefficients and they doesn't matter
Sum: n + k
Hash = self.KeyHash(Key)
BuckLinkedList = self.Buck[Hash]
self.StoredKeys[Key] = Hash
NewNode = BuckLinkedList.ReturnSearch({Key:Value})
if NewNode == None:
BuckLinkedList.append({Key:Value})
else:
NewNode.StoredValue.StoredValue = Value ```
For some reason, when adding to a hashtable, the key is added recursively for infinity. Can anyone see where this is happening
all the same key
Look at the memory addresses - the issue seems to be that your node's successor is the node itself. So you only have one node, which is its own child.
ight thanks
Fun fact: [x^x]' = x^x
you mean, like, derivative? that's false, the derivative is x^x (ln(x)+1).
https://cses.fi/problemset/task/1072
for problems like the one above, am i supposed to find the formula myself or can i just look the formula up
because i am sure that i wouldve never been able to come up with something like
and if i am not supposed to look such formulas up, how am i supposed to find one myself
you are supposed to come up with it on your own
and it shouldn't be that hard
just a bit of casework
Experience with counting problems. Start by asking yourself a more simple version of the same problem and try solving that.
(Maybe with pawns and if that is complex choose an even more simple question until you can answer it)
(Also remove / relax constraints. What if you don't care if the knights are attacking each other or not?)
Hi, I have a task:
Where e is number of opponents that are being eliminated in the round
c is number of remaining opponents.
What algorithm should I use?
Well, thatโs an interesting puzzle. For trying to solve these sorts of things, thereโd be two opposite approaches - solving it analytically, by figuring out a formula to give the answer, or by getting the computer to try lots of solutions until you find the best. Now the latter is going to become prohibitively expensive quickly since this looks to increase the number of solutions factorially. I would though suggest trying to solve the first few K values that way, see if you can find a pattern. Or try and derive a formula, or maybe even a partial one.
I think it can be solved in O(number of opponents) using dynamic programming
is the number of remaining opponents meant before or after elimination?
Hi. I have a question. I have this code
for enum in enum_fields_list:
for key, value in master_json_dict.items():
if enum in value:
print(key, value)
else:
print("Not in the master_json")
Currently, it's very inefficient and I'm looking to improve it. I got some few ideas which are not exactly meeting my requirements but I'll post them below.
So for the code above, the issue is that the enum_fields_list list has about 1752 items. The master_json_dict has also about 27 keys and within each key there is a list with an average of 200 items. This makes the for loop very very inefficient and cause the code to be slow. Double checking also occurs.
My first idea was to do this.
flattened_dict_values = chain.from_iterable(master_json_dict.values())
Which takes all the dicts values and put them into one list so I don't have to have to have an exponent loop. But the problem with this approach for me is that I also need the key of each item that is found. Flattening them does not give me access to the key's but only to the values.
Any help appreciated.
Before elimination
Your approach is not changing asymptotic at all
Wouldn't the if enum in value: be O(1) if value was a dictionary instead of array? (I am not good at this so don't take this as a serious answer. I am just wondering)
Yes, but value is a list
Really? I think it reduces it because I don't have to check the list diff list every time. I just need to do one in.
for enum in enum_fields_list:
if enum in flattened_dict_values:
print('yes')
Yea as denball said value is a list
You still need O(enums*list length) time on second line
Ok that makes sense. But then at least the double, triple etc checking would be removed since I have only one list.
You can achieve O(1) by using other data structure
Can you name it?
No, you have to figure it out for yourself.
Ah. This is for work not an assignment.
Anyway that's fine. Thanks for the help
