#algos-and-data-structs
1 messages · Page 85 of 1
@severe smelt this is not an R server. Let's see if there is one.
I've tried looking, but cannot find one
Lots of Python users are fluent in R as well
that's why I asked here
#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.
here's an invite: https://discord.gg/010z0Kw1A9ql5c1Qe
@undone ore just ask. It depends on the question
Since it's a robotics question, it should probably go in an individual help session.
@severe smelt What is the problem you are having? I know a bit of R but not a lot.
oh thanks!
So I have uploaded some data from IBEXfarm surveys I conducted
the files are javascript
and then the output it a .txt
is ram classed at storage
I keep getting this error when trying to create columns
What is the error you are getting and how does your code look?
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
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.
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)
does str(y) return an expected structure of the data?
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
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
I wrote a program a while ago that did similar stuff. Let me see if I can find the method I used.
oh that would be wonderful
I could send you my data if you would like to try it yourself
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
thanks
@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
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
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
I have no idea how to do this for my data set
I want to add columns
you are deleting them it seems
I am deleting some of em then I am appending sort of
Oh blimey, I do not actually add any. I thought I had a cbind in there somewhere but I do not
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?
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.
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
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
Hi, sorry I was away
No worries, I went dark a bit when I was experimenting as well 😄
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
I see
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.
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
you could make a column called word_answer or something similar and have it as a 3-level factor containing plurals {cats, catten, cuts}
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
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 😄
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
by the way, just doing it manually in Excel by transposing. I think it's the only way
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)
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
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
Computer Science students: do you use flash cards? (random question, I'd be really pleased to talk with someone experienced with flash cards)
Guys, where do you study? And where do you recommend to study computer science with 12k dollars budget?
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?
@glossy verge
Not sure if it still works (feedback needed)
- Make a new e-mail account on outlook.com
- Use that e-mail to register for free microsoft dev esentials https://visualstudio.microsoft.com/dev-essentials/
- One of the gifts for should be a coupon for 30 days free access to Pluralsight (normally it's 30USD/month or 300USD/yead)
- 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 this looks like something for a for loop.
But the teach specifically says using a while loop 😟
For would have been easier yaa
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 😉
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 .......🙃
I literally put "tensorflow object detection" into google and found this https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10
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 "
print("Hello World")
@frigid obsidian errr.. This is a python server. You could ask it in a an off topic channel, but there are servers for C++
oh alright
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...)
It's called a Ceasar Cipher.
Hi Anyone know any java discord server i can join?
You would need to know how to loop over strings and build new ones
or anyone know java who can help me please
Ok, thanks for your help @quasi oracle, much appreciated
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).
why is java is terrible
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:
oh ok
@fiery cosmos because of the specification of the language. The off topic channels are the place to rant about that, though.
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?
I think this could better go in #data-science-and-ml
Thanks!
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)
the problem is it's not synchronized
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)
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
last cow
https://docs.python.org/3/library/heapq.html
it uses a normal list, it guarantees that 0th element is the minimum if you add and remove things with these functions
so it just takes cows with the least time first
oh yes
i think i get it now
im still here trying to debug my slow-butt program lol
max is unnecessary
what's unnecessary?
in my solution, I mean, there's no risk of reducing time to negative
that just goes into a comment
if I need clarity, i could comment "won't become negative"
true
I need a cow input file
https://hatebin.com/qpbkyqtyla There's my version, using a nice on run_once decorator on the signal method
how do people get to know about areas of interest and publish papers?
how do people publish papers, or how do people get to know about published papers?
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.
i dont get it
Anyone know anything about using programming to solve math related problems?
Like ramsey numbers?
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
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.
but if i use mean, wouldnt it be that the one with the highest rank is better?
Didn't you say low ranks were smarter?
yes
So you'd go for the group with the lowest average rank
as so u mean that later, the one with the lowest mean is better, am i right?
Yes, using the lowest average rank is one way to compare.
understood, thanks alot!
Does anyone listen to music whilst coding
Pretty sure everyone does
I usually do, but often cut it when I need to think too much haha
I don't listen to music at all
no words is the best
so classical music
but then opera also has words
i only listen to words that i do not understand
@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".
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
mit happens to be a pretty good school
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
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 ]])
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.
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
How long will it take for me to learn C language if I already know the basic concepts of Python programming properly?
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.
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
returnstatement, 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.
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
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
@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?
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
@fiery cosmos check out #tools-and-devops to talk about git.
@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
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()
Same text just edited some indentions but I am still getting errors
NM I figured it out
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.
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
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?
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, inLinkedList.__init__you doself.head = Node()(not providing any data), andNode.__init__hasdata = None, so thedatadefaults toNoneandself.head.data == None
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?
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.
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.
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?
Fwiw, x is None and x is not None is more Pythonic than x == None and x != None respectively.
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
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
should have something for you.
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.
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.
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.
then while we're at it, all of the () around if and while conditions and around values being passed to return are unusual.
You can also replace a couple of the while loops with for loops
!pep 8
Thanks for the pep Guide
@dapper sapphire did you finish the linked list?
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.
!resources @fiery cosmos
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
@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.
# 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
this is in Python 2
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...
yeah
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.
!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)
@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
interesting
!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)
You are not allowed to use that command here. Please use the #bot-commands channel instead.
hii
@plucky warren hi
What do you wanna talk about?
@fiery cosmos let me know if you have any questions about how that's written.
!pep 7
Anyone know how to check if more than 2 checkboxes are checked at the same time? (Tkinter)
checkbox1 and checkbox2 ?
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
you could sum them
so like
if sum(Checked_CB1.get,Checked_CB2.get, Checked_CB3.get) > 2 :
sure
nvm that doesnt work
you wanted to check if more than 2 right?
yeah
oh you had 3
are they booleans?
yes
did you mean to call the method?
wdym?
method() instead of method
im doing it within a function
did you mean to write Checked_CB1.get() instead of Checked_CB1.get
That gave me TypeError: 'int' object is not iterable
in the if/sum statement?
you can't use sum()
so in the if statement?
yes
Which part do you need help with
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?
nope
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
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.
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?
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?
@heady wasp and @fiery cosmos check out "Invent Your Own Computer Games With Python" by Al Sweigart
Amazing tool for beginners
guys, any good free material about pytest (not the docs, something more teachable)
YouTube
@cold cloak why do you think the output should be 101?
@lofty hedge Thanks for the tip! I just got the book from the library!
Anyone know how alpha 0 works? the chess AI
More specifically how does it use a Neural Network?
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
Thank you
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
anyone really good with curl?
hey, i need help.
i'm a beginner, and trying to make a quicksort algorithm. However as you can see there are many errors and stuff going on with the code: https://paste.pythondiscord.com/dodamohozo.py
@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
@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
no lists or scalars
I'm getting an error
from the matrix triangularization algorithm you wrote
I'm trying to understand it
whats the error
TypeError: can't multiply sequence by non-int of type 'float'
is it cause youre multiplying a list by a float?
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))
😦
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?
I didnt use the randint with numpy
but i have a list of lists of floats too
wait lemme print the lines object directly
well the problem with a list of lists and not a numpy array is you can't do -=
np.array(my_list_of_lists)
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!
also need a multiply function
i can do that with a lambda function?
yo guys which one is a better option to go into btw, computer science or software engineering?
or does it matter?
software engineer
oh I see, hmm...aight thanks
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?
@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
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
gaussian elimination ...
remember anything like that?
when you get a triangle of zeros
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
I dont swap, i just use this Adding a multiple of one row to another row.
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)
oh lemme send the full class
this looks like you're on the diagonal all the time
because i is the index of row_top
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)
are you not allowed to use numpy?
python 🤮
it's not an assignement, I'm making this so I can "cheat" in upcoming math exams
basically to go faster
oh shit i did that
you should use numpy then
my calculator allowed me to upload python programs to it
because I'm going to be honest with you, the helper methods aren't pretty
yea but I want to understand my cheat
lol
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?
no but I didn't like your subtract and multiply methods
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
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
ok
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?
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.
how hard would it be to get a job with a cs degree?
This isn't the channel. Try #career-advice. The tl;dr though is that it's hard but not impossible
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])
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]])```
where all discrete math is used in computer science?(excluding graphs)
I would say encryption, error correcting codes and such
ah
best place to learn OS?
Does anyone know of a good reference for pythonic implementations of union find?
@fiery cosmos https://teachyourselfcs.com/#operating-systems
All the resources you need to give yourself a world class computer science education
hmm, google gives me plenty, but because PyPI for some reason doesn't have sorting by downloads, no idea what's a good one
https://github.com/eldridgejm/unionfind
this one uses Cython
https://github.com/deehzee/unionfind
this one only Python+numpy
Thanks!
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
okay, apparently there is https://en.wikipedia.org/wiki/Knuth–Bendix_completion_algorithm
which looks hardcore, but might be what I need
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.
@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
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
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,
- 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.
- 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
you can perform binary search since result is sorted
You could use bisect, assuming you're allowed to import a builtin
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])
You are not allowed to use that command here. Please use the #bot-commands channel instead.
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?
use , not +
the reason is because you can't concatenate a string and an int
@agile sundial @hazy basalt Thank you
http://usaco.org/index.php?page=viewproblem2&cpid=990
so yeah
how do i do this one
so do i go through each pair or something and split it into 2 baskets?
but what would constitute a pair or something?
Are there any sorting algorithms with asymptotic complexity between O(n logn) and O(n^2)?
yup, there's one with 4/3 I think
EDIT: nope, I thought of stooge sort, which is ~2.2
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
hmm, or I was misremembering
In-place merge sort and shellsort
the latter is O(n^2) worst
oh, I see, average 3/2. Yup, that works. Guess I wasn't entirely wrong.
probably some kind of append to a list, while i >= 5... IDK im a noob, but it would approach it that way
is that homework?
Even I felt like that
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 **
http://usaco.org/index.php?page=viewproblem2&cpid=990
so yeah
what do i do for this one?
so do i go through each berry tree or something and split it into 2 baskets?
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?
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?
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
!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]))
@oblique panther :white_check_mark: Your eval job has completed with return code 0.
[1, 1, 1, 2, 2, 6, 6]
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))?
@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
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.
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...
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
@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.
@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.
@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?)
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)
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.
http://usaco.org/index.php?page=viewproblem2&cpid=990
so yeah
what do i do for this one?
so do i go through each berry tree or something and split it into 2 baskets?
use pprint.pp rather than print
thank you, thats way better 😄
{'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?
@crude meadow you are using the pycharm debugger?
yup fixed it already, it was a mistake with the params
ok 👍
http://usaco.org/index.php?page=viewproblem2&cpid=990
so yeah
what do i do for this one?
so do i go through each berry tree or something and split it into 2 baskets?
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)
thanks . values() just did what i needed 😄
If you ran self.values() what would be returned?
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.
it would be nlog(n), would have to be sum i to be log^2 n
Ah I see, it only sums the first item, so its slower then. Thanks a bunch 🙂
I always get these sums messed up
Yeah that had me confused. Thanks
lmao in school im learning python 2 instead of python 3 ;-;
F
When making a game should you make a user interface (start screen) first or last
@fiery cosmos personally id focus on core game mechanics first. Worry about asetic shit later
But you want a good balance. 🤷♂️
Thanks @random talon
No problem
@pulsar bay I would ask on #tools-and-devops
@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.
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
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
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.
The problem is I can't use that kind of method either I can only have one function defined
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"
Got it. I think I know what to do now. Thank you
If you haven't learned in yet you could also just do that with 5 separate conditions.
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
Good luck!
Thanks my man
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
I've seen quite a few. What are you having trouble with?
I'm a beginner so I can't even imagine how to do that program :c
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?
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)
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
like conditionals (if) and loops (while)
that should be pretty simple
if you can't, that's where I suggest starting
Okay, thank you :3
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
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
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?
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
that may help one get started
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?
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
well, actually I know Python uses a PEG parser since 3.9 after using LL(1) for a long time, but I don't know exactly what that implies.
https://docs.python.org/3.9/whatsnew/3.9.html#pep-617-new-parser
What do you start with for Data science or machine learning? pandas, numpy, ?
@proud spade Both Pandas and Numpy are essential for both Data Science and ML. Also look into sklearn for ML
@marsh swallow ok, how much can you learn on your own? Vs when you need college?.... can someone get a position without college?
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.
@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?
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.
@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)
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.
guys I am having an issue with some code, it is very very basic can someone help me out? Thank you
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?
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
Yeah, it means cubicle
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?
so line 9 should be options.sort() for entry in options:?
ok thx
When creating an abstract class, how do you know which methods should be abstract methods (using ABC)
The ones for which you cannot come up with a default implementation that is meaningful.
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?
this would be the actual function:
and its very exponential graph:
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
log10 y scale
I believe it is more common to express exponential complexity with a base of 2 but yeah, only keep the largest term
Are you referring to removing lower order terms ?
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
right, but im not sure if what i have is lower order terms since its not a polynomial
You don't really get to choose the k in O(k^n) btw, it's completely dependent on the algorithm
so i say O(k^n)?
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
well i have no idea what the actual k is
can i somehow rewrite the function i gave in exponential terms?
then you can say O(k^n) or just say it's exponential
but really you want to know that k
how would i figure it out?
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
no
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
ok, thanks 🙂
yup
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
gotcha
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
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?
probably a question for #career-advice
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
okey, and witch is most valuable, they are so many
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
gotta say, very weird choice of channel
@vocal gorge the name of this channel is not very communicative for most of our users so I wouldn't hold it against them.
since many courses are named computer science ____, there was a request for a name change though
You should claim an available help channel #❓|how-to-get-help
what file format is [[,,,],[,,,],...]
@raven oracle any if u format the data like that
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?
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.
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?
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.
hey so for dijkstra's do i stop as soon as i reach to destination node?
@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
Hey everyone, is maximum binary tree somehow differ from the normal binary tree ?
@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
@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
@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.
@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...
alright. thanks for telling me. leetcode was actually the first result when I searched for "maximum binary tree"
Hahah that seems right.. so let's discuss about the problem ?
are you familiar with recursion?
yeah
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?
sorry, you're in a hospital? are you okay?
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..
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)
why 40?
What ?
if leftsubtree.__sizeof__() != 40:
Ohh because the size of empty list is 40, right?
I've seen cases where it increases the size right after adding the first element
what are you trying to check, that the list is empty?
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
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?
whats the difference between float and int
real vs integers
yes, because they also have precision issues, you can't represent all numbers using floats
Anyone there?
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.
bruhh
i need help
- Write a Python program to find the repeated items of a tuple.
this is the q
how do u solve it?
someone help
@heavy zenith can you give me an example of the input and expected output?
yes
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}
use Counter
but my comp teacher hasnt taught it
use Counter
@agile sundial
you want to print the number of repetations in the tuple?
so your teacher wants you to iterate throught tuple and find duplicates that way
have you learnt the count() method
no
yea
okay we can use that
the simplest way would be using sets but i doubt they know it
idk sets
considering list they gave
Are you allowed to use dictionaries?
they dont even know sets i doubt they gone that far
Concatenation
Repetition
Membership
Iteration
tuple updating
tuple swapping
conversion of tuples into list and vice versa
I LEARNT ONLY THAT
yes
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
@manic shard a lot of people don't learn sets for a while.
we can teach him now
Are you allowed to use dictionaries?
@oblique panther yea
They probably have to solve it using what they've been taught so far.
try the method i mentioned above, panda
Okay, so you can use a for loop to go down the tuple and use a dictionary to store the counts
@heavy zenith how's it coming along?
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)
@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
The input format for this question is the most bizarre I've ever seen.
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?
uh
so they give you some stuff to buy
and yeah- best combination of special offers, but some single purchases may be necessary
I'm pretty sure understanding the input format is more difficult than the actual problem.
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.
yeah ok
Can you show the link to the challenge? I think there's some context missing
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
@eager hamlet you could try a greedy algorithm.
At each step, pick the special sale that's the most profitable.
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
You think there's an instance where greedy wouldn't work?
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.
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
It may pick 3 * A + 3 * B over 1 * A, + 2 * B + filling the rest with singles
What do you mean?
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.
I mean that because you can have offers with a combination of items a greedy algo might skip a better deal down the line.
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
How would you suggest valuing a sale in that case? ranking them from best to worst.
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...
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
Yeah I just found another example
Sans, I refactored your solution to a more classic bfs one and it takes 1 sec on my laptop now
can someone help me convert python script to exe file
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.
@jaunty eagle look into pyinstaller, but that question isn't on topic for this channel.
@sudden lance take a look at #cybersecurity
oh ok sorry
No problem
Oh ok
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
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)
@eager hamlet from __future__ import annotations backports referring to a class by its name within the class
feel like it'd still work w/o the __future__
@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.
oh i see
it would work without the __future__ in 3.8 and possibly some number of earlier versions.
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?
https://github.com/comp-think/comp-think.github.io I found this which looks kinda good
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
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
@faint pike take a look at #❓|how-to-get-help to open a help session
@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.
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 🙂
@fallen bluff take a look at #game-development
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?
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"?
I have two lists. I want it to take one of em and slice that one
I have two lists. I want it to take one of em and slice that one
@stable sand then what does the otherlistdo?
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
@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
Would that also work for 1, 2, a, 3, b, c
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
Ah I see, so I won't be able to do it otherwise than to call each element individually
