#algos-and-data-structs

1 messages ยท Page 23 of 1

sharp junco
#

(was thinking of commenting the uneeeded lines)

glass swan
#

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
flint arrow
#

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)
slender sandal
# glass swan Hi below is code which has puzzled me about dictionaries: Love it, if anyone cou...

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).

smoky tapir
#

how to keep counter for number nodes for doubly linked lists

willow mason
#

can anyone solve this question please

keen rover
#

!dictionary

limpid smelt
#

no help or suggestions at all?

sharp junco
#

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)

flat hornet
#

guys for be developer advanced in python what i need to know?

haughty mountain
#

how many times does the inner part of the loop run?

sharp junco
#

wait what

haughty mountain
#

err

#

wrong channel for the last thing

sharp junco
#

npnp

sharp junco
#

it is linear time

#

QED

haughty mountain
#

correct

sharp junco
#

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

haughty mountain
#

generate a hard case

sharp junco
#

like u did here?

#

the command with the max

haughty mountain
#

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

dusky field
#

and test the constraints?

haughty mountain
keen hearth
#

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 ๐Ÿ˜„

dusky field
#

so what would the inputs be

#

im curious now

haughty mountain
#

I'm not sure, seems like you would want to maximize the number of overall neighbors within 2 steps

agile sundial
haughty mountain
#

I think connecting a bunch of nodes with 70 connections each together is the best you can do

#

but not entirely sure

agile sundial
#

ah

haughty mountain
#

so gcd ends up mattering

keen hearth
haughty mountain
#

it's a diophantine equation

keen hearth
haughty mountain
#

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 ...

keen hearth
#

Ah right ok ๐Ÿค” How would I go about solving for x and y?

haughty mountain
#

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

keen hearth
haughty mountain
#

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

tender atlas
#

what is the best way to calculate operations of graph/path finding algorithms

willow mason
#

then i can code

#

in general we can use dictionary

#

but is there any better way

languid nymph
#

Just to check my understanding of time complexity, this thing is time complexity O(n), right?

covert thorn
# languid nymph Just to check my understanding of time complexity, this thing is time complexity...

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

agile sundial
haughty mountain
#

but for some reason int hashes weren't randomized like str hashes were

agile sundial
#

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

haughty mountain
#

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

haughty mountain
agile sundial
#

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

haughty mountain
#

I'm sure it must have been pretty easy to construct collisions

#

otherwise no-one would have cared

agile sundial
haughty mountain
#

strings are probably more common as a type in general

#

but that doesn't really justify leaving int with a bad default hash

agile sundial
#

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?

haughty mountain
#

I don't think modern hash algos have that much overhead

haughty mountain
#

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

agile sundial
#

rust also uses siphash

urban kiln
sharp junco
#

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)

urban kiln
sharp junco
#

i wanna understand it

urban kiln
#

its empty

sharp junco
#

what

urban kiln
#

bcs without the -1 it would just output 1

#

char

#

wait

#

i think 4

#

nvm sry

sharp junco
#

uhh

urban kiln
#

i think D bcs without -1 it would output a string but with its doing steps of -1 and idk how to say it

sharp junco
#

wheres the -5 string

urban kiln
#

-5 is just index from end

#

wait

#

i cant word it correctly

sharp junco
#

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

urban kiln
#

yes

#

xs[-5] should output 5

sharp junco
#

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

foggy berry
#

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

mystic fractal
#

python

granite vortex
#

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?

haughty mountain
#

print prints space separates, but you get a newline then a space

#

you can use .strip() to remove surrounding whitespace from the string

granite vortex
high sorrel
#

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?

delicate ore
#

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?

fiery cosmos
#

should I change this wide format to long ? say add a column with wine,beer,vodka,champagne,brandy

lucid wyvern
#

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

agile sundial
#

lookup tables are the best. you can precompute chances of all the possibilities

restive kraken
#

Anyone know an Algo to compare the data of two non binary trees. For example compare the following two trees

woeful crescent
#

Hey guys do you have any resources to practices recursion questions

iron tangle
#

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 :/ )

heavy sinew
glass river
#

is bfs [1,2,4,5,9,7,10,3]
and dfs [1,2,5,9,7,10,3,4]?

lucid wyvern
keen hearth
#

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.

iron tangle
#

I see. Interesting, thank you

granite vortex
#

is it bad to get there warnings everytime i install a new package?

hallow river
#

Can someone help me do a really simple mvvm javascript code?

#

I can't find any simple one that can run online

limpid smelt
granite vortex
#

bcs with just pip install tensorflow it wouldn't work

limpid smelt
tardy prairie
#

negative step goes from left to right ex. 'hello world'[::-1] would return 'dlrow olleh' ('hello world' spelled backwards)

copper night
#

How can I loop through my dictionary to find values > 1?

agile sundial
#

use dict.values()

granite vortex
harsh hedge
#

Is there a way to get a hashing algorithm by a string value?

dusky trellis
dusky trellis
#

if the latter, you can use hashlib.algorithms_available

harsh hedge
limpid smelt
fiery cosmos
#

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

frank bluff
#

what about||```py
s = "pineapple"

l = 0
while s[l:]:
l += 1

print(l)

fiery cosmos
#

omg

#

you're kidding me

fiery cosmos
haughty mountain
#

ctypes isn't builtins pithink

#

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)
halcyon plankBOT
#

@haughty mountain :white_check_mark: Your 3.11 eval job has completed with return code 0.

c_ulong(26)
snow garden
#

guys what does null value do in database?

fiery cosmos
#

how to calculate the proportion of sales ?

#

in percent

royal ether
#

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!

agile sundial
mystic dust
#

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.

surreal nova
#

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()
hollow stone
# royal ether Hi Everyone, Question! If I have a Series which contains something similar to ...

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 ^^

silver dock
#

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

cursive garden
#

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?

royal ether
sacred rivet
#

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.

hollow stone
# royal ether I ended up using a for loop and copied the initial list twice each time using an...

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 ๐Ÿ˜‰

royal ether
wise blade
#
    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?

vagrant anchor
#

when you don't know when to take a break from typing, your compiler will let you know :v

half lotus
# sacred rivet Heyo! So I've been learning stacks, and part of the applications is conversion o...

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.

fiery grove
#

I wanted to ask if anyone knew Solana blockchain development in python

sacred rivet
half lotus
#

No problem. Glad it helped

lean walrus
random kraken
#

oops wrong

half lotus
vital talon
#

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.

agile sundial
#

isn't that just a list, then

#

if you just have __eq__ (not even __lt__), then you pretty much can only use a list

vital talon
#

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.

agile sundial
#

yeah or just 2 lists

ionic crystal
#

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? ๐Ÿ™

agile sundial
#

tensorflow?

marsh flicker
#

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?

lean walrus
#

Because dict are not ordered on old python versions

#

What version are you using?

#

Dict are ordered after 3.7 iirc

lean walrus
hollow ibex
#

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!

rocky stream
#

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

frosty plover
#

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"๐Ÿค”

topaz otter
#

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 == "":

fiery cosmos
#

do SAS plats like AWS utilize parallel processing?

agile sundial
#

it's hard to imagine why they wouldn't

copper palm
#

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

agile sundial
#

i mean, switching languages is just a constant factor speed increase :P

copper palm
#

so whats your point?

agile sundial
#

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

copper palm
#

whats dsa?

#

but whats the point of learning these concepts, if your not gonne implement them?

agile sundial
#

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

copper palm
#

no you just use the builtin sort in python

agile sundial
copper palm
#

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

agile sundial
#

sure

copper palm
#

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

keen hedge
#

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

granite vortex
keen hedge
#

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

haughty mountain
#

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

prime atlas
#

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 :)

keen hedge
#

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

fiery cosmos
#
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 :/

acoustic yew
#

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?

stable pecan
acoustic yew
#

is that a 5x5 grid?

stable pecan
#

yeah

acoustic yew
#

yeah that fits what i need

#

like that would be a way to fill 5x5

#

they just have to be squares

stable pecan
#

makes it tougher, but i suppose there's probably some smart way to break it into smaller pieces

acoustic yew
#

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

harsh hedge
#

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) + ")")
harsh hedge
#

How do you mean this?

river inlet
harsh hedge
#

This didn't fix my problem

harsh hedge
#

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

austere flame
#

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

woeful cove
#

@codeine#1240

harsh hedge
#

Yes. You have to set flush=True, because normally the buffer is only flushed after a new line or longer string

foggy lynx
#

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?

quaint halo
nimble coral
#

What do u guys think about 4/6/8 month-1 year data science bootcamp? Especially for undergraduate IT student

old rover
#
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

#
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?

#
LeetCode

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

agile sundial
#

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

old rover
#

so then

#

if i used a list it would still work?

agile sundial
#

yea

old rover
#

weird, bc a list doesnโ€™t work for the test cases

agile sundial
#

why

#

probably speed issues

old rover
#

yes

#

it says it timed out

agile sundial
#

but it is correct

barren skiff
#

Wait

#

Lists times out?

#

That is strange

#

N only goes up to 1e5 and the solution is O(nlogn)

agile sundial
inland tusk
#

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?

harsh hedge
#

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

vocal gorge
agile sundial
#

also i think ThreadPoolExecutor uses that as the default

vocal gorge
#

processpoolexecutor, presumably

agile sundial
#

yeah something like that

barren skiff
#

The sol with lists sorts the lists

#

Which is O(nlogn)

agile sundial
#

not his solution with lists

barren skiff
#

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

fiery cosmos
#

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

harsh hedge
#

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?

lean dome
austere sparrow
urban kiln
#

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

fallow garnet
#

How can I make a hash function that's around as fast as the inbuilt hash function?

#

Also without using any other libraries

calm verge
calm verge
fallow garnet
calm verge
#

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

fiery cosmos
#

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?

fallow garnet
fiery cosmos
#

nvm got it

calm verge
#

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?

fallow garnet
fallow garnet
calm verge
#

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

fallow garnet
#

How is that possible

calm verge
#

For your particular input, perhaps

fallow garnet
#

I see

calm verge
#

It's hard to talk about absolutes without doing some mathematical analysis on what the distribution would actually be like

fallow garnet
#

Like around 15 million words

#

Just normal English words

calm verge
#

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

fallow garnet
#

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

calm verge
#

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

fallow garnet
calm verge
#

Ah I see

fallow garnet
#

I've never used the time it module so I'll try it

tacit thorn
#

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

urban kiln
urban kiln
#

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 = ...

agile sundial
#

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)

urban kiln
#

ah ok

#

is this important to know how to handle?

#

"multilevel doubly linked list"

agile sundial
#

i've never seen that before

urban kiln
#

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
"""
calm verge
agile sundial
#

it's not a tree it's directed

urban kiln
urban kiln
#

idk

#

ill try to solve it later

#

ez

urban kiln
#

oh

urban kiln
#

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

urban kiln
#

damn i was so close to solving it

fiery cosmos
urban kiln
#

ok

mint zephyr
#

any youtube playlist recommendations for into to dsa with python?

subtle ravine
#

anyone wanna help me debug some pytorch code

copper hawk
fiery cosmos
#

Can anyone here help me with a discrete problem really stuck on it?

fiery cosmos
#

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...

river shell
#

Json some expert here

#

?

austere flame
#

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

vocal gorge
#

itertools.permutations?

quaint perch
#

what is the formula for load factor in hash table

quaint perch
#

oh nvm ik it

#

can someone review my hash table implementation

halcyon plankBOT
austere flame
#

thanks, i will try

ivory fern
#

help me please

dapper sapphire
#

I'm interested in learning to optimize sql.

Do leetcode sql questions deal with sql optimization?

rare prism
#

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

languid nymph
#
    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?
lean walrus
#

No, it is O(N^2)

languid nymph
# lean walrus 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

lean walrus
#

pop is also not

languid nymph
#

Oh :/ Thanks for letting me know

old horizon
worldly jolt
#

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

sand iron
#

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

untold torrent
#

Can anyone explain what Im doing wrong in this post order traversal code

gaunt forge
#

Practice, practice, practice. There's really no substitute.

worldly jolt
vital scaffold
#
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 
sand iron
worldly jolt
#

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

sand iron
#

If you hold the state you'll avoid having to iterate over triangles you've already seen

worldly jolt
#

what do you mean by that?

main kiln
#

does anyone know altair python?

sand iron
#

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)))

worldly jolt
#

I am not looking for the 2 largest triangles, im looking for the pair with largest sum

sand iron
#

The pair with the largest sum will be the two largest triangles from all possible triangles.

worldly jolt
#

*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

sand iron
#

You didn't mention this initially

worldly jolt
#

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)

sand iron
#

You've precomputed the areas?

worldly jolt
#

sry im having trouble copy pasting as the code is indented

#

triangle_list_area is computing the area itself

sand iron
#

triangle_list_area computes the area of two triangles?

worldly jolt
#

any amount but for our case yes

sand iron
#

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

worldly jolt
#

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

sand iron
worldly jolt
#

this would actually also break

sand iron
#

When you use distinct_combinations you'll iterate over points rather than indicies.

worldly jolt
#

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

sand iron
#

You're bringing in new constrains as we speak.
I think at this point see what works best for you ๐Ÿ‘

worldly jolt
#

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

sand iron
#

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

worldly jolt
#

I see, I thought it was tossing out similar values where it is tossing out permutations that contain the same variables, thenks ๐Ÿ‘

heady obsidian
#

ayo can anyone suggest a website that teaches dsa courses for free

#

kinda urgent...

plain folio
#

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.

haughty mountain
worldly jolt
#

how would that help tho?

fiery cosmos
#

bunu nasฤฑl รงรถzerim

worldly jolt
# fiery cosmos

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

fiery cosmos
#

where should i add this

steady finch
#

ill fix it

fiery cosmos
#

@steady finch thankss

#

bro

steady finch
#

you're welcome

urban kiln
urban kiln
worldly jolt
#

I know of the other ways but considure your target audiance

worldly jolt
urban kiln
#

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
worldly jolt
#

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

urban kiln
#

ik

urban kiln
#

cant check what i did wrong since it is a premium question

heady obsidian
#

im prefer a website

urban kiln
#

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)

urban kiln
#

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

bronze gorge
#

Hello guys I need a good resource for DSA?

#

I'm a beginner.

urban kiln
#

how can i measure an angle, knowing the coords of points which are connected to each other

opal oriole
urban kiln
#

part of the problem ๐Ÿ’€

#

probably the easiest sub problem

fiery cosmos
#

i read but i don't understand

urban kiln
#

just put a space before the red marked line

rare moss
#

this is python pseudocode, i wanna ask what property of OOP is in the Pink shape image?

cinder cave
earnest cave
#

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

covert thorn
# earnest cave

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

earnest cave
rare moss
#

how do I even test this

#

and idk what X[100] means

covert thorn
rare moss
#

how do you test the output

covert thorn
#

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

rare moss
#

also how to port X[100] to python

#

I know some conversion like

N = int
K = int

N = 4
K = 1
while K <= N:

covert thorn
#

probably X = [0 for _ in range(100)]

rare moss
#

but idk about X[100] or something like array

#

what is the '_' ?

covert thorn
covert thorn
rare moss
#

what about X[N/2], will it becomes X = [0 for _ in range(N/2)]
?

covert thorn
#

!e

l = ['a', 'b', 'c', 'd']
print(l[3])
halcyon plankBOT
#

@covert thorn :white_check_mark: Your 3.11 eval job has completed with return code 0.

d
rare moss
#

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)])
halcyon plankBOT
#

@rare moss :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 4
002 | 1   9
covert thorn
# rare moss 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

rare moss
#

how is it 41 9

#

print(X[int(N/2)])should be in the first line

#

I mean how 4 and 1 be concatenated

covert thorn
#

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
rare moss
#

write is print in python

#

correct?

covert thorn
#

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

rare moss
#

I got it from course, basic pseudocode

#

I try to convert them all to python

fiery cosmos
#

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

old rover
#
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

tepid pivot
#

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

tepid pivot
#

Ok add me, yes i need just a few people so we can have a voice chat while we are solving the exercises

round valley
#
def is_anagram(a, b):
    return sorted(a) == sorted(b)
fiery cosmos
#

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?

old rover
#
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()
#
LeetCode

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?

old rover
#

i'm confused

#

but i'll look at it again tomorrow

haughty mountain
#

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

royal torrent
#

Is this the channel to ask about leetcode?

#

I see there is no leetcode channel here
leetcode doesn't even have a discord server

haughty mountain
#

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

teal basalt
#

I saw it EM_keklmaoOwO

#

Should delete the msg

fiery cosmos
#

also there's such thing as +=, instead of x = x + y, x += y

teal basalt
#

lol

haughty mountain
#

I had an argument that by extension said that "there are only a constant number of floating point numbers", so O(1)

royal torrent
#

how come

haughty mountain
#

my point is just that if you don't include the relevant parameters in your complexity it's kinda garbage

royal torrent
#

if i ever feel the need to i would
if channel not dedicated for it then no point

haughty mountain
#

no, O(length of string) is correct, and I see people all too often completely gloss that fact over

haughty mountain
#

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

old rover
#

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

old rover
#
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

old rover
#

how the keys of the dictionary are being formed

#

sure, but how does that build it?

#

it calculates the ascii values and then what

keen karma
#

can someone help

#

what is the answer to this

urban kiln
#

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

hollow oasis
#

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?

old rover
#

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

old rover
#

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

maiden cradle
#

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()

tepid needle
#

!d json.load

halcyon plankBOT
#

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.
tepid needle
#

or json.loads

maiden cradle
#

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

tepid needle
#

d = json.loads(...)
print(d["SwitchKey"])

maiden cradle
#

OHHHH

#

im so stupid

#

i thought you do like json.load("SwitchKey")

#

its 2 AM im tired sorry

tepid needle
#

!e ```py
import json
data = """
{
"a": "b",
"c": "d"
}
"""
parsed = json.loads(data)
print(parsed["c"])

halcyon plankBOT
#

@tepid needle :white_check_mark: Your 3.11 eval job has completed with return code 0.

d
maiden cradle
#

oh 3.11 right now sucks for me, i cant debug

#

i tried everything to fix it btw

tepid needle
#

!d json

halcyon plankBOT
#

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:

maiden cradle
#

i got it, thanks lad

maiden cradle
tepid needle
maiden cradle
#

wha

urban kiln
#
  1. Two Sum II - Input Array Is Sorted

can i just do the same hashmap approach like in part 1?

haughty mountain
urban kiln
#

oh hmm

#

is 2pointer constant space?

haughty mountain
#

it is

urban kiln
#

n log(n) is faster than n^2 right?

#

yea it is

#

ig binary with 2pointer

grim tendon
#

is this a good channel to talk automation? or which channel is best

hardy imp
#

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

urban kiln
#

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

urban kiln
#

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

#

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

ruby grove
#

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

urban kiln
#

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

#

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

haughty mountain
#

what rank is 1.1k again?

urban kiln
#

unrated

haughty mountain
#

ah

#

2007, though I haven't competed in years

#

yes

urban kiln
#

i want to reach 1.6 or 1.8 next year

haughty mountain
#

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

haughty mountain
#

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

urban kiln
#
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

crude karma
#

What's the command for formatting code in chat? Is it backticks?

urban kiln
#

` 3times on each side

crude karma
#

Thanks ๐Ÿ™‚

urban kiln
crude karma
#

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)?

haughty mountain
#

not heuristic ones

#

other than practice and pick up new stuff, not much

haughty mountain
#

without knowing ranges for loops you can't say much

#

and the while loop could be a lot of different things

crude karma
haughty mountain
#

big O is just about counting the number of overall operations and how it scales with parameters

urban kiln
haughty mountain
crude karma
#

Yeah. In practice, this thing is very slow. But I can't give an accurate Big O based on the loops alone

haughty mountain
urban kiln
#

is popping the last element of an array O(n) or O(1)?

haughty mountain
#

last element is O(1)

urban kiln
#

first element is O(n) right?

haughty mountain
#

yes, you need to shift everything after the deleted element

urban kiln
#

oh ok

humble flower
#

what is balanced bst and why do we use it for dynamic lists?

agile sundial
#

we don't

humble flower
#

and what is it?

agile sundial
#

sets, maps

#

reptile already explained it to you

#

did you not understand the explanation?

humble flower
agile sundial
#

ask those then

humble flower
#

but please explain it again because i didnt 100% understand it

agile sundial
#

what parts did you not understand

humble flower
agile sundial
#

what do you mean "what it actually does"

#

it's used for sets and maps

humble flower
#

what does the algorithm do on a technical level.

#

what is its purpuse and how does it do that

agile sundial
#

there are multiple ways to implement a BBST. i'm most familiar with the red-black tree. another common one is the AVL tree

humble flower
#

could you explain what those two things are?

agile sundial
#

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

urban kiln
#

should be english

#

about red black

humble flower
#

can someone please explain the very basics of balanced bst to me?

tepid pivot
#

Am looking for a study buddy, anyone interested?

urban kiln
#

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

urban kiln
#

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

narrow mirage
#

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)

urban kiln
#

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())

urban kiln
#

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

quasi reef
#

anyone have time to explain to me the logic behind a codeforce problem?

urban kiln
#

and m the num of keys in a room

#

idk

#

probably

#

this one is easy

#

yea

#

bu mean the new problem i send?

urban kiln
#

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)```
urban kiln
#

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

#

?

urban kiln
#

ill also do it later

real oriole
#

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

haughty mountain
#

yeah, that's minimal set cover

real oriole
#

soo how would you recommend approaching the problem, is it more of a machine learning problem? sorry if I''m asking stupid questions ๐Ÿ˜…

haughty mountain
#

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

ionic locust
#

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

real oriole
haughty mountain
#

ouch

#

if you want to solve that optimally you'll have a bad time

weak moat
#

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

vocal gorge
#

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.

humble flower
#

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

haughty mountain
#

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

solemn moss
#

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?

sage flame
#

it does stop

sage flame
solemn moss
sage flame
#

it does

solemn moss
#

it can't work

#

found is False always

#

can you send that code?

sage flame
#

it turns into true

#

in the second condition

solemn moss
#

but that condition is always False

#

because days_of_week[i] is a string

#

and can't be equal to 5

sage flame
#

it's not equal to 5

#

it's equal to S

solemn moss
#

ahh

#

lol

#

sorry

solemn moss
#

no

#

ok.. nevermind

sage flame
#

so it's O(n)

solemn moss
#

It's O(nk) - because we should take worst case
When S is "Sun" and K substracts by 1 on each loop

sage flame
#

so it's quadractic time complexity

solemn moss
#

ye

sage flame
solemn moss
#

What are you trying to achieve?

#

This looks weird

sage flame
#

like is this the most effecient way to do it

solemn moss
#

No, i mean, can you tell in words what you want to do? I don't really understand what you try to get here

sage flame
#

given days of the week when entering a number return that day

#

so enter wed, 2 return fri

solemn moss
#

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]
sage flame
#

can you explain how it's n + k and not n*k

solemn moss
#

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

fiery cosmos
#
        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

vocal gorge
# fiery cosmos 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.

fiery cosmos
#

ight thanks

fiery cosmos
#

Fun fact: [x^x]' = x^x

vocal gorge
#

you mean, like, derivative? that's false, the derivative is x^x (ln(x)+1).

urban kiln
#

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

clever fable
#

and it shouldn't be that hard

#

just a bit of casework

opal oriole
#

(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?)

midnight sorrel
#

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?

ivory yacht
# midnight sorrel Hi, I have a task: ```Find maximum possible reward and number of eliminated oppo...

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.

lean walrus
#

I think it can be solved in O(number of opponents) using dynamic programming

languid nymph
last fulcrum
#

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.

midnight sorrel
lean walrus
languid nymph
lean walrus
#

Yes, but value is a list

last fulcrum
last fulcrum
lean walrus
last fulcrum
lean walrus
#

You can achieve O(1) by using other data structure

last fulcrum
lean walrus
#

No, you have to figure it out for yourself.

last fulcrum