#algos-and-data-structs

1 messages · Page 94 of 1

jade ridge
#

i need help with an algorithm that has a bit of explaining to do.

#

i'm creating a byte starting from 0, and building it with data

#

per BYTE

#

i need to set the next BIT after the first BYTE

#

so essentially

#
[bit, bit, bit, bit] [identifier] [bit, bit, bit, bit] [identifier] [bit, bit, bit, bit]
#

using struct.pack how would i do this?

#

essentially shifting each byte but assigning data in its spot

#

and what if the first set is 2bytes?

#
[bit, bit, bit, bit, bit, bit, bit, bit] [identifier] [bit, bit, bit, bit] [identifier] [bit, bit, bit, bit]
rain prawn
#

So I am doing a lot of graph theory research lately. I have seen all of these algorithms made for the identification of articulation points in these graphs. My question is, how can I find out not only articulation points, but how important a part is to a graph? Such as, giving score(s) for points that if removed, would cause major detours, ect.

#

Anyone know of anything they can point me to, or have any ideas? @ me when responding 🙂

autumn timber
#

Don’t have an answer but just did a project for data struct class and one of the methods was finding articulation points. Tough concept

fiery cosmos
#

maybe the degree of the articulation point can help?

#

if the degree is large then it is more important

atomic mulch
#

What are some malicious file extensions to blacklist on my server?

mint jewel
#

exe scr js vbs bat sh

agile sundial
#

you could probably start with the ones that this server blocks

mint jewel
#

we block everything but what discord embeds and some things we use internally

atomic mulch
#

@agile sundial where can i find that?

#

could you send me a link?

agile sundial
thorn bay
#

Hi

autumn mason
#

Hello everyone
Guys where do you start in algos and dst?

#

like what algorithm should I learn to solve?

oblique panther
#

@autumn mason you could make a doubly linked list and explain the runtime complexity of each operation.

autumn mason
#

@oblique panther I hope it's not difficult Im just starting to learn them ))

oblique panther
#

and if you do it using dunder methods, you also get to learn more about those.

rocky shore
#

who knows dynamic programming

#

?

keen hearth
#

What is your end goal?

autumn mason
#

Well, I started to.learn python year ago and I want be confodent that I know I knoe it well
Unfortunately, I didn't do any algos and dst and do not know how to them
End goal I suppose is to develop that mindset(mentality) to solve complex problems on programming

autumn mason
keen hearth
#

Also check out the "where to go from here" section at the end for links to further resources.

#

It does use Javascript for some of the exercises. But the concepts are general and apply to any programming language.

#

If you'd like to solve the problems using Python instead and want feedback, just post your solution here.

pale fable
#

can anyone reccomend me a good plagiarism checker algorithm for comaparing to two documents.

wispy hare
oak obsidian
hardy magnet
#

is there any site in which I can practice python algos for beginners(im a newbie in python)

lean glade
#

I've been learning about linked lists, and I can see how insertion is very easy and simple, because you just input node in which to insert and data. But for to find the node after which you want to insert, you need to use things like linkedlist.root.next.next.next, or do while loops for to find the node with the value you want. So I dont understand how the insertion in linked lists is any better than in normal arrays

#

Cause you waste the time finding the node after which you insert

lean dome
# lean glade I've been learning about linked lists, and I can see how insertion is very easy ...

yes - finding things in a linked list is slower than finding them in an array. But inserting or removing elements is faster in a linked list than inserting or removing them in an array. An array is made up of contiguous memory, so if you've got an array containing people's names in alphabetical order:

students = ["Ashley", "Bret", "Carl", "Debbie", "Fred", "George", "Harold", "Iggy", "Javier"]

and then an "Eddie" joins the class, you need to figure out where to insert "Eddie" - index 4, after "Debbie" and before "Fred" - and then you need to make room for it. Even if the array already has capacity to hold 10 names (instead of the 9 it's currently holding), you need to move "Javier" from index 8 to 9, then move "Iggy" from 7 to 8, then move "Harold" from 6 to 7, then move "George" from 5 to 6, then move "Fred" from 4 to 5, then you can put "Eddie" in 4.

#

with a linked list, you don't have to move all of those later names - you just make "Debbie" say that "Eddie" is next, and make "Eddie" say that "Fred" is next, and you're done.

#

so, yes - iterating over the first part of the list to figure out where to stick the new name is much faster with an array than a linked list, but actually inserting it once you've found the spot is much faster with a linked list than an array.

ionic pasture
#

is this the channel to ask about dirs and paths

hardy magnet
#

nope it is to ask abt algos

ionic pasture
#

alright

ionic pasture
#

i mean which channel should i head to

hardy magnet
ionic pasture
#

oh ok

hardy magnet
#

maybe u could ask the owner/admin or mod

idle imp
#

I have a 2D array like [[Joe, Sim, Pal], [Lary, Joe, Sim], [Howard, Pal, Joe,], [Joe, Howard, Pal]]

I want to print that every list that contains JOE at position 0 i.e first position

Output : [Joe, Sim, Pal] , [Joe, Haward, Pal]

How can I iterate in a 2D array ?

runic tinsel
#

you don't need to iterate the inner ones

#

it's just same as 1d

wispy hare
#

or in a more Pythonic way:
print([arr for arr in arr2D if arr[0] == 'Joe'])

idle imp
wispy hare
#

Then your input is probably wrong

lean glade
#

Oh now I get it @lean dome Thank you very much!

gaunt lotus
#

I have shifted from C++ to Python. Suppose we are in a recursive function ( i.e dfs) and we are in a specific instance of that function. I need to store something so that I can use it later. I only need that info and the info can be found in that specific instance. C++ for example I would assign the info to a global variable. But how do I do that in python

fleet mica
#

hello buddys im new member.. anyone here can tell the rules for asking in this server

fiery cosmos
#

i want to find out recursively the i-th element of a list

def element_at(xs, i):
    if i == 0:
        return lista[0]
    else:
        return element_at(xs[1:], i - 1)

i m trying something like this but it shows the first element of the list everytime

#

what i do wrong?

agile sundial
#

what is lista

fiery cosmos
#

oh fuck

#

okay

#

i am fucking dumb

#

now it works

lean glade
lean glade
#

Does it give better performance or is it good practice to delete nodes with del after removing the from a linked list?

oblique panther
lean glade
#

And is there anything that would do that?

oblique panther
lean glade
#

Oh ok

oblique panther
#

It would actually be a huge change to the language to add that

#

because the interpreter assumes that objects exist until it decides to delete them

#

and if you let the user decide when to force delete something, tons of code would have to be re-written to account for the loss of that earlier assumption.

#

!e

thing = 'hello world'
del thing
print(thing)
halcyon plankBOT
#

@oblique panther :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | NameError: name 'thing' is not defined
oblique panther
#

@lean glade this is a NameError because del thing had the effect of making the name "thing" no longer point to anything. We don't know if any memory was actually deallocated.

#

am I boring you now?

lean glade
#

But can the interpreter later decide to garbage collect the object?

oblique panther
#

yes, the interpreter will always garbage collect everything by the end of the program, even if that's the last step.

lean glade
#

But that may amount to useless stuff just being stored in your memory

#

Causing problems

oblique panther
#

there's a procedure it uses to decide when it's safe to delete something

lean glade
#

And is it like ultra-conservative when doing that procedure?

oblique panther
#

I don't know how you'd quantify how conservative it is. It uses reference counts

#

so as long as there's a reference left to an object, it won't get deleted. But once the reference count reaches zero, it will be deleted at some point.

agile sundial
#

there's also a funky algorithm that detects circular references

lean glade
#

And if I del'd the only reference to that object, it will destroy it?

#

Or variable

#

Maybe there are more references

oblique panther
#

I'm not sure how to quantify how far into the future that is.

#

I think it might be every time you exit a scope. Like when you return from a function, it might be that that's when everything for that function gets deleted. Or something like that.

agile sundial
#

the only thing you can really say is "on the next pass of the gc"

lean glade
#

Sorry, I meant, does an independently created object, like a list, get destroyed when you del it? cause the variable name was the only reference to it, unless there's other reference somewhere else

oblique panther
agile sundial
#

it doesn't get gc at the exact time you del, but there are no longer any references, so it will get gc in the future

#

you can manually run the gc

lean glade
#

Really? how?

oblique panther
agile sundial
#

yeah, but for the point of this

oblique panther
#

that would be an interesting experiment

#

create a linked list with a million elements

#

and call the garbage collector after each deletion

lean glade
#

Yeah

oblique panther
#
import gc
import time
from collections import deque

class catchtime:
    def __enter__(self):
        self.t = time.time()

    def __exit__(self, type, value, traceback):
        print(time.time() - self.t)


class GarbageDeque(deque):
    
    def pop(self):
        super().pop()
        gc.collect()


def test(cls):
    d = cls(range(1_000_000))
    with catchtime():
        while d:
            d.pop()


test(deque)
test(GarbageDeque)
#

@lean glade @agile sundial first one ran very quickly

#

second one is still running

agile sundial
#

wild

oblique panther
#

so apparently, calling the garbage collector is expensive

agile sundial
#

hm, it has to check each object that it's tracking

lean glade
#

Yeah, noticed when doing that with what I have

agile sundial
#

theoretically objects that it has checked before are pushed up a level, and are checked less frequently

late rose
#

Im unable to understand the error what does this mean??? HELP ASAP

keen hearth
#

An object should be garbage-collected when it becomes unreachable. No references is a sufficient but not necessary condition for unreachability.

lean glade
#

Ok

lean glade
fiery cosmos
#

how can I duplicate elements from an array in a recursive way?

#
def duplicate(xs):
    if len(xs) == 1:
        xs.extend([xs[0]])
        return xs
    else:
        
        return duplicate(xs[1:])
#

i tried something like this but i didn t solve anything

#

i tried to find a formula or smth but i didn t find anything

lean glade
#

Duplicate like, from [3,4] to [3,4,3,4]?

fiery cosmos
#

no

#

like

#

[3,3,4,4]

fiery cosmos
#

solved it

wispy hare
# gaunt lotus I have shifted from C++ to Python. Suppose we are in a recursive function ( i.e...

You can for example use a non-recursive function that creates a list (or any other data structure) and passes it to the recursive function
For example, here we are searching for all positive values from a binary tree

  if tree is None:
    return
  else:
    if tree.val >= 0:
      pos_vals.append(tree.val)
    rec(tree.left)
    rec(tree.right)

def get_pos_vals(tree):
  pos_vals = []
  rec(tree, pos_vals)
  return pos_vals```
wispy hare
# fiery cosmos solved it

hey, I think that when mentioning that you found the solution, it's better to briefly explain what you did

fiery cosmos
#

I used concatenation

def duplicate(xs):
    
    if len(xs) == 0:
        return []
    else:
        return [xs[0], xs[0]] + duplicate(xs[1:])
    
#

how can I recursively delete an element from a list? I don t have any ideas on that since I can simply xs.remove() it. I was thinking about slicing the list or something, but it doesn t look like a great idea

wispy hare
fiery cosmos
#

i know it s slow, but my teacher wanted recursion

wispy hare
#

A better solution would be to create another list, then you append each element twice

#

Yes you can do it recursively

#
  if i == len(xs):
    return
  else:
    dup.append(xs[i])
    dup.append(xs[i])
    rec(xs, dup, i+1)

def duplicate(xs):
  dup = []
  rec(xs, dup)
  return dup```
wispy hare
fiery cosmos
#

I am allowed to do what I want, the condition is that the function is recursive

wispy hare
#

you can for example use recursion to search for the indexes where you can find your element and delete

wispy hare
fiery cosmos
#

well you append in xs, so i suppose xs is an empty list?

wispy hare
fiery cosmos
#

was talking about the first function

wispy hare
fiery cosmos
#

so, he wants a recursive function that deletes the nth element from a list and it shows the deleted element and the list without the nth element

#

remove_at([1,2,3,4,5,6], 2) --> (3, [1, 2, 4, 5, 6])

#

so i know the index of the element that i wanna delete

#

and this is why I m confused, because i can simply return (xs[index], xs.remove(xs[index]))

wispy hare
#

shift all elements to the left starting from that index then pop to remove the extra element at the end

fiery cosmos
#

is there a python function for that?

#

or method

wispy hare
#

do it recursively

#

since you can't directly .remove()

fiery cosmos
#

i was talking about a method for shifting

wispy hare
#

just xs[i-1] = x[i]

fiery cosmos
#

hmm, yeah, that'll do

wispy hare
#

tell us if you couldn't do it

fiery cosmos
#

but how do i save the x[i] element that i wanna print

#

at the end of the recursion

wispy hare
#

save it somewhere before you start shifting

fiery cosmos
#

i have an index out of range error

wispy hare
#

try to find the reason

fiery cosmos
#

it s because the way i save that element

#

but i don t know why, it doesn t delete right

wispy hare
#

bring code

fiery cosmos
#
def remove_at(xs, ind):
    if ind >= len(xs):
        return xs
    else:
        xs[ind - 1] = xs[ind]
        return remove_at(xs, ind + 1)

[1,2,3,4,5], 2 -> [1,3,4,5]

#

it should be

#

[1,2,4,5]

#

oh

#

it duplicates the last element also

#

oh, forgot to pop

#

wow i can t pop

#

out of range

#
def remove_at(xs, ind):
    if ind == len(xs) - 1:
        xs.pop(ind)
        return xs
    else:
        xs[ind] = xs[ind + 1]
        return remove_at(xs, ind + 1)
#

i still don t know why do i have an out of range error

#

oh, solved it

#

it s pop(ind)

wispy hare
#

try to use a non-recursive function for popping

#

did it work?

#

just write xs.pop()

fiery cosmos
#

you make pop on the index or on the value?

wispy hare
#

just call it without params, it will remove the last element

thorny cipher
#

is it ok if i put 50 messeges here so i can voice chat?

mint jewel
#

as long as they are part of natural conversation

#

not just spam

lean glade
#

is it useful to add an attribute to a linked list which holds the last node? or should I just go for a doubly linked list?

lean glade
#

No, for appending

wispy hare
#

okay but by "last node" do you mean the previous node or the last node of the linked list?

lean glade
#

The last node of the linked list, for appending

wispy hare
#

yes it's useful

lean glade
#

Ok thx

wispy hare
#

you're welcome!

#

don't forget to adapt your code

lean glade
#

To what specifically?

wispy hare
#

to take in consideration your tail attribute

fiery cosmos
#
def remove_at_secundar(xs, ind):
    if ind == len(xs) - 1:
        xs.pop(ind)
        return xs
    else:
        xs[ind] = xs[ind + 1]
        return remove_at(xs, ind + 1)

def remove_at(xs, ind):

    valoare = xs[ind]
    tuple = (valoare,)

    
    if isinstance(xs, list) == True:
        return tuple + (remove_at_secundar(xs, ind),)

print(remove_at([1,2,3,4], 2))```

i have these 2 functions, one that removes recursively the element on the index ind, and the one that should make a tuple with the element that I removed and the list without that element.

it should print (3, [1,2,4])
why is it (3, (4, [1, 2, 4]))?
lean glade
wispy hare
#

for example, when deleting a node by index or by value, you have to make sure that if the last node gets deleted, then it updates the tail

lean glade
#

But now that I think about that, I would need to recalculate what is the last node each time I remove the last node

wispy hare
lean glade
#

Yeah, hmm, I think i'll just move on to implementing a doubly linked list now. Anyway not making them for any real use

wispy hare
#

remove_at_secundar is calling remove_at

fiery cosmos
#

yes

wispy hare
#

it should call itself

fiery cosmos
#

i cannot print the number that i delete in the remove_at

#

because it s recursion, it will never be that element*

#

the index is incrementing

wispy hare
#

and few things to know:
== True isn't necessary in a condition
here you're making sure that xs is a list, so you are not sure that your input is valid, in that case, you still have things to check (that ind is a number and that it's not out of list)

#
    if ind == len(xs) - 1:
        xs.pop(ind)
        return xs
    else:
        xs[ind] = xs[ind + 1]
        return remove_at_secundar(xs, ind + 1)


def remove_at(xs, ind):
    valoare = xs[ind]
    return (valoare, remove_at_secundar(xs, ind))```
fiery cosmos
#

but how

#

like...how..

#

i did this and it didn t work

wispy hare
#

it worked for me

eager hamlet
#

it's not like you can get from 1 to 2 because some values aren't possible, so idk how to "jump over" those values

#

so any help? (ping 2 help thx)

fiery cosmos
wispy hare
#

look at your remove_at_secundar function, it's calling remove_at, not remove_at_secundar

fiery cosmos
#

ohhh

slow crow
#

Is there a way to consistently match groups of words that works faster or better than levenshtein distance. I'm working with fuzzywuzzy.

#

I having difficult matching a company name to similar name in a group of company names.

#
result = process.extractOne(x, clean_comp_list)
#

I have a list of over 6k names that I am matching against. So each match takes at least 9 seconds to make

wispy hare
slow crow
#

Lol ya

wispy hare
#

you implemented it by yourself or you're using a lib?

slow crow
#

the fuzzywuzzy lib

#

@wispy hare

wispy hare
#

I found this

slow crow
#

@wispy hare Ya I can't use the C+ library python-levenshtein

#

I'm using the code on an academic system where I can't use visual studios

#

If you know of a way to get this library without installing visual studios I'd like to know

wispy hare
#

you don't need visual studio, I think that you just need to pip install python-Levenshtein then you can use it

slow crow
#

Nah I'm getting a error message saying that I must install it

wispy hare
slow crow
#

Ya but I can't install it because I'm not using visual studio's IDE and I'm going to be running the code directly into a interpret

#

@wispy hare

wispy hare
#

oh, I don't know much about packages problems then, check the right server and ask this question there

slow crow
#

What would be the right server?

wispy hare
#

Maybe python-general

slow crow
#

Ok thanks

wispy hare
#

you're welcome

native verge
#

Given a long list of json objects and a key-value pair to search for, what is the most efficient way of searching for that key-value pair in the long list of json?

frozen ermine
#

hi everyone, the round() function is being a piece of shit. i'm really angry lmfao

this is what i have written

    for num in list:
        print(round(num, 3))```
        
roundlist(liberalMindZScores)
the goal is to round every number in the list to three decimal places
when i run, i get this error

```---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-66-fcef4bcaa5f3> in <module>
      3         print(round(num, 3))
      4 
----> 5 roundlist(liberalMindZScores)

<ipython-input-66-fcef4bcaa5f3> in roundlist(list)
      1 def roundlist(list):
      2     for num in list:
----> 3         print(round(num, 3))
      4 
      5 roundlist(liberalMindZScores)

TypeError: round() takes 1 positional argument but 2 were given```

and the most fucking annoying thing is it was working like ten minutes ago
and nothing changed
shrewd cradle
#

Did you define a function named round?

lusty sand
#

Hi all

#

I need help with graphs, could someone provide some insight of this error?

fiery cosmos
#

Hello, I need help.
Im new to algorithms and my teacher told me to make a simple duplicate number algorithm.

#

She told me to use the "hare and tortoise" thingy.

#

Btw the language is python.

lean dome
fiery cosmos
#

Ok

subtle hearth
wispy hare
#

if yes then just def get_diag_rows(square_array): n = len(square_array) diagonal = [square_array[i][i] for i in range(n)] antidiagonal = [square_array[i][-i-1] for i in range(n)] return diagonal+antidiagonal

fiery cosmos
#
import numpy as np

def tester():
    np.seed(100)
    return np.random.random((4, 7))
```Im trying return numpy  random array but seed the numpy random number generator with the see `100` , how do I do so ?
burnt hamlet
unreal forum
#

is anyone doing advent of code here?

drifting drum
ashen wharf
#

this shell works but in the wrong way

def shellSort(l):
    interval = len(l)//2

    while interval >= 1:
        for i in range(len(l)-interval):
            for j in reversed(range(0, i+1, interval)):
                if l[j] > l[j + interval]:
                    l[j], l[j + interval] = l[j + interval], l[j]
                else:
                    break

        interval //= 2

    return l
vast whale
#

anyone well versed with java?

oblique panther
#

@vast whale you can join the Together Java discord to talk about that.

rough pivot
#
print("Hello there") ```
#

I need a hashmap

wispy hare
#

hashmap = {} here it is

agile sundial
#

HashMap<Integer, String> public static void hashmap = new stream(hashmap).collect(hashmap);

lofty jewel
#

Anyone here have experience with Tesseract?

lean glade
lofty jewel
#

Why can't Tesseract convert these images to a string with '0'? Tried changing dimensions, sharpness etc.

lean glade
#

Idk if in this chat, but maybe elsewhere

foggy phoenix
#

Hi guys, I need help with this problem, I'm new to Python and I don't remember what the solution will be

#

xd

lofty jewel
foggy phoenix
#

really? xD

sand pilot
#

We do not really appreciate using that word here, even if it is meant for yourself.

foggy phoenix
#

oh sorry

sand pilot
#

no worries, just wanted to let you know

subtle hearth
plucky slate
#

Hi Someone please help with this targetSum problem,
I am given an array of numbers and a target, and i have to find out if any or number from numbers array can sum up to target (number from numbers array can be repeated)
I wrote this dp approach

def canSum(targetSum, numbers, memo={}):
    if targetSum in memo:
        return memo[targetSum]
    if targetSum == 0:
        return True
    if targetSum < 0:
        return False
    for i in range(len(numbers)):
        remainder = targetSum - numbers[i]
        if canSum(remainder, numbers, memo):
            memo[targetSum] = True
            return True

    memo[targetSum] = False
    return False


print(canSum(7, [2, 3]))
print(canSum(7, [5, 3, 4, 7]))
print(canSum(7, [2, 4]))
print(canSum(8, [2, 3, 5]))
print(canSum(300, [7, 14]))
#

it prints
True
True
True
True
True

#

but for 3rd and last test cases it should return False, which it does if i run it separately, then why is it not working with multiple testcases?

wispy hare
#

It's because of Python

#

I got the same problem once

agile sundial
#

!mutable

halcyon plankBOT
#

Mutable Default Arguments

Default arguments in python are evaluated once when the function is
defined, not each time the function is called. This means that if
you have a mutable default argument and mutate it, you will have
mutated that object for all future calls to the function as well.

For example, the following append_one function appends 1 to a list
and returns it. foo is set to an empty list by default.

>>> def append_one(foo=[]):
...     foo.append(1)
...     return foo
...

See what happens when we call it a few times:

>>> append_one()
[1]
>>> append_one()
[1, 1]
>>> append_one()
[1, 1, 1]

Each call appends an additional 1 to our list foo. It does not
receive a new empty list on each call, it is the same list everytime.

To avoid this problem, you have to create a new object every time the
function is called:

>>> def append_one(foo=None):
...     if foo is None:
...         foo = []
...     foo.append(1)
...     return foo
...
>>> append_one()
[1]
>>> append_one()
[1]

Note:

• This behavior can be used intentionally to maintain state between
calls of a function (eg. when writing a caching function).
• This behavior is not unique to mutable objects, all default
arguments are evaulated only once when the function is defined.

agile sundial
#

ugh, i hate how long that is

lean glade
#

Oh, didn't know that kwargs will create a new object

plucky slate
#

@agile sundial thanks you so much!!!, it resolves my issue

autumn mason
#

hello everyone

#
    l = len(seq)
    for x in range(l - 1):  # we subtract 1 from length because we
        # can't make comparison on the last element of
        # the list because there is no numbe after it
        x += 1
        for i in range(0, l - x - 1): can anyone explain to me this step? 
            i += 1
            if seq[i] > seq[i + 1]:
                seq[i], seq[i + 1] = seq[i + 1], seq[i]
    return seq```
#

guys I need help understanding this

#

as you can see this is bubble sort

#

in the line for i in range(0,l-x-1) i want to know in details what it does

#

thanks in advance

wispy hare
autumn mason
#

yes i did

#

the thing is

#

I know what first for loop does

#

and the one after it kind of confuses me

#

like what l-x subtracts?

wispy hare
autumn mason
#

yes

wispy hare
#

the second iteration does n-2 comparisons only, because the last element is already in the right place

autumn mason
#

hmmmm

wispy hare
#

then the next one does n-3 comparisons only, because the last 2 elements are in the right place (they are already sorted)

autumn mason
#

i think i get it now

#

sorry for being slow and all that))

wispy hare
#

nope no problem man

autumn mason
#

just tryna understand that)

foggy phoenix
#

Hello friends, I want to ask you, how can I improve this code of my first python app? (it's a calculator and the variables are in Spanish)

#

it's made with tkinter

small sage
#
class Solution:
    binary = ""
    output = 0
    def converttodecimal(self,string):
        decimal = 0
        count = len(string)-1
        for i in string:
            decimal = decimal + (int(i) * (2**count))
            count -= 1
        return decimal 
    
    def getDecimalValue(self, head: ListNode) -> int:
        if head.next == None:
            self.binary = self.binary + str(head.val)
            return self.converttodecimal(self.binary)
        self.binary = self.binary + str(head.val)
        head = head.next
        self.getDecimalValue(head)
#

this keeps returning None

#

when it should return 5

#

i dont understand why this statement in the above code does not work:

#
return self.converttodecimal(self.binary)
#

heres the question:

#

can someone pls help me out?

#

thanks!

small sage
#

Wow so empty

#

@keen hearth

#

Can you help?

keen hearth
#

Nope, sorry, I'm just logging off.

#

You could try opening a help channel, if you don't get a response here.

#

Best not to directly ping helpers though.

small sage
#

all g

#

prob solved

zinc tapir
#

hey guyz,
i m doing DS and algo, would anyone like to team up?

small sage
#

im down

#

ive made a tiny server if ur keen

#

i sent on dm

vapid dirge
#

i am writing search algorithms in python for practice but how can i calculate the big o complexity of my code?

vivid horizon
agile sundial
#

does that just run a bunch of tests and run regressions?

raven geode
#

@vapid dirge use master's theorem or you can actually do it manually as well it just takes more time

jaunty loom
#

how can i decrease the complexity of this

def func_30(n):
    return_list = []
    for i in [16, 8, 4, 2, 1]:
        if n >= i:
            n -= i
            return_list.append(i)
    return return_list```
agile sundial
#

you can't

jaunty loom
#

oh

agile sundial
#

what is the complexity right now

jaunty loom
#

O(n)

#

i think

agile sundial
#

what's n

jaunty loom
#

the number of inputs

#

wait

#

so its o(1)?

#

since the output is always one?

#

public santa void main?

agile sundial
#

it only loops 5 times

#

max

jaunty loom
#

so the number of times is linear

agile sundial
#

no

jaunty loom
#

how?

#

should it be o(5) then?

agile sundial
#

sure

#

but O(5) is O(1)

jaunty loom
#

thats because all the constants are taken out right?

#

and it becomes

agile sundial
#

yep

jaunty loom
#

5(O(1))

#

and they remove 5

agile sundial
#

wait, what?

#

it's just O(1)

jaunty loom
#

yeah

#

is there no other way to improve this code?

#

thnx @agile sundial

agile sundial
#

what's it supposed to do?

jaunty loom
#

the code

#

its supposed to take a number

#

and give the numbers from the powers of 2 that give this when added up

#

for example

#

5 gives [4,1]

agile sundial
#

that's the best way then

jaunty loom
#

Yay, thnx for the help

fiery cosmos
#

idk if this is the right channel or not but I'll put it here bc technically it's a linked list ig

#

so I'm writing a undo button for a thing I'm working on but for a thing

#

the code for the main thing is

#
        if keys[pygame.K_LSHIFT] and keys[pygame.K_LCTRL] and keys[pygame.K_z]:
            if state-1 > 0:
                state -= 1
                dots = states[state]
        elif not keys[pygame.K_LSHIFT] and keys[pygame.K_LCTRL] and keys[pygame.K_z]:
            if state+1 < len(states):
                state += 1
                dots = states[state]
#

also earlier in the code I do states.insert(0,dots) every time there's something that'd make it change

#

also did

for s in states:
      if not s == dots:
                  print('true')
#

to test it and it never returned true

#

wait nvm pensivecowboy

#

I think ik what the problem is

#

nvm

#

I thought the problem was that I was doing states.insert(0,dots) so I did

states.insert(0,'replace')
states[0]=dots
#

so it would just be what dots was atm not always dots

eager hamlet
#
A factory is running a production line that requires two operations to be performed on each job: first operation "A" then operation "B". Only a certain number of machines are capable of performing each operation.


Figure 1 shows the organization of the production line that works as follows. A type "A" machine takes a job from the input container, performs operation "A" and puts the job into the intermediate container. A type "B" machine takes a job from the intermediate container, performs operation "B" and puts the job into the output container. All machines can work in parallel and independently of each other, and the size of each container is unlimited. The machines have different performance characteristics, a given machine requires a given processing time for its operation.
Give the earliest time operation "A" can be completed for all N jobs provided that the jobs are available at time 0. Compute the minimal amount of time that is necessary to perform both operations (successively, of course) on all N jobs.

PROGRAM NAME: job
INPUT FORMAT
Line 1:    Three space-separated integers:
N, the number of jobs (1<=N<=1000).
M1, the number of type "A" machines (1<=M1<=30)
M2, the number of type "B" machines (1<=M2<=30)
Line 2..etc:    M1 integers that are the job processing times of each type "A" machine (1..20) followed by M2 integers, the job processing times of each type "B" machine (1..20).
SAMPLE INPUT (file job.in)
5 2 3
1 1 3 1 4
OUTPUT FORMAT
A single line containing two integers: the minimum time to perform all "A" tasks and the minimum time to perform all "B" tasks (which require "A" tasks, of course).
SAMPLE OUTPUT (file job.out)
3 5```
#

ok so

#

i can just greedily figure out

#

all the minimum finishing times for each task to go through the A production line

#

but a similar greedy method won't work for b

#

is there like

#

some other greedy method? (ping 2 reply thx)

fiery cosmos
#

also nvm about my question I just loaded/dumped it with pickle and it worked

north cosmos
#
expression = '48'
decimal = lambda expression: sum(list(x*(2**y) for y, x in enumerate(map(int, expression))))

def octal(base_value):
  values = []
  while True:
    if int(int(base_value)/8) != 0:
      values.append(0)
      base_value = int(int(base_value/8))
    else:
      values.append(int(base_value))
      break
  return values

print(octal(decimal(expression)))

Anyone know why this gives [0, 2]?
because, when it first divides 48 by 8, the answer would not be 0, so it appends 0 to the values, and base_value should be 6 as 48/8 is 6.
Then it sets the base_value as 6, and the loop happens again,
6/8 == 0, so it should append 6 to base_value and break, but somehow it appends 2
anyone know what's wrong here

tepid python
#

why are you converting to int

#

you can just use //

north cosmos
#

eh, that aint the problem here is it?

tepid python
#

no

#

it's because base_value is not 6

#

you need to reassign it first

north cosmos
#

i did reassign it base_value = int(int(base_value/8))

tepid python
#

which is still the original value

#

not the divided one

north cosmos
#

how is it no tthe divided one?

lean dome
#

what is decimal supposed to do?

north cosmos
#

give the base_value

#

which it gives correctly

lean dome
#

what do you mean by "base value"?

north cosmos
#

the argument

lean dome
#

decimal("48") is 20, and I can't figure out what that's supposed to mean.

north cosmos
#

oh my bad

#

oh now its working

deft wraith
#

!e

halcyon plankBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

foggy phoenix
#

?

#

that I have done wrong so that the "info" command does not work?

worn hazel
#

Any really good youtube channels pertaining strictly to algorithms and data structure type puzzles based on algorithms?

agile sundial
wet lantern
void sonnet
#

hi guys got any tool can help to auto buy the things ??
like in lazada , amazon
kindly like can help to buy in the limited time

wet lantern
#

I don't think you can buy things through amazon through a python bot.Won't there be one-time-password sent to phone to verify.Even if you login there will a recaptcha that identifies if you're a bot or a human.It's gonna be difficult.I don't know any tool sorry.

drifting drum
#

This is for aoc's question 1 today. I figured this would be a better place to ask than in the channel, since it has more to do with python itself than aoc.

So, I have two programs for part 1, which was essentially The Game Of Life.

The 1st code is spaghetti code and has conditional checks for every type of cell I could be on in the matrix- corner, edge or other

The 2nd code, I instead used the dirs = [(-1,0), (1,0), ....] trick and eliminated redundant code.
I barely changed any other logic, infact I was trying to refactor and optimise it(For example maintaining a boolean to detect if there was a change in the matrix rather than doing an O(N^2) equality check).

But I don't understand why the first dirty code runs in 2.5 seconds on an average, while the second one with functions takes ~7 seconds

This is the dirty but fast code -
https://paste.pythondiscord.com/origemexes.go

This is the slow but refactored and optimised(???) code:
https://paste.pythondiscord.com/fagewoqene.properties

I initially thought maybe the function calls could be the bottleneck, so I removed the function calls and wrote it in a procedural manner, time reduced from ~7.2 sec to ~6.8
But that's still nowhere close to the less than 3 seconds that the dirty code gives.

So, could someone explain what's up with python?

eternal echo
#

probably some optimizations related to python calling C

drifting drum
#

hm, what do you mean?

compact fog
#

hi can anyone help me with my coursework?

#

ill get you a discord nitro

#

pls dm me :))

north cosmos
#

!rule 6 @compact fog

halcyon plankBOT
#

6. No spamming or unapproved advertising, including requests for paid work. Open-source projects can be shared with others in #python-general and code reviews can be asked for in a help channel.

north cosmos
#

unapproved advertising, including requests for paid work.

whole glade
#

Hi I'm trying to create an algorithm to find the row and index of the n'th letter in a series of rows such as this.

This is a simplified version of the problem.
There would be random data in each of these indexes, but the lettering from a-Z is their order.

Its constructed by removing every other letter in a-Z, and putting them into the next row. Then the next row you remove every other letter and put it in another row, and so on.

I've managed to get an algorithm to determine the exact row to check. I've also found a very close solution to getting the index in that row, but it's having a few mistakes.

This sequence is very close to getting the index correct, but any index a multiple of 8 returns around an index or two short in my test case: https://oeis.org/A003602

Do you guys think it's possible to have a straightforward function that returns the nth piece of data in this without iterating through it all?

whole glade
#

wait actually I tested on a large-scale case and it seems to work perfectly fine 🤔

fiery cosmos
#

c

#

c

#

cc

halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied mute to @fiery cosmos until 2020-12-11 19:50 (9 minutes and 58 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied mute to @novel cargo until 2020-12-11 21:30 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

formal aurora
#

hey guys, how do i determine the time complexity for specific sorting algorithm?

#

for instance, how do i determine the time complexity for Selection and Merge sort?

quick lark
#

import string
lowerbet = string.ascii_lowercase + '_'
"".join([lowerbet[randint(0,len(lowerbet))] for n in range(randint(4,12)
) ])

#

why does that work? And...

#

words = ['test' for m in range(10)]

#

works

#

but:

#

["".join([lowerbet[randint(0,len(lowerbet))] for n in range(randint(4,12)
) ]) for m in range(size)]

#

yields IndexError: string index out of range

wet lantern
#

for me a different error is shown

Traceback (most recent call last):
  File "D:\programming projects\python programs\trial.py", line 3, in <module>
    lowerbet = ["".join([lowerbet[randint(0,len(lowerbet))] for n in range(randint(4,12))]) for m in range(size)]
NameError: name 'size' is not defined
hoary finch
#

it should only indexerror if randint(0, len(lowerbet)) == len(lowerbet), so you might want to change that to randint(0, len(lowerbet) - 1) or randrange(0, len(lowerbet))

#

or just change it completely to random.choice(lowerbet)

dapper turret
#

Idk if this belongs here bnut how woulod i set a np array with no deffiended shape

echo lantern
#

i'm trying to find the len() of an itertools.combinations(), but my kernel keeps getting "killed" because the number is just too big... (im guessing its ike 350,000 combinations or so). Anyone have suggestions how i can counter this?

oblique panther
#

^ already answered in another channel

zenith pagoda
#

any tips on analyzing how a recursive function works? like visualizing through diagram or table or any other way

wispy hare
median stream
#

[Solved]

sour crown
#

Can someone help?

#

Please

tepid python
#

looks like it's not in the correct directory

fiery cosmos
#

Hello everybody I have a question concerning datastructurs in Python ! How do you know about data structure like XOR, List, etc... Thank you for reading me and respond to it 😉

jaunty loom
#

what is n factorial?

#

and why is it the time complexity of randomly sorting an array

agile sundial
#

that is really just not what he asked

#

although it probably was what he meant 🤔

agile sundial
jaunty loom
agile sundial
#

then melio's explanation was right

jaunty loom
#

that is if we make sure we don't repeat the last permutation right?

#

but if we don't check if the permutation has already been permuted

#

is it infinite then?

austere sparrow
#

Factorial of n, written as n!, is the product of all natural numbers from 1 to n, e.g. 5! = 1 * 2 * 3 * 4 * 5 = 120

#

The time complexity of randomly sorting an array is O(infinity) or something like that. Doesn't really make sense to talk about the complexity of that algorithm, since it's pretty silly 🙂

jaunty loom
#

yeah lol

#

so all possible permutation of n

#

is n! ?

austere sparrow
#

Yes.

wispy hare
# jaunty loom is n! ?

yes, because if for example your array has 5 elements, then the first element of the permutation has 5 possibilities. The second element has only 4 possibilities, because we already used the 5th one for the first element. Then the third element has only 3 possibilities, because we used the two other ones in the first two elements

#

and it continues like that 5 * 4 * 3 * 2 * 1 (in a general way: n * (n-1) * (n-2)*...21), and this product represents n!

austere sparrow
#

First, you have n choices, then n-1 choices, and so on

wispy hare
#

here is one with 4 elements

austere sparrow
#

That's a slightly better drawing 😅

jaunty loom
#

lol, thnx, that tree helped me understand it so much better

wispy hare
#

try to write (or at least understand) the algorithm that generates all the permutations of a string/array

jaunty loom
full current
#

Any recommendations ?

naive lichen
naive lichen
pale garnet
#

Is there a high performance tree library in python? I've tried anytree and treelib so far, and while treelib is a lot faster than anytree, constructing the tree still takes almost as long as parsing the data for it. For context: I'm trying to create a directory tree from a TLV-mapped VFS file with around 50k entries (directories and files). Is there a better way to do this? I probably don't need most features of these libraries for my purposes. Should I make my own tree implementation? Curious to hear your thoughts on this.

wraith valve
#

i think scipy or some other math lib allowed you to make a kd tree

tacit ether
#

Hello everyone! Can anyone help me with one dp task?

pale garnet
pseudo geode
#

Hey guys , just a general question , I am a beginner in web dev and i dont know any DS and Algo (except the basic ones) , so should i stop for a bit and learn those before continuing or should i learn them as i encounter need for them
Also , what language should it be in ?? I am ol with c,cpp,python , javascript

tacit ether
zenith pagoda
#

is this an example of post-order traversal?

def common_ancestor(root, p, q):
    if root is None:
        return None

    if root == p and root == q:
        return root

    x = common_ancestor(root.left, p, q)
    if x is not None and x != p and x != q:  # found common ancestor
        return x

    y = common_ancestor(root.right, p, q)
    if y is not None and y != p and y != q:
        return y

    if x is not None and y is not None:
        return root  # this is the common ancestor
    elif root == p or root == q:
        return root
    else:
        return y if x is None else x
lean glade
ashen wharf
#
def sort(l):
    for i in range(len(l)):
        right_idx = len(l)
        while True:
            if right_idx == i:
                break
            for j in reversed(range(i+1, right_idx)):
                if l[i] > l[j]:
                    l[i], l[j] = l[j], l[i]
                    break
            right_idx -= 1
    return l

does this sorting algorithm exist

lean dome
ashen wharf
#

why do i keep on making sorts that seem new but are just weird variations of already existing sorts XD

#

however this one is slightly faster than selection sort

agile sundial
#

how slight lol

lean glade
#

Use range(right_idx-1,i,-1) instead of reversed(range(i+1,right_idx))

lean dome
#

and while right_idx > i: instead of ```py
while True:
if right_idx == i:
break

lean glade
#

And don't use the letter 'l' as a variable name, it's confusing

lean dome
#

I don't agree with that as a general rule, but in this case left_idx would be a better name.

eager hamlet
lean dome
#

it can, however, be done in a single pass over the input data, instead of in multiple iterations. And that would probably let you make something fast enough.

#

something like:

results_lists = []
for e in input_numbers:
    for result_list in result_lists:
        if e > result_list[-1]:
            result_list.append(e)
            break
    else:
        # Smaller than the highest value in every list
        result_lists.append([e])
eager hamlet
#

i mean that'd still be n^2

lean dome
#

ah, there is a place where you could use a binary search there, if that's not fast enough.

#

each of those sublists winds up being sorted in descending order by the highest value. You can binary search through result_lists to find the earliest one where the element is greater than the max of that list

dapper turret
#

Yo so can someone help me with this problem I have a for loop that runs a unknow amount of times and each time it calls a funtion with is going to return a list of ints and each time i need it to append a np array but in a new layer (so instead of it being 1111 it would be ```
1
1
1
1

eager hamlet
#

maybe run another for loop that appends it to the array?

lean dome
# lean dome each of those sublists winds up being sorted in descending order by the highest ...

that is, let's say you've got 10 result lists. You can iterate over them one at a time to figure out which one to append to, but it would be more efficient to check last element of the 5th one. If your number is lower than that, it must be lower than the highest element of the 1st through 4th as well. If it's higher than that, it must be higher than the 6th through 10th as well. So you can narrow down your search space from there, and check the 3rd or the 7th.

eager hamlet
#

wait

#

how do we know

#

that the results'll be sorted by last element

#

at any step in the iteration

lean dome
#
results_lists = []
for e in input_numbers:
    for result_list in result_lists:
        if e > result_list[-1]:
            result_list.append(e)
            break
    else:
        # Smaller than the highest value in every list
        result_lists.append([e])

Because at every step in the iteration, we append the new item to the earliest result list where it's greater than the current max element.

eager hamlet
#

the current max?

#

oh yeah i see

#

but wait

#

let's say we had a list

lean dome
#

A natural consequence of that is that the first list will always contain the largest number encountered so far, and the second list will always contain the largest number that was excluded from the first list, and the third will always contain the largest number excluded from both the 1st and 2nd...

eager hamlet
#

wow

#

that's big brain

#

thx man

lean dome
#

That was actually a fun little problem - binary search requires a sorted input, so at first I couldn't see how it could possibly apply here

#

it's neat that there's a way to apply it here, thanks to building up a sorted set of result lists 🙂

eager hamlet
#

yeah

#

i was thinking

#

like that too

#

the cloest thing i could do

#

was sort it each time after

lean dome
#

FWIW, if it's not immediately obvious, your worst case input will be 200,000 values that are sorted from most to least.

#

if your input is 5 4 3 2 1, then your output is 5 separate one-element lists.

#

so, if you're timing this yourself, test your performance of different versions against that input to see how they stack up against one another.

eager hamlet
#

@lean dome thanks, the algo worked! wanna see my code?

lean dome
#

sure

eager hamlet
lean dome
#

nice 🙂

lean glade
#

And yeah ik im answering late

eager hamlet
#

hey, anyone know why i & -i returns the greatest power of 2 less than i

#

and why doesn't it work for larger numbers

lyric bramble
#
def happines(check_array,set_a,set_b,set_c):
    happy = 0
    for i,j in zip(set_b,set_a):
        if i in check_array:
            happy += 1
        if j in check_array:
            happy += 1

    for k in set_c:
        if k in check_array:
            happy-=1

    print(happy)
#

time complexity of this code?

agile sundial
#

what do you think

lyric bramble
#

o(n)

#

im i right?

half lotus
#

It's not certain, but I don't think so

#

Consider the worst case of if j in check_array

#

Judging by its name, check_array is likely a list. Therefore, in could do a linear search through the entire list.

#

And such search is being done for every item iterated

#

Furthermore, the loops iterate over different objects. Therefore, excluding the previous consideration, it's not just n but rather a sum of two variables representing their lengths.

fair summit
#

you first need define your input variables

#

here there is more than just n

shy zenith
#

Code:

fmt = '{:<4} {:>10}\n'
a+=fmt.format(row[0],row[1])

Output:

StrA          50
StrAStrBStrCStrD    12```

**How to get the output like this (equally aligned)?**

```yaml
StrA                50
StrAStrBStrCStrD    12```
wispy hare
lean glade
#

Lol

#

It would be nice if somebody pinned that

fiery cosmos
#

hi

barren grotto
#

hello

halcyon rain
#

increase key heap implementation code is here

#

please help with testing case for increase key

lofty cosmos
#

does anyone have exercises divided by algorithm and data structure topic?

tepid pier
#

Idk where is the best place to ask this question but i thought this would be a good place. How do you determine whether an algorithm is P, NP, NP-complete or NP-hard. I've currently made a program that can only possibly be solved in exponential time, and can also only be verified in exponential time. Does this mean its NP-hard?

eager hamlet
#

any help?

#

an idea would be to use integer divison

#

to simulate until he can't add any more, than divide for the time until he has to add some water

#

so the level sort of fluctuates between 2 extremes

lean dome
#

I think there's a purely mathematical answer here; I don't think you need the loop.

#

If the amount withdrawn each day matches the amount that can be deposited each day, then the only way to lose is if there's not enough room to make a deposit on the first day, and making a withdrawal drops below the lower bound.
If the amount withdrawn each day is one greater than the amount that can be deposited each day, then:

  1. if you cannot make a deposit on day 1 and the amount to withdraw puts you too low, you lose immediately
  2. if you cannot make a deposit on day 1 and the amount to withdraw is OK, you lose after k-l days
  3. if you can make a deposit on day 1 you lose after k-l+1 days
    I'm pretty sure this can be generalized to a formula that works for all possible inputs...
lean dome
#

if it does need to be done iteratively, note that you can stop as soon as you hit any number you've already seen before. If it's possible to get from some number back to that same number, you can do that any number of times indefinitely.

sleek breach
#

So curious if a dictionary of sets would be the best. I have a giant csv and I want to pull out ports and hosts, which I can do. But now I want to store all hosts (keys) with the ports (values) and do it the fastest way possible, without any duplicates... Any suggestions?

lean dome
#

multiple ports per host? a dictionary keyed by host with sets of ports as values sounds entirely reasonable.

pallid phoenix
#

Hello, i'm trying to add 2 lists to each other, however if any value in the list is a permutation of another, the value to which the permutation belongs, has to be added to another list, and the permutation has to be removed from the initial list.

#

EG. ['123','321','459','945'] should turn into ['123','459']

stable pecan
#

you could use a set of sets

pallid phoenix
#

so if i add ['123','321','459','945','552'] and ['525','667'] the result should be : ['123','459','552',667] where the other list should be ['123','459','552']

#

my problem comes in where i need to remove the permutation, currently my for loop loops through every permutation, if it finds it in the list removes it, but i need to keep the first one

stable pecan
#

need something like this?:

In [57]: split_duplicates(['123','321','459','945','552'])
Out[57]: (['123', '459', '552'], ['321', '945'])
#

oh, the duplicates should be the original items

pallid phoenix
#

yes, and im having a hard time, removing every permutation, but keeping the original item

stable pecan
#
In [60]: split_duplicates(['123','321','459','945','552'] +  ['525','667'])
Out[60]: (['123', '459', '552', '667'], ['123', '459', '552'])
#

i think i got there

#

i did this by keeping track of "seen" permutations in a dictionary

#

using frozenset, though you could use other data structures

pallid phoenix
#

hmm, ive nevr really worked with sets, nevermind frozensets, so if you keep track of all the permutations you see, how do you make sure you dont remove all of them? since the permutations of "123" includes itself

stable pecan
#

well, frozensets are just sets that are hashable meaning you can use them as keys in a dict

#

i started here:

    seen = {}
    unique = []
    duplicates = []

    for item in my_list:
        as_set = frozenset(item)
#

we check if it's in seen, if not then we append it to unique and add the permutation to the dictionary like so: seen[as_set] = item

#

if it is in seen then we just append seen[as_set] to duplicates

pallid phoenix
#

so would my_list be the lists you add, or a list of each items permutations?

stable pecan
#

my_list is what i passed to the function

pallid phoenix
#

oh i see, this last code part is inside the split_duplicates function?

stable pecan
#

yep

pallid phoenix
#

okay so i'm trying to wrap my head around it but i feel kind of stupid

#
seen = {}
unique = []
duplicates = []
list1 = ['123', '321', '459', '945', '552']
list2 = ['525', '667']

def split_duplicates(duplist):
    for item in duplist:
        list1permutations = [''.join(p) for p in permutations(item)]

        for permutation in list1permutations:
            as_set = frozenset(permutation)
            if permutation not in seen:
                unique.append(permutation)
                seen[as_set] = permutation
            else:
                duplicates.append(seen[as_set])


split_duplicates(['123', '321', '459', '945', '552']+['525', '667'])

print(unique)
print(duplicates)
#

unique should be the 2 lists added, but with each items permutations removed? and then duplicates should be the permutations that we kept?

stable pecan
#

you don't need the loop on the outside

#
def split_duplicates(my_list):
    seen = {}
    unique = []
    duplicates = []

    for item in my_list:
        as_set = frozenset(item)
        if as_set in seen:
            duplicates.append(seen[as_set])
        else:
            unique.append(item)
            seen[as_set] = item

    return unique, duplicates
pallid phoenix
#

oh from what i can see it works perfectly, thank you for your help! i just want to ask a few questions so i fully understand what we do. So as_set is basically a tuple of our list item? except it stays an item(i'm still looking for a proper explanation online on frozenset())?, if as_set is not in seen, we create a dictionary entry(dictionary because they cant have duplicates?) why do we add item to unique and not as_set?

stable pecan
#

a set only cares about the elements inside the set --- the order doesn't matter

#
In [61]: set("123") == set("321")
Out[61]: True
#

so we make a set or frozenset of the item, because we don't care about the order of the numbers

#

we use a frozenset so we can use it as a key to our dictionary, where we store the original item that made the set as a value

#

it's not like a tuple at all --- tuples care about the order of the elements

#

it's hashable

#

so we can use it as a key to a dictionary

#

normal sets are mutable and not hashable

pallid phoenix
#

OOH, so frozenset(X) will be equal to all values in the permutations of X?

stable pecan
#

basically

#
In [62]: set("123") == set("132") == set("213") == set("231") == set("312") == set("321")
Out[62]: True
hollow isle
#

hey guys

#

described my problem here can someone help

pallid phoenix
#

if sets are so useful, why have i never seen them in any python tutorials, thank you again for your help

stable pecan
#

it's a data structure you usually don't use as a beginner

#

maybe

#

@hollow isle did you have some question that's related to the channel topic?

hollow isle
#

uhm yes

#

its not discord related

stable pecan
#

how is it related to algorithms and data structures?

hollow isle
#

basically I'm getting a 400 Bad Request though all my dictionaries etc are right and need assistance

#

if you have a suggestion as to a better place to ask, go ahead and tell me

#

asked in #web-development and 2 other servers waited an hour got no response , thought it'd be slightly relevant to data struts cos i clearly messed up some dict values thats why asked here

stable pecan
#

maybe open a help channel, the code snippet seems to be missing a lot of relevant code

hollow isle
#

what do you think i'm missing? i can provide

#

and wdym open a help channel, how and where

stable pecan
hollow isle
#

oh ty LOL since Selenium is a module, all this while i been thinking there were modules called potassium fluorine etc LOL im so dumb thanks

eager jetty
#

Hi, I'm trying to implement a MinMax Algorithm (recursively) but I'm facing this annoying error related to recursion:

RecursionError: maximum recursion depth exceeded in comparison

This my code:

import math as m
list = [11 , 4 , 8 , 9 , 2 , 7 , 17]
list.sort()
def MinMax(A , low , high):
if (high - low) == 1:
if A[low] < A[high]:
return A[low] , A[high]
else:
return A[high] , A[low]
else:
mid = m.floor( ( low + high ) / 2 )
x1 , y1 = MinMax(A , low , mid )
x2 , y2 = MinMax(A , mid + 1 , high)
x = min( x1 , x2 )
y = max( y1 , y2 )
return x , y

print('sorting ...')
print(list)
mm = MinMax(list , 0 , len(list)-1)

print(mm)

anyone can help me with that ?

fiery cosmos
#

hey, am new to coding and i would really like to know how are algos are made in python. Would you guys have any documentation or good youtube videos where i could find answers ?

sick juniper
#

Could someone explain in some relatively layman's terms what a shunting-yard algorithm is?

lean dome
#

It's an algorithm for resolving associativity and precedence in a mathematical expression

#

In other words, figuring out that a + b * c represents multiplying b by c and then adding a to the product, and not adding a to b and then multiplying the sum by c

sick juniper
lean ice
#

Essentially but with reverse polish notation

lean dome
#

Well, RPN is a potential output from it, but so is any other unambiguous parse tree

#

It's a way to figure out what operators should be called with what operands, given that the operators' associativities and precedences are inputs to the algorithm.

#

If it were parsing Python, for example, you would tell it that + is left associative (meaning that a+b+c is evaluated as (a+b)+c) and that ** is right associative (meaning that a**b**c is evaluated as a**(b**c), and that + has lower precedence than **, and it would then tell you that a+b+c**d**e is evaluated as (a+b)+(c**(d**e))

#

And RPN is a useful human readable way of representing that final result without any ambiguity.

wet furnace
#

Hi, may I know if anyone is familiar with SLAM algorithm?

gusty grove
#

yup! i havent done a lot of work with it, what do you want to know?

fiery cosmos
#

Is there a way to add code snippets to word document that it isnt a image but wont be counted as word count ?

pallid phoenix
#

Hello, i'm trying to get the value in a 2D List, by passing in the index of the item i want, as i understand 2dlist[0,0] returns the first value in the first list

oblique panther
#

for lists it needs to be _2d_list[0][0]

#

(you can't start the name of a variable with a numeric character)

#

a numpy array/matrix is one object, no matter what shape it is. But if you have nested lists, you're actually doing two separate lookup operations.

#

on two separate objects.

#

think of it as (_2d_list[0])[0]. That's what the order of operations is

#

Is that more information than you wanted? 😄

pallid phoenix
#

yes that's perfect thank you

drowsy hornet
#

.

half lotus
#

I need a hash set data structure that's ordered and supports O(1) indexing. Is there anything like that?

#

It's pretty close except it's a dictionary not a set. I could use it and just set a dummy value for every key.

wispy hare
half lotus
#

I have heard that before

#

I guess it doesn't matter then

wispy hare
#

What you're searching for is probably an ordered set

#

which can be implemented with a self-balancing binary search tree

lean dome
#

Usually this is implemented using something like a set plus a linked list, from what I've seen. If I understand what you need.

#

Like, OrderedDict is a dict plus a linked list, so you could build an OrderedSet the same way

half lotus
#

I'm looking at an ordered set implementation right now

wispy hare
half lotus
#

They seem to keep the index as the value in a dict

lean dome
#

What's the overall goal? This seems like a strange data structure to need.

half lotus
#

I have media files and each file has streams (audio, video, subtitles, etc). For each file I need to add all its streams to a ordered set and then remove some items that are excluded. After some items are removed I need to look up the index of certain streams.

lean dome
#

Hm, why not just a dict mapping stream to index? You would read each stream from your media file, keeping a counter. Each read stream would be added as a key to the index, with the counter as the value. You'd remove the entries that are excluded (or never add them), and then you'd look up the index of your certain streams with regular dict lookups

half lotus
#

Because when I remove items the indices need to be updated

#

And I don't want to loop through the entire data structure decrementing indices

lean dome
#

So are you removing streams, and trying to write the kept ones back in the original order?

half lotus
#

That being said, i think i can avoid this by getting the streams that should be excluded, then getting all streams, then adding them to a dict 1 at a time while ignoring those that were originally fetched for exclusion.

#

I originally didn't think I could get the excluded streams that's why i was over complicating this

lean dome
#

In Python 3.7 or higher, dicts preserve insertion order. You can do what I said, adding every stream, them removing the ones that should be removed, then iterate over the dict with enumerate. For each stream encountered, the value is its old index, and the enumerate counter is its new index

half lotus
#

I see what you mean. Just do one more iteration to correct the indices after things are removed

fiery cosmos
#

Does anybody have experience using the struct.unpack and pack modules?

lean dome
#

Sure, what about them?

half lotus
#

For some reason i thought I had to update the index after every removal

#

Thanks

fiery cosmos
#

it seemed to work, so just wondering why even bother using unpack()

lean dome
#

Which is to say, you don't need struct.unpack to read one byte out of a byte string, but you do need it to read a multiple byte long integer. (Well, not need it, but it makes the job easier)

lean dome
fiery cosmos
#

thanks for explaining that

lean dome
#

"rb" gets you the ability to see the value of each byte, but when a value is composed of multiple bytes, interpreting it takes more work.

fiery cosmos
#

would this also work the same:

#

unpack('<i', chunk[0x1B8:0x1BC]

#

and just set that to sector_address

lean dome
#

that would read an entirely different value - one is the 4 byte unsigned integer starting at 0x1BE, the other is the 4 byte unsigned integer starting at 0x1B8

fiery cosmos
#

so just use [0x1BE + 8 : 0x1BE + 12] isntead?

lean dome
#

yes

#

and i should be I, I think

#

because, as far as I can tell, the number is unsigned, not signed.

fiery cosmos
#

holy shit it worked

#

ty

small drift
#

Can someone help me with this linear regression algorithm im trying to write ? The step size isn't converging for some reason and I dont know why.....

class LinearModel(object):
    def __init__(self, x, y, learning_rate=0.01):
        self.learning_rate = learning_rate
        self.X = x
        self.Y = y
        self.coeffs = np.zeros(x[0].size)

    def gradient(self):
        """
        Calculates the gradient
        :return:gradient as a numpy array
        """
        labels = self.Y
        features = self.X

        gradient = np.array([])

        dw = 0
        for f in range(len(features[0])):
            for i in range(len(labels)):
                dw += (labels[i][0] - np.dot(self.coeffs, features[i])) * features[i][f]
            dw /= len(features)
            gradient = np.concatenate((gradient, np.array([dw])), axis=0)

        return gradient

    def step_size(self):
        """
        Calculates and returns the step size
        :return: step_size
        """

        step_size = self.learning_rate * self.gradient()
        return step_size

    def fit(self):
        """
        Find values of the coefficients that minimize the loss function, LSE
        :return: void
        """

        for _ in range(12):
            self.coeffs -= self.step_size()
            print(self.step_size())

    def predict(self, x):
        """
        Predicts using linear regression algorithm
        :param x: Features
        :return: Predicted label
        """
        return np.dot(self.coeffs, x)
dry ember
#

What do you think of the use of Enum like such:


from enum import Enum

class Day(Enum):
    Monday = 'mon'
    Tuesday = 'tue'
    Wednesday = 'wed'
    Thursday = 'thu'
    Friday = 'fri'
    Saturday = 'sat'
    Sunday = 'sun'
fiery cosmos
tulip cairn
tulip cairn
lean glade
#

First of all, take selective screenshots with windows+shift+s

fiery cosmos
#

that seems like a test

dry ember
#

sry I had to...

spare pivot
#

im currently learning python and im trying to make a basic "command prompt" but whenever the code runs and i type lets say start it stops the program how do i make not end the program once it is executed

#

basically the program keeps running after its executed

#

how do i do that

wispy hare
spare pivot
#

i dont want that i just need it to not stop

wispy hare
#

or you can wait for the user to press Enter

input('press Enter to continue')
spare pivot
#

i need them to input so it can execute

nova plume
#

@spare pivot try an infinite loop

spare pivot
#

how do i do that?

nova plume
#

Ex : while 1: your code

spare pivot
#

i tried a while loop but i might have done it wrong

#

ill try it again

nova plume
#

Go ahead

spare pivot
nova plume
#

While True:

#

Or 1

spare pivot
#

oh so i should make a boolean variable or lets say i = 1 then while i == 1:

nova plume
#

Or while command ! = 'exit' : cuz u want to exit the program after the exit command is given right

spare pivot
#

yep

#

thx

nova plume
#

Then put the input inside the while loop

spare pivot
#

also putting the input in the while lopp doesnt work

#

nvm i fixed it

small drift
peak wave
#

What does the circled function do?

small drift
#

@peak wave it checks all numbers from 2 upto x and sees if they are divisible. if x%i is not 0, then it returns false.

#

since 0 is treated as false

peak wave
#

Is tere a reason for "return False" to be written then?

#

Oh wait

#

nevermind lol

small drift
#

lol

cyan nova
#

lets say I wanted to create a program that reads different files and the file names were all identical except for they all had a number between 1-20 how would i do that

balmy siren
#

@cyan nova you can make a use of fstrings when describing the file name.
for example : suppose, if you've files -> test1.py, test2.py, test3.py....... then you can make the string like this

i = 1
while i <= 20:
  try:
    with open(f'test{i}.py', 'r') as file:
      print(file.read())
  except Exception as err:
    print(err.args[0]) # or use args[1]
  i += 1
#

possible exception could be FileNotFoundError()

subtle hearth
#
i = 1
while i <= 20:
    with open(f'test{i}.py', 'w') as file:
        file.write('test'))
    i += 1
``` Works with write at least @balmy siren
balmy siren
#

yeah you can perform any operation read, write or whatever.. but he asked for read, so i used that

#

also, write will overwrite the previous contents of file

subtle hearth
#
test
test
test
test
2  # file 5
test
test
test
test
... etc
``` output when run with file5 deleted
#

2 is the result of print(err.args[0])

balmy siren
#

using mine code ?

subtle hearth
#

yeah

#

I generated the files and then used your code to read them after deleting the 5th file

balmy siren
#

yes, you can make a simple print statement there..

#

all the files should need to be exist in the system already

#

otherwise it will give you an exception

subtle hearth
#

Then it works right? the program finished fine after it hit the except statement

balmy siren
#

no no no, if any file doesn't exist then whatever is assigned under except statement will perform, once it is done then control goes to the next line or whatever is after try....except block i.e., i+=1

fiery cosmos
#

Dreams of those who do not learn software: 01010101 ehe heçkırım ehe
in reality:
import random
x = random.randint (1, 100)
print (x)
pc: you wrote a program from bravo python that writes between 1 and 100 numbers

primal loom
#

anyone who is familiar with searchalgorithms, linear, binary, jump, interpolation, exponential? I need some help since I have to send an assignment in a couple of hours, if you can, pls call or pm me

primal loom
#

its that ive made linear, binary, jump and interpolation search. Im trying to check time on all of them and see which one is faster by testing for hte same list, but it gives me 00.00.00 on some of them

#

sry let me send the list first

#

l = list(range(0,100000000))

#

so thats my range

agile sundial
#

you can fit that in memory?

primal loom
#

@agile sundial i got lucky

#

one more 0 and it fialed

agile sundial
#

wdym you got lucky

primal loom
#

idk man

agile sundial
#

well

primal loom
#

can you possibly hop on a call

#

much easier to explain

#

im shit at writing in english

agile sundial
#

i can't

primal loom
#

ok :/

trim fiber
#

Are you want to compare execution times?

primal loom
#

i have

#

just wanted to screenshare

#

cause i have to write a whole lot before i get my point out

#

therefor its easier on voice chat

trim fiber
#

I don't have mic 😞 drivers broke it

primal loom
#

i can try to explain it here, but if you want to, we can voicechat 😄

#

well can i screenshare then and you can type 🙂

#

takes ages for me to explain , sry

agile sky
#
DLower = datetime.strptime(DLower,'%Y-%m-%d')
Date = DLower
Print(Date)``` When I print the variable Date it also includes the time, how would I get rid of this??
pallid phoenix
#

@stable pecan really sorry to @ you, but i have a question regarding the algorithm you helped me with, the list contains bot 007 and 770, and 007 is being flagged as a duplicate due to 770 being in seen, i thought the sets look if all the values in the string match?

stable pecan
#

in that case you might want to use collections.Counter instead of set

#

though you'd have to create a hashable version --- which you could do by sorting the items

pallid phoenix
#

so using collections.Counter, somethign will only be flagged if a permutation of it has been seen?

stable pecan
#

yeah, i assumed all the items in the strings would be different

#

In [1]: from collections import Counter

In [2]: Counter("007") == Counter("070")
Out[2]: True

In [3]: Counter("007") == Counter("770")
Out[3]: False
pallid phoenix
#

so i can replace frozenset with Counter and it should be fine?

stable pecan
#

well, you have to do a little more work actually, because Counter isn't hashable

#

can you post the code as it was

pallid phoenix
#

yes sorry i should have mentioned, its explicitly to remove duplicate permutations, and mark them

#
def split_duplicates(my_list):
    seen = {}
    unique = []
    duplicates = []

    for item in my_list:
        as_set = frozenset(item)
        if as_set in seen:
            duplicates.append(seen[as_set])
        else:
            unique.append(item)
            seen[as_set] = item

    return unique, duplicates
stable pecan
#
from collections import Counter

def split_duplicates(my_list):
    seen = {}
    unique = []
    duplicates = []

    for item in my_list:
        as_multiset = tuple(sorted(Counter(item).items()))  # Transform Counter into a tuple so it's hashable
        if as_multiset in seen:
            duplicates.append(seen[as_multiset])
        else:
            unique.append(item)
            seen[as_multiset] = item

    return unique, duplicates

I think this will take care of it

pallid phoenix
#

thank you so much for your help, this time we are? sorting the items, counting the and putting them into a tuple? would that flag 321 if 213 has been seen?

stable pecan
#
In [7]: split_duplicates(["213", "321"])
Out[7]: (['213'], ['213'])
#

splits it up, and even replaces it with the original permutation

#

what Counter does is count the occurences of each letter in the string

#
In [8]: Counter("123")
Out[8]: Counter({'1': 1, '2': 1, '3': 1})
#

so two Counters are equal if the counts are equal

#
In [9]: Counter("123") == Counter("321")
Out[9]: True
pallid phoenix
#

ohhh i see, how are you so quick to solve things i mush my brain over?

stable pecan
#

maybe practice

pallid phoenix
#

once again ,thank you a ton for helping, and if you could maybe recommend where i can practice this kind of problem-solving?

stable pecan
#

codewars maybe

#

but i would also bookmark the itertools and collections pages

#

if you get familiar with these two libraries, few problems will stand in your way

pallid phoenix
#

codewars isn't a paid subscruption correct?

stable pecan
#

i don't think it is, i haven't been there in a while

#

think it's free

pallid phoenix
#

alright, thank you i'll definitely check on the documentation and look at codewars

stable pecan
#

that's a good way to get familiar with some python

pallid phoenix
#

ooh thank you, ill watch it too^^

stable pecan
#

that talk is a bit old (print statement doesn't work like that anymore!), but still has useful stuff in it

pallid phoenix
#

ah is it back in python2? but that's fine, fortunately I've mastered the print() function , thank you a ton

stable pecan
#

np

finite pond
#

hey, I have a quick question. I'm trying to implement a rotate-lines-along-axis function for the project I'm working on. I made a function that takes a 3 x n input array of points, and returns the rotated points the same way

However, I'm starting off with the points belonging to my Line class (supposed to represent Fibres), which has a start and end point and ideally I need to rotate up to a 1000 or more lines at a time. I can more or less nicely list comprehend and reshape the points into the input array, but what would be a nice way to funnel the rotated points back into the class instances?

nova plume
#

Hi guys, so i want to cast this string for example '2.56400' to float and when i print it iget this result 2.564 it's correct i know but instead i want this result 2.56400, how i can keep zeros, any ideas

brave oak
#

floats don't have the concept of trailing zeroes

#

or you could use the Decimal class

#

or you could format it when you want to print it

#

!e print(f'{1.23:.4f}')

halcyon plankBOT
#

@brave oak :white_check_mark: Your eval job has completed with return code 0.

1.2300
nova plume
#

@brave oak i ve tried that but i want to return float type not string type, thnx anyway

pallid phoenix
#

Hello, i have an open help channel (help-lithium) in case someone here has some time to spare

deep phoenix
#

ops wrong channel

pallid phoenix
#

@deep phoenix did you mean stuff things like !@#$%^&*,.'? ?

deep phoenix
#

yup

pallid phoenix
#

well if word[0] isnt a letter, maybe add word[0] instead of its translation

deep phoenix
#

@pallid phoenix

#
def pig(word):
  ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #no space
  VOWELS = "AEIOU"
  INTERPUNCTION = ",.!?:"
  i = len(word)
  
  if word[0] in VOWELS and word[i] in INTERPUNCTION:      # Easy case. "IS" becomes "ISYAY" INTERPUNCTIE
    return word[0:i-1] +'ay' + word[i]  
  
  elif word[1] in VOWELS and word[1:i] in INTERPUNCTION:    # Consonant followed by vowel. "BIN" becomes "INBAY" INTERPUNCTIE
    return word[1:i-1] + word[0] + "ay" + word[i]
  
  elif word[0:i] in INTERPUNCTION:
    return word[2:i-1] + word[0:2] + "ay" + word[i] #"STOP" becomes "OPSTAY" INTERPUNCTIE
  
  elif word[0] in VOWELS:      # Easy case. "IS" becomes "ISYAY"
    return word +'ay'
  elif word[1] in VOWELS:    # Consonant followed by vowel. "BIN" becomes "INBAY"
    return word[1:i] + word[0] + "AY"
  else:
    return word[2:i] + word[0:2] + "ay" #"STOP" becomes "OPSTAY"
#

this doesn't work

#

the first 3 if statements don't get used at all eventhough it should

pallid phoenix
#

what word did you test it with?

deep phoenix
#

BIN.

#

comes out with "IN.BAY"

pallid phoenix
#

and it should be?

deep phoenix
#

INBAY.

agile sundial
#

you could just take all the punctuation out of the string and add them back later

deep phoenix
#

"just"

agile sundial
#

well, yeah

pallid phoenix
#

why not create a new word instead of editing the old one? so do neword.append(word+ay) neword.append(word[i]) note, only testing the last index of the word wont account for something like I'm

deep phoenix
#

It doesn't need to be so sophisticated

#

but why doens't this work?

pallid phoenix
#

well its quite simple in my opinion, if the ltter meets condition-translate it and add it, if its a special character, add it without translation?

deep phoenix
#

oh I see

#

I'll try something else

deep phoenix
#

@pallid phoenix

pallid phoenix
#

correct seems to be larger than the index range

deep phoenix
#

I don't understand

pallid phoenix
#

when you look for the index of word, you use word[correct], and correct is either too small or too big, and index equaling correct does not exist(sorry i'm bad at explaining)

placid lantern
#

So I have a dictionary that has multiple different keys named the same thing. I have the value of one of them and I need to get when that variable occurs so that I can grab other repeated variables that occur around it.

#

Like there is a owner and I have the owners name but there are multiple different owners stored in the same dictionary.

#

and then where the owner I need is stated, there are also other bits of information like name for example, which there is also multiple of.

#

so then say I wanted to get the name for a specific owner, how would I do that?

raw cobalt
#

where others can copy and paste

#

in discord

wispy hare
calm spade
#

So i am making this thing where theres 2 tiles and a player the path tile (🟫) and the off-map tile (⬛) and the player (🤠) so basically i want to randomly generate a path for the player.

Which is better?

  • Locating the last path tile and finding the possible options for a new path tile to be placed.
  • Randomly generating the whole path.
halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied mute to @calm spade until 2020-12-20 08:59 (9 minutes and 58 seconds) (reason: discord_emojis rule: sent 72 emojis in 10s).

austere sparrow
#

!unmute 470866478720090114

halcyon plankBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @calm spade.

calm spade
#

Sry i didnt know

austere sparrow
#

An image would be better, i guess 🙂

calm spade
#

Thanks sm

calm spade
quasi oracle
#

What do you consider the last path tile here?

calm spade
#

so the player is fixed position

#

I start from it

#

And go on

quasi oracle
#

Right, but the layout ends in two spots in your example

calm spade
#

So i ment like i place tile by tile

#

So player then the tile under it then from there u'd have 3 possibile options

#

The next tile

#

The previous tile

#

And the under tile

#

In my example its the under one

#

Down*

quasi oracle
#

Next as in right?

calm spade
#

repeat

#

Like that

#

And repeat until the amount of tiles i choose has been placed

#

It works on my head but idk how to implement it 😂

quasi oracle
#

So you want to just randomly make decisions until you visited enough unique tiles?

calm spade
#

Exactly

subtle hearth
#

You need to set some rules, like don't immediately go towards the wall, don't go right 3 times etc

calm spade
#

Well after i figure out how to actually place a tile then those can be done

subtle hearth
#

Use random to choose a random shift, left right or forward. The shift can re represented by a tuple containing a value that each index should be shifted by.

#

You are using a nested lsit to represent the board?

quasi oracle
calm spade
#

Okay but... How do i make it ? 😂

quasi oracle
#

By last I guess you mean the latest tile you visited

calm spade
wispy hare
calm spade
#

yeah i'll be specifying that

#

so if the layout is 6x7 lets say the number is 12 tiles

subtle hearth
calm spade
#

Won't it be easier by integers?

wispy hare
#

so the player starts at a certain cell (i, j) then randomly traverses a path of k tiles right?

subtle hearth
#

A nested list lets you think about the space in 2d easier

#

for me anyways

calm spade
#

Then i'd have three options (left, right, down)

#

And so on until i placed the number of tiles i need

calm spade
#

That'd be easier to work with right?

subtle hearth
#

Oh yeah use whatever value you want in the list

calm spade
#

Oh ok i thought you wanted me to make them into strings

subtle hearth
#
path = 1
[['0', '0', '0'],
['0', '0', '0'],
['0', '0', '0']]
``` ```py
board[0][0] = path
``` ```py
[['1', '0', '0'],
['0', '0', '0'],
['0', '0', '0']]
calm spade
#

aha i was doing it like

[[0,0,0],
[0,0,0],
[0,0,0]]
subtle hearth
#

It makes it easier to read :p

calm spade
#

Ye kinda

subtle hearth
#

so how how about...

calm spade
#

I know how to add / remove and loop over the nested list and stuff

#

But what i dont know is

#

How do i track the last path

#

And check the posibile decisions

#

And add the next tile

#

And repeat that

subtle hearth
#
tile = 1
start = (0, 0)
up = (-1, 0)
down = (1, 0)
left = (0, -1)
right = (0, 1)

r, c = start
board[r][c] = tile
``` then you can manipulate the r and c
#

That is part of it maybe

calm spade
#

But i'd have to create the entire layput with this

subtle hearth
#

But the decision making is gonna be a challenge

calm spade
#

I need that layout to be defined before but change its values

#

Aka add a path to it

subtle hearth
#

You can use the random module to randomly shift the position around

calm spade
#

Yeah i know

subtle hearth
#

check if the box has a tile path

#

I think a simple solution would be to just try random spaces like that

wispy hare
#

man I just finished making the algorithm

#

but I noticed something

subtle hearth
#

You could also check to see if placing a tile would cause that tile to touch another, which you could then avoid by choising a differnt tile

calm spade
wispy hare
#

when you visualize the final state of the gird, the path isn't clear

subtle hearth
#

hahaha

calm spade
#
layout = [[0,2,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]]
for row in range(0,len(layout)):
    for col in range(0,len(layout[row])):
        if row == 0: pass
``` this is as far as i can go
#

...

wispy hare
calm spade
#

wow...

#

can you help me make it?

wispy hare
#

I think that it's better to put the number of the tile in the path

#

like 1 2 3 4...

subtle hearth
# wispy hare

you need to make sure the next move doesn't touch a path tile