#algos-and-data-structs

1 messages ยท Page 141 of 1

jolly mortar
#

assuming the list isnt sorted of course

raven kraken
#

Okay got it thank you so much for your time.

glossy breach
#

I think maintaining the 10 max numbers and updating it as you iterate through the array might be faster

#

so O(n * 10) is faster than O(n * logn) ig

fiery cosmos
#

Isn't heapify of o(nlogn) which comes from adding every element having o(logn)

jolly mortar
#

i forget exactly how but heapify can be implemented in O(n)

fiery cosmos
#

Not really aware. Refs would be appreciated.

jolly mortar
glossy breach
#

I didn't know heaps could be initialized in O(n) ๐Ÿ˜… thanks for the information

jolly mortar
fiery cosmos
#

Wow it's a long answer. Thanks for the ref. I'll read it.

fiery cosmos
#

Hey guys, I have some problems with a leapcode problem I'm working on. I am not very experienced with OOP (simply because I chose not to learn it). It is a BT (data structure) problem and I have issues with some specifics. First of all, in the function isCousins(), it introduces a new type, TreeNode(). As a relative beginner to OOP, I do not understand how to convert the TreeNode object to a list, or to interpret it as a list as part of my problem. I would really appreciate help ๐Ÿ™‚

glossy breach
#

from what i can see here TreeNode represents a node on your binary tree, and node.left, node.right are two another TreeNodes representing its children

fiery cosmos
fiery cosmos
#

I dont understand how to obtain a node, inter a node or replace a node.

#

Wait forget my definition of cousin btw. They have defined it differently.

fiery cosmos
#

Also this is a bt and not bst. So yeah. Let's see. You know what is bt right?

fiery cosmos
#

It was in an assessment

#

But it wasnt an important assessment or exam or anything

agile sundial
#

quick select also works, not sure if it'd be faster

jolly mortar
#

hm

#
  • If you only seek the top 5 elements out of an array, then the binary heap is likely to beat QuickSelect, irrespective of how many elements I have. The binary heap will fit in one or two cache lines, and the log k factor will be small.
  • If I keep k at a sizeable 128, but I increase substantially the size of the array, then QuickSelect will start to win big.
  • However, if I keep increasing the array size, the benefits of QuickSelect might start to fade. Indeed, QuickSelect will start to operate in RAM whereas the binary heap will remain in CPU cache. QuickSelect will become increasingly limited by potentially expensive cache misses.
  • QuickSelect still has the worst case quadratic-time scenario that could be triggered by really bad input data. The binary heap is more likely to provide consistent speed.
    (https://lemire.me/blog/2017/06/14/quickselect-versus-binary-heap-for-top-k-queries/)
agile sundial
#

ยฏ_(ใƒ„)_/ยฏ easiest to just profile ig

jolly mortar
#

that would require implementing both ๐Ÿ˜”

agile sundial
#

does numpy have a heap thing

#

I know it has np.partition

#

wait that uses introselect

#

that's pretty much quickselect

ornate crane
#

uh hi, so essentially for bfs i should use stack right? and dfs, i should be using recursion, i believe?

jolly mortar
#

bfs needs a queue because the vertex you pushed in the earliest is the one you visit next

#

you can implement dfs via recursion yeah

#

and also via stacks

agile sundial
ornate crane
#

ah right

austere sparrow
#

(at least conceptually)

#

in some languages, recursion does get nice optimizations

agile sundial
#

maybe I should add a macro to add "(in python)" ๐Ÿ˜”

rough anvil
#

Any advice for learning algorithms? Im currently reading "Dive Into Algorithms" right now

dapper sapphire
#

Is there a built in function on method, where we can do a comparison that would return diffs of two strings?

Example:
string1 = "This is a test to see how does it work"
string2 = "This is a testofsorts to see how does it work"

diff1, diff2 = some_method(string1, string2)
diff1 >> test
diff2 >> testofsorts

#

I can see some complexity involved, if one string is longer than the other string, overlapping diffs might also be an issue.
So I didnt want to build it up from scratch if something like this already exists.

halcyon plankBOT
#

Source code: Lib/difflib.py

This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce information about file differences in various formats, including HTML and context and unified diffs. For comparing directories and files, see also, the filecmp module.

vocal gorge
#

the functions there work on lists of strings. You seem to want diffs of entire words, so split your string into words and use that as the input.

dapper sapphire
#

oh sweet!! I'll look at difflib. Thank you!!

balmy oak
#
def search(start_node: Node) -> Iterable[Node]:
    structure = DataStructureOfYourChoice()
    structure.add(start_node)
    
    while structure:
        node = structure.get()
        yield node
        
        for edge in node.edges:
            structure.add(edge)
fiery cosmos
#

just started programming today and confused why this script isnt working

#

Name_Getter = input("What's your name :\n")
Lgth_Getter = (len(Name_Getter))
a = "there are "
b = + str(Lgth_Getter)
c = + "in your name"
d = a + b + c
print(d)

vocal gorge
#

The unary + operator has no meaning on strings, so + str(Lgth_Getter) fails

dry cliff
#

Is there any way to ask for input but not validate the input? I want to make a bot, just for fun, that asks what you want on your burger and asks for input but doesnt actually value what the input is, he just has to want any input. I can send the code if necessary

fiery cosmos
#

so how to fix?

vocal gorge
#

Don't try to use unary + on strings. I don't really see what you mean by trying it, here.

fiery cosmos
#

this whole time i thought they were needed to show variables with print

balmy oak
#

๐Ÿ˜…

#

No, you can print anything using print

fiery cosmos
#

worked when i removed the +

dry cliff
#

So this is my code, don't wonder, the text is german. After "Welches Fleisch?" I dont want the code to value any specific input, just any input. How do I do that?

balmy oak
#

I dont want the code to value any specific input, just any input. - What do you mean?

dry cliff
#

I dont want any specific input, I just want the program to continue after it got input, no matter what it said

balmy oak
#

Just do nothing really

#

There's no need for any if checks

dry cliff
#

But then it wouldnt wait for input right

balmy oak
#

Yep, it would

#

Ah, you want to continue after any keypress maybe?

dry cliff
#

I want it to only continue after it got any input. If it didnt care about input it would just continie

#

Yess

#

Well

#

Kinda

#

Normally, I would say if Antwort == "word":

#

But I want the input, in this case "word" to not matter so whatever I send him he continues

balmy oak
#

You want to check if input is not empty? ๐Ÿ˜…
Just try to explain what kind of input you want to get

dry cliff
#

So the program asks me what kind of meat I want on the burger ("Welches Fleisch") And then asks for input. I give him any input, even if it makes no sense at all. The program only checks if it got input, doesnt matter what the input said and then continues with the code

#

Its pretty hard to explain further but Im trying my best

balmy oak
#

e.g. "" or " "

dry cliff
#

What do you mean?

balmy oak
#

I give him any input, even if it makes no sense at all. - program should accepts empty strings too?

dry cliff
#

Nope, it has to be something

balmy oak
#

Just check for it's truthiness:

value = input("Input something: ")
value = value.strip()
if value:
    print(f"Got value! - {value}")

All strings with length greater than 0 are truthy

#

You might want to use str.strip to strip any whitespace characters from your string

dry cliff
#

I probably should've said this early, but I'm pretty new to coding and especially python so I have never used strip and don't know how it works

balmy oak
#

No worries!

dry cliff
balmy oak
#

You could just omit using strip, are you familiar with strings?

dry cliff
#

If strings are representing your input, then yes

#

Thats what I believe it is

balmy oak
#

Strings are just sequence of characters, they can represent any textual data

dry cliff
#

Makes sense

#

Wait

dry cliff
#

Could I program it so it continues after I press enter

#

So I can type whatever I want and after I press enter it continues

#

So I'm completely avoiding the input value in form of text and just concentrating on if I pressed enter or not, no matter what I was typing

#

I think I'll just scrap that and write a lot of code featuring every possible outcome

#

That'll be fun

#

: |

balmy oak
dry cliff
#

How

#

Well, I did it now with if or

#

So no ignoring the value

#

Just multiple answers

#

Not what I wanted exactly but its fine

#

Thanks tho!

fiery cosmos
#

how do i fix it?

balmy oak
#

Your indentation is off

fiery cosmos
#

i started python today

#

idk what any of those means

#

what about as words

#

like

#

zero

#

didnt work

balmy oak
#

There shouldn't be any spaces before variable names

fiery cosmos
#

worked thanks!

#

just got another error

#

so how would u go about it if u were to make a script that separates the number and adds it

#

example

#

36

#

3+6

#

=9

#

what does it mean?

#

srry for wasting your time!

jade juniper
#

Does anybody know if this sorting algorithm has a name? Just made it up, trying to figure out if it is something new or not.

#
def weirdsort(li):
    if not li:
        return []
    list_of_sorted_lists = [[li[0]]]
    for i in li[1:]:
        for sorted_list in list_of_sorted_lists:
            if sorted_list[-1] <= i:
                sorted_list.append(i)
                break
            if sorted_list[0] >= i:
                sorted_list.insert(0, i)
                break
        else:
            list_of_sorted_lists.append([i])

    combined_sorted_list = []
    while any(list_of_sorted_lists):
        # this could be made a lot more efficient in a lower level language
        combined_sorted_list.append(min(list_of_sorted_lists, key=(lambda i: i[0])).pop(0))
        list_of_sorted_lists = [li for li in list_of_sorted_lists if li]
    return combined_sorted_list
#

essentially you loop through the list a single time, turning it into a few sorted sub-lists

#

and then you merge the sub-lists by finding the smallest value over and over and re-building the list

#

I know it's not better than quicksort or any of the accepted sorting algorithms but I think it's kinda neat

jade juniper
#

Did some sample tests and it uses 101058ish one-to-one number comparisons to sort a random 10000 element list
insertsort took 20x as long and used 23683794 one-to-one number comparisons (235x as many)

#

obviously there will be some variations and I am making my algorithms teacher very sad by measuring complexity like this but

#

I don't think insertsort is a good comparison

#

If there aren't any existing algorithms that are too similar I'm ok with that, have been wanting to come up with my own algorithm since I started CS

#

even if it's not very good :-)

lavish plover
#

hey guys is this bubble sort?

#
def bubble_sort(array:list):
    sorted = False
    iterations = 0
    while not sorted:
        iterations = iterations + 1
        for i in range(0,len(array)-1):
            # Sort the list
            if array[i] > array[i+1]:
                temp = array[i]
                array[i] = array[i+1]
                array [i+1] = temp
            sorted = True

        # Check to see if list is sorted
        for i in range(0,len(array)-1):
            if array[i] > array[i+1]:
                sorted = False
                break
    print('\n',iterations,'iterations')
    return array

# [1,9,3,4,2,1]

if __name__ == '__main__':
    data = [9,3,4,2,1,3,5,10,-1,23,120,1,-3,2]
    a = bubble_sort(data)
    print(a)
#

i wrote myself without looking at the book im reading. The books shows a different method

ornate crane
#

but i think yeah it is bubble sort, even though id prefer two for loops (its shorter code)


def bubble_sort(elements):
  iterations = 0
  for i in range(len(elements)-1):
      iteration += 1
      swapped = False
      for j in range(len(elements)-1-i):
        if elements[j] > elements[j+1]:
          elements[j], elements[j+1] = elements[j+1], elements[j]
          swapped = True
      if not swapped:
        break
  print(iterations)
fervent bay
#

Can u suggest a good resource for learning das?

#

Dsa

tall fable
#

Hey, I need some help, I had an assignment writing an algorithm with O(n) complexity and i can't decide if I done it right, can I send the code here?

tall fable
#

I'm supposed to go through an array P and build array S such that s = { k | k <= index and P[j] <= P[index] such that j = i - k +1,..., i }

#

Is that good ?

#

and they advised to use stack to make it O(n)

magic merlin
#

hi community, can someone lead me into the right direction: i have a dataset with duplicate values, so at the moment I use df.groupby.sum() to deal with the issue. The problem is that some columns require other operatons than sum (in my case I would also need to average values, not only add them) and I have to drop them altogether. is there a way to perform sum() on some columns and average the other columns with df.groupby? Thank you!

raven kraken
jade juniper
#

this seems vaguely related, I bet you could use the same technique

#

method #4 does it in O(N)

#

although method #5 could be more similar to what they want you to do, since they don't care about extra space complexity

tulip crest
#

Hi, I need to do a test with the calculation of points at the end. The test itself has already been done, but I do not know how to calculate. Now throw the code.

halcyon plankBOT
#

Hey @tulip crest!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

โ€ข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

โ€ข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

tulip crest
#

Do not pay attention to the fact that some elements are in the Ukrainian language. Correct answers to 3 questions 1.a 2.ะฑ 3.ะฒ
Answers on the Russian layout

#

I hope for help, if you said something unclear, please contact.

cunning valve
#

Hi! I am a newcomer to Python. I am creating an app working with data got from remote CRM through API requests. The data returns in JSON format. I convert that into Python structures with json library, in particular it results in a list of dictionaries (a dictionary per each item). My question is what is the optimal way (timewise) to filter the data? The app uses a lot of filters which should update the outcome result constantly. Is pandas good for such a task? Any other tools? working with iteration through the list and dicts with standard Python tools seems to be a bit slow when it comes to updating the data array after any change of any filter

balmy oak
#

You could send a sample of data and what kind of filters you want to apply to it so people can help

worn stream
#

are the pinned posts here updated? or are there better sources for learning algorithms and data structures?

austere sparrow
#

I strongly doubt that something fundamental about algorithms and data structures has changed over the last 9 months.

#

Although nowadays, you never know.

dapper sapphire
#
def test_this(param1:str, param2: str, param3:str):
    print(param1)
    print(param2)
    print(param3)

param_1 = "This is param 1"
param_2 = "This is param 2"
param_3 = "This is param 3"

params = {"param1": param_1, "param2": param_2, "param3": param_3}
test_this(**params)

Instead of doing the above by using **params to pass in parameters as a dictionary. We can also do the below to pass in the paramters via a tuple??

def test_this(param1:str, param2: str, param3:str):
    print(param1)
    print(param2)
    print(param3)

param_1 = "This is param 1"
param_2 = "This is param 2"
param_3 = "This is param 3"

params = (param_1, param_2, param_3)
test_this(*params)
#

!e

def test_this(param1:str, param2: str, param3:str):
    print(param1)
    print(param2)
    print(param3)

param_1 = "This is param 1"
param_2 = "This is param 2"
param_3 = "This is param 3"

params = (param_1, param_2, param_3)
test_this(*params)
halcyon plankBOT
#

@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.

001 | This is param 1
002 | This is param 2
003 | This is param 3
austere sparrow
#

yes, any iterable, in fact

dapper sapphire
#

What do you mean by any iterable?

austere sparrow
#

A list, a string, a dict etc.

dapper sapphire
#

oh ok!!

austere sparrow
dapper sapphire
#

This entire time I had been creating a dictionary to pass in multiple parameters lol. ok this is good!

austere sparrow
#

well... very often named parameters are better

#

What does this do?

intersect(x + dx, y + dy, ax, ay + d_ay**2, False, False, True)
dapper sapphire
#

Yeah, I agree, but the paramters that I am passing in, I get their values few lines earlier.

rich pelican
#

i need to create an algo, looking for inspiration.. links, raw ideas plz.
say I have 5 jars, each jar has a limit of items..
some jars are full, some are not.
each item in the jars has ratings..
rating 1 chocolate type, milk, dark, white
rating 2 almonds, peanuts, cashews
ratings 3 rasberry, cream, coffee
and I would need to search all the jars and distribute the candy evenly.

idle pier
#

Hello folks, hope everyone is having a great start to 2022.
And I'm back to DS and Algo's ๐ŸคŸ
I'm currently doing 58. Merge Intervals on Leetcode

def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        if not intervals: return
        intervals.sort()
        res = []
        
        for i in intervals:
            if not res or res[-1][1] < i[0]:
                res.append(i)
            else:
                res[-1][1] = max(res[-1][1],i[1])
        return res```
This is both `O(n)` for runtime and spacetime correct?
agile sundial
#

no, intervals.sort will be at least n log n

idle pier
agile sundial
#

sounds about right

fiery cosmos
#

Age_Current = input("how old are you (in years):\n")
Age_Old = input("which age do you wanna live to (in years):\n")

Age_months = Age_Current * 12
Age_weeks = Age_Current * 52
Age_days = Age_Current * 365
Age_hours = Age_Current * 365 * 24

Age_Old_years = Age_Old - Age_Current
Age_Old_months = Age_Old *12 - Age_months
Age_Old_weeks = Age_Old * 52 - Age_weeks
Age_Old_days = Age_Old * 365 - Age_days
Age_Old_hours = Age_Old * 365 * 24 - Age_hours

print(f"you have used ",{Age_months},"months of your life or,\n"
"you have used ",{Age_weeks},"weeks of your life or,\n"
"you have used ", {Age_days},"days of your life or,\n"
"you have used ", {Age_hours},"hours of your life.\n")

print(f"you have ",{Age_Old_years},"years of your life or,\n"
"you have ", {Age_Old_months},"months of your life left or,\n"
"you have ", {Age_Old_weeks},"weeks of your life left or,\n"
"you have ", {Age_Old_days},"days of your life left or,\n"
"you have ", {Age_Old_hours},"hours of your life.\n")

#

how do i fix this?

#

this is my second day coding so use English

gloomy wigeon
#

!e
Age_Current = input("how old are you (in years):\n")
Age_Old = input("which age do you wanna live to (in years):\n")

Age_months = Age_Current * 12
Age_weeks = Age_Current * 52
Age_days = Age_Current * 365
Age_hours = Age_Current * 365 * 24

Age_Old_years = Age_Old - Age_Current
Age_Old_months = Age_Old *12 - Age_months
Age_Old_weeks = Age_Old * 52 - Age_weeks
Age_Old_days = Age_Old * 365 - Age_days
Age_Old_hours = Age_Old * 365 * 24 - Age_hours

print(f"you have used ",{Age_months},"months of your life or,\n"
"you have used ",{Age_weeks},"weeks of your life or,\n"
"you have used ", {Age_days},"days of your life or,\n"
"you have used ", {Age_hours},"hours of your life.\n")

print(f"you have ",{Age_Old_years},"years of your life or,\n"
"you have ", {Age_Old_months},"months of your life left or,\n"
"you have ", {Age_Old_weeks},"weeks of your life left or,\n"
"you have ", {Age_Old_days},"days of your life left or,\n"
"you have ", {Age_Old_hours},"hours of your life.\n")

halcyon plankBOT
#

@gloomy wigeon :x: Your eval job has completed with return code 1.

001 | how old are you (in years):
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | EOFError: EOF when reading a line
fiery cosmos
#

!e

halcyon plankBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*

fiery cosmos
#

Age_Current = input("how old are you (in years):\n")
Age_Old = input("which age do you wanna live to (in years):\n")

Age_years = Age_Current * 1
Age_months = Age_Current * 12
Age_weeks = Age_Current * 52
Age_days = Age_Current * 365
Age_hours = Age_Current * 365 * 24

Age_Old_years = Age_Old - Age_years
Age_Old_months = Age_Old *12 - Age_months
Age_Old_weeks = Age_Old * 52 - Age_weeks
Age_Old_days = Age_Old * 365 - Age_days
Age_Old_hours = Age_Old * 365 * 24 - Age_hours

print(f"you have used ",{Age_months},"months of your life or,\n"
"you have used ",{Age_weeks},"weeks of your life or,\n"
"you have used ", {Age_days},"days of your life or,\n"
"you have used ", {Age_hours},"hours of your life.\n")

print(f"you have ",{Age_Old_years},"years of your life or,\n"
"you have ", {Age_Old_months},"months of your life left or,\n"
"you have ", {Age_Old_weeks},"weeks of your life left or,\n"
"you have ", {Age_Old_days},"days of your life left or,\n"
"you have ", {Age_Old_hours},"hours of your life.\n")

v

#

!e Age_Current = input("how old are you (in years):\n")
Age_Old = input("which age do you wanna live to (in years):\n")

Age_years = Age_Current * 1
Age_months = Age_Current * 12
Age_weeks = Age_Current * 52
Age_days = Age_Current * 365
Age_hours = Age_Current * 365 * 24

Age_Old_years = Age_Old - Age_years
Age_Old_months = Age_Old *12 - Age_months
Age_Old_weeks = Age_Old * 52 - Age_weeks
Age_Old_days = Age_Old * 365 - Age_days
Age_Old_hours = Age_Old * 365 * 24 - Age_hours

print(f"you have used ",{Age_months},"months of your life or,\n"
"you have used ",{Age_weeks},"weeks of your life or,\n"
"you have used ", {Age_days},"days of your life or,\n"
"you have used ", {Age_hours},"hours of your life.\n")

print(f"you have ",{Age_Old_years},"years of your life or,\n"
"you have ", {Age_Old_months},"months of your life left or,\n"
"you have ", {Age_Old_weeks},"weeks of your life left or,\n"
"you have ", {Age_Old_days},"days of your life left or,\n"
"you have ", {Age_Old_hours},"hours of your life.\n")

halcyon plankBOT
#

@fiery cosmos :x: Your eval job has completed with return code 1.

001 | how old are you (in years):
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | EOFError: EOF when reading a line
fiery cosmos
#

so how do we fix it

#

Age_Current = input("how old are you (in years):\n")
Age_Old = input("which age do you wanna live to (in years):\n")

Age_years = Age_Current + str(0)
Age_months = Age_Current * 12
Age_weeks = Age_Current * 52
Age_days = Age_Current * 365
Age_hours = Age_Current * 365 * 24

Age_Old_years = Age_Old - Age_years
Age_Old_months = Age_Old *12 - Age_months
Age_Old_weeks = Age_Old * 52 - Age_weeks
Age_Old_days = Age_Old * 365 - Age_days
Age_Old_hours = Age_Old * 365 * 24 - Age_hours

print(f"you have used ",{Age_years},"years of your life or,\n"
"you have used ",{Age_months},"months of your life or,\n"
"you have used ",{Age_weeks},"weeks of your life or,\n"
"you have used ", {Age_days},"days of your life or,\n"
"you have used ", {Age_hours},"hours of your life.\n")

print(f"you have ",{Age_Old_years},"years of your life or,\n"
"you have ", {Age_Old_months},"months of your life left or,\n"
"you have ", {Age_Old_weeks},"weeks of your life left or,\n"
"you have ", {Age_Old_days},"days of your life left or,\n"
"you have ", {Age_Old_hours},"hours of your life.\n")

gloomy wigeon
fiery cosmos
#

where?

gloomy wigeon
fiery cosmos
#

for old or current or both?

#

like Age_old

gloomy wigeon
#

!e
Age_Current = input("how old are you (in years):\n")
Age_Old = input("which age do you wanna live to (in years):\n")
for period, coef in zip((months, weeks, days, hours), (12, 52, 365, 365 * 24)):
print(f'you have used {Age_Current * coef } {period} of your life')

halcyon plankBOT
#

@gloomy wigeon :x: Your eval job has completed with return code 1.

001 | how old are you (in years):
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | EOFError: EOF when reading a line
fiery cosmos
#

gtg

#

dm me the code

gloomy wigeon
#

and you have to use int() to get an int from a string. like int(input()) or later int(Age)

#

!e
Age_Current = int(input("how old are you (in years):\n"))
Age_Old = int(input("which age do you wanna live to (in years):\n"))
for period, coef in zip(('months', 'weeks', 'days', 'hours'), (12, 52, 365, 365 * 24)):
print(f'you have used {Age_Current * coef } {period} of your life')

halcyon plankBOT
#

@gloomy wigeon :x: Your eval job has completed with return code 1.

001 | how old are you (in years):
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | EOFError: EOF when reading a line
gloomy wigeon
#

!e
Age_Current = int(input("how old are you (in years):\n"))
Age_Old = int(input("which age do you wanna live to (in years):\n"))
for period, coef in zip(('months', 'weeks', 'days', 'hours'), (12, 52, 365, 365 * 24)):
print(f'you have used {Age_Current * coef } {period} of your life')

halcyon plankBOT
#

@gloomy wigeon :x: Your eval job has completed with return code 1.

001 | how old are you (in years):
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | EOFError: EOF when reading a line
gloomy wigeon
#

weird. it works in pycharm

dapper mountain
#
N = int(input())
candie = 0 
for i in range(1, int(N**0.5) + 1):
    if N % i == 0 and i % 2 == N // i % 2:
        candie += 1
print(candie)

currently only printing how many candie packet combination are possible(so output is 3 now) i want to print that packets like for 45, 3 combination are possible so, output will be {5,7,9,11,13}, {13,15,17}, {45}. how can i do that?

cunning valve
# balmy oak Afaik pandas is used for data analysis, it wouldn't be correct to use it to proc...

[
{
"id": "15880",
"code": "662621341",
"brandId": "119",
"modelYearCode": "2021",
"modelCode": "234",
"bodyCode": "base",
"complectationCode": "R5",
"packageCode": "8D234R5",
"statusCode": "RD",
"colorCode": "71700",
"trimCode": "RC0000",
"vin": "LVYPS08ADMP099980",
"mpv": "23408R50D173",
"keyNumber": null,
"inStock": "1",
"sold": "1",
"deleted": "0",
"readyForReleaseDate": "2021-12-02 16:47:34",
โ€ฆ
},
{
"id": "15880",
"code": "662621341",
"brandId": "119",
"modelYearCode": "2021",
"modelCode": "234",
"bodyCode": "base",
"complectationCode": "R5",
"packageCode": "8D234R5",
"statusCode": "RD",
"colorCode": "71700",
"trimCode": "RC0000",
"vin": "LVYPS08ADMP099980",
"mpv": "23408R50D173",
"keyNumber": null,
"inStock": "1",
"sold": "1",
"deleted": "0",
"readyForReleaseDate": "2021-12-02 16:47:34",
โ€ฆ
},
โ€ฆ
] It's a list of cars. I need to be able to apply filters on engines, models, colors, ect. And it is need to be possible to apply them in combination at the same time

gloomy wigeon
cunning valve
#

The question is what tool to use. I am not sure if pandas is a good choice for a mobile app

gloomy wigeon
cunning valve
#

kivymd

gloomy wigeon
cunning valve
#

it's not the way of display I need

buoyant falcon
#

What is the best way given a unique ID input as a Constructor to identify whether or not an object with that ID already exists and if so to access that object instance? I have my own method of doing this currently but it does not seem as clean or efficient as I suspect is possible with a truly pythonic solution. Any ideas?

For reference, my current solution is to create a dictionary with the ID as the key and the object itself as the value, it grabs the object from the ID when a request is made but requires a bunch of conditionals and the method itself is less cohesive then I would like. Is there a better solution or am I stuck with this sort of dictionary storage pattern?

junior laurel
#

What's the issues with the current method?

restive python
#

I have hundreds of waypoints (x,y), how could I sort them to get the most efficient route ?

agile sundial
#

through all of them?

restive python
#

yes through all of them, Ive read about Dijkstras algorithm, but Ive only found it with one unit X (e.g. meters), so to speak , whereas my coords are X,Y(Latitude,Longitude)

agile sundial
#

look up the traveling salesman problem, you should find resources that can help

#

you could use a premade solver

restive python
#

whats a 'premade solver' ?

#

I guess a better way to say this is , that most samples only use vertices

agile sundial
restive python
#

this leads to the question how to create a graph for this purpose , guess a simple line equation to calc the distance should be more than enough

#

and not have the lines crossing over

idle pier
#

any good resources you folks recommend for bit manipulation?

fiery cosmos
#

I dont know how to normalize, calculate variance, or run algos on my data

#

because i do not understand my data, and i need help to understand it

#

does anyone here work with audio processing?

uncut egret
#

hi.

#

im new to python programming, and i was wondering if there is anyone who can help me with a problem

bitter wigeon
#

If your application involves noise reduction read about filters and convolution topics..

barren oracle
#

Any good resources for learning two pointer technique?

fiery cosmos
#

these books wont help me

#

neither will filters

#

i am not trying to design a filter

#

I want to talk to someone who understands my data, i do not wish to understand it myself. it is far too complicated for me, i have anxiety attacks just functioning at my own level. it is not a complex application.

storm night
bitter wigeon
#

Probably lol

bitter wigeon
tacit halo
#

Or ds

fiery cosmos
#

how would you make a sliding window of dimensions [1, 2] over a 2d array?

cinder wigeon
#

sliding window?

fiery cosmos
fiery cosmos
#

but i want a sliding window that goes over a 2d array vertical so this

#
0, 1, 2,
3, 4, 5,
6, 7, 9

i want the pairs

0, 3
3, 6
6, 1
1, 4
4, 7
7, 2
2, 5
5, 9
cinder wigeon
#

The first element of the t'th pair should be
x(t) = t // 3
y(t) = t % 3
myList[x(t)][y(t)]
and the second element, is just t+1

stable pecan
# fiery cosmos a regular sliding window goes like this a sequence 1,2,3,4 a sliding window give...
In [7]: a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In [8]: from itertools import tee, islice

In [9]: def pairwise(iterable):
   ...:     a, b = tee(iterable)
   ...:     return zip(a, islice(b, 1, None))
   ...: 

In [10]: def sliding_window_1_2(iterable):
    ...:     for a, b in pairwise(iterable):
    ...:         yield from zip(a, b)
    ...: 

In [11]: list(sliding_window_1_2(a))
Out[11]: [(1, 4), (2, 5), (3, 6), (4, 7), (5, 8), (6, 9)]
fiery cosmos
#

nope

cinder wigeon
stable pecan
#

that's a sliding window, dunno what else you need

fiery cosmos
#

this doesnt match the behavior that i described

cinder wigeon
#

dude, I told you how

stable pecan
#

well, i'm sure you have enough information to figure it out now

fiery cosmos
#

its close

cinder wigeon
#

wdym by that?

fiery cosmos
#

and ive done that

cinder wigeon
#

send screenshot of the pairs

#

I think that'd be easier for me to understand

#

I didn't try the code myself

fiery cosmos
#

2d array

1,2
3,4

i want the pair values. (these are not indexes)

1,3
3,2
2,4
cinder wigeon
#

aaaaand, what do you get?

fiery cosmos
#

what do you mean?

#

my code?

cinder wigeon
#

this doesnt go over the boundary

fiery cosmos
#

it doesnt get 3, 2

#

only 1,3 and 2,4

cinder wigeon
#

that's not right
do you make sure to increment t only by one, for each new pair?

#

yeah, show the code actually

fiery cosmos
#

wait now i think you might be right but i dont know hold on lemme think.

#

you flip the columns and rows which is correct

#

alright imma rewrite it.

#

maybe i was just thinking about it wrong.

#

i got it to work but you made it seem simple

stable pecan
#
In [23]: a = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

In [24]: def sliding_window_1_2(iterable):
    ...:     transpose = zip(*iterable)
    ...:     flat = chain.from_iterable(transpose)
    ...:     a, b = tee(flat)
    ...:     return zip(a, islice(b, 1, None))
    ...: 

In [25]: list(sliding_window_1_2(a))
Out[25]: [(0, 3), (3, 6), (6, 1), (1, 4), (4, 7), (7, 2), (2, 5), (5, 8)]
fiery cosmos
cinder wigeon
#

but glad it's working

fiery cosmos
cinder wigeon
#

ah okay

fiery cosmos
#

you swapped them

#

but i think it was becuase i was working with a larger algorithm that used this that i got confused

#

im embaressed on how simple it was

strong dust
#

Hi peoples! I'm puzzling with a data structure challenge:
I want to make a system to serialize and deserialize product codes.
e.g. ENG-PUMP-CENT-SS-DN50 turns into:

  • Dropdown 1: Engineering Items
  • Dropdown 2: Pump
  • Dropdown 3: Centrifugal Pump
  • Dropdown 4: Stainless Steel
  • Dropdown 5: Size DN50

Each dropdown has multiple choices, each choice can lead to a different dropdown. The system should go from code to full description and also the other way around. I wanted to try out some kind of graph representation. Good idea or bad idea?

cinder wigeon
#

A tree maybe?

#

Where each node has both the code and full description

#

I suppose trees are technically directed graphs too, so...

fiery cosmos
#

soemthing like

i = n // rows;
j = n % rows;
#

you swap them and use rows instead of columns.

cinder wigeon
#

You're right. The number of rows, is how elements are in a column. And, since we're scanning from the first column and down along it...

fiery cosmos
#

some person on twitch did it like this.

    int *arrLast = NULL;
    int *baseRow = arr;
    int height = size / width;
    int cWidth = width;
    while(cWidth--)
    {
        int i;
        for(i = 0; i < height; i++)
        {
            if(arrLast)
            {
                printf("%d, %d\n", *arrLast, *arr);
            }
            arrLast = arr;
            arr += width;
        }
        arr = ++baseRow;
    }

This is for a 2d indexed array though

cinder wigeon
#

Right, as in he's using stride right?

fiery cosmos
#

meaning a array with one index but you index it like a 2d array

#

probably

cinder wigeon
#

that's the kind of spaghetti code, you get for using C

fiery cosmos
#

it doesnt use division or modulus though

#

so its pretty sexy

cinder wigeon
#

yeah

#

I guess

fiery cosmos
#

but thanks for helping. im embarresed that i thought this was so complicated.

cinder wigeon
#

glad I could help

west timber
#

what are algs and data-structs that i should be familiar with for interviews

shut breach
#

check the pins

rich pelican
#

sturgling to comeup with a way to process data in 1 function, that doesnt requie an if statement to sort each classification..
classifications
priority 1, secondary
priority 1, tertiary
priority 2, secondary
priority 2, tertiary
repeated till
priority 5, septenary

fiery cosmos
#

print("Welcome to the Love Calculator")
name1 = input("What is your first and last name?\n")
name2 = input("What is their first and last name?\n")
love = {
"T",
"t",
"R",
"r",
"U",
"u",
"E",
"e",
"L",
"l",
"O",
"o",
"V",
"v"
}
Love_percentage = 0
named_1 = str(name1) #i tried turning them into str
named_2 = str(name2)
Lover = len(named_1+named_2[love])
Lovers = int(Lover)
Love_percentage = 100 / Lovers * 10
print(f"you are a %{Love_percentage} match with your crush")

#

its my 4th day coding

#

so please talk english

fiery cosmos
#

i have never gotten help from here, but i have given it quite a few times.

fiery cosmos
#

print("Welcome to the Love Calculator")
name1 = input("What is your first and last name?\n")
name2 = input("What is their first and last name?\n")
love = {
"T",
"t",
"R",
"r",
"U",
"u",
"E",
"e",
"L",
"l",
"O",
"o",
"V",
"v"
}
Love_percentage = 0
named_1 = str(name1) #i tried turning them into str
named_2 = str(name2)
Lover = len(named_1+named_2[love])
Lovers = int(Lover)
Love_percentage = 100 / Lovers * 10
print(f"you are a %{Love_percentage} match with your crush")

#

why doesn't this work?

shut breach
tiny pulsar
#

What's the fastest way to perform face recognition? I tried using face_recognition but it was too slow for my use case.

fiery cosmos
rich pelican
#

i got it sorted it out i think, just needed to create a couple of flags to sperate catagories.

naive grove
#

could anyone provide me with an implementation of the deque class in python?

glacial iris
#

Hey I have problem with implementation of bst delete function. If I try to delete a node from left side, instead of deleting that particular node, it's deleting the entire sub tree. Same with node containing at the right side, it'll delete entire subtree.

#

def delete(self, root, value):
if root is None:
print("Tree is empty")
return
elif value < root.value:
root.lnode = self.delete(root.lnode, value)
elif value > root.value:
root.rnode = self.delete(root.rnode, value)

    else:
        if root.lnode is None:
            temp = root.rnode
            root = None
            return temp
        
        if root.rnode is None:
            temp = root.lnode
            root = None
            return temp

        else:
            Node = root.rnode
            while Node.lnode:
                Node = Node.lnode
            root.value = Node.value
            root.rnode = self.delete(root.rnode, Node.value)
    return

if name == 'main':

bst1 = BST()
l = [19,2,3,65,6,9,41,45,63,58,87,89,98]
root = Node(50)
for i in l:
    bst1.insert(root,i)


bst1.postorder(root)
bst1.delete(root, 9)
print("\n")
bst1.postorder(root)

output
9 6 3 2 45 41 19 58 63 98 89 87 65 50
58 63 98 89 87 65 50 (after deletion of 9 which lies in left side of root)

#

Here's the code.

#

Any help would be amazing.

mild dove
#

if you replace the node pointer to None all the subtree will be deleted, you can to put a child in its place

signal knot
#

For this question, is it enough to use sorted() and check the equality to see if they're the same or do I need to iterate through one list and check with the other after both are sorted?

Check Permutation: Given two strings,write a method to decide if one is a permutation of the

other.

Is this good enough

def checkPermutation(s1, s2):
    return sorted(s1) == sorted(s2)
idle pier
#

Hello folks, currently doing 438. Find All Anagrams in a String on Leetcode
I was having trouble solving it, so I looked up the solution
I found this sliding window solution

def findAnagrams(self, s: str, p: str) -> List[int]:
        start = 0 
        dic_pattern = collections.Counter(p)
        dic_s = {}
        result = []
        
        for end in range(len(s)):
            if s[end] not in dic_s:
                dic_s[s[end]] = 1
            else:
                dic_s[s[end]] += 1
            
            if dic_s == dic_pattern:
                result.append(start)
                
            if (end - start +1) >= len(p): 
                if dic_s[s[start]] > 1:
                    dic_s[s[start]] -= 1
                else:
                    del dic_s[s[start]]
                start += 1
        return result    ```
I'm having trouble understanding this part
```py
if dic_s[s[start]] > 1:
  dic_s[s[start]] -= 1
else:
  del dic_s[s[start]]```
#

Is this basically checking that we don't use the same characters again and again?

vast canyon
#

Yes, it save characters as dict with count. There it minus in every step if it left 1 it will delete dict key

gentle merlin
#

use the Counter() one its easy

hushed escarp
#

Hi All,
I have probably a basic query but i cant see to figure it out.

I have a dict nested in the key of a dict.

data = { '{"request_id":5300353,"token":"value".....} : "value" }

Im trying to update "request_id" value but i cannot call it since its the key of my initial dict.

#

( next(iter(data)) ) # 'Key1'
returns the nested value.
But i cant do anything with this then.

print(list(data.keys())[0])
also gives me the nested value, but list converts it to string so again i cant do anything.
also since its outputting the key only, i cant convert back to dict (easily)
Plus its in the original data i need to make updates so ideally dont want to export a splice of the file as a variable.

wraith kayak
hushed escarp
#

I loaded a string and replaced

#

I tried c. Invert the key/value pairing. But the dict inside it is considered a string when I load it.

hushed escarp
#

Yup. B worked.

wraith kayak
#

๐ŸŽ‰

austere sparrow
wraith kayak
austere sparrow
#

I'm not sure what you mean

#

well, NamedTuple isn't really a dict - it doesn't support arbitrary keys

#

but yeah, you can use frozendict or better immutables.Map

austere sparrow
#

if you have a stringified dict as a key, you're probably doing something wrong somewhere else

wraith kayak
austere sparrow
#

well, you're stretching the definition of a dict ๐Ÿ™‚

#

actually, frozenset would be better here

#

because {"foo": 1, "bar": 2} and {"bar": 2, "foo": 1} should be equal

wraith kayak
brisk aurora
#

can I slice a numpy array by byte start and end instead of element indices?

onyx root
agile sundial
#

it's sorta like a linked list, but instead of each node having 1 child, it has any amount of children

cerulean elk
#

how can I check is a words starts with a specific letter in context of if and else

agile sundial
#

searching is a big use case, yeah

#

method

cerulean elk
#

Im using this: if string.startswith(letter): #action, will it work?

halcyon plankBOT
#

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

ho
cerulean elk
#

oaky! thank you

agile sundial
#

some databases use something called a HAMT, which is just a really fancy tree

#

i think others use Btrees

#

no, it would just loop over the list and find the max

hushed escarp
austere sparrow
#

Why do you need a dict?

halcyon plankBOT
round glacier
#

how does my hash table implementation look

#

Did I miss anything

half lotus
#

json is stricter. it may work in some cases. one common failure is that it rejects strings using single quotes, which is what Python uses in its repl of strings in dicts

#

In that specific case it does look like json would be okay

meager geyser
#

.

fiery cosmos
#

@placid geode

waxen delta
halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied mute to @patent spire until <t:1641824427:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

grave warren
#

lets say i have a list 3x3
and I want to go 1,1 -> 1,2 -> 1,3 -> 2,3 -> 3,3 -> 3,2 -> 3,1 -> 2,1
so basically cycle around 2,2 item. Any advice how to approach this?

keen hearth
#

Oh so you just want to go around the perimeter?

#

Hmm, what is a good way to do this? ๐Ÿค”

#

I guess you could have "walls" and treat it like a state machine. The state is the current position and direction. You keep moving forward, until you hit a wall, where you turn right.

#

So something like this:

slender sandal
keen hearth
#

!eval ```py
def is_wall(position):
r, c = position
return (r in (0, 4)) or (c in (0, 4))

def vadd(u, v):
return (u[0]+v[0], u[1]+v[1])

def turn_right(direction):
dr, dc = direction
return (dc, -dr)

position = (1, 1)
direction = (0, 1)
for i in range(20):
print(position, direction)
if is_wall(vadd(position, direction)):
direction = turn_right(direction)
position = vadd(position, direction)

halcyon plankBOT
#

@keen hearth :white_check_mark: Your eval job has completed with return code 0.

001 | (1, 1) (0, 1)
002 | (1, 2) (0, 1)
003 | (1, 3) (0, 1)
004 | (2, 3) (1, 0)
005 | (3, 3) (1, 0)
006 | (3, 2) (0, -1)
007 | (3, 1) (0, -1)
008 | (2, 1) (-1, 0)
009 | (1, 1) (-1, 0)
010 | (1, 2) (0, 1)
011 | (1, 3) (0, 1)
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/cugocoluwa.txt?noredirect

keen hearth
#

@grave warren This probably seems like over-kill, but this approach is general enough to be extended in various ways.

#

Yep it is. Check out the C code for it, if you know C, it's surprisingly readable.

#

It's a doubly linked list. But each node in the list is actually an array that contains several items.

#

Yeah I'll find it for you.

#

It might have enough comments that you can understand it without knowing C.

#

Yeah essentially. It's kind of like a namedtuple in python, if you know about that.

#

Actually, there's two things going on there.

#

A struct definition, and a type definition.

#

They're often combined into one statement.

#

Yeah actually it's like a class with attributes and no methods.

#

I think it's worthwhile fwiw ยฏ_(ใƒ„)_/ยฏ

#

It's a ubiquitous language, it's very relevant to Python, and it's also a relatively small language so doesn't take too long to learn (except maybe pointers if you find them tricky).

#

Yeah fair enough ๐Ÿ˜„ I'm often guilty of not managing my time well, so don't take my advice.

old rover
#
def combination_sum(candidates, target):
  if target == 0:
    return [ ]

  if target < 0:
    return None

  for num in candidates:
    remainder = target - num
    remainder_result = combination_sum(remainder, candidates)
  print(remainder)

print(combination_sum([1,2,3,], 6))
#
Traceback (most recent call last):
  File "main.py", line 13, in <module>
    print(combination_sum([1,2,3,], 6))
  File "main.py", line 10, in combination_sum
    remainder_result = combination_sum(remainder, candidates)
  File "main.py", line 5, in combination_sum
    if target < 0:
TypeError: '<' not supported between instances of 'list' and 'int'
#

idk what's going on here... it's comparing b/w list and int?

#

i don't get this

#
def combination_sum(candidates, target):
  if target == 0:
    return [ ]

  if target < 0:
    return None

  for num in candidates:
    remainder = target - num
    remainder_result = combination_sum(candidates, remainder)
    if remainder_result != None:
      return [*remainder_result, num]
  print(remainder)



print(combination_sum([1,2,3], 6))
keen hearth
#

@old rover Did you mean to swap the arguments?

old rover
#

just caught that

keen hearth
#

Yeah, looks like you figured it out.

#

Is it working?

#

I feel it might make more sense to build up the list as you recur ๐Ÿค”

old rover
#

yeah it's still not working

#

i was trying an approach i learned from freecodecamp

#

yeah no

#

didn't work

fiery cosmos
#

I have a project. Implementation & display of Bubble Sort algorithm using Turtle library. Do you have any ideas?

twilit sky
#

not sure if this is the right place to ask but does anyone have a fast way to write a function that takes in a 2d array of coordinates and then outputs a 3d array of the original array minus each value? So using a for loop

input = np.zeros([m, 2])
output = np.zeros([m, m, 2])
for i in range(m):
  output[i, :, :] = input - input[i, :]
#

im looking for a way to vectorise this though

slender sandal
#

Do you have a better solution? Either faster or uses less memory, and no libraries.

def n_ranges(begin: int, end: int, n: int) -> tuple[tuple[int, int]]:
    """
    Divides an inclusive range: begin..end to n smaller ranges similar in size (the difference (end - begin + 1) in the ranges returned by n_ranges(1, 100, 10) is 10 for all of them).
    :param begin: the first number in the range
    :type begin: int
    :param end: the last number in the range
    :type end: int
    :param n: the number of ranges to split from the range and to return
    :type n: int
    :return: a tuple of smaller range tuples with similar sizes
    :rtype: tuple[tuple[int, int]]
    """
    ranges = []
    inc: int = (end - begin + 1) // n
    i: int = 0
    curr_begin = begin
    curr_end = begin + inc - 1
    while i + 1 < n:
        ranges.append((curr_begin, curr_end))
        curr_begin = curr_end + 1
        curr_end = curr_begin + inc - 1
        i += 1
    ranges.append((curr_begin, end))
    return tuple(ranges)
#

The intention was to split an inclusive range for n threads to find all of the prime numbers in the range.

slender sandal
austere sparrow
slender sandal
#

I prototyped this in Python, it's for C++

austere sparrow
#

ah

slender sandal
#

It will work with multiprocessing in Python, though, right?

#

If we're talking about a massive range like 0..1000000 (range(int(1e6) + 1))

#

So if I use 16 processes (I don't know what's good for this), it will be fast, right?

#

In one thread it did it in about 9.5 minutes in C++

austere sparrow
#

what is the problem about?

vocal gorge
#

that sounds really slow for primes up to 1 million. Are you using Eratosthenes' sieve?

slender sandal
#

Basically, write a function writePrimesToFile(begin, end, n) which will split begin..end to n ranges and search in n for prime numbers and write them into a file

slender sandal
vocal gorge
#

that's not eratoshenes's sieve, it's the divisor checking method

slender sandal
#

I think more than this would be overkill for homework

slender sandal
vocal gorge
#

your method takes O(sqrt(n)) for each number, which is a total of O(n^(3/2)) for all primes up to n

#

eratosthenes' sieve takes very slightly above O(n) (something like O(n log log n)) for all primes up to n

austere sparrow
vocal gorge
#
D:\Programming\Rust\primes\target\release>primes.exe 1000000
Elapsed:0.004842067s
Head:[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Tail:[999863, 999883, 999907, 999917, 999931, 999953, 999959, 999961, 999979, 999983]
Length:78498

my Eratosthenes' sieve implementation in Rust takes around 5ms to do this, it looks like

#

(It's single-threaded, for that matter)

slender sandal
#

Milliseconds?

vocal gorge
#

yeah

slender sandal
#

๐Ÿ˜ณ

#

Is it huge

#

The algorithm

vocal gorge
#

It really isn't, eratosthenes' sieve is fairly simple:

pub fn prime_sieve(n: usize) -> Vec<usize> {
    if n < 2 {
        vec![]
    } else if n == 2 {
        vec![2]
    } else if n < 5 {
        vec![2, 3]
    } else {
        let mut not_primes: Vec<bool> = vec![false; n + 1];
        let mut results: Vec<usize> = vec![2, 3];
        let mut end = n.integer_sqrt();
        if end % 2 == 1 {
            end += 1; // guarantees end being even
        }
        for k in (5..n + 1).step_by(6) {
            for &i in &[k, k + 2] {
                if !not_primes[i] {
                    results.push(i);
                    if k <= end {
                        for j in ((i * i)..(n + 1)).step_by(i) {
                            not_primes[j] = true;
                        }
                    }
                }
            }
        }
        results
    }
}

(basically, every time you detect that k is a prime, you mark 2*k, 3*k up to n as not primes. Then whenever you encounter an unmarked number, it must not be a prime.

#

(I'm also checking 2 numbers out of every 6, which is a nonobvious optimization; a simpler idea would be to check only odd numbers)

#

(The reason it works is because: there are 6 possible remainders of division by 6, from 0 to 5.

  1. The even remainders go straight out, because then the number is even. We are left with 1,3,5.
  2. 3 can also be thrown out because then the number must be divisible by 3
    so we can only check numbers with remainder 1 or 5 under division by 6)
slender sandal
vocal gorge
#

You must have implemented it wrong somehow, then

#

try also removing threading, but I doubt that's the reason

#

more likely you're redoing some expensive calculation for each number or something.

slender sandal
halcyon plankBOT
slender sandal
#

Oh I didn't realize I didn't use n_ranges ๐Ÿ˜

vocal gorge
#

What's the C++ code?

#

the Python code looks fine

#

<@&831776746206265384>, here again

austere sparrow
#

!pban 870500198865055785 nsfw

halcyon plankBOT
#

failmail :ok_hand: applied purge ban to @chilly crescent permanently.

vocal gorge
#

because this is a CPU-bound task, and threading is limited to one actual CPU thread

#

you'd need multiprocessing, which, note, has a lot of overhead

slender sandal
#

Yeah, increasing the number of threads in Python does nothing but increase the number of seconds it takes.

#

What object do I use to store the numbers using multiprocessing?

austere sparrow
#

wdym?

slender sandal
#

A regular list won't do

austere sparrow
#

with processes, you don't have shared memory: you pass messages from one process to another.

#

you'll have to use something like multiprocessing.Queue/Pipe

slender sandal
#

I will just use a file

#

And read from it

austere sparrow
#

concurrently writing to a file?

slender sandal
#

Why not

#

I'll have a lock

#

On the actual writing

austere sparrow
#

make each process write to its own file, that will be 1000 times easier

vocal gorge
slender sandal
#

I'm all ears

vocal gorge
#

it'll automate stuff like splitting for you

austere sparrow
#

also that, yeah

slender sandal
#

I don't have that in C++

vocal gorge
#

!docs multiprocessing.pool.Pool.map

halcyon plankBOT
#

map(func, iterable[, chunksize])```
A parallel equivalent of the [`map()`](https://docs.python.org/3/library/functions.html#map "map") built-in function (it supports only one *iterable* argument though, for multiple iterables see [`starmap()`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.starmap "multiprocessing.pool.Pool.starmap")). It blocks until the result is ready.

This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. The (approximate) size of these chunks can be specified by setting *chunksize* to a positive integer.

Note that it may cause high memory usage for very long iterables. Consider using [`imap()`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.imap "multiprocessing.pool.Pool.imap") or [`imap_unordered()`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.imap_unordered "multiprocessing.pool.Pool.imap_unordered") with explicit *chunksize* option for better efficiency.
slender sandal
#

Cool

vocal gorge
#

So, what does your C++ code do?

slender sandal
#

Threaded

#

n threads

#

I believe order doesn't matter

vocal gorge
#

I don't see how it can possible take minutes instead of Python's seconds unless it's doing something really weird, that's why I'm asking

slender sandal
#

I have no idea myself

#

I will check the code again

vocal gorge
#

number-crunching is something Python is really bad in, so even a naive solution in C++ should be way faster

slender sandal
#

Maybe I accidently reopen the file or something

vocal gorge
#

by the way, if all your threads write to the same file one number at a time, taking a lock, that'd basically mean only one thread can ever work

slender sandal
#

I open it once

vocal gorge
#

because calculating each prime will probably take less time than waiting for the lock

slender sandal
vocal gorge
#

I'd instead collect all primes to a list, and only write it to the file later, or at least write in chunks

slender sandal
#

Or at least, I could wait until I have one thread with all of its primes found and then let it write all it found

vocal gorge
#

even a one-threaded solution should be fast

#
use std::time::Instant;
fn main() {
    let start = Instant::now();
    let v:Vec<_> = (0..1_000_000u64).filter(|&x|is_prime(x)).collect();
    println!("{}", start.elapsed().as_secs_f64());
}

fn is_prime(n:u64) -> bool{
    if n < 2 {
        false
    } else if n == 2 || n == 3 {
        true
    } else if n % 2 == 0 || n % 3 == 0 {
        false
    } else {
        let end = (n as f64).sqrt() as u64;
        for i in (5..end + 1).step_by(2) {
            if n % i == 0 {
                return false;
            }
        }
        true
    }
}

This takes 7s on a debug build and 170ms on a release one - no threading here, though this doesn't write to a file

#

as if it's uncommon ๐Ÿฅด

#

one day I'll casually dump a wall of Rust code into pygen and ask for help because it's for a PyO3 library ๐Ÿฅด

#

i must resist

slender sandal
#

I honestly don't know what I did then with the C++ code

#

Single-threaded takes about as much time as Python

vocal gorge
#

lol, just now I was wondering why my rust solution is taking forever

#

turns out I typoed, wrote 0.. and was trying to find all primes up to infinity (well, to u64::MAX)

#

okay, there

0.193565583s to calculate the primes
1.113025647s to write to file
#

single-threaded Rust solution which uses the is_prime above

#
fn handle(max_n:u64) {
    let start = Instant::now();
    let v:Vec<_> = (0..max_n).filter(|&x|is_prime(x)).collect();
    println!("{}s to calculate the primes", start.elapsed().as_secs_f64());
    let before_dump = Instant::now();
    let mut file = OpenOptions::new().write(true).truncate(true).create(true).open("primes_dump.txt").unwrap();
    for (i,v) in v.into_iter().enumerate(){
        if i>0{
            file.write(b"\n");
        }
        file.write(v.to_string().as_bytes());
    }
    std::mem::drop(file);
    println!("{}s to write to file", before_dump.elapsed().as_secs_f64());
}
agile sundial
#

wait just get nightly and do cargo bench ๐Ÿ˜”

vocal gorge
#

i'm using a Rust kernel for jupyter

#

so don't wanna bother

agile sundial
#

is compilation slow?

#

might have to try that ๐Ÿ‘€

vocal gorge
#

it doesn't count compilation

#

the entire cell gets compiled before being run

agile sundial
#

right i'm just saying the jupyter xp in general

vocal gorge
#

not slower than cargo in my experience

agile sundial
#

cool

vocal gorge
#

(which I always forget the name of. excvr? evxrc?)

#

now, lemme try threading

agile sundial
#

how would you thread this? just assign different threads different ranges?

vocal gorge
#

My first idea would be to not think at all

#

and use rayon's map ๐Ÿฅด

#

for 10 million without threading,

4.907431416s to calculate the primes
8.359831334999999s to write to file
agile sundial
#

rayon is so cool

vocal gorge
#

was as simple as a (0..max_n).into_par_iter().filter(...)

#

that's on my CPU which has, like, 2 physical cores

agile sundial
#

let me try

slender sandal
#

Good god C++ is fast

vocal gorge
#

I wonder what's the right way to parallelize the writing

#

lemme try making proper threads

slender sandal
#

0..1000 ten threads

agile sundial
#

for such a small range the threads might be too much overhead

slender sandal
#

0..1000000

#

I'm reminding you my method of finding prime numbers is wacky

#

Validating*

agile sundial
#

that seems on the slow end still, tbh

slender sandal
#

I know

#

Let me try up to nine billion and with sixteen threads

#

I should have probably done something smarter

#

It's taking forever

vocal gorge
#

i mean, no wonder, you have O(n^(3/2)) complexity

#

so 1s for 1 million implies ~853ย 814s for 9 billion

slender sandal
#

Oh these are a lot of seconds

#

I'm not waiting that

#

0..1000, 0..100000 and 0..1000000

#

So threading is actually better for... a lot of numbers

#

A single thread performed way better on 1,001 numbers

vocal gorge
#

that's fairly strange, it's faster for me to use threads even for one million

slender sandal
#

It is faster for me in 1,000,001 numbers

#

Are you using my algorithm?

#

For validating primes

slender sandal
#

Well but yours is skipping a few

#

Mine is simple dumb check

dapper sapphire
#

So if we wanted to merge dictionary1 and dictionary2, would folowing be some of the ways to do it:

both_dictionaries = dictionary_one | dictionary_two
both_dictionaries = {**dictionary_one, **dictionary_two}
#

I dont know what |, except that it's a bitwise operator.

#

how does this approach work both_dictionaries = {**dictionary_one, **dictionary_two}, does it deconstruct both dictionaries?

balmy oak
carmine wadi
#

hi everyone, Can someone help me on my project? I am stuck on it

flint trellis
#

Not sure if this belongs here but

#

Whatโ€™s the diff between def functions and a class ?

civic kite
#

anyone familiar with pywinauto

south hawk
balmy oak
south hawk
#

yeah

south hawk
#

just created a matrix

#

can you help me solve this question further

balmy oak
#

You should store individual numbers as integers, not as strings

#

Also i don't really understand what it wants you to print on the second line

jolly mortar
#

rust

cunning ether
#

can anyone suggest some resource to learn data structure and algos and kinda give roadmap

#

thanks buddy

tacit lark
#

After finishing that playlist, is one adequately equipped with everything they need to move onto leetcode?

old rover
#
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        res = [ ]
        
        
        
        def dfs(i, cur, tot):
            if tot == target:
                res.append(cur.copy())
                return
            #if the total is equal to the target, append the current list to the resultant list
            
            if i >= len(candidates) or tot>target:
                return
            #base case
            
            cur.append(candidates[i])
            
            dfs(i, cur, tot + candidates[i])
            
            cur.pop()
            
            dfs(i+1, cur, tot)
        
        
        dfs(0, [], 0)
        return res
#

i don't understand backtracking

#

actually no, it is starting to make some sense

dapper sapphire
#

!e

dictionary1 = {"key1": "value1", "Key2": "value2"}
dictionary2 = {"key1": "value7"}

merged = {**dictionary1 , **dictionary2 }
print(merged)
halcyon plankBOT
#

@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.

{'key1': 'value7', 'Key2': 'value2'}
austere sparrow
#

yep, unlike in a set, where all elements are preserved

#

I personally don't see a big need in | for dicts

dapper sapphire
#

Oh no I'm sorry, I think it when it says Dic Union is Lossy, it's referring to pipe |

dapper sapphire
dapper sapphire
#

Maybe you meant a list/array?

austere sparrow
#

A set union doesn't drop any elements

#

well, I don't think it's a great argument

agile sundial
#

you could technically have two different objects that hashed and eqed the same, but had different satellite data. and you'd lose that data

dapper sapphire
#

oh ok I see what you mean.

dictionary's key is mapped to a value. One key can only have one value. So if we have two keys that are the same then one will be dropped.

Set only stores unique values. So we dont have to worry about it dropping anything.

agile sundial
#

that was his reasoning yeah

dapper sapphire
#

I know I will get a lot of hate for even saying thing, but wondering if they considered using plus + operator instead.
I think that would have been a lot of work and rewrite on top of current code base they have for + operator.

mint jewel
#

+ was also an option

#

but the operation is more a dict union than a dict concatenation

#

so the | operator, which is already a set union, makes more sense IMO

#

it wouldn't be a lot of effort to make it the + operator

#

the callback would just be in different slots

dapper sapphire
#

Is the notion for | on a set/dictionary compared to two nums, so:

#

!e

merged = 24 | 3
print(merged)
halcyon plankBOT
#

@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.

27
mint jewel
#

if you imagine an integer as a bitset, it is also union

#

and well, or is a very similar operation to union

#

either it's set in the left, or in the right, or in both

#

it being a bit, or a set element

dapper sapphire
#

But pipe | used in the context of dictionary or set is called Union Operator?

mint jewel
#

it's pretty much always the bitwise or operator

#

but it gets overloaded for unions as well

dapper sapphire
#

Oh I think I see what you mean.

#
  • operator is used for adding nums, but it gets overloaded so it can concatenate strings or lists/arrays together.

So the | or operator is like that, it gets overloaded for union?

mint jewel
#

more or less

dapper sapphire
#

So when we merge two dictionaries or two sets together, using dict unpacking {**d1, **d2} or union operator | both would give us the same result?

weary glen
#

what ways are there for a graph to not have a valid mst

austere sparrow
#

what do you need to parse from it?

#

!d csv

halcyon plankBOT
#
csv

Source code: Lib/csv.py

The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to attempts to describe the format in a standardized way in RFC 4180. The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.

austere sparrow
#

@idle pier You can read from stdin incrementally, line by line.

#

Then split each line.

#

you know about input()?

#

input() reads a line from standard input, or raises EOFError if there isn't any more input

grizzled river
#

Hi, im a learning python for a exam today. May I know how to sort an array with boolean values?
My current code :

has_done_homework.sort()
print(has_done_homework)```
returns `[False, False, False, True, True]`
austere sparrow
#

Make a list of records. Then process that list

grizzled river
#

nope i need true to come first

#

is it possible?

somber kiln
#

Are there ways to do three-way merges on rich text? Going through markdown or another markup language can lead to invalid markup even if the 3 inputs were

grizzled river
#

hello please answer, i am very desperate have been working on this for 50 hours already

austere sparrow
grizzled river
#

thank you mister duck

rich pelican
#

whats an effiecient way to process 2 sets of 5 conditionals on the same data?
condition1 = priority 1-5
condition2 = position secondary-septenary

hollow stratus
#

anyone good with probabilities analysis in code?

merry scroll
#

Town positions and N are given
Example:

Town positions:
(4;9); (9;5); (0;2); (7;1); (3;4)
Minimum cost:
5

(4;9) - (3;4) - (9;5)
          |
        (0;2) - (7;1)

Please ping me if you can help.
Thanks in advance!

#

I was thinking of Kruskal's algorithm...

glossy breach
#

kruskal works here

merry scroll
glossy breach
#

you can just generate all n^2 edges

#

and apply kruskal directly to find the minimum spanning tree of the graph

#

it will be O(n^2 log n)

merry scroll
#

N can go up to 10**5

glossy breach
#

oh

merry scroll
#

Generating all edges may not be the way...

glossy breach
#

you didn't mention that

merry scroll
glossy breach
#

I think this can be done in O(n log n) with prim's algorithm

merry scroll
glossy breach
#

I don't think I know how to solve this with prim's algorithm yet

#

but I have a O(n (log n)^2) solution using boruvka's mst algorithm

merry scroll
#

hmm...

glossy breach
#

well so about boruvka's algorithm
you start with n connected components in the graph, and all the edges in the graph are considered unused
and for each component, you find an unused edge to another component with the least weight, use it and therefore connect the two connected components into one

#

there's some kind of proof that after O(log n) iterations every component will be connected into one

#

so for this specific problem its easy to find the unused edge for each component in O(log n) so therefore it's O(n (log n)^2)

merry scroll
#

So I need to generate edges?
And use it later?

glossy breach
#

no you don't have to

merry scroll
#

So how can I "find an unused edge with the least weight" without generating unused edges?

glossy breach
#

well you can inspect the cost of the edge
min(|x_i, x_j|, |y_i - y_j|)

#

it is clear that for a point (x_i, y_i)

#

you just have to find the point with x closest to x_i

#

and the point with y closest to y_i

#

right

merry scroll
#

yes

glossy breach
#

also it must not be in the same component as point i

#

this can be done in O(log n) by sorting the points by x and by y

#

and simple binary search

fossil minnow
#
key_string  = {
    "2" : "abc",
    "3" : "def",
    "4" : "ghi",
    "5" : "jkl",
    "6" : "mno",
    "7" : "pqrs",
    "8" : "tuv",
    "9": "wxyz"
}
#count the number of permutations formed in total in above code 
def key_comb_count(pr,u_pr,key_string): 
    #for storing the answers of key combinations possible
    #exit condition 
    count = 0
    if len(u_pr) == 0:
        count += 1 
        return count 
    #logic 
    for i in u_pr: #i here refers to the key entered  #say u_pr = "3" , so i = "3"
        val = key_string[i] #"abc"
        for i in val:
            org_pr = pr #saving the above function call value of pr here 
            count  += key_comb_count(org_pr + i ,u_pr[1:],key_string,count) #u_pr = "bc"
        return count 
    return count 

x = key_comb_count("","2",key_string) 
print(x)
            
#

this is giving the permuations formed from the letters associated with keys on mobile phones

#

can anyone help me in getting to know the time complexity with some details

languid plover
#

I am trying to verify a csv column depending on the value from a second column. eg column B should be 'hi' or 'hello' if the value of column A is "Python' or 'Duck'
I tried

          if(df['A'].values == 'Python'or df['A'].values == 'Duck')
                if(value != df['B'].apply(lambda x: 'hi' or 'hello'))
                      return False
                else:
                      return True

I am new to python please
Thanks

atomic quest
#

My father is looking for a python alternative for matlab. He's been coding in matlab for decades and now trying to combine it with a python project.
He was looking into alternatives and was introduced to numpy, yet can't tell if it's reliable.
He wants to have python run on a machine that doesn't have matlab, and so he's looking for such an alternative

bitter wigeon
#

I agree Matlab is wonderful but numpy has perhaps a larger user base now esp in ML/AI.. More users in academia too. I have replicated computations in both and no issues but it may depend on the use case.

atomic quest
#

alright, and what about reliability? I mean, what if the creator of numpy has made a mistake that wasn't made in matlab? Matlab has many mathematical wonders especially in terms of efficiency and speed. The question is if python libraries can offer that at the very same level

jolly mortar
#

its quite unlikely that numpy would have bugs, given how many users it has and how large an ecosystem depends on it

atomic quest
#

understandable

bitter wigeon
#

Yep used it in ML too

atomic quest
#

so in terms of efficiency and speed, is it "worthy"?

jolly mortar
#

id say it should be comparable with matlab

#

you just have to keep in mind that you use the operations implemented in C

bitter wigeon
#

I have tried both
..yes

atomic quest
#

that's great to know

#

so numpy can actually offer all the features in matlab?

#

that's quite impressive

bitter wigeon
#

There is also octave which is closer to matlab but free but I havent tried

atomic quest
#

I'll make sure to take a look at that as well

bitter wigeon
#

If your father is stuck with Matlab syntax then Octave might be a better fit

atomic quest
#

syntax isn't the problem, but rather the tools

#

for example matlab's wonderful sort functions

bitter wigeon
atomic quest
#

yeah my father apparently knows octave too

#

alright so I think that's covered up a lot for me, my father said he'd love to try numpy then

#

he'll see how it performs and decide accordingly

#

I apparently have to go now, but thanks a lot. If you send anything further I'll come back to read here later just to confirm I haven't missed anything

bitter wigeon
#

Only way to know is to let him use them ...there may be edge cases where Matlab is better or Numpy ie better...Pandas can do sorting and holding data in a spreadsheet like dataframe...

#

Python has many libraries so if it is not in numpy there is probably another library that covers the functionality

atomic quest
#

Alright thanks

bitter wigeon
#

Oh my dad is also an engineer but retired and not as active as your dad lol

atomic quest
#

Well my dad is only 52 years old...

bitter wigeon
#

Ah ok mine significantly older

atomic quest
#

Well I'm not even 17 haha

bitter wigeon
#

Ah cool

atomic quest
#

Aight it was a pleasure to meet, thanks a lot for your help. Have a good day!

bitter wigeon
#

Im closer in age to your dad then lol

#

Likewise, have a good day too and good luck.

fiery cosmos
#
Write a python program that must accept an integer matrix of R*C and an integer โ€˜nโ€™ as the input. Exactly one element in the given matrix is missing, which is denoted by a character โ€˜mโ€™. The integer โ€˜nโ€™ represents the sum of all the integers in the column of the missing element. You must find the value of โ€˜mโ€™ by replacing it in the given matrix and print the same (integer matrix with all R*C integers) as the output.
Note:ย Print โ€˜invalidโ€™, if the boundary condition is not met.
Boundary Conditions:
2 <= R, C <= 50
1 <= matrix element value <= 1000
1 <= n <= 10^5
ย 
Input Format:
The first line contains R and C separated by a space
The next R line contains the matrix elements integers separated by space(s)
The last line contains integer โ€˜nโ€™
Output Format:
ย The first R lines, each contains C integer values separated by space(s)
Sample Test case Input-1:
3 3
2 5 8
1 5 m
9 7 6
17
ย 
Sample Test case Output-1:
2 5 8
1 5 3
9 7 6
Explanation:
Here, the missing element is present in the 3rdย column
The sum of the elements in 3rdย column is 17
So, the value of the missing element โ€˜mโ€™ is 3 (17-(8+6))
ย 
Sample Test case Input-2:
4 5
62 25 69 62 80
15 10 17 34 75
99 m 76 79 23
48 15 73 22 68
100
ย 
ย 
Sample Test case Output-2:
62 25 69 62 80
15 10 17 34 75
99 50 76 79 23
48 15 73 22 68 ```
#

solve this please

halcyon plankBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

fiery cosmos
#

I have tried it bro ,but its still a problem , well if u can help it would be a big help

#

Thats a practice problem not my online exam problem lol ๐Ÿ˜‚

raven kraken
#

Hey all I have just started learning Dynamic Programming and just want to cross check If my understanding of Dp is correct or not? Its just basically recursion + storing the repetitive stuff, right?

atomic quest
austere adder
#

can some one help , i was trying to download the dependencies .

fiery cosmos
atomic quest
#

I don't like your attitude

#

"solve this please"
"not my online exam problem lol๐Ÿ˜‚ "
"give me the algorithm"

fiery cosmos
graceful hatch
#

Hey guys, could someone suggest good github or maybe discussion on Kaggle about most popular datasets in Kaggle? I'm practicing right now, and usually before working with dataset I check a few Kaggle notebooks to get new ideas, however I have spent already one week doing this and really run out of datasets on Kaggle with many notebooks, therefore I'm trying to find new ones. Any help is appreciated.

hollow stratus
#

Can someone help me with probability analysis in code

haughty mountain
# raven kraken Hey all I have just started learning Dynamic Programming and just want to cross ...

DP itself is about splitting a problem into several independent smaller versions of the problem, and then only computing the problems once.

Recursion with memoization is just one way of implementing a DP. That way tends to be called the top-down version where you start with the big problem and break it apart into smaller once.

The other way is bottom-up where you compute the values directly in the order they need to be computed (so when you solve a larger problem all subproblems are already solved). The bottom-up approach can sometimes allow you to save a lot of memory because you control the order of things

E.g. for something like fibonacci the naive memoization or table approach uses O(n) memory, but you only really need the two previous elements if you do the work in the right order. In the case of fibonacci the right order is obvious, but it might be less obvious for more complex problems.

haughty mountain
sullen siren
#

I hope any of you guys could help me and point me in the right direction.
I have been making a cpu scheduler - priority using pandas, and I have been stuck for ages. So any help would be much appreciated.

Originally I used openpyxl to read the xlsx and create the scheduler which worked fine, until I tried to adapt it to round-robin algorithm. So I decided to try with pandas, and now I am stuck with my new code. I managed to sort the list, so that first it follows priority, and a fallback is FIFO (arrival time) as you can see in the code. But, now my simulator will not work, and the output to user is not working either (output should be similar to screenshot)

Here is the code: https://pastebin.com/4BrRUpUy
Old code that worked: https://pastebin.com/RGTsdXfH

Thanks a lot for any help, am I asking in the wrong place please tell me where to go

Kindly
Frank

lone mason
#

Except for collections is there any library that we generally use for ds-algo problem statements? Can anyone provide list of helpful inbuilt modules which we can use while solving ds algo problems

agile sundial
#

itertools is awesome

fiery cosmos
#

also functools namely for the @cache (or lru_cache) decorator that can help with dynamic programing problems

#

also heapq for heap stuff

#

not to mention math for gcds and such

whole chasm
#

hey everyone

#

im new to python

#

any ideas on how to write a nested loop

#

?

#

like my c++ habits are killing me in python lol

#

since its like hyper syntax heavy

#

ideally i want to create a nested for loop

#
def twoNumberSum(array, targetSum):
    for i in array:
        j = i + 1
        for j in array:
            sum = i + j
            if sum == targetSum: 
                result = [i, j]
                return result;
#

i created this

#

i want to loop through eaach element

#

and have the nested element starting the next element from the first loop

#

to store the values in the array

#

that match

#

what about this?

#
def twoNumberSum(array, targetSum):
    for (i=0; i<len(array); i++):
        for (j=i+1; j<len(array); j++):
            sum = i + j
            if sum == targetSum
                result [i, j]
                return result
haughty mountain
fiery cosmos
#

but this looks a lot like the LeetCode TwoSum problem, and this solution is not the optimal one - you may need something faster using dictionaries

raven kraken
raven kraken
# whole chasm what about this?

Hey I noticed you are using a variable sum to store the sum, ig you might not be aware of the fact that python have a inbuilt function sum() so it can give you a error.

slim crest
#

hello could i get some help

winter niche
#

hey can somebody help me out with this question :
infix to postfix :

A * ( B + D ) / E - F - ( G + H / H)
drifting jacinth
#

Um

#

Hi

keen hearth
keen hearth
keen hearth
drifting jacinth
keen hearth
cerulean elk
#

For anyone who has worked with networkx

#
import numpy as np
import networkx as nx
import pylab as plt




conn = http.client.HTTPSConnection("covid-19-data.p.rapidapi.com")

headers = {
    'x-rapidapi-host': "covid-19-data.p.rapidapi.com",
    'x-rapidapi-key': "#my-api-key"
    }

conn.request("GET", "/country/code?code=it", headers=headers)

res = conn.getresponse()
data = res.read()

#print(data.decode("utf-8"))

graph=np.array([data]*2)
print(graph)
y=nx.graph``` okay basically im tryna make a graph from the covid 19 array which I got from an api. I made it into a 2d array but im still gettin an error
#

any ideas?

#

nvm I was makin a few errors

#

yeah sorry it says that its a 1d array still but i check stack over flow they said jus use the * operator and it can change but im still geting an error

slim crest
#

honestly i have stared at it for abt 30 mins

#

I am running python 3.10

#

heres is my result

keen hearth
#

It looks as if your search function expects the array to be sorted in ascending order. Is this correct?

raven kraken
slim crest
#

it works

keen hearth
#

I think the fact that when target < val you set e to midpoint - 1.

slim crest
#

yea?

keen hearth
#

The trick with binary search is to think in terms of an invariant, which is just a property that remains true throughout the execution of the algorithm. In your case the invariant is that any value to the right of e is greater than the target, and any value to the left of b is less than the target.

haughty mountain
#

oh god, seeing binary search with inclusive on both left and right looks so weird to me, I'm so used to inclusive left, exclusive right

slim crest
#

sorry i kinda just woke up from sleep in a data sturctures and algorithms class so please bear with me

keen hearth
#

But usually in Python the version you describe is more natural.

haughty mountain
#

with inclusive exclusive, left is always has the predicate being true, and right always false, which is a nice invariant

slim crest
#

so how do write my algorithm so that it doesnt matter the order of list

keen hearth
#

But you could maybe add a key argument ๐Ÿค”

haughty mountain
#

binary search must have a property that what you're searching goes from being false to being true (or vice versa)

slim crest
#

and how would i apply that key argument in the algorithm

keen hearth
haughty mountain
#

you're searching for the point where the switch happens

haughty mountain
#
midpoint = ...
if predicate(midpoint):
  ...
else:
  ...
#

in your case the predicate is target < sequence[midpoint]

slim crest
#

yea

haughty mountain
#

just one switch from 0 to 1

slim crest
#

so i am doing the oppsite?

#

*opposite

haughty mountain
#

err...it probably should be

1 1 1 1 1 0 0 0 0
haughty mountain
lone mason
#

Hey guys can someone refer a good book for preparing ds algo with python. Need everything at one place

haughty mountain
#

(but it's just a matter of inverting the predicate, no big difference)

lone mason
slim crest
#

i am not sure if you are allowed send pdf in this channel

lone mason
slim crest
#

i dont understand the terminology predicate

lone mason
haughty mountain
slim crest
#

i am not a cs student

haughty mountain
slim crest
#

ohh okay

cerulean elk
slim crest
#

can you use binary search to find the element in a linked list

haughty mountain
#

the binary search I have in my head when I write one is like

def bs(lo, hi, pred):
  l = lo
  r = hi
  while r - l > 1:
    mid = (l + r)//2
    if pred(mid):
      l = mid
    else:
      r = mid
slim crest
#

ohh okay

#

"pred()" is ?

haughty mountain
haughty mountain
slim crest
haughty mountain
#

It's worth noting that binary search does not at all depend on that you're working on an array or similar, you could have some increasing function f(x) and you wonder when it becomes > value

#

If you're only interested in integer points the code is identical

slim crest
#

ooh that's cool

reef forge
#

Dunno if this is the right spot for this, but i made this just now:

import matplotlib.pyplot as plt
import numpy as np

num = int(input("Enter a number: "))
while num < 1:
    print(f"{num} is too small. Enter a positive integer.")
    num = int(input("Enter a number: "))
scoreNum = int(num)
score = 0
steps = []
valList = []

print(int(num))

def collatz():
    global num, score, valList, steps
    
    valList.append(int(num))
    
    while num != 1:
        if num % 2:
            num *= 3
            num += 1
        else:
            num /= 2
        valList.append(int(num))
        score += 1
    if num:
        score += 1
    
    steps = [i for i in range(score)]
    
collatz()

print(steps)
print(valList)


plt.plot(steps, valList)
if 0 < len(valList) <= 50:
    plt.xticks(np.arange(0, score + 1, 1.0))
plt.title(f"Collatz of {scoreNum}")
plt.xlabel("# of steps")
plt.ylabel("# at step X")
plt.show()
slim crest
#

i made something like it during december

reef forge
#

First time working with matplotlib

slim crest
#

is there a problem?

#

if there is i dont know matplotlib yet

#

but i made this simple program

#

can someone recommend Mathematics books

#

i'm in my first year highschool

#

i'm prolly gonna be here alot

old rover
#
def group_anagrams(list_of_strs):
  res = defaultdict(list)

  for s in list_of_strs:
    count = [0] * 26

    for c in s:
      count[ord(c) - ord("a")] += 1
    
    res[(tuple(count))].append(s)
  
  return res.values()


print(group_anagrams["dog", "god", "sog"])
#

this is supposed to group anagrams together

#

but i'm getting a typeError

#
Traceback (most recent call last):
  File "main.py", line 15, in <module>
    print(group_anagrams["dog", "god", "sog"])
TypeError: 'function' object is not subscriptable
#

idk what the problem here is

cerulean drift
fiery cosmos
slim crest
#

really? i should try this internet sometime

fiery cosmos
#

Yeah it has all the books you need, if you donโ€™t find what youโ€™re searching, try to put more details in your search

slim crest
#

I typed something in my searchbar it asks to enable safe search

#

anywhy i need help

#

heres my attempt

haughty mountain
#

the logic is a bit weird, isn't it enough to find the first position where the node data is >= the data to insert

#

with a special case for insertion at the end

#

and a special case when the list is empty

slim crest
#

empty linked list?

haughty mountain
#

yeah

slim crest
#

so i append all values less than data in the empty list?

haughty mountain
#

huh?

#

the weird logic to me is the one in the loop, feels like it can be done simpler

slim crest
#

hmm

#

how would you have done it?

fiery cosmos
#

Is anyone read the book design and analysis of algorithms by Thomas H Coremen?

haughty mountain
# slim crest how would you have done it?

Here is a stab at it, though it has more cases than I prefer. IIRC there is a classic way to reduce the number lf cases, but idk how it translates to python

def insert_sorted(head, data):
  new_node = Node(data)
  if head == None:
    return new_node

  prev = None
  cur = head
  while cur != None:
    if cur.data >= data:
      if not prev:
        # Before head
        new_node.next = head
        head = new_node
        break
      else:
        # Between nodes
        new_node.next = prev.next
        prev.next = new_node
        break
    prev = cur
    cur = cur.next
  else:
    # At end
    prev.next = new_node
  return head
#

decent test case

def ll_items(cur):
  while cur != None:
    yield cur.data
    cur = cur.next

head = None
head = insert_sorted(head, 3); print(list(ll_items(head)))
head = insert_sorted(head, 1); print(list(ll_items(head)))
head = insert_sorted(head, 2); print(list(ll_items(head)))
head = insert_sorted(head, 4); print(list(ll_items(head)))
#

should output

[3]
[1,3]
[1,2,3]
[1,2,3,4]
flint jackal
#

hey guys i am studing Genetic Algorithems would it be possible for one of you guys to help me with one question

Discuss the different solutions to address the failure of simple crossover strategies(to solve the disadvantages) for the travelling salesman problem.
In particular:
why they are necessary
how they are applied
how they preserve the parental traits
what other possible methods are available

slim crest
#

okay lemme have a go

high pewter
#

Can you guys help me with something

slim crest
slim crest
high pewter
#

With my code

#

For a problem

slim crest
#

i mean show me your code

#

or problem

high pewter
#

this is it

#

#Part 2

#Input
v1 = eval(input("Enter Mr. Veera's average speed(m/h): "))
v2 = eval(input("Enter Mr Anderson's average speed (m/h): "))
distance = eval(input("Enter the distance (m): "))

timeToCharge = eval(input("Enter number of minutes to fully charge electic bike: "))
minToCharge = eval(input("Enter number of minutes to operate before next charge: "))
minToChargeDefault = minToCharge

#Variables
hours=distance
minutes=hours*60

v1timetaken=0
v2timetaken=0
veeraD=0
andersonD=0

veeraC=0
andersonC=0

#Mr.Veera
while veeraD<distance:
#Time
v1timetaken=v1timetaken+1
#Distance
veeraD=veeraD+(1*v1)

#Mr.Anderson
while andersonD<distance :
if(minToCharge>0):
#Time
v2timetaken=v2timetaken+1
#Distance
andersonD=andersonD+(1*v2)
minToCharge = minToCharge -1
else:
v2timetaken=v2timetaken + 1 + timeToCharge
minToCharge = minToChargeDefault

#Distance comparison
for comparison in range(hours):
if(veeraC>=distance) or (andersonC>=distance):
break
veeraC=veeraC+(1v1)
andersonC=andersonC+(1
v2)

print("Mr.Veera's position:", veeraC)
print("Mr.Anderson's position:",andersonC)

if v2timetaken<v1timetaken:
print("After",v2timetaken,"hour(s)","Mr.Anderson reaches finish line first")
else:
print("After",v1timetaken,"hours(s)","Mr.Veera reaches finish line first")

#

this my code

#

can u check what is wrong

slim crest
#

what error is raised?

halcyon plover
high pewter
#

i am trying to fix it but i am unable to do it

halcyon plankBOT
halcyon plover
#

oh.

#

maybe you cant?

#

srry if you cant

high pewter
#

dont worry

slim crest
slim crest
high pewter
#

yeah i cant figure what is the problem

slim crest
#

are you looking for a solution or just help?

high pewter
#

idc

#

either is fine

slim crest
#

okay gimme a few i am tryna fix some of my program

high pewter
#

k

#

@slim crest you still there?

haughty mountain
slim crest
high pewter
#

i pasted in there now what @slim crest?

#

this my code

#

@slim crest

slim crest
#

i'm working on it

high pewter
#

this the first part i already finished it

#

but it will give u a better understanding

slim crest
#

thx

#

i see

#

do you still have the program to part 1?

high pewter
#

Yes

slim crest
#

okay

#

lemme write it on my own

high pewter
#

okay

haughty mountain
#

what's with the "using simulation" thing?

#

in part one you can just compute the answer directly

high pewter
#

But you don't use math at all

#

By using using simulation and using loops u can get it

haughty mountain
#

I mean, you can. But it feels silly when the answer is pretty much right there

#

the smaller distance_left/vel dictates everything

high pewter
#

I just started coding so I am not the best when it comes to this stuff

haughty mountain
#

I feel like the second part kinda lacks information, we can get there faster by maybe doing a partial charge at the end. I'm assuming that's not allowed, but the task doesn't say

slim crest
high pewter
#

Yeah this semester

slim crest
#

I almost done with part 1

#

obviously Mr anderson travels twice as fast as mr V

high pewter
#

Yeah

slim crest
#

but looking at your code you used a while loop to record timetaken why tho?

haughty mountain
#

if you want to do a raw simulation it's probably a good idea to allow for a smaller time step, e.g. have some dt that dictates how long a simulation step is, rather than it being 1 as in your current code

slim crest
high pewter
#

Cause this a question our teacher assigned us and he hates us using functions we never learned in class

#

And gives us a 0

slim crest
#

but the equation for time is = distance/speed

high pewter
#

But our teacher said without using math equations

#

So this is where loops come in

slim crest
#

i didnt know

high pewter
#

Ohh my bad I should have informed you

#

Sorry

haughty mountain
#

part 1 is just doing this I guess

while pos < goal:
  pos += vel*dt
  t += dt
#

for both scenarios

#

(maybe in parallel?)

high pewter
#

Yeah but no math involved

#

Should i send my code for part 1

slim crest
slim crest
high pewter
slim crest
haughty mountain
#

good luck without any math at all ๐Ÿ˜›

high pewter
slim crest
#

i didnt know that too

high pewter
#

Omg my bad

#

Cause it was how he programmed it

haughty mountain
#

the real answer is 25, I guess the extra .02 is because of the simulation time step