#algos-and-data-structs

1 messages · Page 92 of 1

fiery cosmos
#

i knew it had to be a simple change

#
def solution(A, B):
    A.sort()
    B.sort()
    i = 0
    for a in A:
        while i < len(B) - 1 and B[i] < a:
            i += 1
        if a == B[i]:
            return a
    return -1
#

yep got it

#

open to any other suggestions however if u notice any

#

see this it works

#

also what will be the time complexity of your code?

#

the new while loop does work, is a while loop more effcient than an if?

#

hmm lemme check

#

while loop is log(n)

#

@desert cedar The problem is Given two sequences A, B find the smallest element that is found in both A and B. If not return -1

#

@fiery cosmos nope

desert cedar
#

There is nothing to be counted then, so no counter should be used.

fiery cosmos
#

from my quick google search the answer for a while loops complexity is log(n)

desert cedar
#

While loops don't have a fixed complexity.

#

It depends on how you end the loop

fiery cosmos
#
A.sort()
B.sort()
This part takes O(n log n)
------------------------------------------------
for a in A:
    while i < len(B) - 1 and B[i] < a:
        i += 1
    if a == B[i]:
    return a

How much does this part take?

#

wow this time complexity stuff can get a little confusing 2 secs

#

o(n2)?

desert cedar
#

Why was the if changed to a while?

fiery cosmos
#

@desert cedar to make it more efficient

#

O(n^2)??

#

no it is not to make it efficient, it is to make the code correct

mint jewel
#

that is O(n**2)

fiery cosmos
#

Well im guessing, i remember something like one loop is o(n), then another within it is o(n) again

mint jewel
#

well, O(len(A)len(B))

fiery cosmos
#

yes sorry o(n^2) is what i meant

#

Am I correct?

mint jewel
#

yes

#

assuming both lists are n long

fiery cosmos
#

nice

#

hmm

mint jewel
#

since if B was fixed at 1k elements, it would be O(n)

fiery cosmos
#

Im allowed to change 2 lines of the solution but im wondering if anything needs changed other than while loop that could improve it further

mint jewel
#

you could do that in O(n) with sets I think

desert cedar
#

Are you supposed to optimize it or just fix it?

fiery cosmos
#

fix it but hopefully optimise it in the process as it will have extreme test cases run against it to test if it still holds up

#

as it works initially but bugs need to be fixed

#

I am thinking this is actually O(n) time complexity

#

the second while loop has some condition

#

and how can I be sure that it runs for every el in A?

mint jewel
#

consider A of only positive numbers and B of only negative numbers.

#

B[i] < a will always hold

fiery cosmos
#

there are some assumptions to be made i should make clear

#

what about the i < len(B) - 1 after first el in A?

#

1, 2, 3, 4

#

each element in the arrays is an int between 0 - 1,000,000,000

mint jewel
#

oh, i does not get reset

#

that is probably a bug

fiery cosmos
#

no it is not why would you need to reset i?

desert cedar
#

It doens't need to reset, since it's sorted.

fiery cosmos
#

since you can't find greater than first element of A

#

and you stop at the last element

mint jewel
#

true

fiery cosmos
#
[1, 2, 3, 4]
[-1, -2, -3, -4]

after comparing with 1

[-1, -2, -3, -4]
              |
              i

i will stay there for rest of the code
#

so it is actually O(n) time

#

I cant believe I spent 50 minutes just to realise if should be while

#

this is like a technique called two pointer where you really write two loops

#

but the whole TC is O(n)

mint jewel
#

yeah, O(n) actually.

fiery cosmos
#

why is while loop better than if loop for this?

mint jewel
#

interesting

fiery cosmos
#

does the while loop change it from o(n^2) to o(n)

#

?

desert cedar
#

It's not better, the if just not the correct solution.

snow swift
#

if loop?

fiery cosmos
#

haha algorithms are interesting

mint jewel
#

if is wrong

fiery cosmos
#

sorry if statement

#

it works with an if statement though

#

🤔

desert cedar
#

It doesn't for all inputs

fiery cosmos
#

yeah so thats the problem

#

what inputs break it?

#

Id like to test it

#

uhh

desert cedar
#

inputs where you have to search farther than 1 in b

mint jewel
#

A=[6],B=[1,2,3,4,5,6] probably

fiery cosmos
#

yep

#

it breaks in this

#

you will be extinguished by the first loop

#

but you really have 6 as the answer

#

I just tried it with the while loop and that works, so im assuming im on the right track

#

nice quick test case :)

#

I am so bad at making testcases

#

any suggestions on test cases that could break the while loop?

#

I write a program for that 🥴

#

nope

#

a correct solution will not break

#

woop woop 😄

fiery cosmos
#

If I split a string, how do I then reverse that split?

#

I know my question isnt well worded so I will show an example

mint jewel
#

.split() is impossible, .split(sep) with sep.join

fiery cosmos
#

Does anyone know how to make my code specifically remove entries with 'NULL' and not those with 'ANULLED'?

def solution(S):
    # write your code in Python 3.6
    S = S.split("\n")
    #Skip first row
    for i in S[1:]:
        #Only contains NULL not nill or ANNULLED
        if 'NULL' in i:
            S.remove(i)
    #Convert back to string with \n seperator
    str1 = "\n"
    return str1.join(S)

Example input:
'header,header\nANNUL,ANNULLED\nnull,NILL\nNULL,NULL'

Expected output:

ANNUL,ANNULLED
null,..)```

My output:
Removes ANNUL and ANNULLED
shy gate
#

@fiery cosmos if 'NULL' in i: checks if the string contains NULL try if i == 'NULL': instead

fiery cosmos
#

so i tried that

#

but it then breaks my other test cases and still does not fix my original test case

#

this is so annoying because I know youre right

shy gate
#

i just realized this is *not #python-discussion. youre probably better off asking in a help channel

fiery cosmos
#

ok np thx anyway dude

delicate trail
#

can i ask for help for math in general not just python? im just stuck on this one exericice and i cant find teh answer, i only have 30min left to submit it or i get 0

agile sundial
#

check the channel description

delicate trail
#

well im bad with english its not my fmother language so i dont know if mathematical concepts counts as sequences

agile sundial
#

the key part is as they relate to solving problems with Python

delicate trail
#

ah then yes, i need to make a program from that

agile sundial
#

that doesn't look very python related

delicate trail
#

that no but after i needt o make aprogram that will return the result of given n

#

but i first need to find the formula to that n which i cant find

agile sundial
#

it's given, u_n+1 = 6u_n

frail sun
#

Can someone help with creating Conways Game of Life? My code is nearly complete I'm just confused on this last bit. Please DM

oblique panther
#

@frail sun you can get help in the server instead of over DMs

fiery cosmos
#

can someone eli5 search engine services like elastic search and solr

#

do people have a server for their data and a server for their search engine?

#

how does the search engine server grab the data from the database, like a mongodb server for example

brave oak
#

do people have a server for their data and a server for their search engine?
@fiery cosmos yes

fiery cosmos
#

why dont people use the search engine thats built into things like mongodb

#

this is what i do so far

old thunder
#
def repeatedString(s, n):
    if s == "a":
        return n
    
    if 'a' not in s:
        return 0
    
    string = s*(math.floor(n/len(s)))
    rem = s[:(n-(math.floor(n/len(s)) * len(s)))]
    
    a = 0
    
    for c in string:
        if c == 'a':
            a += 1
            
    for c in rem:
        if c == 'a':
            a += 1
  
    return a```
#

This seems to work, but gives a memory error with larger len(s) and n

brave oak
#

how does the search engine server grab the data from the database, like a mongodb server for example
@fiery cosmos separate

#

sorry I got a call

#

why dont people use the search engine thats built into things like mongodb
@fiery cosmos efficiency

#

@old thunder post the question

#

and I’ll have a look

fiery cosmos
#

@brave oak separate?

#

and why is

#

the built in one less efficient

brave oak
#

@brave oak separate?
@fiery cosmos or rather

#

in some cases

#

you need to store two copies of the data

#

one on your normal database, and one on ES (this will probably be a subset)

#

but I understand there are ways to integrate ES with your database (Mongo is one case)

#

the built in one less efficient
@fiery cosmos hm

#

ES is quite a mature product

#

and lots of time has been spent tuning it for its specific usecase

#

searching.

old thunder
#

@brave oak ```
Lilah has a string, s, of lowercase English letters that she repeated infinitely many times.

Given an integer, n, find and print the number of letter a's in the first n letters of Lilah's infinite string.

For example, if the string s='abcac` and n=10, the substring we consider is 'abcacabcac', the first 10 characters of her infinite string. There are 4 occurrences of 'a' in the substring.

brave oak
#

ah, okay, I get it

#

let me read your code

#

@old thunder

#

you have this line string = s*(math.floor(n/len(s)))

#

can you explain your thought process?

old thunder
#

Sorry, just saw this. Basically I was trying to get all of the characters that I could, without subdividing s

#

And then rem would be whatever is left, in order to make n characters

brave oak
#

Sorry, just saw this. Basically I was trying to get all of the characters that I could, without subdividing s
@old thunder okay, so think about this

#

if n is big and s is small, what happens?

#

your idea is kind of correct

#

but the implementation is weird

#

it's solvable in two lines, btw

#

I don't really think I'm golfing but

#

yeah

fiery cosmos
#

I succeeded learning some oop from making clear and nano programs

halcyon plankBOT
covert scaffold
#

is it possible to define new pandas dataframes as part of a loop?

brave oak
#

is it possible to define new pandas dataframes as part of a loop?
@covert scaffold yes. but why? (#data-science-and-ml probably more appropriate)

covert scaffold
#

Aren't loops algorithms ? I figured it would fit here

#

I'm like clueless

brave oak
#

how about

#

tell us what you wanna do

#

Aren't loops algorithms ? I figured it would fit here
@covert scaffold loops are part of algorithms, but the approach to solving problems with pandas can differ quite significantly from what you would do with less complex data structures

#

and pandas is a DS-specific tool, so

covert scaffold
#

Ah that makes sense

brave oak
#

you're more likely to get someone who knows how to solve the problem in the best way for pandas there

covert scaffold
#

I will keep all my pandas related questions over there

oblique panther
#

@covert scaffold loops are used in algorithms in the sense that they're a building block of programs. Though this channel is mostly about classical algorithms like efficient sorts, graph traversal, etc.

brave oak
#

anyway, yeah, just post your question there and we can help you out

covert scaffold
#

Thank you, I was just trying to assess whether its possible to create them within the loop or if I should just look for a workaround

#

I'm unwilling to post questions I haven't tried to solve by myself first

#

back to failing at coding 👀

brave oak
#

sure, atb!

oblique panther
#

atb?

brave oak
#

all the best

agile sundial
#

adenosine tri bhosphate

eager hamlet
#

ok so i'm no expert in cryptography
but i was looking at rsa-2048 in https://en.wikipedia.org/wiki/RSA_numbers#RSA-250
and they said that it hasn't been factored yet
but if it is then how the frick did they find it in the first place (ping 2 reply thx)

flat sorrel
#

The organizers have the prime factors and used them to create the number, but the participants don't have it

#

The challenge is for the participants to compute said factors

#

@eager hamlet

pallid phoenix
#

Hello!, si i have a 2D list, every list in the list(there are X*X-1 lists in the list), is a list of 53 values, each value are SA/A/NAD/D and SD, except for the last value, being an email adress, i want to find how many SA/A/NAD/SD there is in total for each email adress so say we take 4 lists, 3 of them have email adress algo@gmail.com, and in the first value for all 3 of its lists it has SA, i want to save 3 to say a list with the name of the column, and then move o nto the next value a bit hard to explain but i've been stuck on making the algorithm for a while now and i would appreciate any help

#

TLDR 2Dlist, list has say 90Lists, these lists have 53 values, for the unique values in spot 53, i want to count all the values in the previous spots for each column, columns SA/A/NAD/D and SDcan have values

twin edge
#

Use Counter data structure

pallid phoenix
#

ooh thank you!, didn't even know it existed so ill go check it out

vagrant condor
#

!code

halcyon plankBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

vagrant condor
#

hey! i'm a bit lost here.
ive got the result of a http links and what i have to do its to update those new links into my previous link.
For that i know that i must use a .get() function.
and i know also that

n = (u.get("href"))

is a dictionary. now when i try to update to the previous link

n[url] = n.get(url,0) + 1

i got traceback because url is a string.
this is my entire code

import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
s = input("Enter position: ")
m = input("Enter count: ")

m = int(m)
while m > 0:
    html = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(html, 'html.parser')
    tags = soup("a")
    m = m - 1
    u = tags[18]
    n = (u.get("href"))
    print(n)
    n[url] = n.get(url,0) + 1
    print(url)
#

what im doing wrong?

#

any help or advice please. thanks in advance 😄

pallid phoenix
#

maybe its because you are adding a string and an int together? if you try n.get(url,0) + str(1)? or n.get(url,0) +"1", or maybe convert the number part of the url to int, add 1, and append it back as a string? @vagrant condor

vagrant condor
#

My n is a string maybe that’s why I have a traceback

#

I think if I try to index the tags it would be easier

eager hamlet
#

so i first made a sliding window and (without considering the second part) just stuffed as many diamonds as possible in one case

#

then i removed those diamonds and did another

#

the thing is it fails for some test cases

#

any help?

#

(my code is in java so idek if i should ask here)

#

(ping if you wanna help plz)

eager hamlet
#

turns out greedy dooesn't work frick

torpid rivet
eager hamlet
#

wait what

#

@torpid rivet you just type them into the console

#

and @clever orbit what have you tried so far?

pseudo pilot
#
Given a set of distinct integers, A, return all possible subsets.

NOTE:

Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
Also, the subsets should be sorted in ascending ( lexicographic ) order.
The list is not necessarily sorted.

can anyone tell me the approach for this using recursion/backtracking?

eager hamlet
#

@pseudo pilot what are the points?
bc this should be like exponential time

pseudo pilot
#

i was able to solve it, but thanks anyways

eager hamlet
#

oh ok

#

well, given a list of numbers, i have to find the sum of a distance between a number and every other number

#

like [1, 2, 3, 4]

#

for 1, it'd be (2 - 1) + (3 - 1) + (4 - 1) = 6

#

and p much the same thing for 2, 3, and 4

#

is it possible to do this with O(n)

#

precomputation for each element?

wraith valve
#

this depends on ur assumptions

#

if u compute each difference before u decide to run ur function

#

ur gonna get ur linear

#

but if u compute ur difference in ur function thats gonna be quadratic

#

i think if u memonize u will prob get slightly better runtime than quadratic

forest sand
#

Guys, I need help

#

I have created a stock price predictor algorithm that predicts the data with 97% accuracy

#

However, it fetches an year old data. How can I make it so that it gets the latest data? cuz the predictions are worthless if they are one year old

brave oak
#

well, given a list of numbers, i have to find the sum of a distance between a number and every other number
@eager hamlet why?

fiery cosmos
#

there is a O(2^n) brute force solution for generating every subset

next swallow
#

Hi everybody. I got a minor problem of extracting list's element. (X X )
I would like to ask how I can remove string from the list if the substring contains non-targeted str?

For example, there is a list.
list = ["aabb","baza","babab","acba","aabbd"]

I want to screen out any string in the list that contains character that is not a or not b and then remove the corresponding string.

So the output will be
list = ["aabb","babab"]
when printed out

How can I use the loop to approach to the output? please help :$

stable pecan
#
In [1]: s = set("abc")

In [2]: s
Out[2]: {'a', 'b', 'c'}

In [3]: s.difference_update("ab")

In [4]: s
Out[4]: {'c'}

In [5]: s = set("a")

In [6]: s.difference_update("ab")

In [7]: s
Out[7]: set()

maybe this will give you an idea

sudden phoenix
#

hello

#

Is there any interactive page for algorithms

#

where I can create them using block

eager cairn
#

happy diwali to indians
🪔

next swallow
#

Thanks @@stable pecan (_ _ )
However, I have no idea on it
As I am not allowed to split the element in the list
The example I given here is just the simplified ver. So
I would like to ask for the code input

#

(_ _ )

stable pecan
#
In [4]: my_list = ["aabb","baza","babab","acba","aabbd"]

In [5]: [set(string).difference("ab") for string in my_list]
Out[5]: [set(), {'z'}, set(), {'c'}, {'d'}]
next swallow
fast arch
#

What's the difference between arrays & Stack?

eager hamlet
#

well clearly the list index is out of range i mean

clever orbit
#

well clearly the list index is out of range i mean
@eager hamlet why

eager hamlet
#

do some debug prints, see why it's like that

clever orbit
#

do some debug prints, see why it's like that
@eager hamlet well i think when i = 0 -> i - 1 = - 1

eager hamlet
#

i mean why are you telling me lol
just go with it and see what happens

#

try and fiddle around with the loops, there's probably some dumb off-by-one error

clever orbit
#

and I don't understand why still out of range

fiery cosmos
#

is there a faster algorithm that finds strings between 2 special strings and adds them to a list? my algo:

def FindBetween(string,a,b,once=False):
    string = str(string)
    i = 0
    start = 0
    end = 0
    active = 0
    found = []
    while i <= len(string): 
        if string[i:i+len(a)] == a and active == 0:
            i += len(a)
            start = i
            active = 1
        if string[i:i+len(b)] == b and active == 1:
            end = i
            found.append(string[start:end])
            active = 0
            if once == True:
                break 
        i += 1
    return found

example:

fruits = "apple lemon orange    apple banana orange    apple pineapple orange"
FindBetween(fruits, "apple", "orange")
[" lemon ", " banana ", " pineapple "]
eager hamlet
#

probably one of -1's or array indexes that makes everything go wonky
and maybe name your variables better names lol
no one can tell what you mean by c or h

forest sand
#

Hey guys! anyone up?

#

I mean is anyone online?

hollow stratus
#

Anyone here good with proving correctness in algorithms?

languid vector
#

@fiery cosmos why didn't use Regex?

wet blade
#

Can anyone help in finding optimized form of below code it is giving TLE, finding length of LIS of list ```py
def lengthOfLIS(nums):
tails = [0] * len(nums)
size = 0
for x in nums:
i, j = 0, size
while i != j:
m = int((i + j) / 2)
if tails[m] < x:
i = m + 1
else:
j = m
tails[i] = x
size = max(i + 1, size)
return size

n,q,s = map(int,input().split())
arr = [int(a) for a in input().split()]
last = 0
while(q):
l,r = map(int,input().split())
l = (l+slast-1)%n+1
r = (r+s
last-1)%n+1
if l>r:
t = l
l = r
r = t
temp = arr[l-1:r]
last = lengthOfLIS(temp)
print(last)
q-=1 ```

fiery cosmos
#

probably one of -1's or array indexes that makes everything go wonky
and maybe name your variables better names lol
no one can tell what you mean by c or h
@eager hamlet even I forgot my own code. only know it when Im coding at the moment. someone in another server said this is faster:

import re


def find_between(string, start, end):
    pattern = re.compile(f"{start}(.+?){end}")
    return pattern.findall(string)
rocky shore
#

can someone guide me how to solve a problem?

fiery cosmos
#

what probelm?

rocky shore
#

i have a problem you have to sign a message with the number of letters that contains the message including the sign with words

fiery cosmos
#

wdym by sign a message?

rocky shore
#

like at the end of your message you add a string like this message contains n times lettre_k,....

#

but you need to take into account what you are adding

fiery cosmos
#

what are you trying to find with your algorithm?

halcyon plankBOT
#

Hey @rocky shore!

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

rocky shore
#

@fiery cosmos i am trying to get a verification in the way that this signature matches the number of letters

#

or char

fiery cosmos
#

have code?

halcyon plankBOT
rocky shore
#

yes

fiery cosmos
#

what do you mean by signature?

rocky shore
#

like a postscript

#

postdata: os animamos a comprobar que: en este mensaje aparece cuatrocientas treinta ycuatro veces la letra a, veinte veces la letra b, doscientas cuatro veces la letra c, ciento dosveces la letra d, quinientas setenta y tres veces la letra e, veintisiete veces la letra f,veintitrés veces la letra g, dieciséis veces la letra h, ciento ochenta y tres veces la letra i,veintiséis veces la letra j, tres veces la letra k, ciento ochenta y seis veces la letra l, cientocinco veces la letra m, doscientas treinta y ocho veces la letra n, cinco veces la letra ñ,doscientas doce veces la letra o, cincuenta y nueve veces la letra p, treinta y una veces laletra q, doscientas cuarenta y siete veces la letra r, doscientas cincuenta y una veces laletra s, doscientas veintiuna veces la letra t, ciento trece veces la letra u, sesenta y sieteveces la letra v, una vez la letra w, seis veces la letra x, veintisiete veces la letra y, y onceveces la letra z

fiery cosmos
#

is there a specific snippet of code you need help on or is it the whole thing?

rocky shore
#

no i have to code an algo to find a signature that is valid

#

for any given message

fiery cosmos
#

where is the signature located?

rocky shore
#

def firmar_mensaje(mensaje, conteo)

#

it gives u the signature for the message but you have to somehow take into account the signature so that message + signature contains the number of letters that the signature specifies

fiery cosmos
#

so all you need to do is find out if both the message string and the signature string are the same size?

rocky shore
#
  • if it contains the same nmber of letters
#

the signature is of the form "this mesagge contains four houndred times the letter e , etc"

#

take this msg: Buenas tardes

#

output: Buenas tardes; en este mensaje aparece dos veces la letra e

#

but the message contines more than two time the letter e

#

ill translate

#

Good morning; in this message the letter e appears two times

cobalt sedge
#

Could anyone help me with this? I am pretty confused with this question...

I was thinking like Bob will refill the water when he reaches the oasis... and the volume of water will equal to the distance between the current oasis and the next oasis

fiery cosmos
#

@rocky shore

import re
def find_between(string, start, end):
    pattern = re.compile(f"{start}(.+?){end}")
    return len(pattern.findall(string))

this function finds the number of times a string was found between 2 special strings. is this what you wanted?

#

I dont think I can be of help much because I lack Spanish skills. maybe someone who speaks the language here will help you?

rocky shore
#

ok thx

worthy breach
#

hello im trying to write a recursive function that can take a number and return 1 if the sum of digits is even and 0 otherwise...

#

i managed to write a function that can get the sum recursively but i dont know how to check if the answer is even before using a return statement

#

im implementing the function in c but any help even if in python would be appreciated

#
int even_sum(int num)
{
    int sum,dig;
    if (num == 0)
        return 0;
        
    
        
    dig = num % 10;

    sum = dig + even_sum(num / 10);

    return sum;
}```
fiery cosmos
#
def sum(n):
  if n < 10:
    return n
  return n % 10 + sum(n//10)

def check(n):
  if sum(n) % 2 == 0:
    return 1
  return 0
worthy breach
#

sorry i probably should have mentioned it should be one function @fiery cosmos

#

thank you for the answer btw!

fiery cosmos
#

oh I see

#

then

#
def sum_and_check(s, n):
  if n == 0:
    if s % 2 == 0:
      return 1
    return 0
  return sum_and_check(s + n % 10, n//10)
worthy breach
#

o i see!

#

very nice

#

thanks for the help

#

im assuming u first call s as 0 right?

fiery cosmos
#

yep :)

worthy breach
#

awesome, never thought of taking advantage of using another parameter

#

could come in handy often

#

i dont know if the person checking my homework might appreciate it but i do XD

fiery cosmos
#

just code more

#

you will get to know more shortcuts

tender crest
#

I'm storing a NxN matrix in a file (2D list) and I need a way to rotate it by 90 degrees, i.e.:
from:

1 2 3 4
5 6 7 8
9 0 0 0
1 1 1 1

you'd get:

1 9 5 1
1 0 6 2
1 0 7 3
1 0 8 4

This could be easy if I just loaded the list into a python list and did something like: list(zip(*reversed(lst)))
Problem is that this 2D list is way too big to load it whole into memory so that's not possible.

The way I'm storing this list is basically in "blocks" in which the matrix is flat, each block containing certain amount of data (let's call this amount b), so basically for the example above, with block size of 2 the stored list would look like this: [1, 2], [3, 4], [5, 6], [7, 8], [9, 0], [0, 0], [1, 1], [1, 1]

I need some meaningful way to rotate this list without loading too many blocks into memory.
The storing works in a way where the amount of data each block can contain (b) is known and n (size of matrix) is also known and it will always be a multiple of b

I figured I could just go through these elements, get the block they're in, read it, get the element from that block, store it and get the block in which the corresponding element number (after rotation) would be. Then just swap those and write them back. Problem is that this would make way too many calls to write and read (2xN^2) calls to read and another (2xN^2) for write, which would be way too slow. Is there a more meaningful way to do this than just going through every element, finding the rotate pos and swapping it directly?

clever orbit
#

my sorting doesn't work

fiery cosmos
#

do you need to implement a sorting algorithm on your own?

clever orbit
#

do you need to implement a sorting algorithm on your own?
@fiery cosmos yes

#

it gives
A.sort(key=lambda k: k[0]) TypeError: 'int' object is not subscriptable

fiery cosmos
#
  1. your count of inversions is too slow
#

n goes up to 10^6

#

also you need to sort a and b combined

clever orbit
#

i think i need total run time O(n lo n)

#

also you need to sort a and b combined
@fiery cosmos how please ?

fiery cosmos
#

so

c = [[fi, se] for fi, se in zip(a, b)]
c.sort()    # by default it is sorted based on first element
clever orbit
fiery cosmos
#

yeah they assumed arr is list of pairs

#

but in your code a is list of integers not list of pairs

azure nymph
#

can I ask scripting question to read data from a csv file here?

fiery cosmos
#

there is csv module for that

#

@azure nymph

azure nymph
#

@fiery cosmos thank you

#

I did not clariffied my question, I wanted to use regex to search for certain passwords in a csv file using python script. I got it to work but my regex is not matching the right characters.

fiery cosmos
#

So i want to look for a item in inventory with this code for thing in users[str(user.id)]["inv"]: n = thing["item"] a = thing["amount"]
but i want it to only look for the item fishingrod. how can i do that?
right now it scans al the items but i want to make it so it only looks for fishing rod and the ammount of fishingrods a person has

{"728265216453771274": {"wallet": 12839.0, "bank": 0, "inv": [{"item": "apple", "amount": 1}, {"item": "fishingrod", "amount": 0}]}

#

idk if i put this here

clever orbit
#

so

c = [[fi, se] for fi, se in zip(a, b)]
c.sort()    # by default it is sorted based on first element

@fiery cosmos thx so the sorting i did isn't needed ?

shrewd cradle
#

What's a good data structure in Python for one-to-one mappings?

#

Kinda like a dictionary but all the values are also unique and I want to get the key using the value

#

The keys and values are guaranteed hashable

#

I guess Enum does the job but I'm not sure how efficient it may be fore large datasets

stable pecan
#

might be best to make your own class for this

stable pecan
#
class OneToOne:
    def __init__(self, **kwargs):
        self._keys_to_values = {}
        self._values_to_keys = {}

        self.update(kwargs)

    def update(self, other):
        for key, value in other.items():
            self[key] = value

    def __setitem__(self, key, value):
        keys = self._keys_to_values
        values = self._values_to_keys

        if value in values:
            raise ValueError(f"{values[value]} already mapped to {value}")

        try:
            values.pop(self[key])
        except KeyError:
            pass
        keys[key] = value
        values[value] = key

    def __delitem__(self, key):
        keys = self._keys_to_values
        values = self._values_to_keys

        values.pop(keys.pop(key))

    def __getitem__(self, key):
        return self._keys_to_values[key]

    def __repr__(self):
        return repr(self._keys_to_values)

    def getkey(self, value):
        return self._values_to_keys[value]

something like this

#

@shrewd cradle

shrewd cradle
#

Ah thanks! Lemme try to understand this...

stable pecan
#

the __setitem__, __delitem__, __getitem__ dunder methods allow you to access it like a dictionary

#
In [2]: o = OneToOne()

In [3]: o[1] = 2

In [4]: o[3] = 2
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-67a184e225d8> in <module>
----> 1 o[3] = 2

~\Documents\Python\sacks\bijection.py in __setitem__(self, key, value)
     15
     16         if value in values:
---> 17             raise ValueError(f"{values[value]} already mapped to {value}")
     18
     19         try:

ValueError: 1 already mapped to 2

In [5]: del o[1]

In [6]: o[3] = 2

In [7]: o._keys_to_values
Out[7]: {3: 2}

In [8]: o._values_to_keys
Out[8]: {2: 3}
#

well, that's just playing around with it --- i don't guarantee no bugs

shrewd cradle
#

I get the general idea 😄

zenith creek
#

trying to get some help on a topic - do I post here or do I just grab a help channel and start posting there??

latent cradle
#

Hey guys, I have a question with linked lists. Can someone help me in #help-pancakes?

fresh arch
cobalt sedge
#

Can anyone help me with this?

All I can think of is a more than O(n^2) method...

My idea is to put v in a max heap, and for any time that Bob does not have enough water to proceed, extract max until he has enough water to proceed but it seems that it takes O(n^2logn) time to do it

#

And the most thing that disappointed me is that i only got 3 more days to do it and 4 more questions need to be solved. I've tried to use chegg but it seems to have lots of fake answer... fml

sweet cipher
#

Why default dict takes a callable , it's very easy Directly assign a default value?

mint jewel
#

consider having a defaultdict of lists

#
a = []
k = defaultdict(a)
k[3].append(4)
print(a)
#

a would be [4] in this case

#

which is very often not what you want

sweet cipher
#

May be for instantiation of lists or any data type for functions as well

oblique panther
#

@mint jewel I don't think that would work because it would be calling __call__ on the list instance, yes?

#

it would have to be defaultdict(list) to get a new list each time, or defaultdict(lambda: a) to get a reference to a every time

mint jewel
#

as I understood his question, he was asking why does defaultdict need a function, so this was an example if it were to just take a value

stable pecan
#

also you can just use k.setdefault for that behavior

sweet forge
#

Hello?

oblique panther
#

@sweet forge hi

sweet forge
#

thanks for responding

#

I was told to come here by member

#

I am currently live on the help-copper forum

oblique panther
#

Were you going to ask a question? You can always just ask and people who are here can take a stab at it.

sweet forge
#

its not more of a question more can you explain it potentially?

oblique panther
#

I can try. I'm semi-afk

sweet forge
#

hi any help is appreciated thanks

#

think it isnt live any more Ill post it here

oblique panther
#

If you're sure you're done with that channel, remember to !close it

sweet forge
#

yeah Ill do that now

#

no worries

chrome needle
#

hey guys, someone could help me to create this data interpreter?

I have one matrix of 7 columns and 6 lines (7x6)
and each one has a matrix of 1000 x 1000 inside.

the total matrix is 7000 x 6000 (42.000.000 possibilities)

how can i translate the 'local coordinates' to the 'global coordinates' ?

it's not some data science basic question, the root of this is very simple, imagine a huge retangular grid of 7 x 6 with 1000 x 1000 matrix inside each segment

#

when I select the "major element (one of the 42 parent elements)" i want to be able to return 2 lists of 2 objects

[global_x, global_y], [local_x, local_y]

chrome needle
#

solved 😄

vagrant condor
#

hey guys

#

im having a trouble with the .get() function

#

!code

halcyon plankBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

vagrant condor
#
u = tags[s]
    url1 = u.get(url)

i just want to use the .get() to update my new link that i found.
i know that inside the .get() i must use the previous url so the variable stores
when i print url1 i recive None in my output.

#

really i have been struggeling with this issue for days

vagrant condor
#

😫

trim fiber
#

@vagrant condor what is u? Is it a dict or what?

burnt hamlet
sweet forge
#

Hello was wondering if anyone could help me with this code error just trying to get it to run but it says
IndentationError: unindent does not match any outer indentation level

#

line 18

fiery cosmos
#

can you share your code?

sweet forge
fiery cosmos
#

I'll peek into it

sweet forge
#

sorry line 14

#

thanks

fiery cosmos
#

I'll peek into it

sweet forge
#

really appreciate it those returns are ment to be outside the loop aswell sorry

fiery cosmos
#

it is running fine on my machine 🤔

#

It doesn't produce any output tho

sweet forge
#

may thats it how do I get an output is that the print function

#

maybe

fiery cosmos
#

are you trying this on a Jupyter Notebook?

#

can you show the screenshot of the error

sweet forge
#

yeah ill do that give me a sec

fiery cosmos
#

remove that 4 space above return

sweet forge
#

synatxerror

foggy drift
#

I would help

#

But I'm a beginner

#

😩

sweet forge
#

so am I lol

fiery cosmos
#

now give 2 spaces before return

sweet forge
#

actually go that sorted

#

sorry

#

saying this

fiery cosmos
#

yeah you are not indenting line 17

sweet forge
#

sorry my coding skills aint the best what does that mean lol

fiery cosmos
#

like you need to add spaces for that return statement

#

add 2 spaces on line 17

#

like this

def function():
  ....
  ....
  return ...
#

see how return is inside the function

sweet forge
#

aww ok is mine outside I guess then

#

aww ok is mine outside I guess then

fiery cosmos
#

yeah

sweet forge
#

ill try that and get back to ye

rocky shore
#

how to a *?

#

a star

#

anyone can help?

crystal birch
#

hello people.. I had a need.

#

I want to initialise a list of a givent size

#

if 4 : mylist = (0, 0, 0, 0)

#

if 5 : mylist = (0, 0, 0, 0, 0)

#

someone knows how to do that without an iteratioN ?

#

gotcha

#

a = (0,) * 15

a
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

agile sundial
#

that's not a list btw, that's a tuple

crystal birch
#

and you are right.. () tuple [] list

lunar jacinth
#
class Node(object):

    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None


class BinarySearchTree():

    def __init__(self, root: Node):
        self.root = root

    def insert(self, node: Node):
        current = self.root
        while current.data is not None:
            if node.data < current.data:
                current = current.left
            else:
                current = current.right
        current = node
#

can someone tell me whats wrong with this code please?

#

I'm trying to make a binary search tree

#

i have to use isnert there somewhere?

#

like would it be insert(current.left)?

somber kiln
#

I have a ReDoS report from dlint but I suspect it's a false-positive, could anyone confirm?
The regex: ^POLYGON ?\(\([0-9 .]+\)(, ?\([0-9 .]+\))*\)$
(also #help-falafel)

#

there are two identical groups in there but I don't see how it could be DoS
(is ^POLYGON ?\(group(, ?group)*\)$)

minor chasm
#

i have to use isnert there somewhere?
@lunar jacinth what u mean by insert there somewhere ??

#

like use that method ?

buoyant pine
#

hey

twin edge
#

What bs tree should I choose for rope data structure?

fiery cosmos
#

hi

fleet plume
#
class Node(object):

    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None


class BinarySearchTree():

    def __init__(self, root: Node):
        self.root = root

    def insert(self, node: Node):
        current = self.root
        while current.data is not None:
            if node.data < current.data:
                current = current.left
            else:
                current = current.right
        current = node

@lunar jacinth Your while loop condition should be while current is not None: or while current: because we insert at leaf nodes, leaf nodes are denoted by None. Also, you need two node pointers, current and parent_of_current to enable you to insert a new node in correct location. BST = Node or Leaf where Node is Node, Leaf is None

ruby pumice
#

hi , please it there any ressource to learn the binary tree I got stuck with it can't understand it very well ?

solid rune
foggy drift
#

Yee

raw bridge
#

can someone explain how merge sort works? just the process, i didnt understand from geeksforgeeks

agile sundial
#

which part?

raw bridge
#

oof sorry for late reply, ik that it divides it and then merges, but what does it do after it has reached the part where it cant split anymore

agile sundial
#

if you can't split anymore, then your section has one element

#

a list of one element is always sorted

raw bridge
#

yeah, then how do we get a sorted list when we merge

#

i mean, when it merges, how does it take care of the order

agile sundial
#

i mean

#

try coming up with something that can do that

raw bridge
#

does it compares the other parts which have been splitted and are at the point of having just one element ?

#

and then keeps the order based on the comparison

#

smaller number first

agile sundial
#

pretty much

raw bridge
#

ah i see, i thought this was done without comparing

#

thanks

fiery cosmos
#

the order is taken care when you merge
merge takes 2 sorted lists and merges them

night socket
#
>>> def cvi(c, n, x):
...     divisor = 0
...     dividendo = 0
...     for i in range(len(x)):
...         for j in range(len(x[i])):
...             dividendo += c[i] * n[i] * x[i][j]
...             divisor += c[j] * n[j]
...     return dividendo / divisor
... 
>>> a
[1, 2, 3]
>>> b
[2, 3, 4]
>>> x
[[1, 2, 3], [2, 3, 4]]
>>> cvi(a,b,x)
1.65
>>> 
#

is this alg right for the above formula?

#

i have the understandig that the formula would be like this code i sent

#

my friend says is something like {

n = 3
c = 5

CVI = ( x11+x21+x31 + x12+x22+x32 + x13+x23+x33 + x14+x24+x34 + x15+x25+x35) / (n1+n2+n3+n4+n5)
#

now we are in doubt

#

can someone light our issue?

fiery cosmos
#

@night socket why are c, n lists?

night socket
#

i suposed theyre lists

#

because the formula uses a sum

#

of elements

#

dont it?

fiery cosmos
#

no according to the formula c,n are constants

night socket
#

i may be wrong

fiery cosmos
#

you know when you write a summation in math you normally iterate only indices from start to end

night socket
#

from 1 to c

#

so the second is right?

fiery cosmos
#
def cvi(c, n, x):
    divisor = 0
    dividendo = 0
    for j in range(c):
      for i in range(n):
          dividendo += x[i][j]
      divisor += n[j]
    return dividendo / divisor
#

yeah the second one is right

#

also note the changes to the code

#

divisor should be not indented to second for loop

#

because you will be adding n[j] i times

night socket
#

i see

#

thank you

fiery cosmos
#

ping me if you got any more issues

#

or the implementation is wrong

night socket
#

ty

#

i will

halcyon rain
#

hi

#

i am stuck with my home work problem on algorithm

#

can someone help me

#

i tried googling and youtube.. still

fiery cosmos
#

17 is easy

#

you just need to code a function called hash and send 'boneyhun' into it

#

the code would look like this

#
def hash(s):
  n = len(s)
  hashed_result = 0
  for i in range(n):
    hashed_result += (128 ** (n - i - 1)) * ord(s[i])
  return hashed_result
#

and 18 seems like you return 7 for every integer

#

so whatever you hash it gets chained into a list

#

so searching would take O(n)

#

illustration

[7] => [1, 34, 43,4, 3,123, 454,5]
#

@halcyon rain do you understand?

halcyon rain
#

i just tried to code that function

#

understood very well

#

thanks a lot

halcyon rain
#

22 is key staple

#

23 .. yes

#

20 and 21 i have no idea

#

reply only when anyone is free, no hurries. thanks again

#

also pls check my answers for 22 and 23

tropic oxide
#

so for an assignment i got a massive JSON with every game on steam in april 2019

#

and i don't necessarily need to

#

but i'm trying to make every game into an actual object

#

but i want the objects to be named after their appId+g ultimately

#

and this is probably not the best place to putthis

#

but i don't understand how to generate a lot of objects

#

or is that just a bad idea

fiery cosmos
#

Whats heap sort

#

Could i send my sort code

agile sundial
#

sure

#

heap sort involves creating a min/max heap and popping elements off the root

fiery cosmos
#

what max heap mainly about

agile sundial
#

it's a smart way to store data

fiery cosmos
#

no the max word

agile sundial
#

the max element is at the root

fiery cosmos
#

Aha

hoary scarab
#

I'm having a little trouble with wording
I am trying to look up an algorithm for picking an element from an array but some elements are harder to get than other elements
Like in games that has a [Normal, Rare, Super] type of system... What to google?

vernal venture
hoary scarab
#

Just like a percentage of the chances to acquire that item.
For example:

Name      | Rarity
-------------------
Bulbasaur | 1
Ivysaur   | 1
Venesaur  | 0.5
Charizard | 0.25
vernal venture
hoary scarab
fast walrus
#

Has anyone tried interviewespresso.com for algorithms and data structure interview prep? How is the material covered? Good enough for the interview readiness?

fiery cosmos
sly lotus
#

anyone know how to type a search algorithm on students interests then group them based on their interests

raw bridge
#

you should make b a copy of a

#

b = a.copy()

#

other wise your code will take effect on both the lists

kindred ermine
kindred imp
#

i'm trying to traverse a data structure

#

wondering if there's a neater way of doing this

#

i can't access the help channels for some reason

agile sundial
#

you have a cooldown, which means you have one open already

kindred imp
#
def traverse_tree(root_node,dict_pairs):
    if root_node not in dict_pairs.keys():
        return f"{root_node}"
    elif len(dict_pairs[root_node]) == 1:
        return f"{root_node}({traverse_tree(dict_pairs[root_node][0],dict_pairs)})"
    elif len(dict_pairs[root_node]) == 2:
        if dict_pairs[root_node][0] < dict_pairs[root_node][1]:
            return f"{root_node}({traverse_tree(dict_pairs[root_node][0],dict_pairs)})({traverse_tree(dict_pairs[root_node][1],dict_pairs)})"
        else: 
            return f"{root_node}({traverse_tree(dict_pairs[root_node][1],dict_pairs)})({traverse_tree(dict_pairs[root_node][0],dict_pairs)})"```
kindred imp
#

there

#

s a problem

agile sundial
#

hm, let me ask about it

#

although, this channel is a pretty good place to ask

kindred imp
#

I am trying to build an s-expression to represent a tree

#

turn this (B,D) (D,E) (A,B) (C,F) (E,G) (A,C)
into
(A(B(D(E(G))))(C(F)))

#

so my cleaned nodes then returns this ```return f"({traverse_tree(list_root_nodes[0],dict_pairs)})"

#

starts with the very top node and builds out the expression

#

it works, but i was just wondering if there's nicer way

fiery cosmos
#

The tuple represents the connections?

kindred imp
#

this is the complete code i have written

fiery cosmos
#

no I mean (B, D) does it mean B is connected to D?

#

and A is always the root?

kindred imp
#

yes

#

i have a code lenth limit

#

sorry, let me remove some chsrs

halcyon plankBOT
#

Hey @kindred imp!

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

#

Hey @kindred imp!

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

kindred imp
#
def sExpression(nodes):
    # Write your code here
    list_root_nodes, list_parent_nodes, list_child_nodes = [], [], []
    dict_pairs, dict_parent_nodes, dict_child_nodes = {}, {}, {}
    max_children = 2
    max_child_nodes = 1
    
    # error codes
    error_codes = {"E1": "More than 2 children",
        "E2": "Duplicate Edges",
        "E3": "Cycle present (node is direct descendant of more than one node)",
        "E4": "Multiple roots",
        "E5": "Any other error"}
        
    # create a list of unique nodes
    unique_nodes = [(node[1], node[-2]) for node in pd.unique(nodes.split())]
  
    # Populate the node dictionaries
    for n, node in enumerate(unique_nodes):
        list_parent_nodes.append(node[0])
        list_child_nodes.append(node[1])
        
        # count parent nodes
        if node[0] not in dict_parent_nodes:
            dict_parent_nodes[node[0]] = 1
        else:
            dict_parent_nodes[node[0]] += 1
            
        # count child nodes
        if node[1] not in dict_child_nodes:
            dict_child_nodes[node[1]] = 1 
        else:
            dict_child_nodes[node[1]] += 1
        
        # create the pairs dictionary
        if node[0] in dict_pairs.keys():
            dict_pairs[node[0]].append(node[1]) # append the child node
        else:
            dict_pairs[node[0]] = [node[1]] # parent = chiild```
#
    # build a list of root nodes
    list_root_nodes = [node[0] for node in pd.unique(list_parent_nodes) if node not in list_child_nodes]
    
    # store the length as I check this more than once
    len_root_nodes = len(list_root_nodes)
    
    #check for errors
    if any([True for k, val in dict_parent_nodes.items() if val > max_children]):
        return "E1" # error_codes["E1"]
    if len(nodes.split()) > len(unique_nodes):
        return "E2" # error_codes["E2"]
    if any([True for k, val in dict_child_nodes.items() if val > max_child_nodes]) or len_root_nodes == 0:
        return "E3" # error_codes.keys["E3"]
    if len_root_nodes > 1:
        return "E4" # error_codes["E4"]
    
    # recurse through the tree and return the lexicographically smallest way oxpressing the tree
    return f"({traverse_tree(list_root_nodes[0],dict_pairs)})"```
#

thats the full function

#

which calls traverse_tree

fiery cosmos
#

how is the input taken

kindred imp
#

(B,D) (D,E) (A,B) (C,F) (E,G) (A,C)

#

thats theinput

fiery cosmos
#

okay tuples with spaces

kindred imp
#

this is th eoutput
(A(B(D(E(G))))(C(F)))

#

the whole thing works, just wondering i can make the traverse_tree clener

fiery cosmos
#

hmm I made the code 16 lines tell me if it is understandable

from collections import defaultdict

edges = input().split()
tree = defaultdict(lambda : [])

for edge in edges:
    tree[edge[1]].append(edge[3])

def dfs(root):
    rep = "(" + root
    for child in tree[root]:
        rep += dfs(child)
    rep += ")"
    return rep

print(dfs("A"))
#

@kindred imp is this understandable?

#

I didnt write comments to make it more clear

#

you need to know 2 things

  1. How to traverse the tree - Here dfs should be used
  2. How to store the tree efficiently - This is done by popular adjacency list
    both are easy to learn
kindred imp
#

Thx

kindred imp
#

@fiery cosmos Taj KS that’s really helpful

craggy ermine
#

Hey, I have more of a math problem than a python one, but I'm trying to figure out if my issue is worth trying to solve in numpy rather than pure python:

I have an object that gives me values based on input. It's effectively a kind of transformation where if I give it (10, 12, 1, 3), it might give me (1, 4, 0.3, 0.003). The real meaning of these numbers is a bit complex (involving chemistry), but the issue is that when one number gets very close to zero (and they can not be negative), the solver starts to freak out and give errors because part of the calculations involve logarithms of the input. I need to be able to either be able to handle logarithms (some way of representing infinity or zero) or deal with exploding numbers. I know numpy can handle -inf, but the solver I'm using is SciPy's LM-BFGS, and I don't know how it will handle this.

My question is: Will numpy -inf terms be handle-able in scipy solvers, and does anyone have any suggestions for me to try for alternative methods of handling complex iterative solutions?

#

My field is membrane chemical engineering, so I'm solving concentration profiles of multicomponent mixtures

tulip plinth
#

Hey would u guys say learning data structures and algorithms is important for being a data scientist

craggy ermine
#

yes...

#

@tulip plinth

tulip plinth
#

Um should I go in depth or just understanding the basics is enough ??

#

Like I know how to create a linked list and how it works

#

Should I learn more about it ?

craggy ermine
#

It really just depends on what you're doing

tulip plinth
#

Well tbh when I’ve been doing project related to ML or DL

#

I haven’t used data structures that much

#

ppl are like even thou u don’t use it just learn the basics of it

#

Wat do u think ??

fiery cosmos
#

you will learn those in university, but a start now won't hurt

tulip plinth
#

well I’m in uni but not a cs student that’s why

fiery cosmos
#

then you need to understand the basics

#

it may or may not come along in your ML or AI part

unique minnow
#

any good resources for DSA for a beginner ?

fiery cosmos
#

Im using import socket to create a sever on python , I got the code from a youtube video and im trying to run it on my cmd. What I dont understand is I use a certain port number and I got the error sock.bind(('0.0.0.0', 10000))OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted . Also when I connect to a sever and I try to do telnet , I seem to be stuck in a infinite loop. Then I close the cmd , does this leave the server unclosed or something ? Could someone try explain to me what im doing wrong

pseudo fog
#

It will be free after some time, but you can search for how to reduce the wait time

fiery cosmos
#

@pseudo fog how do stop or reduce the wait time ?

pseudo fog
#
fiery cosmos
#

@pseudo fog I tried ,but got this error . What am I doing wrong ?

pseudo fog
#

like if PID is 13201 then you have to write taskkill /f /im 13201

fiery cosmos
#

taskkill /f /im 8080[PID of the port 8080 got from previous command]

#

like this ?

frigid cypress
#

Hi guys. I was wondering if anyone could give me a pointer on how to keep track of objects. I assign the objects like

for index, row in sdf.iterrows():
    tmp = station(row[3],row[6],row[7],row[4])
                  #ID , #Long, #Lat, #Numer
    listOfStations.append(tmp)

When adding values to the objects later on, I run this stupid thing... ^^

# sId and eId passed from func
for s in listOfStations:
        if s.getId() == sId:
            s.updateChange(-1)
            sId=False
        if s.getId() == eId:
            s.updateChange(1)
            eId=False
        if not sId and not eId:
            break

So I guess that alot of stuff can be done to optimalize the code, but my question is if i can do a lookup on object id? I guess i could do a dict like {'Id':Obj1,'Id2':Ob2.... }
But how do do this most effective?

fiery cosmos
#

@pseudo fog If I want to kill 8080 , what should I enter ?

pseudo fog
fiery cosmos
pseudo fog
#

first use netstat -ano | findstr :8080 command

fiery cosmos
#

okay done and nothing returned

pseudo fog
#

Then your port 8080 is already free

fiery cosmos
#

okay bare with me , I run my program and im still getting the same error

#

Will I show you my program ?

pseudo fog
#

Yes please

fiery cosmos
#

@pseudo fog any idea ?

pseudo fog
#

According to the error you previously stated, it's port not free only

#

try after changing port in the code

fiery cosmos
#

@pseudo fog Sorry what do I change ?

lean glade
#

I made this quicksort function (just learning, so it's not the best at all), and I made this swaps variable for to know how many swaps have been done, but Im pretty sure I did it wrong, because it's giving me insane numbers. def quickSort(k,swaps=0): n=len(k) if n==1 or n==0: return k,swaps pivot=k[-1] i=0 for j in range(n-1): if k[j]<pivot: k[j],k[i]=k[i],k[j] i+=1 swaps+=1 k[i],k[-1]=k[-1],k[i] swaps+=1 k[:i],swap=quickSort(k[:i],swaps=swaps) swaps+=swap k[i:],swap=quickSort(k[i:],swaps=swaps) swaps+=swap return (k,swaps)

#

For a list of 100 shuffled numbers, it said it did 16412864521840461437626774873808948705 swaps, and I'm pretty sure that's wrong

agile sundial
#

yeah that's wrong

lean glade
#

How can I fix it?

#

Oh nevermind, I think that taking out the swaps=swaps keyword when I did the recursion fixed it

pliant crane
#

<@&267629731250176001> i am supressed in every voice channel is this normal

#

or am i being heavily trolled by someone

torpid crown
#

We have created a voice verification system to increase quality of messages sent and too keep trolls out of voice. See #voice-verification for more info.

pure terrace
#

Hello I want to prevent users from entering level command before nick command. I'm using the following code to do that: https://mystb.in/WorseAugHack.python, but apparently if conditional doesn't work as expected because else statement doesn't get triggered when I type level command before nick. Ty in advance, any help is very welcome.

fiery cosmos
#

So ill answer it in a different way

#
def quick_sort(arr):
  if arr == []:
    return []
  mid = arr.pop()
  big, small = [], []
  for i in arr:
    if i > mid: big.append(i)
    else: small.append(i)
  return quick_sort(small) + [mid] + quick_sort(big)
lean glade
#

Oh that's waay nicer and more understandable than what I was doing

fiery cosmos
#

thanks man

lean glade
#

Thanks!

fiery cosmos
#

side note: find the worst case complexity

#

I actually learned it form Derrick Sherrill

fiery cosmos
lean glade
#

Who is he?

lean glade
lean glade
fiery cosmos
#
def heapify(arr, n, i):
    largest = i  # largest value
    l = 2 * i + 1  # left
    r = 2 * i + 2  # right
    # if left child exists
    if l < n and arr[i] < arr[l]:
        largest = l
    # if right child exits
    if r < n and arr[largest] < arr[r]:
        largest = r
    # root
    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]  # swap
        # root.
        heapify(arr, n, largest)


# sort
def heapSort(arr):
    n = len(arr)
    # maxheap
    for i in range(n, -1, -1):
        heapify(arr, n, i)
    # element extraction
    for i in range(n - 1, 0, -1):
        arr[i], arr[0] = arr[0], arr[i]  # swap
        heapify(arr, i, 0)


# main
n = int(input())

arr = input().split()  # [2, 5, 3, 8, 6, 5, 4, 7]

heapSort(arr)
map(float , arr)
for i in range(n):
    print(arr[i])

#

here is my code

sweet cipher
#

Why isn't bool an iterable it would be very helpful in cases with any(...) syntax? Will python core-devs make booleans an iterable objects, just out of curoisty asking

fiery cosmos
#

i want to get mean of evrey iteration of the array

sweet cipher
#

They didn't answer so here i tried

#

Nope

fiery cosmos
sweet cipher
#

Why boolean objects are not iterable I mean

fiery cosmos
#

why shoud be

sweet cipher
#

For optimization purposes

fiery cosmos
#

so ur like

#

for i in range(True):

#

that just doesn't make sense

#

idk

#

then its abtually a list

#

not boolean

#

and list are iterable

#

ye, thats what he was asking for

#

sort of

#

To make Booleans iterable

#

hmm

snow swift
#

uh how would iterating over a bool work

#

how do you iterate over a single value

#

@sweet cipher

flat sorrel
#

It appears that they have gotten their question answered if you look at their* chat history

agile sundial
#

it still makes no sense

lean forge
#

hi

hot bobcat
#

you are creating new arrays each iteration making it more complex in space

hot bobcat
eager hamlet
fiery cosmos
#

how can I make a key function that I can pass into the sort function? i have a list of tuples that i wanna sort and the key is the sum of the elements in the tuple

#
# tried smth like this but i m stuck
def suma(tuplu):
    return tuplu[0] + tuplu[1] + tuplu[2]

sortare = suma()

tupluri = sorted(tupluri, key=sortare)
topaz pulsar
#

@fiery cosmos you can just use key=sum, but for your own custom functions you would pass it as key=suma in your case

fiery cosmos
#

it wants me to put a parameter

topaz pulsar
#

it just passes each item to the key function and sorts by the value that it returns

fiery cosmos
#

should i delete tuplu

#

from the function parameter?

topaz pulsar
#

don't try to call it wiht (), just pass the function name like in my example

fiery cosmos
#

without sortare?

#

huh, it worked

#

what s the philosophy behind this

topaz pulsar
#

you don't need it, no, you can use it but sum would also work

#

like I said, if you pass a key argument, you can think of it instead of comparing items as if item1 < item2: ... it does if key(item1) < key(item2): ...

fiery cosmos
#

so the parameter will be automatically the element from the list

topaz pulsar
#

yep

fiery cosmos
#

I got confused because I saw examples that passed a function through a variable

#

but that function was a lot of nested functions actually

#

that was doin' a lotta things once

#
def cheie_cmmdc(t):
    def cmmdc(element):
        while t != element:
            if t > element:
                t -= element
            else:
                element -= t
    
        return t

    def cmmdc_aux(element):
        return cmmdc(t, element)

L = [20,18,46,100,90,35,8,11]
t = 4
sortare = cheie_cmmdc(t)
L = sorted(L, key=sortare)
print(L)
``` smth like that
topaz pulsar
#

afaik, key can be any callable that requires one positional argument (and optionally uses default arguments)

#

that works because cheie_cmmdc(t) returns another function so sortare is still callable

#

actually it doesn't in that case, there is on return inside the outer function so i'm not sure how that works

fiery cosmos
#

hmmm

#

thank you

lean glade
#

Well, it seems that my attempt at implementing an iterative quick sort was a complete and utter failure.

#

100x slower than the recursive one I implemented

#

lol

#

Might as well die

eager hamlet
#
with open('cowcode.in') as read:
    theString, charNum = [i for i in read.readline().split()]
    charNum = int(charNum)


def findChar(position: int, findIn: str) -> str:
    if position <= len(findIn):
        return findIn[position - 1]

    currTwoPower = 0  # this will be how many times we'll have to apply it (given that the original string's there alr)
    while True:
        currTwoPower += 1
        if position <= 2 ** currTwoPower * len(findIn):
            break
    lowerBound = len(findIn) * 2 ** (currTwoPower - 1)

    if position == lowerBound + 1:
        return findChar(lowerBound, findIn)  # bc of the rotation
    return findChar(position - lowerBound - 1, findIn)


with open('cowcode.out', 'w') as written:
    answer = findChar(charNum, theString)
    print(answer)
    written.write(str(answer) + '\n')
#

this works

#

but i have no idea why (i wrote it like 4 months ago)

#

programmer pain

#

does anyone know why? (ping 2 reply plz)

lunar jacinth
#

hey guys, im trying to make an undirected graph(ADT) using linkedlists

#

and i was just wondering if i could get some help with my add_vertex function?

#


class Node:

    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next


class LinkedList:

    def __init__(self):
        self.head = None

    def append(self,data):
        if not self.head:
            self.head = Node(data)
            return None
        curr = self.head
        while curr.next:
            curr = curr.next
        curr.next = Node(data)


class Vertex:

    def __init__(self, id):
        self.id = id
        self.neighbors = LinkedList()

    def add_neighbor(self, neighbor, weight=0):
        self.neighbors.append({neighbor: weight})

    def get_connections(self):
        return self.neighbors.keys()

    def get_id(self):
        return self.id

    def __str__(self):
        lst = []
        for x in self.nieghbors:
            lst.append(x.id)
        return "vertex ID: " + str(self.id) + "is neighbor of " + str(lst)


class Graph:

    def __init__(self):
        self.vertList = {}
        self.vertices = 0

    def add_vertex(self, val):
        self.vertices += 1
        newV = Vertex(val)
        self.vertList[key] = newV
        return newV
#

if someone does help , can you just @ me?

atomic mulch
#

why does everyone shit on java

dense ibex
#

i feel that there are more appealing languages

stable pecan
#

either way it's offtopic here

dense ibex
#

true

lunar jacinth
#

i still need help on adding edges haha

#

if anyone could

lethal swallow
#

I have implement some sorting methods in python, namely selection sort, quicksort, insertion sort, bubblesort and mergesort, and when I time them, quicksort turns out to be the slowest

#

but, it is supposed to be the fastest right?

#

this is my code

#

What have I done wrong?

lethal swallow
#

Please ping me if you find the solution

hoary finch
#

i haven't looked at your code yet but maybe try a larger sample size of numbers

fiery cosmos
#

@lethal swallow

for i in left + right:
    if i < chosen:
        sorted_list.insert(0, i)
        chosen_idx += 1
    else:
        sorted_list.append(i)
#

the sorted_list.insert(0, i) takes O(n) worst time

lethal swallow
#

oh... so I just insert it at a random position before (or after) the chosen number?

fiery cosmos
#

wait hold up I may be wrong

#

ah yes so you are iterating twice

#

the for loop takes O(n) time and the insert takes O(n) again

#

so worst case you do O(n^2) work

lethal swallow
#

oh... so how do I fix that?

#

Can I fix that?

fiery cosmos
#

yes you can

#

idk how to implement it rn but the partition should take O(n) time

#

then it will result in O(n log n)

lethal swallow
#

wait I didn't see the solution yet, because I want to try to fix it my self. So will it be better if I write sorted_list = [i] + sorted_list?

#

it still takes the most time

#

here are the results:

Time taken for the inbuilt sorted() method (1000 rounds): 0.00034409999999999996
Time taken for the selection_sort() method (1000 rounds): 0.006560099999999999
Time taken for the   quicksort()    method (1000 rounds): 0.021209599999999995
Time taken for the  insertionsort() method (1000 rounds): 0.0047648
Time taken for the  bubblesort()    method (1000 rounds): 0.0010583999999999871
Time taken for the   mergesort()    method (1000 rounds): 0.012199299999999996
                     Results:                     
inbuilt_sort()  : [0, 4, 6, 6, 34, 39, 43, 49, 57, 59, 63, 78, 84]
selection_sort(): [0, 4, 6, 6, 34, 39, 43, 49, 57, 59, 63, 78, 84]
quicksort()     : [0, 4, 6, 6, 34, 39, 43, 49, 57, 59, 63, 78, 84]
insertionsort() : [0, 4, 6, 6, 34, 39, 43, 49, 57, 59, 63, 78, 84]
bubblesort()    : [0, 4, 6, 6, 34, 39, 43, 49, 57, 59, 63, 78, 84]
mergesort()     : [0, 4, 6, 6, 34, 39, 43, 49, 57, 59, 63, 78, 84]
#

should I try a larger list like how poke suggested?

#

(sorry for the ping)

fiery cosmos
#

okay what you can do is have two separate arrays for left and right

#

fill those in one loop

#

and then do your usual algo

lethal swallow
#

hmmmmm ok let me try that

hoary finch
#

it's fine, but yeah i think you should try a larger list if you haven't already because quicksort does a lot more computation per iteration than something like bubblesort, so bubblesort is faster for smaller lists

fiery cosmos
#

moving less than pivot to left and greater to right

#

and then calling quick sort on left and right

#

shall I code a stub if you want?

#

(if you are unclear with what I said)

lethal swallow
lethal swallow
# hoary finch it's fine, but yeah i think you should try a larger list if you haven't already ...

In a list of 200 numbers, bubble sort is the fastest and quicksort is the second fastest:

Time taken for the inbuilt sorted() method (1000 rounds): 0.006825499999999998
Time taken for the selection_sort() method (1000 rounds): 0.5805222
Time taken for the   quicksort()    method (1000 rounds): 0.3959051
Time taken for the  insertionsort() method (1000 rounds): 1.3347014000000001
Time taken for the  bubblesort()    method (1000 rounds): 0.013528400000000218
Time taken for the   mergesort()    method (1000 rounds): 0.22213100000000008
hoary finch
#

do 100 cycles of 10000 if it doesn't take too long

#

see if there's a difference

lethal swallow
#

2,000 numbers took 7 s

fiery cosmos
#
def quicksort(lst=target):
    if len(lst) in [0, 1]:
        return lst
    list_to_sort = copy(lst)
    rand = randint(0, len(list_to_sort) - 1)
    chosen = list_to_sort(rand)
    # this is the change I was mentioning
    #-----------------------------------------------
    left = right = []
    for i in range(len(list_to_sort)):
        if i != rand:
            if list_to_sort[i] < chosen:
                left.append(list_to_sort[i])
            else:
                right.append(list_to_sort[i])
    #-------------------------------------------------
    return quicksort(left) + [chosen] + quicksort(right)
lethal swallow
#

100 cycles of 10,000 will take 3500 seconds

hoary finch
#

how fast are they for 2000

lethal swallow
#

its still running

#

aah I stopped it

#

😦

fiery cosmos
#

this is O(n)

#

your code is still O(n^2)

lethal swallow
fiery cosmos
#

no

lethal swallow
#

oh wait

#

one second

flat sorrel
#

You are assigning both left and right to the same list instance, that probably causes some problems

fiery cosmos
#

you are still doing unnecessary work

#

which will lead to O(n^2) making it slow

lethal swallow
#
def quicksort(lst=target):
    if len(lst) in [0, 1]:
        return lst

    list_to_sort = copy(lst)
    rand = randint(0, len(list_to_sort) - 1)
    left, chosen, right = list_to_sort[:rand], list_to_sort[rand], list_to_sort[rand + 1:]

    sort_left = []
    sort_right = []
    for i in left + right:
        if i < chosen:
            sort_left.append(i)
        else:
            sort_right.append(i)

    return quicksort(sort_left) + [chosen] + quicksort(sort_right)
```is this better?
fiery cosmos
#

yes

flat sorrel
#

Is there a good reason why are you using a random integer to split the list?

lethal swallow
#

No

fiery cosmos
#

many ways to choose pivot element

lethal swallow
#

Where I read it said that you should pick a random pivot point

fiery cosmos
#

random is one

lethal swallow
#

Wait but the best case is when the pivot point is somewhere in the middle right?

fiery cosmos
#

idk no matter what pivot is, you still need to scan the other things beside the pivot

#

the best case is n log n

flat sorrel
#

I guess random is good enough

#

I think copying lst is unnecessary

fiery cosmos
#

well there are testcases that can break the normal quicksorts

#

yeah quicksort is inplace

#

you can even remove those left and right arrays

#

and do swappings

lethal swallow
lethal swallow
fiery cosmos
#

uhh as I said, idk the implementation but you can checkout other codes in online for optimizations

onyx mist
#

Hey guys. I am working with a pandas DataFrame like this and am looking to create a nested dictionary keyed by 'id' with values being dictionaries with keys and values for 'capacity' and 'level' for only the ids where is_customer is True. Anyone know how to do this?

lean glade
#

Hey @lethal swallow, here you have the same quicksort function you wrote, but I got rid of the unnecessary parts, probably making it faster: ```def quicksort(lst=target):
if len(lst) in [0, 1]:
return lst

rand = randint(0, len(lst) - 1)
left, chosen, right = [], lst.pop(rand), []

for i in lst:
    if i < chosen:
        left.append(i)
    else:
        right.append(i)

return quicksort(left) + [chosen] + quicksort(right)```
#

If you check google you'll find faster quicksorts anyway

raw bridge
#
def Quicksort(arr: list):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr)//2-1]
    lhs = [i for i in arr if i < pivot]
    rhs = [i for i in arr if i > pivot]
    eq = [i for i in arr if i == pivot]

    return Quicksort(lhs) + eq + Quicksort(rhs)
``` ![UwU](https://cdn.discordapp.com/emojis/624350494072242206.webp?size=128 "UwU")
lean glade
#

^better

raw bridge
#

its basically a shorter version of what you did

lean glade
#

From what I read list comprehensions are faster

raw bridge
#

yeah maybe

#

i like them a lot KoishiDerp

lean glade
#

One of the best features of python I think

#

From what I checked, the list comprehension one was faster than the other two in the worst case scenario, and the original one was slower than the other two in the normal scenarios

agile sundial
#

the list comprehension version loops over the list 3 times, while the not list comp version only loops over the list one time

raw bridge
#

ye true

agile sundial
#

per recursion

raw bridge
#

so slower i guess

lethal swallow
#

wait

#

nevermind its slower

raw bridge
#

ye its fast, i learned that method from eivl

lethal swallow
#

no wait its faster!

agile sundial
#

how is that faster

lethal swallow
#

¯_(ツ)_/¯

raw bridge
#

idk about fast

#

it just seems easy to me so i use it

agile sundial
#

wait you actually use this algo to sort things?

lethal swallow
#

Yes

#

its called quicksort

agile sundial
#

... not the algo in general, i mean the one he wrote

raw bridge
#

why would i use it if theres a built in method

agile sundial
#

you said "so i use it"

raw bridge
#

eh my bad, didnt mean it that way though

agile sundial
#

¯_(ツ)_/¯

lethal swallow
#

I think it is faster becase vinam chose the approximate midpoint as the pivot

#

while I am choosing a random number

agile sundial
#

well, they should be about the same

toxic grotto
#

hlo

#

i am a new one

#

plz some one clearmy dout

#

what are gethut and there uses

agile sundial
#

github?

lethal swallow
toxic grotto
#

ok sir

lethal swallow
#

I think that is a more appropriate place. Also, it is github, not gethut

#

!e

from time import perf_counter
from random import randint

target = [randint(0, 100) for _ in range(2000)]


def vinam_quicksort(arr: list):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr)//2-1]
    lhs = [i for i in arr if i < pivot]
    rhs = [i for i in arr if i > pivot]
    eq = [i for i in arr if i == pivot]

    return vinam_quicksort(lhs) + eq + vinam_quicksort(rhs)


def chococookies_quicksort(lst=target):
    if len(lst) in [0, 1]:
        return lst

    rand = randint(0, len(lst) - 1)
    left, chosen, right = [], lst.pop(rand), []

    for i in lst:
        if i < chosen:
            left.append(i)
        else:
            right.append(i)

    return chococookies_quicksort(left) + [chosen] + chococookies_quicksort(right)


for func in (vinam_quicksort, chococookies_quicksort):
    strt = perf_counter()
    func(target)
    print(f"Time taken for {func.__name__}: {perf_counter() - strt}")  
halcyon plankBOT
#

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

lethal swallow
#

aw man

lethal swallow
#

look here

raw bridge
#

ye, the main reason seems to be the list comp, it is faster than normal for loops

#

like for 200k length list the difference is already 2 seconds

median ridge
#

@raw bridge just to get a comparison, could you time the standard timsort (sort()) as well?

#

doubt it will be any different to the best quicksort implementation tho, as timsort is only faster on "real" data, not scientific data

agile sundial
#

compared to python, sort() should be much much faster

#

it's implemented in C

final lodge
#

Hello Earthlings, I am reading a book on algorithms and I would like to practice it in python. The problem is python doesn't have many data structure build in like linked list etc. It's getting tiresome to implement the data structure everytime I need it, is their any module in python which contains all common data structure

agile sundial
#

why don't you save the implementations

final lodge
#

yeah i could do that, but I don't think I have written an elegant code, it only works as proof of concept for me but I think I would be much better off borrowing a module.

agile sundial
#

generally there are, which ones are you looking for?

final lodge
#

linked list, double linked list, binary tress. Basically I am reading Ullman Algo book and would like to solve the end of the chapter problem using python

agile sundial
#

hm

#

there is llist, and there's also deque

final lodge
#

from what I read llist does the job, but it only has single and double linked list functionality, so do I have to download all other data structure separetely. I thought all common data structure would be available at single place?

eager hamlet
#

so i have n (n < 1000) lists, each of max length 9
like [2, 20, 22, 47, 7, 32, 23, 8, 48] [36, 0, 39, 42, 18, 26, 27, 31, 25] ...and i have to choose at most 1 element from each list so that the result is as long as possible and is strictly increasing- would this require dp? (ping 2 reply thx)

#

my algo so far does use it

#

it's where dp[i] returns the length of the sequence and the last number in the list

brave oak
#

say you have a list of origin and destination nodes and an approximate cost to travel between them

#

is there an algorithm which generates a graph based on that?

fiery cosmos
#

you need more info

brave oak
#

okay, more like

fiery cosmos
#

I can just construct a graph with src and des and add an edge cost

brave oak
#

there exists a connected graph which I can't see

#

which represents a transport network

#

so the cost of a path is the time taken to get between two points

brave oak
#

like I'm not really sure where to start

fiery cosmos
#

so based on many graphs that are possible you need to construct one which is as close as possible to the original one

#

but there are exponential many graphs 🤔

brave oak
#

would be sufficient

#

like

#

okay, for example, if I have two nodes A and B which each have a set of, say, 10 closest nodes, and the intersection of these sets contains 5 nodes

#

it's a good guess that those 5 nodes are "between" A and B on the network

#

similarly, if choose two random nodes from the 10 closest nodes to A and they have no common close nodes, that suggests that they are on opposite sides of A

#

that's kind of the logic

#

but I'm looking for an algorithm that captures this intuition...?

#

because I don't want to piece together the graph manually

fiery cosmos
#

I have not heard (until now) any algo that does this

brave oak
#

or, another way of looking at the problem

fiery cosmos
#

nor have I come across this question 🙂

brave oak
#

say I have "pieces" of a graph (basically subgraphs)

#

hm, actually, never mind, that's trivial

brave oak
#

maybe I'm going about it the wrong way

fiery cosmos
brave oak
fiery cosmos
#

hmm ok

lunar jacinth
#

can someone help me with undirected graphs?

#

i have a few methods written but im not sure how to get the end result i want

#

this is my code right now

#

im trying to create this somehow...

fiery cosmos
#

you need to make a matrix of some large size or give the number of nodes as an argument and build a size x size matrix

#

then when adding an edge between node u and v you make matrix[u][v] = 1 and matrix[v][u] = 1

lunar jacinth
#

so everything i have right now is decent? do i need a str function?

fiery cosmos
#

im trying to write to a text file, after reading it. Adding 1 to the content and rewriting to it. I get this error

TypeError: must be str, not int
#

what should I do

ionic pasture
#

so change N

fiery cosmos
#

i did

ionic pasture
#

nah wait

fiery cosmos
#

and i get this

ionic pasture
#

n = str(c1.read(1))

#

look

#

what is n equal too

fiery cosmos
#
    if f1 in file:
      with open (f"{key}.txt", "r") as c1:
        n = str(c1.read(1))
        c1.close()
        with open (f"{key}.txt", "w") as c2:
          var1 = n + 1
          var2 = str(var1)
          c2.write(str(var2))
          c2.close()
#

mind adding it to this?

ionic pasture
#

it’s on ur 3rd line

#

remove str

fiery cosmos
ionic pasture
#

if f1 in file:
with open (f"{key}.txt", "r") as c1:
n = c1.read(1)
c1.close()
with open (f"{key}.txt", "w") as c2:
var1 = n + 1
var2 = str(var1)
c2.write(str(var2))
c2.close()

#

like this

fiery cosmos
#

still get the same issue

ionic pasture
#

what is n equal too

#

can u

#

wait

fiery cosmos
#
os.chdir("/var/www/html/.conc/")
    file = os.listdir()
    f1 = f"{key}.txt"
    if f1 in file:
      with open (f"{key}.txt", "r") as c1:
        n = (c1.read(1))
        c1.close()
        with open (f"{key}.txt", "w") as c2:
          var1 = n + 1
          var2 = str(var1)
          c2.write(str(var2))
          c2.close()
#

thats more of the code

ionic pasture
#

if f1 in file:
with open (f"{key}.txt", "r") as c1:
n = c1.read(1)
print (n)
c1.close()
with open (f"{key}.txt", "w") as c2:
var1 = n + 1
var2 = str(var1)
c2.write(str(var2))
c2.close()

#

wait

#

hello

fiery cosmos
#

yes

ionic pasture
#

wait no

#

can u

#

just after

#

n = c1.read(1)

#

add this line :
print (type(n))

fiery cosmos
#

retruns as a string

ionic pasture
#

got it

#

and

fiery cosmos
#

should i make it a int?

ionic pasture
#

now change « print(type(n)) » to « print (n) »

fiery cosmos
ionic pasture
#

what do u get

#

did it print the value of n

fiery cosmos
#

no

ionic pasture
#

what

#

ok

#

k so try putting int

#

to the 3rd line

#

n = int(c1.read(1))

fiery cosmos
ionic pasture
#

like do u know what u are taking

fiery cosmos
#

i get this erro rnow

flat sorrel
# brave oak say you have a list of origin and destination nodes and an approximate cost to t...

I would try a physics based approach. Initially, put the nodes randomly in some N-dimensional space, then in each iteration, the nodes apply forces on one another based on the known distances (if a node is closer than it should be, push it away, etc.). Sum up all of the force vectors for the entire set before applying them together. At the end of X iterations, calculate the distance between each node pair to get a dense distance matrix.

ionic pasture
#

do u know what c1.reaad(1) is ?

fiery cosmos
#

yes

ionic pasture
#

what is it

#

an int ?

fiery cosmos
#

yes

#

it is an int

ionic pasture
#

then why it isnt

#

putting it as int

fiery cosmos
#

im not sure

#

it has the value of 1

#

@ionic pasture i got it to work

#

thanks

ionic pasture
#

how

#

what did u do

fiery cosmos
#

i changed the variable type like u said

#

and changed the file to a diffrnet number

ionic pasture
#

well if it returned a literal base 10 error

#

that means it wasnt an int

fiery cosmos
#

ohhh

ionic pasture
#

it was a character else than a number

brave oak
#

but how does that help me construct the graph?

fiery cosmos
#

imean i had it set it to 0

#

is 0 an int?

ionic pasture
#

yes

#

well yes

fiery cosmos
#

then it should of

#

but idk

#

but ty

ionic pasture
#

weird

fiery cosmos
#

i got it to work

ionic pasture
#

maybe there is something else in the code linked to that

#

and that caused to not work