#algos-and-data-structs

1 messages · Page 85 of 1

severe smelt
#

Hi! Can anyone help me with a problem in R? I'm new to it, and I'm stuck

oblique panther
#

@severe smelt this is not an R server. Let's see if there is one.

severe smelt
#

I've tried looking, but cannot find one

#

Lots of Python users are fluent in R as well

#

that's why I asked here

oblique panther
#

#data-science-and-ml would be the place to ask given the use cases for R but if there's no R discord server, you might ask on the general programming discord.

gusty grove
#

@undone ore just ask. It depends on the question

oblique panther
#

Since it's a robotics question, it should probably go in an individual help session.

shell abyss
#

@severe smelt What is the problem you are having? I know a bit of R but not a lot.

severe smelt
#

oh thanks!

#

So I have uploaded some data from IBEXfarm surveys I conducted

#

the files are javascript

#

and then the output it a .txt

fiery cosmos
#

is ram classed at storage

severe smelt
#

I keep getting this error when trying to create columns

shell abyss
#

What is the error you are getting and how does your code look?

severe smelt
#

Error in $<-.data.frame(*tmp*, sex, value = integer(0)) :
replacement has 0 rows, data has 1517

#

it's basically saying that when I am adding a new colum it doesn't have any rows

shell abyss
#

Yeah it looks like some dimensionality mismatch to me. Those are fairly common in R and a bit tricky to solve because they are very dependent on the data and the code.

severe smelt
#

yes they are

#

It's a very frustrating program

#

this is the addColumn function I created

#

function(fieldname) {
repnumber<-count(Survey_data, vars="subj_ID")[2,2]
x <- droplevels(subset(Survey_data, Survey_data$sentence == fieldname))
x <- x$Answers
y <- rep(x,each=repnumber)
return(y)

shell abyss
#

does str(y) return an expected structure of the data?

severe smelt
#

yes, so it returns what I have now

#

I'll post a screenshot here

#

So the questions are in a row above the answer

#

Age
30

#

for example, but I want to reorganize this so that Age becomes a column and is filled with 30 for all 15 questions answered

#

that is what my data frame looks like now

#

I am trying to organize it so that the answers to each of the 15 questions I ask are separate columns

#

but when I try to add a new column it says there is a mismatch because the column I am adding has no rows

shell abyss
#

I think I understand what you are trying to do. Sorry it is a bit confusing at first 😄

#

I am thinking you might be able to use cbind and rbind here instead

severe smelt
#

and then age and sex (spol) are nestled under Questions

shell abyss
#

I wrote a program a while ago that did similar stuff. Let me see if I can find the method I used.

severe smelt
#

oh that would be wonderful

#

I could send you my data if you would like to try it yourself

shell abyss
#

No I think it's ok. I am thinking you might have swapped the row and columns when you are appending to the dataframe

#

Lemme look at my code real quick

severe smelt
#

thanks

shell abyss
#

@severe smelt Ok so I had a quick glance over my program and I am using rbind and cbind to solve a problem similar to yours.
The problem my program is solving is that it is reading csv data from multiple daily covid report files, and then it is building those into a new dataframe. In your problem it would instead be reading in multiple answers and building those into a new dataframe. So I think you might be able to solve it in a similar way.

This is the repo for my R script. It is open source so you are free to use any part that you wish freely. The code is a bit ugly but I would recommend looking at what is happening between line 26 and line 111.
https://gitlab.com/PucchPush/covid-19-visualizer

severe smelt
#

that's quite impressive

#

I barely underatand any of it

#

lol

#

I see what you've done

#

you set a value for the missing columns

shell abyss
#

Neither do I lol, R code is not pretty. If I recall correctly I tackled this problem by creating new temporary data frames and then binding em together sort of

severe smelt
#

I have no idea how to do this for my data set

#

I want to add columns

#

you are deleting them it seems

shell abyss
#

I am deleting some of em then I am appending sort of

severe smelt
#

let me show you the instructions

#

from my IBEX/R tutor

shell abyss
#

Oh blimey, I do not actually add any. I thought I had a cbind in there somewhere but I do not

severe smelt
#

the guy explains it but doesn't provide any troubleshooting

#

Survey_data$sex <- as.factor(paste(addcolumn("sex")))
Error in addcolumn("sex") : could not find function "addcolumn"

#

sorry

#

one sec

#

Survey_data$sex <- as.factor(paste(addColumn("sex")))
Error in $<-.data.frame(*tmp*, sex, value = integer(0)) :
replacement has 0 rows, data has 740

#

so again, it's telling me the error in creating a new column comes from it not having any rows.

#

Do I need to set the value of the column sex to 740?

#

see if that works?

shell abyss
#

Hmm if you have gotten it in an assignment it should work.

#

I thought you were doing some personal project but if it is for school then you should probably ask the teacher since it seems there are some special function written to do just that task.

severe smelt
#

It's not for school. It's from an online tutorial for IBEXfarm

#

cleaning up your data

#

but I am running into all kinds of errors

shell abyss
#

Ok I have managed to replicate the error now

#

and I think I understand why it is happening also

#

Yeah, solved it

#

Let me post you the code @severe smelt

#
# This is the original dataframe containing all the data
dat <- read.csv(file = "COVID-19-master/csse_covid_19_data/csse_covid_19_daily_reports/02-02-2020.csv", fileEncoding="UTF-8-BOM", stringsAsFactors=FALSE)

# This command will create a new dataframe called x and only add the entries from dat where country.region is Mainland China
x <- droplevels(subset(dat, dat$Country.Region == "Mainland China"))
# This command will transform x into a vector containing all the values from x$Deaths. Naturally it will have the same length as x.
x <- x$Deaths
# this command will lengthen x so it is the same length as dat$Deaths. If the length mismatch, you will get that error.
y = rep_len(x, length(dat$Deaths))

# append y to dat using anew category called china
dat$china = y
#

I suspect that he has a bug or something in this line of his
repnumber<-count(dat, vars="subj_ID")[2,2]

#

Because it returns the incorrect length. That is why you are getting an error

severe smelt
#

Hi, sorry I was away

shell abyss
#

No worries, I went dark a bit when I was experimenting as well 😄

severe smelt
#

🙂

#

I am getting so close to getting clean data now 🙂

shell abyss
#

One thing I realized is that that rep function might actually destroy the data

#

Because it will replicate the values even when no more values should exist

severe smelt
#

I see

shell abyss
#

I see why he is replicating the data from a data frame perspective. But it does not make sense from a data science perspective imo. You are introducing bogus data into the set.

severe smelt
#

that's what I think too

#

what I want to do is organize my data so that I get age, sex, and University Education (Y/N) as columns above, and have the rows below filled with the corresponding values, according to user ID

#

there are 15 questions in my survey

#

Speakers are to choose one of three possible variants for a word

#

so, e.g. box

#

make the plural

#

boxes, boxs, boxen

#

for example

#

their choice should go in a row, along with all the other values connected to them (age, sex)

#

is there a way I can get my data frame to do this?

#

let me take another screen shot of what I have

#

it's stacking all the respondents answers from left -> right

shell abyss
#

you could make a column called word_answer or something similar and have it as a 3-level factor containing plurals {cats, catten, cuts}

severe smelt
#

well, you can see their answers above

#

the options will not be reflected in the data, just the choice

#

so I need to have at the a to

#

top

#

15 more columns across for each of the words

shell abyss
#

It is almost half past 11 pm here now, so I gotta start heading to bed. Let's continue this chat some other day if you are still having problems 😄

severe smelt
#

Oh, thanks so much

#

you really helped

#

it's 12:19 here

#

I have to present my data on Sunday at a conference and I am trying to visualize it through R

#

i did this 10 years ago for my dissertation

#

but I forgot almost everything

severe smelt
#

by the way, just doing it manually in Excel by transposing. I think it's the only way

eager hamlet
#

tryna do this: https://hatebin.com/hlsswadmfw

circle = [i for i in range(1, int(input()) + 1)]

waiting_cow = -1
at_index = 0
while True:
    curr_cow = circle[at_index]
    if curr_cow == -1:
        print(waiting_cow)
        break
    circle[at_index] = waiting_cow
    at_index += curr_cow
    at_index %= len(circle)
    waiting_cow = curr_cow
```but 22 outputs 15 instead of 12 (ping plz)
shut osprey
#

First line is just circle=list(range(1, int(input())+1) btw

#

You don't account for asking the same cow to move twice

#

@eager hamlet

low cloud
#

can somebody tell me why this function returns True when the input is (False, 6)

atomic kraken
#

that will be evaluated like
hour < 7 or (hour > 20 and talking) as and is evaluated before or.

So the part in the parentheses will become 6 > 20 and False -> which evaluates to False
So the entire thing becomes if 6 < 7 or False, and 6 < 7 is True,
so if True or False, which will evaluate to True, hence the function returns True

naive basin
#

Computer Science students: do you use flash cards? (random question, I'd be really pleased to talk with someone experienced with flash cards)

eager crag
#

Guys, where do you study? And where do you recommend to study computer science with 12k dollars budget?

glossy verge
#

Hello people I'm a first year computer science student. Have the course python this semester. I was wondering what's the best way to teach myself in the best way possible. Any special tricks and tips?

fallen dragon
#

@glossy verge
Not sure if it still works (feedback needed)

  1. Make a new e-mail account on outlook.com
  2. Use that e-mail to register for free microsoft dev esentials https://visualstudio.microsoft.com/dev-essentials/
  3. One of the gifts for should be a coupon for 30 days free access to Pluralsight (normally it's 30USD/month or 300USD/yead)
  4. Make Pluralsight account and look at learning path named Python
    VERY high quality courses from complete newbie to pro.
#

(or just pay 30 USD for Pluralsight access)

#

I probably sound like I get payed by them, but the truth is that website helped me to move from level of "code monkey" to "senior" and now to "subject-matter expert".

fiery cosmos
#

I'm struggling with a basic while loop program can anyone help me

fallen dragon
#

@fiery cosmos this looks like something for a for loop.

fiery cosmos
#

But the teach specifically says using a while loop 😟

#

For would have been easier yaa

fallen dragon
#

What do you have so far?

#

You can paste code here using:
```python
code here
```

#

` = tilde (next to 1 on US keyboard)

#

print("Value\tSquare") prints out Value Square

#

print("%d\t%d" %(10,100)) prints out 10 100

#

Enough hints 😉

limpid abyss
#

HELLO, do u guys know any tutorial that help to write me tensorflow object detection webcam script {python code} i know there is many tutorial on youtube but i cant find "how to write python script for for object detection" if anyone know can u share link with me .......🙃

fallen dragon
limpid abyss
#

i mean the code part i know that tuturials but i cant find python code "how to write python code for tensorflow ojbect detection api "

torpid cosmos
#

print("Hello World")

quasi oracle
#

@frigid obsidian errr.. This is a python server. You could ask it in a an off topic channel, but there are servers for C++

frigid obsidian
#

oh alright

sonic hawk
#

Hi everyone! I'm a newbie for python and I'm currently enrolled in computer sci. principles, but I just wanted to know what I would have to research in order to make a password generating algorithm that, in question, transforms the user's inputted password into a "encrypted" password that only the user would recognize. My specific idea is to take every character/letter in the alphabet and move it one letter to the right to encode it (Not strong, but just for fun). Any help is appreciated, thanks a lot guys.

#

(For further example, a=b, b=c, etc...)

quasi oracle
#

It's called a Ceasar Cipher.

toxic sorrel
#

Hi Anyone know any java discord server i can join?

quasi oracle
#

You would need to know how to loop over strings and build new ones

toxic sorrel
#

or anyone know java who can help me please

sonic hawk
#

Ok, thanks for your help @quasi oracle, much appreciated

halcyon plankBOT
#
No way, José.

Please don't try to ping 98,788 people.

#

:incoming_envelope: :ok_hand: applied mute to @toxic sorrel until 2020-09-04 16:35 (9 minutes and 59 seconds) (reason: everyone_ping rule: pinged the everyone role).

fiery cosmos
#

why is java is terrible

halcyon plankBOT
#

Hey @fiery cosmos!

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

fiery cosmos
#

oh ok

oblique panther
#

@fiery cosmos because of the specification of the language. The off topic channels are the place to rant about that, though.

severe smelt
#

Hey Everyone! I have a really nice dataset that I was able to clean up in R. Now I am about to do analysis. Anyone have suggestions on what the best visualization would be for this?

quasi oracle
severe smelt
#

Thanks!

eager hamlet
#

hey so i'm doing this problem: https://hatebin.com/yaldmukejp
and my code is as follows: https://hatebin.com/pqsqgqmwga
however, when given this output:

10
217 3 9 8 6
9 3 9 10 3
452 3 8 10 6
265 3 9 10 3
45 3 9 3 7
530 4 9 2 8 4
326 3 5 3 7
351 3 2 5 3
240 3 2 8 6
169 5 9 2 8 5 4```, it gives 940 instead of 939. and this isn't a normal off-by-one error, because for others it works just fine.
is there anything wrong with my code? (ping plz)
runic tinsel
#

it doesn't give 14

#

@eager hamlet

eager hamlet
#

wait it doesn't?

#

oh crap

runic tinsel
#

the problem is it's not synchronized

eager hamlet
#

wait

#

here's the code

#
cows = [[int(i) for i in input().split()] for _ in range(int(input()))]


class Cow:
    def __init__(self, time: int, to_signal):
        self.time = time
        self.to_signal = to_signal
        self.time_passed = 0
        self.started = False
        self.finished = False


true_cows = []
for c in cows:
    true_cows.append(Cow(c[0], [i-1 for i in c[2:]]))  # i-1 because let's use 0-based indexing plz
true_cows[0].started = True

total_time = 0
while True:
    for c in true_cows:
        if c.started:
            if c.time_passed == c.time:
                # print(true_cows.index(c), 'finished', total_time)
                for i in c.to_signal:
                    true_cows[i].started = True
                c.finished = True
            c.time_passed += 1

    if all([c.finished for c in true_cows]):
        break
    total_time += 1

print(total_time)
runic tinsel
#

ok

#

still looks like it does that thing

#

where a cow ticks in the same tick it started

#

but only sometimes

#

only looks like, can't prove it yet

#

yeah, compare

4
1 0 2 4
1 0 
1 0 
1 0 3
```and```
4
1 0 2 3
1 0 
1 0 4
1 0 ```
#

same inputs really, but second one gives a cow an early start

#

@eager hamlet

eager hamlet
#

?

#

gives which cow?

runic tinsel
#

last cow

eager hamlet
#

how does it give it a head start though

#

oooh

#

yeah

#

i get it

runic tinsel
#

yeah

#

you update in order of input cows

eager hamlet
#

indeed

#

ok ill fix that, thx tho

runic tinsel
#

and then it will become off by one

eager hamlet
#

wait how did you do that

#

i have no idea what that code does lol

runic tinsel
eager hamlet
#

so it just takes cows with the least time first

runic tinsel
#

yes

#

"priority queue"

eager hamlet
#

oh yes

#

i think i get it now

#

im still here trying to debug my slow-butt program lol

runic tinsel
#

max is unnecessary

eager hamlet
#

what's unnecessary?

runic tinsel
#

in my solution, I mean, there's no risk of reducing time to negative

eager hamlet
#

yeah

#

true

#

but nothing wrong w/ being explicit

runic tinsel
#

that just goes into a comment

eager hamlet
#

which does?

#

i mean wdym by that

runic tinsel
#

if I need clarity, i could comment "won't become negative"

eager hamlet
#

true

stable pecan
#

I need a cow input file

stable pecan
fiery cosmos
#

how do people get to know about areas of interest and publish papers?

runic tinsel
#

how do people publish papers, or how do people get to know about published papers?

fickle fjord
#

Blue is male, orange is female
So you were given data, 10 males and 10 females
for the x axis is ranks
so from rank 6 to 10, theres 2 male and 4 females. rank 11 to 15 theres 3 males and 2 females, and so on
is there an equation it will explain that which gender is smarter.

chilly burrow
#

i dont get it

light orchid
#

Anyone know anything about using programming to solve math related problems?

#

Like ramsey numbers?

fickle fjord
#

Okay so you were given 10 girls and 10 boys. you were told to find out which is smarter, the boys or the girls

#

and so the boys and girls tell their iq score.

#

or ranks. so the closer the rank to 0. the smarter they are

#

like what kind of equation to figure that out, like because you already know each ranks. you can conclude that the boys/girls is smarter than the others

#

sorry for my bad english bt

low palm
#

You could study that data in different ways @fickle fjord depending on what your criteria for one group being smarter is. You could calculate the average, or median, rank for each group and compare those. Or you could decide on a certain rank being the "smartiness threshold" and see which group has a higher fraction below that threshold.

fickle fjord
#

but if i use mean, wouldnt it be that the one with the highest rank is better?

low palm
#

Didn't you say low ranks were smarter?

fickle fjord
#

yes

low palm
#

So you'd go for the group with the lowest average rank

fickle fjord
#

as so u mean that later, the one with the lowest mean is better, am i right?

low palm
#

Yes, using the lowest average rank is one way to compare.

fickle fjord
#

understood, thanks alot!

light orchid
#

Does anyone listen to music whilst coding

rustic helm
#

Pretty sure everyone does

north zealot
#

I usually do, but often cut it when I need to think too much haha

runic tinsel
#

I don't listen to music at all

agile sundial
#

no words is the best

wraith valve
#

so classical music

#

but then opera also has words

#

i only listen to words that i do not understand

oblique panther
#

@split needle did you finish your algorithm thing?

#

I saw that you said "so the merge part is O(n*log(n)) and the divide and conquer part is O(n)?"

#

The whole algorithm is O(nlogn). I'm not sure what you mean by the "divide and conquer part".

agile sundial
#

for this type of thing it's nice to draw a tree of all the things that are happining

#

mit ocw has a video on merge sort

#

i think it's 6.006

wraith valve
#

nah watch the hungarian dudes

#

they r the best

agile sundial
#

mit happens to be a pretty good school

quasi gyro
#

Hello fellow students!

#

So I'm kinda stuck, I'm trying to make an algorithm that triangulates a given matrix

#

and yea I've started, I already have a chain of nested loops, so yea not ideal 😢

#
class matrix():
    def __init__(self,*lines):
        self.lines = lines
        self.n = len(lines)
        self.m = len(lines[0])
    def show(self):
        for line in self.lines:
            x = ""
            for integer in line:
                x+=f" {str(integer)}"
            print(x)
    def triangulate(self):

        newlines = self.lines
        currentlineindex = -1
    #From here is nonsense, kinda works but weird and not  done and trash and not performant at all, my head hurts
        for line in newlines:
            currentlineindex+=1
            if currentlineindex > 0:
                for i in range(currentlineindex):
                    n1 = line[i]
                    for x in lines:
                        if x[0] == n1:
                            for i in newlines:
                                i-=x[0]

        return newlines

    def show_triangulate(self):
        for line in self.triangulate():
            x = ""
            for integer in line:
                x+=f" {str(integer)}"
            print(x)
        
#

little drawing to illustrate the init and the different propreties

#

btw

#

theres numpy function that does this

#

but i kinda want to make my own

stable pecan
#

you can do something like this, but you need to account for leading zeros which I haven't -- that means you may need to permute rows before the loops:

In [33]: import numpy as np
    ...:
    ...: def triangularize(m):
    ...:     # Assume leading values are non-zero
    ...:     for i, row_top in enumerate(m[:-1]):
    ...:         for j, row_bottom in enumerate(m[i + 1:], start=i + 1):
    ...:             m[j] -= (row_bottom[i] / row_top[i]) * row_top
    ...:
    ...:     return m
    ...:

In [34]: t = np.random.randint(1, 10, (5, 5)).astype(float)

In [35]: triangularize(t)
Out[35]:
array([[ 5.  ,  6.  ,  9.  ,  6.  ,  7.  ],
       [ 0.  , -1.6 ,  1.6 ,  2.4 , -0.2 ],
       [ 0.  ,  0.  ,  1.  ,  8.  ,  4.25],
       [ 0.  ,  0.  ,  0.  , 87.  , 43.5 ],
       [ 0.  ,  0.  ,  0.  ,  0.  , 11.5 ]])
proven matrix
#

Hey Developers I am a 2nd year student and I want to build a system like jarvis of iron man. So i need your help I don't know where to start and what to do.

fathom saffron
#

that depends on you're end goal

#

if you want to to be smart you'll have to use things like VADER in sentiment analysis

fiery cosmos
#

How long will it take for me to learn C language if I already know the basic concepts of Python programming properly?

vocal gorge
#

I'd say it'd barely help.

#

Some general-programming things are applicable - flow control, assignments, data structures, etc - but mostly it's extremely different.

lean dome
#

I disagree. Both C and Python are imperative high level languages. They're very similar, in the grand scheme of things. C is further from Python than Java or C#, but much closer than Python is to Haskell or Lisp or Prolog or Brainfuck or SQL, etc.

#

Once you have a reasonably solid understanding of one language following a particular paradigm, people underestimate how much it helps when picking up a similar one. Other concepts that C has in common with Python:

  • A program has an entry point.
  • Control flow moves linearly forward from that entry point until structured control flow statements (if / else, while, for) or function calls (fun(arg1, arg2)) move the flow of control.
  • Functions take parameters and can return values.
  • After a function runs out of statements to execute or executes a return statement, control returns to its caller.
  • Each function call remembers the state which it was called from, allowing each call to know where to return control to, and allowing for multiple calls to a single function to be happening concurrently, each returning to a different frame (and enabling recursion)
  • Variables exist to hold values
  • Assignments to values are done using var = new_value
  • Variables defined outside of a function are global, and can be accessed from anywhere in the program
  • Variables defined inside of a function are local to that function by default, allowing for reentrant and recursive functions where each call has its own state
  • Lots of functionality exists in libraries that can be pulled into your program, including a "standard library" that comes with the language
  • the standard library is the primary way of receiving user input or sending output from your program
#

All of those things are common between Python and C, and for each of those statements there are languages that behave differently. It's easy to underestimate just how much the basics overlap with other languages following the same paradigm.

#

C and Python are this similar because they share a common ancestor, Algol.

past junco
#

anyone know how i can program to get all possible combinations of given values to get a certain number?
the combinations should be in a list in tuple with the amount of that value needed to get the number
for example: given [1, 2, 5] and 10
result: [(10,0,0),(8,1,0),...]

#

its part of an exercise where its one of the methods in the class

#

ive only been able to do this this way but i cant use this way on my exam

#
def betaal(self, bedrag):
        lijst = [0]*len(self.w)
        res = []
        totaal = 0
        for _ in range(50):
            while totaal < bedrag:
                a = random.choice(self.w)
                if totaal + a <= bedrag:
                    totaal += a
                    lijst[self.w.index(a)] += 1
                if totaal == bedrag and not tuple(lijst) in res:
                    res.append(tuple(lijst))
        return res```
#
    def __init__(self, w):
        self.w = w
        self.opslag = []
        for i in w:
            self.opslag.append((0, i)) 
    def __iadd__(self, other):
        if not isinstance(other, tuple) or len(other) > 2 or not isinstance(other[0], int) or other[1] not in self.w:
            return self
        for i in self.opslag:
            if i[1] == other[1] and i[0] + other[0] >= 0:
                self.opslag[self.opslag.index(i)] = (i[0]+other[0], other[1])
        return self
    def __str__(self):
        return '%s' %self.opslag
    
    def betaal_gulzig(self, b):
        l = sorted(self.w, reverse=True)
        res = []
        for i in l:
            res.append(b//i)
            b = b%i
        return tuple(reversed(res))
#

this is what comes before it

jagged flower
#

hey guys can you help, i think that everybody knows how to do it but it den't work for me, in pynput and i think this is: ```python
with pynput.keyboard.Listener(
on_press=test()) as listener:
listener.join()

#

nothing

#

pls help

quasi gyro
#

@stable pecan can you explain it to me ?

#

Like your matrix t , I don’t get how you create it

#

Also what does enumerate do?

fiery cosmos
#

hi

#

Let's say I have two branches. If I want to merge commit from develop to master. Is it fine if I just do git merge master. Or do I ALSO need to do, git checkout master; git merge develop after that

oblique panther
stable pecan
#

@past junco This problem is easier if you break it into similar, but smaller problems recursively:

def partition_sums(factors, target):
    f = factors[0]
    if len(factors) == 1:
        if target % f == 0:
            yield (target // f, )
        return

    for lead_coef in range(target // f + 1):
        for coefs in partition_sums(factors[1:], target - f * lead_coef):
            yield (lead_coef, ) + coefs
#
In [17]: list(partition_sums([1, 2, 5], 10))
Out[17]:
[(0, 0, 2),
 (0, 5, 0),
 (1, 2, 1),
 (2, 4, 0),
 (3, 1, 1),
 (4, 3, 0),
 (5, 0, 1),
 (6, 2, 0),
 (8, 1, 0),
 (10, 0, 0)]
#

That is, the base case of having just one factor is easy to compute, so the rest of your function is just trying to reduce to this base

plain token
#

Hi everyone. I am very new to python and I am trying to complete an assignment for class but keep getting errors. Can anyone help? This is the assignment: Write a program that prints the balance of an account after the first, second, and third year. The account has an initial balance of $1,000 and earns 5 percent interest per year.

#

This is what I have done:

#

interest_percentage = 5;
interest_rate = 0.05 #interest_percentage/100;
for year in range(1, 4): # loop runs for first 3 years

Formula for simple interest is A = P(1+rt)

A = Final amount

P = Initital balance

r = Interest rate

t = Time in years

total_balance = initial_balance*(1+(interest_rate*year));

initial_balance = total_balance; # The initial balance for 2nd year would the total amount of first year
end = 'st';
if year == 1:
end = 'st';
elif year == 2:
end = 'nd';
elif year == 3:
end = 'rd';
print("Balance at the end of" , year,end , "year is :" , total_balance);

balance_of_an_account()

plain token
#

NM I figured it out

fiery cosmos
#

semicolons?

dapper sapphire
#

Hi, I'm learning about Linked Lists and the linked list I created its 0th index prints None. Is this how linked list supposed to be? Below is my code:

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

class LinkedList:
    def __init__(self):
        self.head = Node()
    
    def append(self, data):
        new_node = Node(data)
        current_node = self.head
        if(current_node == None):
            current_node = new_node
        else:
            while(current_node.next != None):
                current_node = current_node.next
            current_node.next = new_node
    
    def length(self):
        current_node = self.head
        count = 0
        while(current_node.next != None):
            current_node = current_node.next
            count = count + 1
        return(count)
    
    def display(self):
        current_node = self.head
        array = []
        while(current_node.next != None):
            current_node = current_node.next
            array.append(current_node.data)
        print(array)

    def getNthIndex(self, index):
        if(index >= self.length() or index <= -1):
            return(-1)
        current_node = self.head
        count = 0
        while(count <= index):
            count = count + 1
            current_node = current_node.next
        return(current_node.data)

    def erase(self, index):
        if(index > self.length()):
            return(-1)
        i = 0
        current_node = self.head
        while(i <= index):
            last_node = current_node
            print(i, current_node.data)

            current_node = current_node.next
            if(i == index):
                last_node.next = current_node.next
            i = i + 1

# Testing linked list
my_list = LinkedList()
my_list.append(11)
my_list.append(22)
my_list.append(33)
my_list.append(44)

my_list.erase(3)
#

Sorry I am trying to figure out how to syntax highlight code so it's easier to read.

lean dome
#

the way you've implemented your self.head, it never stores data. You do self.head = Node(), which is a node where self.data = None, and then you never modify self.head.data

#

so, the 0th index isn't self.head, it's self.head.next

dapper sapphire
#

Oh instead of becoming self.head it becomes self.head.next because of the way I wrote it. Wait is it because when I used LinkedList() to instantiate the linked list 0th index stores None because there is no data?

lean dome
#

your getNthIndex counts forward index elements from self.head. When index=0, it counts forward 0 nodes from self.head, lands on self.head, and then access the data from self.head. And self.head.data is set to None when self.head is created and is never changed after that. self.head is always the initial Node() that you create in LinkedList.__init__, you never set any data for it - you just modify its next in calls to append or erase

#

0th index stores None because there is no data?
Right, in LinkedList.__init__ you do self.head = Node() (not providing any data), and Node.__init__ has data = None, so the data defaults to None and self.head.data == None

dapper sapphire
#

so then the 0th index of a Linked List would/should always point to None?

#

The way I wrote the linked would this be one of the ways to correctly implement a linked list?

lean dome
#

that depends on how you implement it. but that's one way to do it, yes. One way to do it is to say that the LinkedList always contains at least one Node. To do that, you need to say that sometimes a Node doesn't hold any data, to handle the case of an empty list. The other way to make a LinkedList is to say that the list can contain 0 or more nodes, and special case the empty list case to hold a None inside the LinkedList instead of a reference to a Node.

dapper sapphire
#

I get it.

#

Thanks for your help @lean dome ++

lean dome
#

what you wrote looks reasonably correct. I don't believe the if current_node == None case in append can happen. Your getNthIndex should probably raise an exception or return None when the index is out of bounds, to distinguish between successfully retrieving a -1 that was stored in the list vs returning -1 because the index was bad. Your erase only handles the top bound, when getNthIndex handles both the upper and lower bound on the range check, so that's inconsistent. I think you've got an off by one in erase as well, I think it should check for index >= self.length()

#

and both your erase and your getNthIndex have the same bug of looking at head when index==0 instead of looking at head.next in that case.

dapper sapphire
#

Oh yeah I agree, getNthIndex to return -1 for out of bound was a poor choice. There would be no way of knowing if it was an error or if we actually accessed the value successfully. And yeah erase is inconsistent to only check for uppper bound, but not lower bound. Thanks for mentioning these.

#

Can you recommend any python resources that's more Linked List and beginner oriented?

flat sorrel
#

Fwiw, x is None and x is not None is more Pythonic than x == None and x != None respectively.

lean dome
#

you may want to take this as an opportunity to write some unit tests for this piece of code, to make sure you get it right. "When I create a new LinkedList, its length is 0 and trying to access or erase an item from it fails. When I create a list and then append a value, getting index 0 returns that value, and erasing index 0 makes an empty list. When I append 1 then 2 then 3 and remove index 1, index 0 stores 1 and index 1 stores 3. Etc.

#

It's been a long time since I learned.

#

!resources

halcyon plankBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

lean dome
#

should have something for you.

dapper sapphire
#

Oh yead x is None I came across that today, but didn't know it was a pythonic way of doing it. Will definelty be using is and is not Thanks @flat sorrel that was a helpful pointer.

lean dome
#

x == None isn't incorrect, but x is None is more precise. The only thing that == None is None, so checking x is None is faster and more idiomatic.

dapper sapphire
#

Yeah x == None isnt incorrect, but I end writing code in my own way which looks different from regular python, so I'm also trying to adopt pythonic conventions.

lean dome
#

then while we're at it, all of the () around if and while conditions and around values being passed to return are unusual.

flat sorrel
#

You can also replace a couple of the while loops with for loops

lean dome
#

!pep 8

halcyon plankBOT
#
**PEP 8 - Style Guide for Python Code**
Status

Active

Created

05-Jul-2001

Type

Process

dapper sapphire
#

Thanks for the pep Guide

oblique panther
#

@dapper sapphire did you finish the linked list?

fiery cosmos
#

Hey guys which would you recommend I start practising on Codechef/Leetcode/Hackerrank/Hackerearth
I've got decent CP skills I'm not a complete beginner just a bit out of practice.

feral wadi
#

hey guys

#

@oblique panther

#

can you help me on this one

oblique panther
#

!resources @fiery cosmos

halcyon plankBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

oblique panther
#

@feral wadi if it's a computer science question, go ahead and ask, though I'm not sure that I will know the answer or have time to go over it right now.

feral wadi
#
# Python program to print all permutations with 
# duplicates allowed 

def toString(List): 
    return ''.join(List) 

# Function to print permutations of string 
# This function takes three parameters: 
# 1. String 
# 2. Starting index of the string 
# 3. Ending index of the string. 
def permute(a, l, r): 
    if l==r: 
        print toString(a) 
    else: 
        for i in xrange(l,r+1): 
            a[l], a[i] = a[i], a[l] 
            permute(a, l+1, r) 
            a[l], a[i] = a[i], a[l] # backtrack 

# Driver program to test the above function 
string = "ABC"
n = len(string) 
a = list(string) 
permute(a, 0, n-1) 

# This code is contributed by Bhavya Jain 
#

this one man

#

i cant understand the recursion part

oblique panther
#

this is in Python 2

feral wadi
#

dude

#

just change the range it aint a matter

lean dome
#

And the variables have terrible names. The whole comment about what each argument to the permute function means wouldn't be needed if the arguments were named string, start_idx, end_idx...

feral wadi
#

yeah

lean dome
#

So, what don't you understand about the recursion? Do you understand recursion in general, but not in this particular case?

#

When asked to permute an empty range within the string list of letters, it instead prints the string they represent out. This is the base case, and terminates the recursion. In all other cases, it swaps the first character in the range for each other character in the range, and then permutes the remaining characters given each possible choice of first character.

oblique panther
#

!e

def permute(str_):
    to_str = ''.join
    def _permute(a, l, r):
        if l == r:
            yield a
        for i in range(l, r + 1):
            a[l], a[i] = a[i], a[l]
            yield from _permute(a, l + 1, r)
            a[l], a[i] = a[i], a[l]
    yield from _permute(list(str_), 0, len(str_) - 1)

for n in permute('ABCD'):
    print(n)
halcyon plankBOT
#

@oblique panther :white_check_mark: Your eval job has completed with return code 0.

001 | ['A', 'B', 'C', 'D']
002 | ['A', 'B', 'D', 'C']
003 | ['A', 'C', 'B', 'D']
004 | ['A', 'C', 'D', 'B']
005 | ['A', 'D', 'C', 'B']
006 | ['A', 'D', 'B', 'C']
007 | ['B', 'A', 'C', 'D']
008 | ['B', 'A', 'D', 'C']
009 | ['B', 'C', 'A', 'D']
010 | ['B', 'C', 'D', 'A']
011 | ['B', 'D', 'C', 'A']
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/iwogilidep

oblique panther
#

interesting

fiery cosmos
#

!e

def permute(str_):
    to_str = ''.join
    def _permute(a, l, r):
        if l == r:
            yield a
        for i in range(l, r + 1):
            a[l], a[i] = a[i], a[l]
            yield from _permute(a, l + 1, r)
            a[l], a[i] = a[i], a[l]
    yield from _permute(list(str_), 0, len(str_) - 1)

for n in permute('ABc'):
    print(n)
halcyon plankBOT
#

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

plucky warren
#

hii

oblique panther
#

@plucky warren hi

#

What do you wanna talk about?

#

@fiery cosmos let me know if you have any questions about how that's written.

vivid horizon
#

!pep 7

halcyon plankBOT
#
**PEP 7 - Style Guide for C Code**
Status

Active

Created

05-Jul-2001

Type

Process

eternal owl
#

Anyone know how to check if more than 2 checkboxes are checked at the same time? (Tkinter)

agile sundial
#

checkbox1 and checkbox2 ?

eternal owl
#

yes but let's say I have 3 checkboxes, how do I write an if statement to check if more than 2 of the 3 checkboxes are checked

#

I know how to do a single checkbox but checking if multiple, I dont know how to do

#

the checkboxes have the variable "Checked_CB1" "Checked_CB2" etc assigned

agile sundial
#

you could sum them

eternal owl
#

so like
if sum(Checked_CB1.get,Checked_CB2.get, Checked_CB3.get) > 2 :

agile sundial
#

sure

eternal owl
#

nvm that doesnt work

agile sundial
#

you wanted to check if more than 2 right?

eternal owl
#

yeah

agile sundial
#

oh you had 3

eternal owl
#

yeah

#

but

#

TypeError: 'method' object is not iterable

agile sundial
#

are they booleans?

eternal owl
#

yes

agile sundial
#

did you mean to call the method?

eternal owl
#

wdym?

agile sundial
#

method() instead of method

eternal owl
#

im doing it within a function

agile sundial
#

did you mean to write Checked_CB1.get() instead of Checked_CB1.get

eternal owl
#

That gave me TypeError: 'int' object is not iterable

agile sundial
#

oh, right

#

you have to add them with +

eternal owl
#

in the if/sum statement?

agile sundial
#

you can't use sum()

eternal owl
#

so in the if statement?

agile sundial
#

yes

eternal owl
#

Thank you!!!

#

that worked 😄

limpid agate
#

can anyone do this

half lotus
#

Which part do you need help with

limpid agate
#

B

#

how to you convert it

half lotus
#

You have to convert hexadecimal to denary, so you can use the list at the top to figure out the corresponding character

#

Do you know how to do a hex to base 10 conversion?

limpid agate
#

nope

half lotus
#

Have you tried looking up any resources on that?

#

There are some nice expansions online with good illustrations, but I don't have that at hand at the moment

limpid agate
#

Uhh can you recommend any websites?

#

Oh i see

#

is this important to know

half lotus
#

Depends on the field you go into. But the point is to stimulate and challenge your brain, not necessarily to teach you only what'll be practical.

limpid agate
#

i see

#

Thanks alot

heady wasp
#

I have a question regarding learning Python, I am new to programming, I really like Python for machine learning and financial calc.. I am someone that can learn pretty fast by studying with a paperbook.. but I can only find Ebooks.. is there a certain book I that is great to start with? I saw Learning Python and Thinking Python, any thoughts?

cold cloak
#
def x(n):
    if n>100:
        return n-5
    return x(x(n+11))
print(x(45))```
#

can someone explain why the output is 100 and not 101?

lofty hedge
#

@heady wasp and @fiery cosmos check out "Invent Your Own Computer Games With Python" by Al Sweigart

#

Amazing tool for beginners

chrome needle
#

guys, any good free material about pytest (not the docs, something more teachable)

lofty hedge
#

YouTube

quasi oracle
#

@cold cloak why do you think the output should be 101?

slender rivet
#

quick question, what would you suggest to a complete beginner

#

like me

#

😦

heady wasp
#

@lofty hedge Thanks for the tip! I just got the book from the library!

light orchid
#

Anyone know how alpha 0 works? the chess AI

#

More specifically how does it use a Neural Network?

fiery cosmos
#

I have a question regarding learning Python, I am new to programming, I really like Python for machine learning and financial calc.. I am someone that can learn pretty fast by studying with a paperbook.. but I can only find Ebooks.. is there a certain book I that is great to start with? I saw Learning Python and Thinking Python, any thoughts?
@heady wasp you could also ask this on Quora

#

There are some great answers

heady wasp
#

Thank you

vocal gorge
#

Anyone know how alpha 0 works? the chess AI
More specifically how does it use a Neural Network?
@light orchid Sure it does. For details, check out the references section of its wiki page, mainly, well, the article it was introduced in: https://en.wikipedia.org/wiki/AlphaZero

vast axle
#

anyone really good with curl?

ashen wharf
quasi oracle
#

@raven oracle not sure what you mean by dictionary replacements. As for the regex, you can use a lookahead to make sure the 'hex' doesn't continue with 'agonal'

#

I'm still not sure what you're trying to do, but you would do better if you opened a help channel for it #❓|how-to-get-help

quasi gyro
#

@stable pecan this doesn't make any sense : m[j] -= (row_bottom[i] / row_top[i]) * row_top

#

you're substracting a list from a scalar

#

oh no

#

youre not

stable pecan
#

no lists or scalars

quasi gyro
#

I'm getting an error

#

from the matrix triangularization algorithm you wrote

#

I'm trying to understand it

stable pecan
#

whats the error

quasi gyro
#

TypeError: can't multiply sequence by non-int of type 'float'

#

is it cause youre multiplying a list by a float?

stable pecan
#

it means your array is of integer type

#

you should convert it to float

quasi gyro
#

when i switch it to float

#

TypeError: can't multiply sequence by non-int of type 'float'

#

still the same

#

yet

#

for i in secondary:
array2.append(float(i))

stable pecan
#

note that I ran that code as-is in my console

#

so if you're getting errors, I dunno

quasi gyro
#

😦

stable pecan
#
In [33]: import numpy as np
    ...:
    ...: def triangularize(m):
    ...:     # Assume leading values are non-zero
    ...:     for i, row_top in enumerate(m[:-1]):
    ...:         for j, row_bottom in enumerate(m[i + 1:], start=i + 1):
    ...:             m[j] -= (row_bottom[i] / row_top[i]) * row_top
    ...:
    ...:     return m
    ...:

In [34]: t = np.random.randint(1, 10, (5, 5)).astype(float)

In [35]: triangularize(t)
Out[35]:
array([[ 5.  ,  6.  ,  9.  ,  6.  ,  7.  ],
       [ 0.  , -1.6 ,  1.6 ,  2.4 , -0.2 ],
       [ 0.  ,  0.  ,  1.  ,  8.  ,  4.25],
       [ 0.  ,  0.  ,  0.  , 87.  , 43.5 ],
       [ 0.  ,  0.  ,  0.  ,  0.  , 11.5 ]])
#

see how i convert to float?

quasi gyro
#

I didnt use the randint with numpy

#

but i have a list of lists of floats too

#

wait lemme print the lines object directly

stable pecan
#

well the problem with a list of lists and not a numpy array is you can't do -=

quasi gyro
#

you cant substract array from array

#

ohhhh

stable pecan
#

you can't subtract from a list

#

you can subtract from an array

quasi gyro
#

how do i convert into an array

#

(float lists)

stable pecan
#

np.array(my_list_of_lists)

quasi gyro
#

but what if I dont want to use external stuff

#

ill write it myself

#

the substract thing

#

ill write a function

#

sub(list1,list2)

#

thanks for the help!

stable pecan
#

also need a multiply function

quasi gyro
#

i can do that with a lambda function?

noble elm
#

yo guys which one is a better option to go into btw, computer science or software engineering?

#

or does it matter?

quasi gyro
#

software engineer

noble elm
#

oh I see, hmm...aight thanks

opal fractal
#

Hi all! I am taking a beginning programming class and we have been given this hypothetical "##for an input file, like 'hwdata2'
##calculate the mean of a user defined column.
#for instance, you are interested in the mean of Z -- but you don't know where
#'Z' is located. It could be in the first or second or third column.
##how do you figure out where Z is, and then calculate the mean?" I know to find where "Z" is located I would have to do list.index['Z'], but for some reason my code keeps saying "Z is not in list", and I was wondering if someone could help me figure out why?

quasi gyro
#

@stable pecan I fixed it

#

but the algorithm itself doesnt work

#
    def triangulate(self):
        m = self.lines
        for i, row_top in enumerate(m[:-1]):
            for j, row_bottom in enumerate(m[i + 1:], start=i + 1):
                m[j] = self.substract(m[j],self.multiply((row_bottom[i] / row_top[i]),row_top))
    
        return m
#

its supposed to output
1 1 3 -2
0 1 2 1
0 0 1 -2

tidal glen
#

@quasi gyro what?

#

idk if I'm a pro is but I have good experience

quasi gyro
#

So basically I'm making a program that triangulates a given matrix

#

and I don't know how to write a proper algorithm for it

tidal glen
#

I haven't done linear algebra for 3 years

#

hm

quasi gyro
#

gaussian elimination ...

#

remember anything like that?

#

when you get a triangle of zeros

tidal glen
#

I remember some of that topic

#

I might need to reread about it

#

you have rules to determine which one of the following to use?
Swapping two rows,
Multiplying a row by a nonzero number,
Adding a multiple of one row to another row.

#

@quasi gyro

quasi gyro
#

I dont swap, i just use this Adding a multiple of one row to another row.

tidal glen
#

yeah I realized that after reading your code

#

give me a moment

#

not sure what you're doing here
(row_bottom[i] / row_top[i]),row_top)

quasi gyro
#

oh lemme send the full class

tidal glen
#

this looks like you're on the diagonal all the time

#

because i is the index of row_top

quasi gyro
#
class matrix():
    @staticmethod
    def substract(list1,list2):
        finallist = []
        index = -1 
        for item in list1:
            index+=1
            finallist.append(float(item)-float(list2[index]))
        return finallist
    @staticmethod
    def multiply(scalar,list1):
        listmult = []
        for item in list1:
            listmult.append(item*scalar)
        return listmult

    def __init__(self,lines):
        self.lines = lines
        self.n = len(lines)
        self.m = len(lines[0])
    def show(self):
        for line in self.lines:
            x = ""
            for integer in line:
                x+=f" {integer}"
            print(x)
    def triangulate(self):
        m = self.lines
        for i, row_top in enumerate(m[:-1]):
            for j, row_bottom in enumerate(m[i + 1:], start=i + 1):
                m[j] = self.substract(m[j],self.multiply((row_bottom[i] / row_top[i]),row_top))
    
        return m


    def show_triangulate(self):
        for line in self.triangulate():
            x = ""
            for integer in line:
                x+=f" {str(integer)}"
            print(x)
    def show_matrix_obj(self):
        print(self.lines)
tidal glen
#

are you not allowed to use numpy?

lucid mason
#

python 🤮

quasi gyro
#

it's not an assignement, I'm making this so I can "cheat" in upcoming math exams

#

basically to go faster

lucid mason
#

oh shit i did that

tidal glen
#

you should use numpy then

quasi gyro
#

but i dont want to use numpy

#

i want to make a standalone

lucid mason
#

my calculator allowed me to upload python programs to it

quasi gyro
#

version

#

cause numpy has a tri() method

#

which does it

tidal glen
#

because I'm going to be honest with you, the helper methods aren't pretty

quasi gyro
#

I found it kind of lame

#

that it was so easy

tidal glen
#

bruh you want to cheat

#

why care

quasi gyro
#

yea but I want to understand my cheat

tidal glen
#

lol

quasi gyro
#

I'm fucked in the head basically

#

idk

#

I dont like the easy way out, but at the same time im contradicting myself cause im cheating aka easy way out

#

so is the algorithm that hard?

tidal glen
#

no but I didn't like your subtract and multiply methods

quasi gyro
#

yea numpy does that better

#

(also the actual reason why im making this the hard way is to impress my dad)

#

he made this when he was a student

#

in fortran 77

tidal glen
#

I don't see why it doesn't work. Run it and print the results every step

#

take a look at what happens after each step

#

then when you see a step that shouldn't happen, try to understand what you did wrong

quasi gyro
#

ok

safe siren
#

I need help with learning the basic programming for DNA sequences. I am in biochemistry and my professor threw this at me and I have no knowledge about computer programming. Can anyone on here help me?

half lotus
#

This isn't the right channel. Claim an available help channel #❓|how-to-get-help. Furthermore, you need to be specific about your problem, like what the requirements are, what code you have, where you're stuck, etc.

fiery cosmos
#

how hard would it be to get a job with a cs degree?

last blaze
#

This isn't the channel. Try #career-advice. The tl;dr though is that it's hard but not impossible

lament portal
#

ok, so I got this error Input_data = np.array([2.1, -1.9, 5.5], TypeError: array() takes from 1 to 2 positional arguments but 4 were given
but this is my code?

Input_data = np.array([2.1, -1.9, 5.5],
                      [-1.5, 2.4, 3.5],
                      [0.5, -7.9, 5.6],
                      [5.9, 2.3, -5.8])
mint jewel
#

you need to pass it as a list of lists

#
 np.array([[2.1, -1.9, 5.5],
                      [-1.5, 2.4, 3.5],
                      [0.5, -7.9, 5.6],
                      [5.9, 2.3, -5.8]])```
fiery cosmos
#

where all discrete math is used in computer science?(excluding graphs)

mint jewel
#

I would say encryption, error correcting codes and such

lament portal
#

ah

fiery cosmos
#

best place to learn OS?

warped quarry
#

Does anyone know of a good reference for pythonic implementations of union find?

vocal gorge
#

hmm, google gives me plenty, but because PyPI for some reason doesn't have sorting by downloads, no idea what's a good one

warped quarry
#

Thanks!

vocal gorge
#

Is it possible to automatically evaluate a group presentation, like:

"<s1,s2 | s1^2==e, s2^2==e, (s1*s2)^3==e>"

to generate all elements (group must be finite, obviously) and then do simple classification like finding all conjugacy classes? I know how to properly parse the expression and probably how to find the classes too - my question lies in whether there are algorithms for computing all members, since my attempts had... problems with, say, the example above (it's just the S3 group).

#

oh god

#

Novikov–Boone theorem

The negative solution to the word problem for groups states that there is a finite presentation ⟨S | R⟩ for which there is no algorithm which, given two words u, v, decides whether u and v describe the same element in the group. This was shown by Pyotr Novikov in 1955[4] and a different proof was obtained by William Boone in 1958.[5]

#

TFW you not only don't discover a solution to your problem, but find a proof that for some variants of your problem, no solution exists

#

which looks hardcore, but might be what I need

static dune
#

Hello everyone.
So we have this project where we want to train our model with pictures of different objects (Cars, etc) using google street view.
Now the question is, is there a way that street names won't be there lying along the roads and streets?Want the pics to be clean with no written stuff. I would be really thankful if someone can help me with this.

oblique panther
#

@static dune this is a better question for #data-science-and-ml but why can't the images have any writing?

#

if you want to have a model that can identify cars and such in contexts where cars typically appear, you wouldn't want the model to be useless if there happens to be a stop sign in the picture

bronze imp
#

hello pp's i'm new at python i don't know much about it and i got a beefy assigment to do if anybody can help

balmy siren
#

Hey, Anyone here familiar with Ugly Numbers problem ?
I managed to get the answer of first problem that asks only about "if a number is ugly or not" but this problem "find the Nth ugly number" is little complicated in terms of time complexity, and I've read somewhere that it requires DP as an additional approach to solve.

So mine approach is like,

  1. Check if the number is ugly or not by dividing it by 2 or 3 or 5, Also there shouldn't be any other factors than these numbers.
  2. Divide the number, and get the remainder. Check if the remainder is 0 or if it exist in the list of ugly number -> because if the remainder exists in the list, it means we've already checked the number(remainder) and it's ugly.
def uglyN(n: int) -> bool:
    result = [1]
    i = 2
    num = 0

    while num < n-1:
        temp = i
        if temp % 2 == 0:
            temp //= 2
        if temp % 3 == 0:
            temp //= 3
        if temp % 5 == 0:
            temp //= 5

        if temp == 0 or temp in result:
            result.append(i)
            num += 1
        i += 1

    return result[n-1]

The problem with this solution is that, it takes too much time to compute the Nth ugly number if N > 350+, and i guess the problem is with last IF condition

    if temp == 0 or temp in result:
          result.append(i)
          n += 1

Here the value of n only increases if that particular number is ugly otherwise it stays same, and this will put the loop to run on the same value.. I mean, suppose you want to iterate from 2 to 10 but after 6, 7 isn't an ugly number.. so loop iteration won't increase in that case.
Please correct me if i am wrong anywhere and tell me how i can improve it for better complexit

flat sorrel
#

you can perform binary search since result is sorted

shy inlet
#

You could use bisect, assuming you're allowed to import a builtin

runic tinsel
#

In the Python programming language, lazy functional code for generating regular numbers is used as one of the built-in tests for correctness of the language's implementation.

#

by regular they mean ugly

#

interesting fact

#

looks like this (before itertools.tee introduction)```
def merge(g, h):
ng = next(g)
nh = next(h)
while 1:
if ng < nh:
yield ng
ng = next(g)
elif ng > nh:
yield nh
nh = next(h)
else:
yield ng
ng = next(g)
nh = next(h)

def times(n, g):
for i in g:
yield n * i

class LazyList:
def init(self, g):
self.sofar = []
self.fetch = g.next

 def __getitem__(self, i):
     sofar, fetch = self.sofar, self.fetch
     while i >= len(sofar):
         sofar.append(fetch())
     return sofar[i]

def ugly():
yield 1

me_times2 = times(2, m)
me_times3 = times(3, m)
me_times5 = times(5, m)
yield from merge(merge(me_times2,me_times3),me_times5)

m = LazyList(ugly())

print(m[71242])

halcyon plankBOT
#

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

ionic hedge
#

Ok

#

Lol arm better than x86

sullen fox
#

Age = int(input('What is your age? Input it below!:\n'))
print('Your age is' + Age)

#

Hi can someone tell me why this code isn't working?

hazy basalt
#

use , not +

agile sundial
#

the reason is because you can't concatenate a string and an int

sullen fox
#

@agile sundial @hazy basalt Thank you

eager hamlet
austere sparrow
#

Are there any sorting algorithms with asymptotic complexity between O(n logn) and O(n^2)?

vocal gorge
#

yup, there's one with 4/3 I think
EDIT: nope, I thought of stooge sort, which is ~2.2

austere sparrow
#

Are there any sorting algorithms with asymptotic complexity between O(n logn) and O(n^2)?
...well, apart from silly stuff like

def my_sorted(iterable):
    xs = list(iterable)
    xs.sort()
    for _ in range(int(len(xs)**1.7) + 1):
        pass
    return xs
vocal gorge
#

hmm, or I was misremembering

ivory sky
#

In-place merge sort and shellsort

vocal gorge
#

the latter is O(n^2) worst

#

oh, I see, average 3/2. Yup, that works. Guess I wasn't entirely wrong.

fiery cosmos
#

The number pattern one

forest seal
#

probably some kind of append to a list, while i >= 5... IDK im a noob, but it would approach it that way

agile sundial
#

is that homework?

shy zenith
#

Even I felt like that

last aurora
#

I hope my question fits into this channel!
I truly apologize if i'm not wording this properly since i'm new to python.

**Is it possible to write a script/exe that, once clicked, would reduce the pc's clock by 8 hours for example, and another one that adds 8 hours to it once clicked **

eager hamlet
crude meadow
#
payload2 = {'api_key': api_key, 'market_hash_name':'AWP%20%7C%20Hyper%20Beast%20(Field-Tested)', 'page': 5, 'app_id': 730, 'code': my_token.now()}

response3 = requests.post('https://bitskins.com/api/v1/get_sales_info/', params=payload2)

i think my string is wrong for the request. whats the best way to check/print the full string?

gritty oak
#

I have already installed my Tensorflow module using pip but if I'm importing it in my jupyter textbook it gives an error saying no module found. All other modules are getting imported except tensorflow. Can someone help me in fixing it?

half lotus
#

You should claim an available question to get help with that. Help with installing packages is not a suitable topic for this channel. See #❓|how-to-get-help

oblique panther
#

!e

def max_sort(num_list):
    instances = [0] * (max(num_list) + 1)
    for i in num_list:
        instances[i] += 1
    new_list = []
    for i, num in enumerate(instances):
        new_list += [i] * num
    return new_list

print(max_sort([1, 6, 2, 1, 1, 6, 2]))
#

hmm

#

!e

def max_sort(num_list):
    instances = [0] * (max(num_list) + 1)
    for i in num_list:
        instances[i] += 1
    new_list = []
    for i, num in enumerate(instances):
        new_list += [i] * num
    return new_list

print(max_sort([1, 6, 2, 1, 1, 6, 2]))
halcyon plankBOT
#

@oblique panther :white_check_mark: Your eval job has completed with return code 0.

[1, 1, 1, 2, 2, 6, 6]
oblique panther
#

great

#

max(num_list) is O(n)

#

but what about the rest?

#

it's as many steps as whatever max(num_list) happens to be

#

would that be notated as O(max(n))?

scenic canopy
#

@oblique panther it appears that max_sort uses O(n) memory and runs in O(n) time - that being said, there is a more efficient algorithm (only one pass) for the case where you only have 3 unique values in the list: https://en.wikipedia.org/wiki/Dutch_national_flag_problem

The Dutch national flag problem is a computer science programming problem proposed by Edsger Dijkstra. The flag of the Netherlands consists of three colors: red, white and blue. Given balls of these three colors arranged randomly in a line (it does not matter how many balls t...

lean dome
#

I agree, that's just O(n), as far as I can see.

#

You generally keep only the term with the fastest growth rate, and drop constants from it.

vestal mango
#

Hello all, I am reading about the Mixin pattern, and there is a detail that I couldn't understand. The Wikipedia article cites the design of the socketserver python module (specifically, the classes ThreadingMixin and ForkingMixin). My question is, why don't we make ThreadingMixin inherit from BaseServer (instead of leaving it without base classes)? In my mind, this would make it clearer (and more accessible to static analysis tools) that self.process_request overrides a method in the base class, and that the calls to self.finish_request, self.shutdown_request are all directed to the base class. This shouldn't cause any problem, since python already linearizes all base classes in case of multiple inheritance, and thus a class ThreadingUDPServer that inherits from (ThreadingMixIn, UDPServer) under my alternative design, would have BaseServer moved as its last element in its list (and its MRO would be equivalent)...

#

Oh, markdown links are not supported on discord 🤔

#

anyway, I apologize if the question is not really on-topic on the channel, and I am ready to move it to a more suitable one. I couldn't find a channel about design patterns...

north zealot
#

Having a mixin inherit from a base class defeats the purpose IMO

#

You'd usually use a base class, and throw everything you want into the mix

#

If the mixins did inherit from the base class, python would error out, because you have the same ancestor on two different paths

vestal mango
#

@north zealot that's exactly what I am trying to explain in the end. Python won't complain nor error out when faced with diamond inheritance. This is a well-defined case handled by MRO via C3 linearilization.

#

e.g. if we have had:

class BaseServer: pass
class TCPServer(BaseServer): pass
class UDPServer(BaseServer): pass
class ForkingMixin(BaseServer): pass
class ThreadingMixin(BaseServer): pass

class ForkingUDPServer(ForkingMixIn, UDPServer): pass
class ForkingTCPServer(ForkingMixIn, TCPServer): pass
class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass

then the MRO for the last 4 classes would be exactly the same.

#

For example, for ForkingUDPServer after applying C3 linearlization, base classes would be reorganized in a linear list as: ForkingMixin, UDPServer, BaseServer.

north zealot
#

That doesn't make much sense

#

(IMO)

#

A mixin shouldn't have a base class

oblique panther
#

@lean dome I don't think it can be O(n) because if you have ten elements that are each below 100, and then you add 800, it should take eight times longer even though you only increased n by one.

#

I suppose it's O(n) if you assume that n represents the max value of the list and not its length.

oblique panther
#

@scenic canopy I just picked three elements arbitrarily to make sure it would work for repeated elements in general. But I hadn't heard of that problem so thanks for bringing it to my attention. Isn't Timsort a form of quicksort that's optimized to handle repeated elements? (and the best case that it's already sorted?)

vestal mango
#

A mixin shouldn't have a base class
@north zealot I agree, the first thing I learned when I was introduced to Mixins, is that they don't have base classes, but as far as I can see, this is done for no good reason and there are actually some advantages to add base classes to them (as I mentioned in my question originally)

potent shore
#

I recently bought the subscriptions of AlgoExpert, SystemsExpert, Grokking the System Design Interview, Grokking the Object Oriented Design Interview for my interview preparation. I want to share these accounts for some few bucks. Please DM me if you are interested.

eager hamlet
mint jewel
#

use pprint.pp rather than print

crude meadow
#

thank you, thats way better 😄

crude meadow
#
{'data': {'cache_expires_at': 1599926939,
          'items': [],
          'page': 1,
          'rendered_in_seconds': 0.01},
 'status': 'success'}

im trying to get data from a website. if i put the link in my browser, its showing all items unter 'items' correctly. If i do it in my programm in pycharm its displayed ''items': []' as if im not having any items. Am i doing anything wrong or what could be the problem?

stiff sail
#

@crude meadow you are using the pycharm debugger?

crude meadow
#

yup fixed it already, it was a mistake with the params

stiff sail
#

ok 👍

eager hamlet
glacial wind
#

Can you explain what do you mean by first value? Are the values in a list for each key? Either ways, you can either access the individual value for a key by data[key] = value or you can iterate through all values by
For key, value in data.items():
print(key, value)

crude meadow
#

thanks . values() just did what i needed 😄

gaunt forge
#

If you ran self.values() what would be returned?

boreal linden
#

Hey all, I'm trying to figure out this runtime complexity question

#

sum log(n) over n gives n log^2(n) if I'm not mistaken, is that correct?

#

I know generally log(n) over k would be log^2(n) so equally fast, but since this sums over n, I'm not sure.

mint jewel
#

it would be nlog(n), would have to be sum i to be log^2 n

boreal linden
#

Ah I see, it only sums the first item, so its slower then. Thanks a bunch 🙂

#

I always get these sums messed up

vocal gorge
#

note how the summand doesn't depend on i

#

so the sum is just multiplication by log n

boreal linden
#

Yeah that had me confused. Thanks

fiery cosmos
#

lmao in school im learning python 2 instead of python 3 ;-;

mint jewel
#

F

pulsar bay
fiery cosmos
#

When making a game should you make a user interface (start screen) first or last

random talon
#

@fiery cosmos personally id focus on core game mechanics first. Worry about asetic shit later
But you want a good balance. 🤷‍♂️

fiery cosmos
#

Thanks @random talon

random talon
#

No problem

oblique panther
#

@fiery cosmos I would ask on #user-interfaces, but when I make stuff that has any kind of interface, I typically make the interface last.

sand kestrel
#

Yo

#

Anyone on?

sudden ember
#

Hi, I recovered from covid and I have a school assignment due next week (given an extension) that I have next to no real idea on what I need to study to understand/get the problem done. The thing necessary to get my code tested is already made, but I don't have the slightest idea what to really use to write the code besides using recursion

#

My main problem is I have no idea how to make the code recognize A-Z/a-z with recursion

granite salmon
#

When making a game should you make a user interface (start screen) first or last
@fiery cosmos

Honestly: Throwing together a (bad) title screen first makes your prototype feel more cohesive, but make sure to provide a method to skip it for playtesting. My games generally go a single button titles screen > title screen + sandbox > title screen + levels > signature splash screen + polished title screen + levels

lean dome
#

My main problem is I have no idea how to make the code recognize A-Z/a-z with recursion
@sudden ember you can do something like:

def is_vowel(c):
    return c.lower() in "aeiou"

You don't need to check for consonants at all because the problem constraints say that everything is either an uppercase or lowercase English letter, so every character that is not a vowel must be a consonant.

sudden ember
#

The problem is I can't use that kind of method either I can only have one function defined

lean dome
#

That's fine, you just inline that logic into the place where you would call it if it was a function.

#
def consonantReverse(s):
    vowel_first = s[0].lower() in "aeiou"
    vowel_last = s[-1].lower() in "aeiou"
sudden ember
#

Got it. I think I know what to do now. Thank you

lean dome
#

If you haven't learned in yet you could also just do that with 5 separate conditions.

sudden ember
#

I have learned in imma use a statement and make sure all vowel values don't get reversed by making them return [-1]. I think that might be what I need

lean dome
#

Good luck!

sudden ember
#

Thanks my man

late osprey
#

Hi everybody

#

I want to know if someone knows any program written in python about the collatz conjecture
The problem is that I need the process for each number of the sequence

vocal gorge
#

I've seen quite a few. What are you having trouble with?

late osprey
#

I'm a beginner so I can't even imagine how to do that program :c

brave oak
#

I'm a beginner so I can't even imagine how to do that program :c
@late osprey what do you want the program to do?

late osprey
#

for example I introduce 3 at the program, so I want that the program use the Collatz conjeture in sequence until reach a loop (as 1)

brave oak
#

oh, okay, I understand

#

well

#

if you can do basic stuff with Python

late osprey
#

but also y want that the program show me the process
In three is:

3x3 + 1= 10
10/2= 5
5x3 +1= 16
16/2^4 = 1

brave oak
#

like conditionals (if) and loops (while)

#

that should be pretty simple

#

if you can't, that's where I suggest starting

late osprey
#

Okay, thank you :3

brave oak
#

yw

#

I suggest you write out the steps that you would take (like a flowchart) to apply the function to a number until you get your desired result

#

then try to translate that into code

late osprey
#

The problem is that Idk how can the program understand wich is the desired result (in this case is a loop, whatever loop)

#

I suggest you write out the steps that you would take (like a flowchart) to apply the function to a number until you get your desired result
@brave oak But I'll start at this way, thank you so much :3

scarlet citrus
#

does anyone have any tips on how to get coding into algorithms + data structures. I've taken a fair share of DS + Algos (Graduate level), but a lot of the stuff were usually in pseudocode. I can usually also code most of them in java, but is there a way to get myself to start doing it in Python?

stable pecan
#

we have a list of resources

#

!resources

halcyon plankBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

stable pecan
#

that may help one get started

split sigil
#

how does python use infix and postfix expressions?
if I have an expression x+y*z in the script, will it convert to postfix and then evaluate it?

vocal gorge
#

that's an interesting question; might want to ask in #internals-and-peps if you don't get an answer here. All statements and expressions are translated to bytecode before being executed by the Python interpreter, so unpacking of expressions into something more concrete probably happens there. I don't know where to find the exact rules of that, though

split sigil
#

makes sense, didn't think of bytecode

proud spade
#

What do you start with for Data science or machine learning? pandas, numpy, ?

marsh swallow
#

@proud spade Both Pandas and Numpy are essential for both Data Science and ML. Also look into sklearn for ML

proud spade
#

@marsh swallow ok, how much can you learn on your own? Vs when you need college?.... can someone get a position without college?

marsh swallow
#

There are a lot of very good resources online, we live in an era of virtually free, limitless information. As for getting a position, I’m not sure what position you are looking for but being self taught is definitely something people do.

proud spade
#

@marsh swallow I do t mean a bunch of Qs, but what position would a company even have open for someone who is self taught?

marsh swallow
#

I’m not really sure. If you are talented and can illustrate good knowledge, your chances of hiring go up. Again, I’m not sure.

proud spade
#

@marsh swallow thank you. It made a bit of scense to me when I saw a Stock Data Analyses and shows a projection that was 95% correct ( what the graph looked like)

gaunt forge
#

I recommend asking in #career-advice for these sorts of questions, but I have a pretty good job and I am self taught, it's a common story.

cursive siren
#

guys I am having an issue with some code, it is very very basic can someone help me out? Thank you

crude meadow
#
def highlight_values(s): 
    color = 'red' if s < 100 else 'blue'
    return 'background-color: % s' % color 

display(filt_df.style.applymap(highlight_values, subset = pd.IndexSlice[:, ['float_value_x', 'diff_low', 'avg_price']]))

right now the rules for coloring are applied to all 3 columns. how would i define other colors for each column?

fiery cosmos
#

Does anyone know what "the cube" is maybe in context of SDLC? I am reading a text for a course that is for secure programming. It frequently references "the cube".

#

The textbook is a bit dated. I'm just really hoping it's not short hand for a cubicle or something

half lotus
#

Yeah, it means cubicle

faint pike
#

print("What would you like to do")
menu = {}
menu['1']="add"
menu['2']="subtract"
menu['3']="divide"
menu['4']="divise"
while True:
options=menu.keys()
options.sort()
for entry in options:
print entry, menu[entry]
does anyone know why repl.it keeps saying there is and unexpected indent in line 10?

brave oak
#

because there is

#

for should be the same level options.sort()

faint pike
#

so line 9 should be options.sort() for entry in options:?

brave oak
#

no

#

the same indentation level

faint pike
#

ok thx

ornate silo
#

When creating an abstract class, how do you know which methods should be abstract methods (using ABC)

flat sorrel
#

The ones for which you cannot come up with a default implementation that is meaningful.

gusty grove
#

when using big O notation, do i always simplify as much as i can?

#

lets say i have a algorithm and its exact runtime relation to n

#

but its a super complicated function

#

do i then just say O(e^n) because it exhibits exponential growth?

north zealot
#

Looks like you can make an approxiamtion here, I’d say O(n) since it seems to be just proportional, doesn’t it?

#

I might be missing something though

gusty grove
#

log10 y scale

flat sorrel
#

I believe it is more common to express exponential complexity with a base of 2 but yeah, only keep the largest term

fair summit
#

Are you referring to removing lower order terms ?

gusty grove
#

yes

#

yeah base 2 sounds reasonable

fair summit
#

You do so because big-O notation refers to the growth in runtime as the input size grows arbitrarily large

#

So the lower order terms become insignificant

gusty grove
#

right, but im not sure if what i have is lower order terms since its not a polynomial

fair summit
#

You don't really get to choose the k in O(k^n) btw, it's completely dependent on the algorithm

gusty grove
#

so i say O(k^n)?

fair summit
#

just like O(n^3) is not the same as O(n^2); O(2^n) is not the same as O(e^n)

#

no, you say the actual k

gusty grove
#

well i have no idea what the actual k is

#

can i somehow rewrite the function i gave in exponential terms?

fair summit
#

then you can say O(k^n) or just say it's exponential

#

but really you want to know that k

gusty grove
#

how would i figure it out?

fair summit
#

finding complexity of arbitrary algorithms is not a trivial task, it's actually undecidable, but there are methods like the master theorem to find it for some programs

gusty grove
#

hm

#

but isnt k irrelevant?

fair summit
#

no

gusty grove
#

i can always write it as a*e^(c*x) right?

#

and then i drop a and c

#

and am left over with e^x

#

or whatever i choose as base

fair summit
#

you can have c * k^n and drop the c

#

that's it

gusty grove
#

ok, thanks 🙂

fair summit
#

remember that ^ takes precedence over *

#

(ck)^n is not c(k^n)

gusty grove
#

yup

fair summit
#

it makes sense sometimes to not care about the actual complexity other than the class it belong in

#

in such cases, you can just say "it's exponential", "it's polynomial" etc

#

https://en.wikipedia.org/wiki/Time_complexity#Complexity_classes here are the names of the different classes of algorithms, along with examples of runtime

In computer science, the time complexity is the computational complexity that describes the amount of time it takes to run an algorithm. Time complexity is commonly estimated by counting the number of elementary operations performed by the algorithm, supposing that each elemen...

gusty grove
#

gotcha

flat sorrel
#

2^(kn) is equivalent to e^((ln2*k)n),

#

But you need to determine what k is from the algorithm if you want to be exact

placid lark
#

What do you think about getting one of AWS, Google or Microsoft developer certifications?

#

for Junior developer

#

in my country - Poland, any of candidates have got this stuff

#

will i be unique?

#

and is it worth?

vocal gorge
summer reef
#

i know it's recognized worldwide, it's a valuable asset
But I don't know if it makes sense to get it on your own, I'd expect my school/business to pay it

placid lark
#

okey, and witch is most valuable, they are so many

placid lark
#

Acctualy im thinking about buying new pc, what do you think about 8gb ram? in 2021?

#

or just for another 3years, basicly its laptop, for another minimum 3ye

vocal gorge
placid lark
#

for DS, Web Dev

#

hmmm...

oblique panther
#

@vocal gorge the name of this channel is not very communicative for most of our users so I wouldn't hold it against them.

agile sundial
#

since many courses are named computer science ____, there was a request for a name change though

half lotus
manic shard
#

what file format is [[,,,],[,,,],...]
@raven oracle any if u format the data like that

mellow bone
#

Hello, can anyone help for a question about private attributes?

#

Attributes are made private because we don't want people to easily change it, so we add "" before the name (from what i understand), but python doesn't actually make sure that private attributes cannot be change right? So the "" is just there as convention. Is that right?

half lotus
#

Yes, it's just a convention.

#

Assuming you wrote a single underscore

#

Double underscore mangles the attribute name such that it cannot be accessed by its original name outside the class, but it's still possible to change if you really try.

mellow bone
#

but private attributes can still be changed though the methods in that class, but the point is that the client code doesn't mess up the code, like changing the attribute type, etc, is that correct?

lean dome
#

right.

#

Other languages enforce that only the class itself can modify its attributes. Python doesn't enforce that, but the naming convention still tells users if there's something that they shouldn't touch.

mellow bone
#

ok, that makes more sense

#

thank you

eager hamlet
#

hey so for dijkstra's do i stop as soon as i reach to destination node?

oblique panther
#

@eager hamlet I don't think reaching the destination node guarantees that you've yet found the shortest path but let me check.

#

so it stops when the queue of nodes to be examined is empty, but I need to remember why that's significant

balmy siren
#

Hey everyone, is maximum binary tree somehow differ from the normal binary tree ?

oblique panther
#

@balmy siren it looks like a maximum binary tree is a binary tree with a few extra properties

#

namely that every node in the tree has to be the maximum of all its children nodes.

#

it looks like another constraint is that while the root of each (sub)tree has to be the max, you also have to divide the remaining nodes equally between each branch

#

I can think of one solution but it requires sorting the list first

balmy siren
#

@oblique panther thanks for replying...
Yeah as far as I understand, suppose if we've a list of integers then maximum among those integers will be the top root of the tree, right? Next we will divide the tree in two halves,
For example :

num = [1,2,3,6,5,4,0]
here, the maximum is 6
leftsubtree = [1,2,3]
RightSubtree = [5,4,0]

Now, i am little confused in this section like, if we are going to add nodes at the left side of the tree then do we need to add those nodes according to the which node is maximum ?
Like,

leftsubtree = [1,2,3]
max = 3
leftsubtree = [1,2]
max = 2
:

is it like that ??? And same follows for the right side right?

I can think of one solution but it requires sorting the list first
You meant, sort the leftsubtree and RightSubtree list

sorted(leftsubtree, reverse=True)
sorted(rightsubtree)

Now, Keep adding the 0th index element to the leftsubtree and -1st index element to the rightsubtree...
Please tell me if I am wrong somewhere or what else could be your method

oblique panther
#

@balmy siren before we go any further, can you tell me why you're interested in this? I'll still help you even if it's for school so you can be honest with me, I just need to know.

balmy siren
#

@oblique panther Actually i was solving a problem of leetcode and came up with a brute Force solution, it works on few test cases but not with another, I just wanted to know if I ever understood the problem correctly or not, seems like I do but some test cases shows completely different results...

oblique panther
#

alright. thanks for telling me. leetcode was actually the first result when I searched for "maximum binary tree"

balmy siren
#

Hahah that seems right.. so let's discuss about the problem ?

oblique panther
#

are you familiar with recursion?

balmy siren
#

Yes

#

Can I show you my code?

oblique panther
#

yeah

balmy siren
#

Okay wait.. Actually i am in a hospital now, so if I can retrieve the last night version then i will paste it here otherwise I need sometime to implement it again here (just 5-6min.) Okay?

oblique panther
#

sorry, you're in a hospital? are you okay?

balmy siren
#

Yeah completely fine, just came here for a covid19 negative report, most of my reports came negative and now I am just waiting for some papers now..

oblique panther
#

alright

#

just at me when you're ready

#

@balmy siren all good?

balmy siren
#

Yeah man, i am writing
Can't retrieve the code from mobile device

#
## Binary tree tilt

class Solution:
	def constructMaximumBinaryTree(self, nums: list):
		
		def insertLeft(self, data, root):
			if root is None:
				return TreeNode(data)
			root.right = insertLeft(data, root.right)
			return root
		
		def insertRight(self, data, root):
			if root is None:
				return TreeNode(data)
			root.left = insertRight(data, root.left)
			return root
		
		## left and right subtree values
		max_number = max(nums)
		index_mn = nums.index(max_number)
		leftsubtree = sorted(nums[0:index_mn], reverse=True)
		rightsubtree = sorted(nums[index_mn::])
		
		## construct a basic tree
		root = TreeNode(max_number)
		if leftsubtree.__sizeof__() != 40:
			root.left = TreeNode(leftsubtree.pop(0))
		if rightsubtree.__sizeof__() != 40:
			root.right = TreeNode(rightsubtree.pop())
		
		## add nodes
		while len(leftsubtree) != 0:
			root.left = insertLeft(leftsubtree.pop(0))
		
		while len(rightsubtree) != 0:
			root.right = insertRight(rightsubtree.pop(), root.right)
oblique panther
#

why 40?

balmy siren
#

What ?

oblique panther
#

if leftsubtree.__sizeof__() != 40:

balmy siren
#

Ohh because the size of empty list is 40, right?

oblique panther
#

no

#

I mean maybe it's 40 bytes or something

balmy siren
#

I've seen cases where it increases the size right after adding the first element

oblique panther
#

what are you trying to check, that the list is empty?

balmy siren
#

I mean maybe it's 40 bytes or something
Lists are dynamic in nature, so once you add an element in there, it will create a block that can store 3-4 elements within the same size,
Like, once you add first element, the size will increase to 48 or something and again if you add another element, then it will remain on 48 or smth.

For an empty list it would be 40

#

what are you trying to check, that the list is empty?
Yes

#

I guess the problem in my implementation is related to those insertLeft and insertRight function

oblique panther
#

if you're trying to check if the list is empty, don't rely on details about how lists are stored internally

#

just do len(list_) == 0

#

lists are also implicitly false if they are empty so if list_ would be false if the list is empty

#

@balmy siren still there?

dull idol
#

whats the difference between float and int

fair summit
#

real vs integers

dull idol
#

oh ok

#

so if i use float instead of int will it make a difference?

fair summit
#

yes, because they also have precision issues, you can't represent all numbers using floats

dull idol
#

oh alright

#

thankyou!

amber hedge
#

Anyone there?

oblique panther
#

Hey @amber hedge, any time you have a question, go ahead and ask. Make sure you're in the right channel though. Check the channel description to make sure it's a computer science question.

heavy zenith
#

bruhh

#

i need help

#
  1. Write a Python program to find the repeated items of a tuple.
#

this is the q

#

how do u solve it?

#

someone help

oblique panther
#

@heavy zenith can you give me an example of the input and expected output?

heavy zenith
#

tup = (2,34,2,7,8,5,2)

#

then expected output should be 2

manic shard
#

as in there is 2 repeated items ?

#

@heavy zenith

heavy zenith
#

yes

manic shard
#

tup = (2,34,2,7,8,5,2)

print(tup) #(2, 34, 2, 7, 8, 5, 2)
print(set(tup)) #{2, 34, 5, 7, 8}

agile sundial
#

use Counter

manic shard
#

or that

#

sets cant have duplicates so i went that way

heavy zenith
#

but my comp teacher hasnt taught it

use Counter
@agile sundial

manic shard
#

so what has your teacher taught

#

?

heavy zenith
#

creations of tuples

#

tuple swapping

#

updating tuples

radiant belfry
#

you want to print the number of repetations in the tuple?

heavy zenith
#

converting tuple to a list and vice versa

#

yes

manic shard
#

so your teacher wants you to iterate throught tuple and find duplicates that way

radiant belfry
#

have you learnt the count() method

heavy zenith
#

no

radiant belfry
#

okay

#

loops?

heavy zenith
#

yea

radiant belfry
#

okay we can use that

manic shard
#

the simplest way would be using sets but i doubt they know it

heavy zenith
#

idk sets

manic shard
#

considering list they gave

radiant belfry
#

he dosen't know ssets

#

so lets use loops

oblique panther
#

Are you allowed to use dictionaries?

manic shard
#

they dont even know sets i doubt they gone that far

heavy zenith
#

Concatenation
Repetition
Membership
Iteration
tuple updating
tuple swapping
conversion of tuples into list and vice versa
I LEARNT ONLY THAT

#

yes

radiant belfry
#

the procedure would be to have a variable to store the frequency of the letter 2. While we iterate over the tuple, and whenever we come accross the letter 2, we add 1 to the variable @heavy zenith

oblique panther
#

@manic shard a lot of people don't learn sets for a while.

manic shard
#

k

#

thats weird

#

ty for the info

radiant belfry
#

we can teach him now

heavy zenith
#

Are you allowed to use dictionaries?
@oblique panther yea

oblique panther
#

They probably have to solve it using what they've been taught so far.

radiant belfry
#

try the method i mentioned above, panda

oblique panther
#

Okay, so you can use a for loop to go down the tuple and use a dictionary to store the counts

heavy zenith
#

yes

#

will try

oblique panther
#

@heavy zenith how's it coming along?

eager hamlet
#
Write a program that calculates the price a customer has to pay for a purchase, making optimal use of the special offers to make the price as low as possible. You are not allowed to add items, even if that would lower the price.

For the prices and offers given above, the (lowest) price for three flowers and two vases is 14z: two vases and one flower for the reduced price of 10z and two flowers for the regular price of 4z.

PROGRAM NAME: shopping
INPUT FORMAT
The input file has a set of offers followed by a purchase.
Line 1:    s, the number of special offers, (0 <= s <= 99).
Line 2..s+1:    Each line describes an offer using several integers. The first integer is n (1 <= n <= 5), the number of products that are offered. The subsequent n pairs of integers c and k indicate that k items (1 <= k <= 5) with product code c (1 <= c <= 999) are part of the offer. The last number p on the line stands for the reduced price (1 <= p <= 9999). The reduced price of an offer is less than the sum of the regular prices.
Line s+2:    The first line contains the number b (0 <= b <= 5) of different kinds of products to be purchased.
Line s+3..s+b+2:    Each of the subsequent b lines contains three values: c, k, and p. The value c is the (unique) product code (1 <= c <= 999). The value k indicates how many items of this product are to be purchased (1 <= k <= 5). The value p is the regular price per item (1 <= p <= 999). At most 5*5=25 items can be in the basket.
SAMPLE INPUT (file shopping.in)
2
1 7 3 5
2 7 1 8 2 10
2
7 3 2
8 2 5
OUTPUT FORMAT
A single line with one integer: the lowest possible price to be paid for the purchases.
SAMPLE OUTPUT (file shopping.out)
14```the dijkstra's algo i wrote for this was too slow- could there be some sort of dynamic programming sol for this?
#

(i'm really bad at dynamic programming)

#

(and ping 2 reply thx)

oblique panther
#

@eager hamlet I'm trying to wrap my head around the problem

#

I want to say that this is the knapsack problem and that the question is designed to obfuscate that

eager hamlet
#

yeah

#

the thing is i have to fill it completely

#

and there's multiple elements

oblique panther
#

The input format for this question is the most bizarre I've ever seen.

eager hamlet
#

yeah

#

i hate the usaco input formatting asw

oblique panther
#

I've read it a few times and I can't for the life of me understand what it's saying

#

so you're figuring out the best combination of special offers lets you buy every item that's for sale exactly once?

#

or what?

eager hamlet
#

uh

#

so they give you some stuff to buy

#

and yeah- best combination of special offers, but some single purchases may be necessary

oblique panther
#

I'm pretty sure understanding the input format is more difficult than the actual problem.

eager hamlet
#

yeah

#

took me like 10 minutes

oblique panther
#

I probably need to work on my homework but if you can write a more cohesive description of the problem than the one your instructor gave you (which I realize shouldn't be your job), someone else might be able to help. and I'll probably check back later.

eager hamlet
#

yeah ok

quasi oracle
#

Can you show the link to the challenge? I think there's some context missing

eager hamlet
#

yeah ok

#
In a certain shop, each kind of product has an integer price. For example, the price of a flower is 2 zorkmids (z) and the price of a vase is 5z. In order to attract more customers, the shop introduces some special offers.

A special offer consists of one or more product items together for a reduced price, also an integer. Examples:

three flowers for 5z instead of 6z, or
two vases together with one flower for 10z instead of 12z.
Write a program that calculates the price a customer has to pay for a purchase, making optimal use of the special offers to make the price as low as possible. You are not allowed to add items, even if that would lower the price.

For the prices and offers given above, the (lowest) price for three flowers and two vases is 14z: two vases and one flower for the reduced price of 10z and two flowers for the regular price of 4z.```
#

literally the only thing i left out

quasi oracle
#

@eager hamlet you could try a greedy algorithm.
At each step, pick the special sale that's the most profitable.

eager hamlet
#

but then again

#

wait actually greedy might not work

quasi oracle
#

The intuition is that if you had another special sale that was more profitable, you would have picked it already by the algorithm

#

But I didn't think too deeply about it

keen hearth
#

You could try an A* search?

#

Just a slight modification from Dijkstras/min-cost.

quasi oracle
#

You think there's an instance where greedy wouldn't work?

keen hearth
#

Erm, it's tempting to think that it would work...

#

but it's also hard to concretely reason that it would work.

#

My intuition says not.

desert cedar
#

It may pick 3 * A + 3 * B over 1 * A, + 2 * B + filling the rest with singles

#

Trying to modify your bfs leaves me with a version that takes 55896870 iterations to find the solution xd

quasi oracle
#

It may pick 3 * A + 3 * B over 1 * A, + 2 * B + filling the rest with singles
What do you mean?

keen hearth
#

I'm thinking you could go a long way by just re-structuring/cleaning up the code you already have.

#

Separate the Dijkstra's/min-cost search into it's own function, that takes a start state, goal function, and successor/cost function.

#

A different approach would be to try a cached recursive function instead of iterative search. This might be conceptually clearer.

desert cedar
#

I mean that because you can have offers with a combination of items a greedy algo might skip a better deal down the line.

quasi oracle
#

If it's a better deal wouldn't it pick that deal first?

#

Greedy by profit, meaning I first process all the special sales available

desert cedar
#

How would you suggest valuing a sale in that case? ranking them from best to worst.

quasi oracle
#

I would go over each sale, and see how much it would cost if I were to pay for each item individually. The profit is then the cost of the special sale minus the raw cost

#

Although...

desert cedar
#

Say you need 4 A and 4 B
An a costs 50, a B costs 100
There is an offer for 3A's and an B for 200, a profit of 50 in this case
And an offer for 2A's for 75, a profit of 25
And an offer for 2B's for 170, a profit of 30

You'd first get the offer for 3A's and a B, have to fill it up with one more A and 3 more Bs, totalling 200 + 50 + 300 = 550
While getting 2x2 A's and 2x2 B's would be 150 + 340 = 490

quasi oracle
#

Yeah I just found another example

desert cedar
#

Sans, I refactored your solution to a more classic bfs one and it takes 1 sec on my laptop now

jaunty eagle
#

can someone help me convert python script to exe file

sudden lance
#

Hi, I have open end question. I just don't know any examples of where this is the case.
Give an example of a situation in which you would not implement a security program, even though the threat was real, and impacted your business on a regular basis.

oblique panther
#

@jaunty eagle look into pyinstaller, but that question isn't on topic for this channel.

jaunty eagle
#

oh ok sorry

oblique panther
#

No problem

sudden lance
#

Oh ok

oblique panther
#

I implemented this last night because I misunderstood the question someone was asking

#
from __future__ import annotations

import typing as t
from dataclasses import dataclass


@dataclass
class Node:
    value: int
    left: t.Union[Node, int, None]
    right: t.Union[Node, int, None]


def build_tree(nums: t.List[int]) -> Node:
    if len(nums) == 1:
        return nums[0]
    if len(nums) == 2:
        return Node(value=nums[0], left=nums[1], right=None)
    if len(nums) == 3:
        return Node(value=nums[0], left=nums[2], right=nums[1])

    mid = len(nums) // 2

    return Node(
        value=nums[0],
        left=build_tree(nums[mid:]),
        right=build_tree(nums[1:mid])
    )


class MaximumBinaryTree:

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

    @classmethod
    def from_list(cls, nums: t.List[int]):
        nums.sort(reverse=True)  # O(nlogn)
        return cls(build_tree(nums))  # O(n)

    def __repr__(self):
        return f'<{self.__class__.__name__}> {str(self.root)}'
#

I can't think of any potential uses for it

#

the root is always the largest number of its (sub)tree, and the two branches are split from the median of all remaining numbers

eager hamlet
#

ok then

#

why the future thing

#

Write a program that calculates the price a customer has to pay for a purchase, making optimal use of the special offers to make the price as low as possible. You are not allowed to add items, even if that would lower the price.

For the prices and offers given above, the (lowest) price for three flowers and two vases is 14z: two vases and one flower for the reduced price of 10z and two flowers for the regular price of 4z.

PROGRAM NAME: shopping
INPUT FORMAT
The input file has a set of offers followed by a purchase.
Line 1: s, the number of special offers, (0 <= s <= 99).
Line 2..s+1: Each line describes an offer using several integers. The first integer is n (1 <= n <= 5), the number of products that are offered. The subsequent n pairs of integers c and k indicate that k items (1 <= k <= 5) with product code c (1 <= c <= 999) are part of the offer. The last number p on the line stands for the reduced price (1 <= p <= 9999). The reduced price of an offer is less than the sum of the regular prices.
Line s+2: The first line contains the number b (0 <= b <= 5) of different kinds of products to be purchased.
Line s+3..s+b+2: Each of the subsequent b lines contains three values: c, k, and p. The value c is the (unique) product code (1 <= c <= 999). The value k indicates how many items of this product are to be purchased (1 <= k <= 5). The value p is the regular price per item (1 <= p <= 999). At most 5*5=25 items can be in the basket.
SAMPLE INPUT (file shopping.in)
2
1 7 3 5
2 7 1 8 2 10
2
7 3 2
8 2 5
OUTPUT FORMAT
A single line with one integer: the lowest possible price to be paid for the purchases.
SAMPLE OUTPUT (file shopping.out)
14
the dijkstra's algo i wrote for this was too slow- could there be some sort of dynamic programming sol for this?
(i'm really bad at dynamic programming)
(and ping 2 reply thx)

oblique panther
#

@eager hamlet from __future__ import annotations backports referring to a class by its name within the class

eager hamlet
#

feel like it'd still work w/o the __future__

oblique panther
#
@dataclass
class Node:
    value: int
    left: t.Union[Node, int, None]
    right: t.Union[Node, int, None]

This would break in some Python versions because Node isn't done being defined when it's being used here.

eager hamlet
#

oh i see

oblique panther
#

it would work without the __future__ in 3.8 and possibly some number of earlier versions.

rustic helm
#

Hello everyone. I need to get some reading done on "Computational Thinking and Programming" for my uni first semester. Can someone recommend some good resources for the same?

faint pike
#

does anyone know why whenever i type break in line 7 it claims it is incorrect

#

import random
min_value = int(input("please enter the min value you would like: "))
max_value = int(input("please enter the max value you would like: "))

if min_value > max_value:
print("these numbers won't work")

again = True

while again:
print(random.randint(min_value, max_value))

another_roll = input("want to roll again? ")

if another_roll.lower() == "yes" or another_roll.lower() == "y":
continue
else:
print("Thank you for using my script, come again!")
break

old moth
#

hey guys I justed wanted to ask is the first node is same as start node in Binary Tree?
pls fell free to ping me if you have a answer

oblique panther
#

@old moth the "first node" in a binary tree is the root

#

but any node that has more nodes below it is the root of that subtree

#

when you say "first node", are you thinking of nodes in a linked list? "nodes" serve a similar purpose in both linked lists and trees but they're not quite the same.

fallen bluff
#

hiya everyone

#

i'm trying to create a gaming bot for discord pokemon

#

does anyone have time to look at my code

#

and help me with some logic

#

just ping me 🙂

oblique panther
stable sand
#

I'm trying to use the slice function, but have two lists. I can't find anything online. Is it possible to point a certain list out and slice it and then print that slice?

brave oak
#

I'm trying to use the slice function, but have two lists. I can't find anything online. Is it possible to point a certain list out and slice it and then print that slice?
@stable sand what do you mean "point"?

stable sand
#

I have two lists. I want it to take one of em and slice that one

brave oak
#

I have two lists. I want it to take one of em and slice that one
@stable sand then what does the other list do?

stable sand
#

It's just numbers tbh, but I wanna learn it for a future project

h = [1, 2, 3] s = [a, b, c]
And I for example wanna print
1, a, 2, b, 3, c

#

There must be an easy way to do that right? Instead of writing spaghetti code

brave oak
#

@stable sand zip

#

I'm assuming those are strings, not variables (a, b, c)

#
>>> for number, letter in zip(h, s):
...     print(number, letter)
... 
1 a
2 b
3 c
stable sand
#

Would that also work for 1, 2, a, 3, b, c

brave oak
#

well

#

I suggest you read the documentation for zip

#

but in that case

#

no, because zip takes elements in order

#

if you want some interesting order you need to define it yourself

#

i.e. write a function or at least some code to make stuff come out that way

stable sand
#

Ah I see, so I won't be able to do it otherwise than to call each element individually