#algos-and-data-structs
1 messages · Page 79 of 1
I finished implementing Kruskal's, and the next step is to modify it to return all possible MSTs for the same tree. So I'm thinking a brute force would have an awful runtime depending on how large the hidden test cases are.
Maybe recursively creating more searches each time two edges have the same weight?
Guys, does someone know what are the minimal building blocks to make a parser combiner that can parse context free grammars
I mean, if you strip away all the redundancy of a working parser combiner, what kind of constructs will be left?
Hi, not asking for the answer, also its just a pratice exam, but I'm not sure i understand this question:
MC13 (2.5pts)
Suppose we would like to build a dictionary that maps a set of student names (short strings)
to a study group identifier. Which of the following would work as a key function for our
dictionary? Hint: the ordering of the students in the original set should not matter.
(a) Concatenate the names.
(b) Sort the students’ names and then sum the values of the characters in their names.
(c) Sort each name by character, then form a concatenation of all the sorted names.
(d) Sort and then concatenate the first letters of the students’ names.
(e) None of the above is correct., is it asking what is a good hash function
or is it asking somethign else
i think it's asking what would be a good hash function be, yes
so then @spiral swallow , what do you think they mean by sorting, the answers are confusing, i understand that there are 3 rules for a good hash function
(i) A good hash function distributes the keys uniformly over the array.
(ii) A good hash function is deterministic.
(iii) A good hash function is computed in constant time.
sorting things is putting them in a particular order
i think you are looking too deep into that, i'm pretty sure you know the answer to this question
you are probably concerned because it seems too easy, but here i really think it is
lol so b?
the only one that tries to get some values? that could be arbitrary?
but it doesnt say % 10
or rather get some kind of remainder
haha
your definition of value might be a bit too restrictive
what's the point of the hash function we want here?
if you can reformulate the first sentence of the question
to find a random value in a indexed list/array of sorts
to plop down the value, so everytime we hash the key
we get the same value
no, what specific, real world, problem, are we trying to solve here
that's still technical, think about the intent of the program
and we dont want clumping in our list
the good hash function depends on what you want to do with the data
is to be able to access values at o(1) time
the question is much less about theorical properties of a hash function than you think, imho
to be clear, we have students names, what do we want to do with them?
if you had to produce an example of input/output of the program, what would it look like with each proposed hash function? which would be desirable, if any?
put them in a study group identifier
right, and what are the desired characteristics of such study group identifier?
(the hint is important here)
i can't really answer that without giving you the answer, so i'll leave you there, normaly, i said enough.
It seems that the most straightforward solutions to the different variations of the knapsack problem involve sorting your items by their value/weight ratio and then putting them in the bag based on whatever constraints your given variation of the problem are.
But sorting numbers usually has O(nlogn); do these weird tabular solutions have a lower runtime?
I think there are usually constraints on 'better' versions of an algorithm
Like knowing certain information ahead of time
So it may be that they're not considering the complexity of any 'set up'
So if you're given the input data as two parallel arrays and the target weight, the tabular solutions do the computation as they arrays are being read, rather than reading in the entirety of each array, and then following the steps I alluded to?
I don't know that terminology, sorry.
One sec
https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html#g:9
Think about taking a seed value and then building off of that
Let me see if I can find my Knapsack from a while ago
I don't have it on my laptop 😦
That's okay
Sorry, I'm having a hard time trouble understanding what exactly you mean
Are you talking about a memoized version?
So that you store the results rather than recompute them?
If so, yeah. That changes the complexity
Yeah, they have a better time complexity because you perform a simple look up rather than repeating a bunch of computations and whatnot
Would that usually or always have a better runtime than finding the weight/value ratio for each item and going from there, or would it just have a better runtime than if you used the same general approach but without saving the result of previous calclations?
Or maybe I'm wrong. I need to review, so I guess I'll just shut up now
I don't know enough about the topic to know that you're wrong and then criticize you for it
though I suppose people who might be watching this conversation could secretly be doing that.
lol, I just don't want to give you bad information
I'm not scared of being wrong, just of spreading misinformation
Anyway, the solution I imagined is intuitive and I was looking forward to implementing it. Oh well.
Not that I was likely the first person to think of it or anything.
Hey guys could someone give me some advice on this question I posted on Reddit, I hate when I get this sort of choice paralysis and it happens a lot :/
oops, broken link here's the right one https://www.reddit.com/r/Python/comments/g52pqq/advice_on_writing_a_parser_combinator_api/
0 votes and 0 comments so far on Reddit
can anyone check my code for a forward chaining system for poker hands
i have to use transitive properities to check if a hand beats another hand
class Hand(object):
def __init__(self,name,beats_hand):
self.name = name #name of hand
self.beats_hand = beats_hand #the cloest hand it beats
def does_it_beat(self,target):
goal = target
if self.beats_hand == target:
print('yes it does',target.name)
elif self.beats_hand is None:
print('not it doesnt')
else:
self.beats_hand.does_it_beat(goal)
poker_data = ( 'two-pair beats pair',
'three-of-a-kind beats two-pair',
'straight beats three-of-a-kind',
'flush beats straight',
'full-house beats flush',
'straight-flush beats full-house' )
one_pair = Hand('one_pair', None)
two_pair = Hand('two_pair', one_pair)
three_of_a_kind = Hand('three_of_a_kind',two_pair)
straight = Hand('straight',three_of_a_kind)
flush = Hand('straight',straight)
full_house = Hand('full_house',flush)
straight_flush = Hand('straight_flush',full_house)```
I have a file that contains the number of steps a person has taken each year - how do I get the program to display the average numbers of steps each month?? Is there a way to prompt the user to confirm if the specified data was in a leapyear? , sorry if this isnt the right place for the question. If this is the case could you direct me to the right help chat
@fiery cosmos
anyone can help me? I have problem with Linkedlist
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Be patient while we're helping you.
You can find a much more detailed explanation on our website.
class Node:
def init(self, n):
self.name = n
self.next = None
class Linked_list:
root = None
size = 0
def Size(self):
return self.size
def add_Node(self, n):
if self.root is None:
self.root = Node(n)
self.size += 1
else:
self.root.next = Node(n)
def printList(self):
temp = self.root
while (temp.next):
print(str(temp.name))
temp = temp.next
cant add new node into the linkedlist
(would you mind using a codeblock?)
it looks like you add new elements by replacing the second element rather than the root, and you need to not discard the replacement
sounds a lot like a rule 5 @crisp nest
again, looks a lot like a rule 5
@pine sapphire He has changed his nickname. Is everything alright now?
Ah, I see. But it is not a homework.
He just couldn't solve it.
It's for personal development.
i said it looks a lot like homework, which it does
Yes it does but it is not.
i can try and help with the concepts, i think? but i won't help solve these specific problems
It is from a test book. He is trying to improve his Big O notation skills.
Sure, that would be great.
it's hard to know that it's not homework, though, and it's just as much against the rules to provide answers to homework as it is to ask for help on it
this is not a homework. work question. you can explain how I can do it and you can suggest me a similar resource.
How can i scrap раттата this from above code?
Can someone please give me an obvious example of two NP-complete problems where if one was found to be solvable in polynomial time, it's easy to see how this could be applied to make the other solvable in polynomial time? Thanks in advance!
Does anyone have any experience using Glicko-2? I have no education on any of this and struggling to wrap my head around everything
well
first_name = input("Type your first name:")
last_name = input("Type your last name:")
print(f"initials {first_name[0].title()}., {last_name[0].title())}.")
I guess this is what you want?
you ask for first_name from the user
and last_name from him
and you use indexing on strings, as in python, strings are indexable(they're list of chars)
e.g.
"sergen" is ["s","e","r","g","e","n"]
so ["s","e","r","g","e","n"][0].title() will give you "S"
hi there! is anyone able to help me with a simple python problem?
yes although you'll probably get better service if you "claim" an available channel from the list in the upper left
Is there a way to get every suitable output format for a specific format in ffmpeg?
Like if i wanted to convert mp4 to every possible format using ffmpeg, is there a way to get a list of all the formats ffmpeg will convert to from mp4?
Anybody know mips here?
how do i make input log something into my .Log file for example i type something in "input("try: ") and it logs in .Log file heres my code: import logging
input("Check UVB: ")
if type(" "):
Create and configure logger
logging.basicConfig(filename = "C://64/Lumberjack.Log",
level = logging.INFO)
logger = logging.getLogger()
Test the logger
logger.info("")
print(logger.level)
@fiery cosmos use open() to read/write the file
wait
oh im dumb
@fiery cosmos just add a logger.info() function after all the inputs?
or you can make an inputAndLog function that does that for you
def inputAndLog(prompt, logger):
userInput = input(prompt)
logger.info(userInput)
return userInput
so it is printing what you expected right? root is the userInput I presume?
I need some help. I have a large CSV file with columns "AI ID" and "location" plus various other fields. there can be multiple instances of the same AI ID in this csv... what I need to do is compile it to a new dataframe where there is 1 "AI ID" to a list of "locations".
currently loading in a CSV... iterating over the rows... and building this data manually into a dictionary
but I feel like there is a better way?
was hoping that i can do it all in pandas
@twilit rock not really #algos-and-data-structs, why don't you open a help channel?
Its about temperature changing code or sum like that
?
So I'm currently taking some math classes for school, and I started using it in addition around with knowledge I had in computer science.
I noticed that in ASCII 65-90 and 97-122 you have the lower case and upper case alph.
or [41,5A]:[61,7A] in base16
This made me realize that all lower's and upper's are spaced by 32. This has led me to wonder if the function of capslock is done by negating the the multiple of 6 in a byte.
maybe, but notice that caps lock doesn't work for all input keys, only the ones in the range you specified, so at the least it's special cased to just that range
Good point
i always assumed it just used a bit mask 🤷♂️
because as you say theyre all 35 apart
Anyone know how to limit a textbox character limit (tkinter)?
And not allow further input after that limit
can provide my python code via PM if needed
because you skipped typing answer == 4 times
scratch that, that's not the syntax error, it's a different one
the syntax is from line 2, you skipped typing )
The error tells you right what the problem is ...
hi, does anybody know about parallel machine learning easy to understand scientific papers for beginners?
are you asking for resources?
yes
ah, sorry. not sure
hey does anybody know python in here
@fiery cosmos well, the whole discord is about Python.. So yes.
ah i am very new to python and this is a really simple code but i don't know why it is not working
for count in range (21):
if S_summert <= "21" "20" "19" "18" "17":
S_summert = S_hit + S_summert
print(S_summert)
elif S_summert >= 21:
print('Dealerens kort summert er mer enn 21, spilleren har vunnet.')
break
how do i do that
` is a back tick, often found by the ~
is it possible to send the code itself through a file?
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print('Hello world!')
```
Note:
• These are backticks, not quotes. Backticks can usually be found on the tilde key.
• You can also use py as the language instead of python
• The language must be on the first line next to the backticks with no space between them
This will result in the following:
print('Hello world!')
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
ok so i did it now how do i make you able to see it?
for count in range (21):
if S_summert <= "21" "20" "19" "18" "17":
S_summert = S_hit + S_summert
print(S_summert)
elif S_summert >= 21:
print('Dealerens kort summert er mer enn 21, spilleren har vunnet.')
break
Hey @fiery cosmos!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
what did i do wrong?
well you have a lot of strings in the second line
which isn't correct syntax
and probably you don't want to compare an int with a string anyway
for count in range(21):
if S_summert <= 17:
S_summert = S_hit + S_summert
print(S_summert)
elif S_summert >= 21:
print('Dealerens kort summert er mer enn 21, spilleren har vunnet.')
break
maybe you wanted this
this is pretty close but the thing is, this is supposed to be black jack, and the code i sent is supposed to be a bot witch does everything by itself. and i added a code where if the bot gets 17 18 19 20 21, it wouldn''t make another hit.
for count in range(21):
if 17 <= S_summert <= 21:
S_summert = S_hit + S_summert
print(S_summert)
elif S_summert >= 21:
print('Dealerens kort summert er mer enn 21, spilleren har vunnet.')
break
(greater than or equal to 17 or less than or equal to 21)
alternatively you can use in
like this:
if S_summert in (17, 18, 19, 20, 21):
if 17 <= S_summert <= 21:
or
if S_summert in (17, 18, 19, 20, 21):
would both work as the second line
thank you so much i have been stuck for half an hour trying to figure this out
np
Salt die could i ask you another questtion?
Okay, I really should know better but why is this always returning 1? No matter what string I enter
you are wlc
guys, im with problems while trying to loop a list append function
see:
I start the list with
list1 = [''] list2 = ['']
so i start a loop to get info to put into the list
`while True:
add1 = int(input('Insert data: '))
add2 = int(input('Insert data: '))
list1.append(str(add1))
list2.append(str(add2))
condit = str(input('Continuar? y/n \n'))
if condit == "y":
pass
elif condit == "n":
break
else:
pass`
but im getting as output the list1 being correctly added
and the list2 getting a ['', "['']"] content
need help
use triple backticks for multiline code blocks ```py
wym?
print('I mean use triple backticks to make code look like this.')
oh aight
i wrote this code as an example
mine is a little bit different
let me show it
you should probably ask in a help channel though and not this topical channel
aight
I made a neural style transfer in python
hey... was wondering if someone could point me in the right direction... im trying to create some type of ml/ai that can read a smaller image (a minimap of a map) and give me the x,y coordinates in correlation to the larger map... i have already sliced the larger image into smaller bits, with the associated x,y coordinates (of the centroid). All the smaller images are of the same size and i have eliminated as much noise as i can. However, now I am looking for the best way of reading the image and giving me an output of the x,y value(s) & was wondering what method you think i should go. Thank you in advance!
the reason im leaning towards ml/ai is because i need the predicted value in 0.6 seconds (whereas opencv and other similar computer vision software does not have something this fast)
please make sure to ping me at the start of this convo, as i know this channel isnt that active.
Thank you!
I'm really stressing rn and would appreciate it if anyone could help me.
I am trying to make a program that generates all possible combinations to unlock a 3-digit lock (possible combos: 000 - 999). I'm sure you've seen the picture before.
I just don't really know where to start. 🤔 I've been working on this here-and-there for the past 3 days and I've restarted more times than I can count.
I am given inputs in the format XYZ-R-W. XYZ is the 3 digit combo. R is the number of digits that are right AND in the right place. W is the number of digits right but NOT in the right place.
I'd translate each of those five statements into code
edited original message
I'd define two functions: number_of_correctly_placed_digits(n) and number_of_incorrectly_placed_digits(n)
to generate all possibles combos, you can use itertools.product, but this looks more tricky
then I'd try each number from 0 to 999, and call both functions on each number
I'd return any number for which those functions returned... uh ... hmm
to generate all possibles combos, you can use
itertools.product, but this looks more tricky
@slim vault pff, there's only 1,000; I'd just brute-force it
We have to brute-force it. :p
I was thinking constraint programming, but in this range brute-force is probably fine yeah
My confusion is keeping track of everything.
For example, given input 682-0-2, meaning there are 2 right numbers but in the wrong places.
I'd not only have to keep track of the possible numbers 6, 8, 2, but also there position, and also the fact that 2 of those numbers are in the wrong place and the other number is just wrong.
@slim vault constraint programming is indeed the right way to do this in the Real World® but not in homework-land 😐
I think the problem is hard to understand
in a couple of places it talks about "wrong" but I don't know if that means "has no digits at all in common" or instead means "has some digits in common but in the wrong location"
well as for the picture, "all digits are wrong" for 738 means 7, 3, and 8 are not going to be digits anywhere in any correct combo.
right means its part of the lock combination
is this homework?
Yea, which is why i didn't say yo can someone code me this shit lmao
but Prof said it's cool to ask for help, as long as no one sends me the full code, obviously lol
ok
well I can tell you what I'm doing, which I would have thought was correct, but it doesn't find any solutions, so Iv'e got something wrong
You make it sound like u just coded the whole thing in the past 15 minutes?
haha damn.
yes, please.
first I wrote def categorize_common_digits(n1, n2): that returns two sets: digits that are correct and in the correct place, and digits that are correct and in the wrong place
then I did ```py
for n in range(0, 1000):
right, wrong = categorize_common_digits(n, 682)
if len(right) != 1:
continue
...
with four more similar clauses
after the last one I printed out n
hm, ok.
so it'd work running with multiple inputs?
The example he provides for input is:
682-1-0 614-0-1 206-0-2 738-0-0 380-0-1 314-1-0
geez I only tried it with that exact set of inputs
making it more general is doable, but at that point you've got something pretty sophisticated
I hope this isn't a beginner class
🙃 they just started teaching python a few weeks ago
after learning C and Java for the past year
so yea, first project on Python.
so my question is, where do u store ur R and W numbers?
R being number of RIGHT numbers in the RIGHT place
W being number of RIGHT numbers in the WRONG place
i store them in variables obviously
interesting -- my thing returns a single answer when I leave off the 314-1-0; but with that, it doesn't return any answers
might you have mistyped something?
I get the same single answer if I change it to 314-0-1
also 314 isn't in the little picture you posted so I'm suspicious
@manic urchin 
Yea, just saw this. sorry
The professor gave us a set of examples @stark bridge , and the 314-1-0 was one of them
Here's a picture of it all:
I don't see why he hid the answer. :#
Would be easier for error-checking if he provided the output it's suppose to return, like he did for the last example.
any chance you could paste that as text, instead of as an image?
I'm too lazy to transcribe the stuff in that image
Don't know what part, but yeet:
$ python3 lock.py 682-1-0 614-0-1 206-0-2 738-0-0 380-0-1
Trying 682-1-0 614-0-1 206-0-2 738-0-0 380-0-1
*** Solution #1 is ... (there is exactly one answer, hidden)
$ python3 lock.py 682-1-0 614-0-1 206-0-2 738-0-0 380-0-1 314-1-0
Trying 682-1-0 614-0-1 206-0-2 738-0-0 380-0-1 314-1-0
No Solutions Found
$ python3 lock.py 682-0-0 614-0-0 206-0-0 738-0-0
Trying 682-0-0 614-0-0 206-0-0 738-0-0
*** Solution #1 is 555
*** Solution #2 is 559
*** Solution #3 is 595
*** Solution #4 is 599
*** Solution #5 is 955
*** Solution #6 is 959
*** Solution #7 is 995
*** Solution #8 is 999
tx
oh ok, so mine's working perfectly for the first two examples
yep
nice to have some test cases
ok mine works perfectly 🙂
now I can torture you with confidence
btw this is pretty hard
this is way Way WAY harder than the coding puzzles I give in job interviews -- where the candidate has to solve it in 45 minutes -- and these jobs pay hundreds of thousands of $ per year
ok, maybe just "way" harder, not "way Way WAY". But still.
lmao.
in fact I might add this to our internal "coding puzzle library", if you don't think that'd annoy your instructor
lmao I'd ask that you don't post the code anywhere online
ah ok
Anyways
So the easiest part would be to gather all integers that are NOT going to be in the combo.
AKA when R and W are both 0.
For the first example:
682-1-0 614-0-1 206-0-2 738-0-0 380-0-1
That'd be 7, 3, and 8
Which removes 656 possible combos. c:
pity; it's the most interesting problem I've run into since hanging out here in discord
ok here's a huge hint
edited msg
what I did was:
I made a set called common_but_differing_location, and put all the common digits in there regardless of location
(so that means the variable name is a lie; but hold on)
then I went through each digit of both the candidate number, and the clue number, in turn;
if those matched, I added that digit to another set called common_and_same_location, and removed it from the first set
so after going through all three digit positions, I now have two disjoint sets
then the main loop simply count the number of items in each set, and compares those counts with the two numbers in the clue
one tricky thing: numbers < 100 don't naturally split into three digits, because of the leading 0, so I had to do something slightly non-obvious to make those leading zeroes appear
that's basically the entire solution. The rest is filling in the details
lmao i did it a corny way for numbers 1-10 and 11-99:
again, we sorta just started learning python lol
well if you've done other languages you should have suspected that there was a better way
you needn't necessarily have known how
eventually you realize that most programming languages are pretty similar
lol for sure
but given my time restraint and the fact that im already self-teaching myself mostly all of this, i told myself it was good enough :p
and it was
like I said: it gets the job done
and it's clear
it's obvious what you're doing, and why
that's about as much as anyone can ask for
another clue
it's probably a good thing for me that I didn't try to make it general at first; instead I just solved the one set of clues you had in that .png image
because that in itself took some effort
then making it general also took some effort. Had I been trying to do both at once, I'd have probably given up
aha ok, fair enough, thanks for that clue.
and well, thank you for all the help; you've provided me more than i expected and can thank you for.
just gonna spend a little bit more time learning about python and sets and all that before starting on this again. 😛
tf = False
print "What would you like to order?"
print "Taco: $ 3.50"
print "Soda: $ 1.50"
print "Candy: $ 0.50"
print "Fries: $ 1.50"
print "Sushi: $ 8.50"
print "(Type 'done' when finished)"
total = 0
while tf:
taco = 3.50
soda = 1.50
candy = .50
fries = 1.50
sushi = 8.50
order = raw_input('Please choose one of the items from the list, then type DONE when finished.')
if order.lower()=="done":
tf = False
elif order.lower()=="taco":
total = total + 3.50
elif order.lower()=="soda":
total = total + 1.50
elif order.lower()=="candy":
total = total + 0.50
elif order.lower()=="fries":
total = total + 1.50
elif order.lower()=="sushi":
total = total + 8.50
print "Your total is: $",total
need some help
the input isn't popping up
A while looponly runs when the condition is True.
And your file starts with tf = False
Also you appear to be using python2, this version of python is no longer supported and I advice you migrate to py3
oh, i'm working on this for school
it's the language they are teaching us
python mini
good lord
i know it's bad
what school? I'll tell people to avoid it
haha
i don't think they get to choose what language we learned
I really tried to get them to teach us C++ or Javascript
But they couldn't do anything about it.
well python is a nice language. But it should be a crime for a school to teach python2
Hi anyone there to suggest something about career ?
@stark bridge can you share the code for the lock thing? I don't quite get what you did
can someone please explain to me the concept of a virtual machine?
@south slate its basically a computer inside of a computer
you can download an operating system like windows, linux, etc onto a virtual machine and use it to simulate a whole new computer
so its a software that simulates a computer?
yup
ah thanks both of you
I have started with python like 2 weeks ago so still a beginner😅, can someone send me practice problems to clear various concepts
can i send youtube link here?
@south slate you can check on hypervisor, vmware workstation and virtualbox, try to play around and put some virus into these tools you will more familiar with that.
I'm not joking, you can try, it is fun
hello
I'm looking for a python parsing library that has a grammar similar to EBNF and has a separate lexer so I can debug it on its own
I've been looking at lark and parsimonious which do have such a grammar but I dont think they have a separate lexer
offby, I can't really dm you because of your settings, if that is intended, it's fine.
it is intended, sorry
yep, was makin sure cuz was unable to reply to your thing
There's probably some simple explanation to this, but I don't understand why
print(len(list) * [1])
changes everything in the list to 1s
@median plank it does not change everything to 1s, it create a new list by repeating len(list) times the list [1]
[1,2] * 3 would result in [1,2,1,2,1,2] for instance
@median trout that's different syntax from my question
I multiplied it by [1], not 1
And it gives me the same result of all 1s no matter what is inside of the list
Nvm I realized that the list and the number were in swapped places and that was tripping me up, thx for the help
if (valueA + valueB) == 7 or 11:
print("win")
I'm doing something wrong here, but I"m not sure what.
Whenever valueA + valueB = (something other than 7 or 11) it still prints out win. Any help?
I'm a freshman in compsci, so all of this is new to me D:
I've been trying to find the answer in my compsci book, but I can't quite find it.
!or
When checking if something is equal to one thing or another, you might think that this is possible:
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
After all, that's how you would normally phrase it in plain English. In Python, however, you have to have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
oooookay, thanks! I figured it had SOMETHING to do with or.
Curse the English language~
Out of curiosity, why does using or like you would in English break it?
oh lmao
programming languages are utterly unrelated to human languages, despite them both being called "languages"
that leads to a lot of confusion
It's really odd, especially when the truth table makes sense as "this or that"
just one of the things you have to get used to
"if it were easy, everybody'd be doing it" -- Andrew Berg
I mean yeah, that's true LOL
if |(valueA + valueB) == 7| or |11|:
that's how python sees the two operands for or
it or'ed (valueA + valueB) == 7 and 11
and 11 is always True
or, at least, not False
https://docs.python.org/3/reference/expressions.html#operator-precedence this explains why things are evaluated that way, because or is pretty low on the list, it is evaluated later than ==
Sweet, thanks!
and here it explains what evaluates to True and False
these two are the first things you want to look at when you pick up a new language.
Thank you so much!
nP
okay
so how do I do something like this:
if x exists
do this
if x doesn't exist
don't do this
I want my code to skip the if structures if there isn't an existent variable to initiate the code. If I just do the if statement and the variable doesn't exist, it just throws me an error.
would using try/except be applicable here?
hm. Let me give it a shot.
wit nvm confirm is doesnt work
if 'myVar' in locals():
# myVar exists.
if 'myVar' in globals():
# myVar exists.
if hasattr(obj, 'attr_name'):
# obj.attr_name exists.
i was going to say, it'll freak out and say the variable isn't defined.
why would you even want to do that. sounds like something went really wrong.
reflection?
No, I have to write a program that is basically the dice game craps, right?
I have a function that checks the dice value to see whether the roll is a win, a loss, or a point, but it only defines point if it's point, and if it's point, I need it to reroll the dice and check again.
I want it to check if point exists, and if it does, reroll, if it doesn't, just continue with the program.
bro how about let point defaults to False and changed it as needed and just check the value of point
so it is always defined
where are you doing your CS program
okay, thanks!
Well, crap. I've created an infinite loop and I'm not sure what I've done wrong.
point = (valueA + valueB)
while point != (valueA + valueB) or 7 != (valueA + valueB):
valueA, valueB = rollDice()
if (valueA + valueB) == point:
print("win")
elif (valueA+valueB) == 7:
print("lose")
rollDice() simply rolls 2 d6s and then spits back the values as valueA and valueB
I want it to only loop if the values don't equal 7, and if they don't equal whatever point is.
you should put in an else: that just prints both values
if rollDice works reasonably, that loop should eventually terminate
also you probably want to break after winning and also after losing
import random
def rollDice():
return random.randint(1, 6), random.randint(1, 6)
random.seed(0)
def one_round_of_craps():
valueA, valueB = rollDice()
point = valueA + valueB
print(f"Point is {point}")
while point != (valueA + valueB) or 7 != (valueA + valueB):
valueA, valueB = rollDice()
if (valueA + valueB) == point:
print("win")
break
elif (valueA + valueB) == 7:
print("Crap!")
break
else:
print(f"You rolled {(valueA + valueB)}; keep on rollin'")
for _ in range(20):
one_round_of_craps()
# Point is 8
# You rolled 4; keep on rollin'
# You rolled 9; keep on rollin'
# Crap!
# Point is 7
# Point is 7
# Point is 7
# Point is 5
# You rolled 6; keep on rollin'
# You rolled 8; keep on rollin'
# You rolled 11; keep on rollin'
# win
# Point is 7
# Point is 7
# Point is 7
# Point is 6
# Crap!
# Point is 8
# win
# Point is 9
# win
# Point is 4
# You rolled 6; keep on rollin'
# Crap!
# Point is 10
# You rolled 12; keep on rollin'
# You rolled 6; keep on rollin'
# Crap!
# Point is 8
# You rolled 9; keep on rollin'
# You rolled 3; keep on rollin'
# Crap!
# Point is 4
# You rolled 9; keep on rollin'
# You rolled 2; keep on rollin'
# You rolled 8; keep on rollin'
# You rolled 5; keep on rollin'
# You rolled 8; keep on rollin'
# You rolled 9; keep on rollin'
# You rolled 6; keep on rollin'
# You rolled 8; keep on rollin'
# Crap!
# Point is 10
# Crap!
# Point is 6
# Crap!
# Point is 7
# Point is 5
# You rolled 4; keep on rollin'
# You rolled 6; keep on rollin'
# You rolled 9; keep on rollin'
# win
# Point is 7
looks like the odds of winning are 22%
@maiden crow 
Thanks!
I ended up using return to return a win value and a loss value to a separate "summary" function that summarizes the win/loss and asks if you'd like to play again.
I have a gap in my understanding of logarithms and it is preventing me from understanding big O completely. I'm not understanding what O(n log n) means. I tried doing the Khan academy course on logarithms but I'm not understanding why we use n log n and why its significant. Can anyone point me in the right direction?
I find it easiest to think about these in terms of graphs. Remember that n is just the size of the target of your algorithm, so if you ever saw f(x) = ... in highschool math, it's the same principle. So when we say something is O(n), that means it scales linearly with size-- f(x) = x or y = x on a graph, a 45 degree slope. O(1) would mean that the algorithm runs in constant time, regardless of the size of the data set-- a horizontal line on a graph. O(log(n)) is in between, and the specific shape of the growth is the log function, just google log x graph for that one. So O(n log(n)) is just n * log(n) and it's a function that increases faster than an O(n) function.
Hi, I'm new here and english is no my first language, so sorry if I make grammatical mistakes, and if you want to make a point how could make me improve I'm more than happy to hear,
moving to your question a sposker say you need to think the O() complexity has a graph of resources consumption in time, if you have spare time I think this is a superb introduction to the concept o big-O and how that is represented in python => https://youtu.be/Zc54gFhdpLA
MIT 6.006 Introduction to Algorithms, Fall 2011
View the complete course: http://ocw.mit.edu/6-006F11
Instructor: Erik Demaine
License: Creative Commons BY-NC-SA
More information at http://ocw.mit.edu/terms
More courses at http://ocw.mit.edu
if you want to know more about algorithms the entire mit-6006 lectures are public and even you can check the notes in this link => http://courses.csail.mit.edu/6.006/fall11/notes.shtml good luck with you study
What do you guys think about the possibility of creating a low level language in python
like a file directory is specified in such a way that the code would be treated like a drive
and also individual memory stores within the file are treated as separate modules
or sections of the file
as like an esoteric language
That seems like it would be a funny thing to do over quarantine
hi in general for a BST binary search tree
lets say 5 is not a root node
and im deleting 5
i need to find the MIN VAL node to the right of 5
set 5 into 6
delete 6
if im not tracking parent nodes
i can only think of one way to get 6's PARENT Node, to reattach 7 to it, and thats a return_min node that returns the parent to 6 instead?
or returns 2 parametsr
6 and 6 parents?
is there another more inficient way i can stick with less functions?
not sure if I get your question, but also it's 'set 6 into 5' not 'set 5 into 6'
So it's like a recursive function
You copy 6 into the node which has value 5(root)
Then you go down to the node which has value 6, and then you try to delete 6, the procedure being the same so it's all recursive
So here you'll have 7 copied into 6, and you go down hunting for node with value 7.
When you reach 7, you see it's got nothing to right/left, so just delete it
Hi guys, I have a really vague and open ended question that is going to put on full display my lack of understanding of basic computing.
I have a problem, take for example problem 1 in the euler project.
There are many solutions, some are more beautiful than others which is meaningful however I am also aware some are considerably more efficient than others.
How do I get empirical information on how fast one algorithm is compared to another, how do I measure this efficiency in simple algorithms
Thanks
Hey guys was just wondering how i would go about setiing up a virtual machine for linux on my windows 10
anyone care to help me with this?
after entering the file name correctly, the csv file still does not output the 5 lists i need
Hey can anyone help me with my homework i feel as though i dont know where to begin
Create a package called geometry. Inside that package create two modules: rectangle.py and triangle.py. Also create an empty file with name init.py in the geometry package.
Inside rectangle.py define three functions:
- rectArea(): this function takes two parameters length and width of a rectangle, calculates and returns the area.
- rectCircumference(): this function takes two parameters length and width of a rectangle, calculates and returns the circumference.
- isSquare(): this function takes two parameters length and width of a rectangle and returns true if they are equal otherwise returns false.
Inside triangle.py define two functions: - triArea(): this function takes two parameters base and height of a triangle, calculates and returns the area.
- triCircumference(): this function takes three parameters, three sides of a triangle and returns the circumference.
Create main.py in the same directory as the geometry package. Import your modules. Prompt the user to select an operation among 5 different functions. Once the user enters the proper selection, ask the user to input the necessary arguments. Call the proper functions from your modules and print the result. Continue until the user enters a sentinel value such as -1.
@fading plover whats the problem with that?
@fading plover @fiery cosmos i dont know how to begin it, its a homework
Rule 5
Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious/inappropriate or be for graded coursework/exams.
How do you formally say you want to test whether the edges in a list w is part of the edges in an undirected graph G = (V, E)?
for all (u, v) \in w, (u, v) \in G
This is my best guess but I'm unsure if it's formatted correctly.
i'd have
∀ e ∈ w | e ∈ G
but in set builder, it'd be a bit different
{ e | e ∈ w ∩ G }
or just
w ∩ G
I have specified that w contains edges, so is it fine to compare it with G or should i specify im comparing with E?
well, probably context is fine, but E or G(E) might be more correct
dunno, i'd just note that we may mean E or V depending on context and let the reader figure it out
in true mathematical style
Can I do a floored division with a Turing machine?
i guess you could
I'm having some trouble with some time complexity stuff. The task is to test whether all edges in a list c are also present in the edges of a graph G.
My initial thought is that it would take O(|c| * |G(E)|) time, is this correct?
set membership is O(1) in python
if it's two lists of edges then you're correct, if it's a list with a set or two sets then it should be O(|c|)
Would O(|c| * |G(E)|) become O(|G(E)|), since c is a subset of G(E)?
no
This might be really simple but im drawing a blank, can anyone help with this?
@slate dagger Is that 25 random numbers between 0 and 100?
yea
indecies
its supposed to be indices but my teacher is dumb
while loop seems like an awful choice
but whattya gonna do
you should game the system:
while True:
#actual for-loop
break
i honestly don't understand the question itself
pretty sure he wants you to increment an index variable in a while loop
i = 0
while i < len(nums):
nums[i] = ...
i += 2
What about this question?
these questions don't really belong in this channel --- try to get a help channel; and you'll need to ask more specific questions
use a help channel, at the top of the channels list under PYTHON HELP: AVAILABLE
What is nested virutalization useful for?
Can someone help me with Kalman Filters?
What does print do ?
Yeah
Does it repeat any instruction ?
You have the answer in the last screen you posted :p
No lol
Print allows you to print something
so its range?
It doesnt loop or repear instruction
Nope
.-.
is this an exam?
uh
no
exam is way harder.
Why are you asking that scargly xD
EMBER
HALP MEEE
I mean without knowing anything to python you can answer your questions just with your two screenshots
"In Python, the syntax for coding a while loop ..."
ember.;
the first pic
i posted
I thought you were answering that.
.-.
by i just
got it
its print
now about the In Python, the syntax for coding a while loop ..."
you said.
I figured out but not 100%
Read the sentence and read the first picture
Yeah the first picture is print.
the 2nd one?
EMBEER How u so smart.
.-.
I really hate computer science.
uh hello?
This isn't really the proper place for the subject tbh, and even if it's not an exam, we don't really allow giving solutions to questions like these as we're not here to give you answers, but to help with learning the language and concepts, help point people in a certain direction when troubleshooting code, or generally discussing related subjects.
You can say something, sure.
That's not really saying something related to the above, this is asking an additional question.
So I'll have to direct you to a help channel in the Available category.
ok.
is there any help channel about operating system?
i have some simple questions about os, which is paging
thank you
Hi who can help me whith this code
`from tkinter import *
def register( ):
screen1 = Toplevel(screen)
screen.title("Register")
screen1.geometry("300x250")
username = StringVar( )
password = StringVar ( )
Label(text = "Username * ").pack ( )
Entry(textvariable = username)
Label(text = "Password * ").pack ( )
Entry(textvariable = password)
def login( ):
print("Login Session started")
def main_screen ( ):
screen = Tk( )
screen.geometry("300x250")
screen.title("Notes 1.0")
Label(text = "Notes 1.0", bg = "grey", width ="300", height = "2", font = ("calibri", 13 ) ).pack ( )
Label(text = " ").pack ( )
Button(text = "Login", height = "2", width = "30", command = login).pack( )
Label(text = " ").pack ( )
Button(text = "Register", height = "2", width = "30", command = register).pack( )
screen.mainloop( )`
Would a formal language L* be equivalent to L* L since L* is composed of all strings of its alphabet?
can some1 please help me with cs hw pls. Its about flowcharts. dm for details
please, anyone?
Does anyone know what computers are good for beginning programer not too expensive...
@thorny flume off-topic would be a better place for htis, try #ot2-never-nester’s-nightmare - a very short answer is that almost any computer will do
Thank you
total = 0
while total < 10:
global total
num = int(input("Enter a number: "))
total += num
print(f"Total is: {total}")```
whenever I run this
@hushed badge
So I am confused with what an ADT is exactly. How does it relate to data structures? Can you give me an example of what is an ADT and what isn't?
abstract data type?
yes
Abstract Data Types. Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by a set of value and a set of operations. ... It is called “abstract” because it gives an implementation-independent view.
- a random websie
*website
might wanna read that
Is anyone familiar with Linear Quadratic Regulators?
!ask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Be patient while we're helping you.
You can find a much more detailed explanation on our website.
could someone explain to me how a hidden markov model in tensorflow works? i looked at the documentation and i still don't understand
i don't understand this For a batch of hidden Markov models, the coordinates before the rightmost one of the transition_distribution batch correspond to indices into the hidden Markov model batch. The rightmost coordinate of the batch is used to select which distribution z[i + 1] is drawn from. The distributions corresponding to the probability of z[i + 1] conditional on z[i] == k is given by the elements of the batch whose rightmost coordinate is k. Similarly, the conditional distribution of z[i] given x[i] is given by the batch of observation_distribution. When the rightmost coordinate of observation_distribution is k it gives the conditional probabilities of x[i] given z[i] == k. The probability distribution associated with the HiddenMarkovModel distribution is the marginal distribution of x[0],...,x[num_steps - 1].
Guys
i was taking a python certificate course and got to this question which made me redo the test originally i though it was going to be the obvious(actual answer) but no
what is 'a' source code?
lol
if userChoice == random == "p" or userChoice == random == "s" or userChoice == random == "r":
can't i just say
if userChoice == random == ("p" or "s" or "r"):
maybe?
nope
okay thanks
if userChoice == random and userChoice in {'p', 's', 'r'} should work though. i think...
I promise this is not homework. I came across this problem and cannot find a good solution
That looks like the last challenge on that Google doodle thing with the rabbit and the carrots, I think I remember finding a solution using 4 blocks, 2 loops (nested), move forwards, and turn. @south slate see if you can figure it out and ask again if you are still stuck
Also, the solution involves knowing it won't fall off the edge and there are repeated moves, looking at it now I think I know a 6 block solution that should work without those two things
@sudden sinew I don't know the original source. But yeah, I will try again.
Oh yeah, that probably isn't the original but I was saying it reminds me of that
hi i don't know if this is the right saloon.
so I want to change my output camera
ex: if I do cam call on discord and well I wish to be able to modify the rendering of the genre add the text which will be seen on the rendering of my cam
What are the most recommended Design patterns to know? (an example would be Domain Driven Design), and if you have any favorite writeups or guides about it, I'll take those too.
design thinking
guys, newbie question, i'm thinking about studying some web scraping, what type of data is cool to scrape?
i mean, this is something i can freelance one day?
what kind of data should i scrape
for training i mean
white pages @chrome needle
could you give me an example?
mine might work
name = input("Please enter your name: ")
print("Welcome " + name)
@fiery cosmos ?
hello
im just making autoclicker rn
0h 0k
anyone know how to randomise the order of 4 digits
for example I have the int 5262 then I randomise it and it becomes 6252
@jade crater you can convert it to a string so it can be stored in a list then shuffled, then at the end you can use str.join on it like this ```python
import random
def reorder(num: int):
digits = [char_num for char_num in str(num)]
random.shuffle(digits)
new_num = int("".join(digits))
return new_num
ok thanks
@peak notch "Design Thinking" on its own is a lot different from the patterns. This is a very high level thing that I already know about.
Could anyone give me help with printing the tens digit of an input? E.g: I input the number '5436' and I want my program to output '3' as that is the tens digit, ty. I'm using Python btw
Did you know that Windows takes up about 6GB RAM? 😄 That's even more than Call of Duty needs. xD
@tranquil knoll :No, Windows 10
@twin relic Have you figured it out or do you still need help?
help pls
@twin relic https://stackoverflow.com/a/39644706
doesnt help mke
OK, try this:
number = input('Number: ')
print(number[-2])
>>> z = input('Number: ')
Number: 5436
>>> print(z[-2])
3
What's the remainder of 11 / 10?
o ty very much @worthy star
how do I multiply a number in a list, in a loop im checking if numbers are odd or even, if they are odd it's supposed to multiply it by 2 but I'm not sure how to do it
list[x] * 2 doesnt work
What error message are you getting?
@jade crater have you done list[x] = list[x] * 2, you need to assign the result to a variable, in this case you want to assign it back into the same position in the list just twice as big
Cofactor expansion for finding the determinant has an O(n!) runtime. Can you do better with memoization?
My guess is no.
6. No spamming or unapproved advertising, including requests for paid work. Open-source projects can be showcased in #show-your-projects.
Thanks sorry about that this is currently volunteer by invite only with profit sharing options its an open source project under the gnu
@wind idol
Sorry ill post it in the showcase
Its not a request for paid work
Hi
Did you know that Windows takes up about 6GB RAM?
No it only uses 1 GB of RAM in my laptop; 800 MB if I push it
Learn to program, any language, but python is great for beginners.
@willow elk it doesn't matter, your college will teach computer science from the ground up, no previous knowledge required. In the meantime code in whatever you like and DON'T think about practicalities like what languages are popular. Pick something you want to code, pick the language that seems coolest to you and go for it. You're in HS, you have time and freedom to learn what you like. Once you're in college you can be more practical :)
why not #discord-bots
they all think what i need help with doesn't pertain to discord.py, but it does
k
Right now, I just need a person who is an expert at python and is willing to help me, and they know how to program to have a bot compare and find and then say the closest match
Just a thought I'm having while I'm studying: Dijkstra's falls short when you have negative edge weights because you end up with a -inf path that you never break out of. But is it guaranteed that Dijkstra's will discover any negative cycle in your graph?
(If it's reachable, of course.)
@willow elk it doesn't matter, your college will teach computer science from the ground up, no previous knowledge required. In the meantime code in whatever you like and DON'T think about practicalities like what languages are popular. Pick something you want to code, pick the language that seems coolest to you and go for it. You're in HS, you have time and freedom to learn what you like. Once you're in college you can be more practical :)
@oblique shadow alright thanks 🙂
@oblique panther i guess it depends on your implementation, I don't know if the 'true' version would but i made my own version which keeps track of all nodes it has already visited to that it doesn't re visit any (so when initally exploring it doesn't get caught in an infinite loop between 2 nodes even with +ve edge weights) so mine would just traverse that edge max once then never try to revisit that node again
I feel like this is a better way because I can't think of many cases where you would use Dijksta's algorithm and be dealing with -ve weights but i don't think it would be hard to modifiy to identify a loop which sums to an overall -ve so it just breaks the infinite loop and returns -inf
def algorithm(input, k):
positive_tested = 0
for i in range(len(input)):
if input[i] == 1:
positive_tested += 1
if positive_tested == k:
return i
return None
Would the runtime for this simple algorithm be O(n) or O(n-k) in the worst case?
O(n) because of range(len(input))
Are you sure about this because we know 2k = number of 1's in the input, k > 0 and k < n, and the algorithm is guaranteed to halt on finding the k 1's. Would it still be O(n) or is it O(n-k)?
O(n) because run time complexity just considers the worst case scenario of how long the algorithm will take to run compared to its input and because the worst case run time is that it has to consider all n arguments its O(n)
it is similar to if you have 2 for loops it isn't O(2n) its still just O(n) because the run time is directly proportional to the size of the data passed
wouldnt it be n-1 because at least one element has to be a 1?
time complexity doesn't consider constants, it only really describes 'the sape of the graph' that would be made if you plotted time against input size, so you can have O(log(n)), O(n**2), O(1) etc but it doesn't actually mean that all O(n) operations will take the same time
you can expect somthing that is O(n) to take twice as long if you increase the input size by double like a for loop but a for loop that just adds 1 to a number and a for loop that squaress a number, divides it by 2 and then works out if its even are both O(n)
the worst case run time is that it has to consider all n arguments its O(n)
Even if we have the guarantee that we never need to consider all n arguments?
the algorithm is guaranteed to halt on finding the k 1's
We know there are 2k 1's in input, so worst case would be that we would have to loop over n-k indices, isn't this correct?
@fiery cosmos yes although it can stop after finding k 1's, if the input doesn't conatin any 1's as an example then it will need to consider every item in the list still which is the worst case scenario so it would still be O(n)
Not sure if this is the right channel, but is there a server that's sort of like the scale of this one, but for JS?
Can't seem to find one that is large scale
i don't know of any sorry
My algorithm final is in an hour. Guido be with me.
if the input doesn't contain any 1's
@topaz pulsar
as stated, you are 100% guaranteed there will be 1's in the input, so no matter what you will not have to look through n items. i kinda understood when you said earlier that worst case would be n-k, where k = 1, which would basically be O(n).
@fiery cosmos Although you can guarantee that there will be some 1s the algorithm is still O(n)
Would you say this is sufficient proof for O(n)?
We can make a list of people, where 0 represent healthy people and 1 represents infected people. An algorithm could then go through the list, until it finds k 1's. In the worst case our algorithm has to consider the entire list of people giving it an upper bound of O(n), as the algorithm cannot predict the input.
i can be confusing but constants ar not included in processsing time, because they do not affect how long the time taken grows, python for x in range(len(y)): ... and python for x in range(len(y) - 5): ... both have the same time complexity of O(n) because the variable that controls how long the process takes grows with O(n) complexity, because the 10 5 is constant its not counted
If you have a B tree of order b, isn't the runtime for most operations given n nodes O(log_(b) n)?
or something?
how is this a compilation error
PRINT "A lightning flash: between the forest trees I have seen water.": END
nvm
Is there a way I can add a 0 onto the front of an int in an array, for example I have a list like this x = [1,2,3] and I want to make the 1 01
how do i do this: Write a program that accepts a whole number as input, multiplies that number by 12, and then outputs the product.
I would look into #❓|how-to-get-help
x = int(input())
x = x * 12
print(x)
@fiery cosmos
@jade crater ints in python cannot have leading zeros so unless you store them at strings and then convert them when you need them you can't as far as i know
ok
Yes, that wouldn't really make sense mathematically or in terms of how ints work in python. I'm not exactly sure why you would want to do this but I'm guessing you just want the output to be formatted like that in which case you should only format it just before you need to output it if that makes sense
yeah, good idea
hi, so i'm doing this problem: ```Farmer John has discovered the secret to making the sweetest butter in all of Wisconsin: sugar. By placing a sugar cube out in the pastures, he knows the N (1 <= N <= 500) cows will lick it and thus will produce super-sweet butter which can be marketed at better prices. Of course, he spends the extra money on luxuries for the cows.
FJ is a sly farmer. Like Pavlov of old, he knows he can train the cows to go to a certain pasture when they hear a bell. He intends to put the sugar there and then ring the bell in the middle of the afternoon so that the evening's milking produces perfect milk.
FJ knows each cow spends her time in a given pasture (not necessarily alone). Given the pasture location of the cows and a description of the paths that connect the pastures, find the pasture in which to place the sugar cube so that the total distance walked by the cows when FJ rings the bell is minimized. FJ knows the fields are connected well enough that some solution is always possible.```
and im thinking of a brute force sol
where i just try bfs from each pasture, and see which is the minimal
but my program (in py, ofc) has to run under a second so is there a more optimal algorithm i could use?
(ping 2 reply thx)
so you have some kind of network of pastures, and the goal is to find the pasture from which the distance to all others is minimal
but the distance is weighted by how many cows are in a pasture
does that sound right @eager hamlet ?
no they give you the distance between pastures @gusty grove
For this question would I just use a input the number then a for x in numbers then another line with row + 1 then print the numbers increasing each time. Write a program that takes a symbol (+,-,* or /) and a natural number (>0) and makes a table like below for the operation from 0 to n For this example the user has entered “+ 4”:
- | 0 1 2 3 4
0 | 0 1 2 3 4
1 | 1 2 3 4 5
2 | 2 3 4 5 6
3 | 3 4 5 6 7
4 | 4 5 6 7 8
Hello guys I have a question in my mind that I have a tuple and have calculated hash() of that and was wondering that what is the time complexity of calculating hash like in terms of Big-Oh notation
O(1)
what
of course it's O(n)
and ("523", "python") would take roughly three times more than ("1", "2", "3")
@inland sleet how would i use this table tho?
Erm idk that was the question you put like + 4 or 2 different inputs and it outputs the table
oh ok
nvm i found out how to do it
operators = ("+","-","/","*")
operator = ""
# input the operator
while operator not in operators:
operator = input("Please enter an operator: +, -, * or /: ")
size = 0
# input the size and ensure it's a positive integer
while size < 1:
try:
size = int(input("Please enter a natural number: "))
except:
print("That's not a number.")
size = 0
#heading
row = "\n" + operator + "\t|"
for x in range(size + 1):
row += "\t" + str(x)
print(row)
# underline the heading
print("-"*((size+2)*4+3))
# rest of table
for y in range(size + 1):
# using \t to space out the table
row = str(y) + "\t|"
for x in range(size + 1):
# trap invalid calculations, e.g. dividing by zero
try:
row += "\t" + str(round(eval(str(y)+operator+str(x)),1))
except:
row += "\t-"
print(row)
def shit() lol
Hi, how to show that n^2 is a subset of n^3?
n^2 = n * n n^3 = n * n * n = n^2 * n
@royal kestrel really that simple huh?
@runic tinsel are you talking about hash()?
@stable pecan how it is O(1) can you pls explain?
@fast citrus hash()
.
I know that like hash table lookup time complexity is O(1) on average and O(n) in the worst case. Dunno about the underlying algorithm computing these hashes but I guess it depends on the Python's implementation (whatever the object's __hash__() function is).
@fast citrus
@brisk swan thanks
Np!
Yep, O(n) worst case if all the objects in the dict have the same hash value and ends up in the same bucket
hi, so i'm doing this problem:
FJ is a sly farmer. Like Pavlov of old, he knows he can train the cows to go to a certain pasture when they hear a bell. He intends to put the sugar there and then ring the bell in the middle of the afternoon so that the evening's milking produces perfect milk.
FJ knows each cow spends her time in a given pasture (not necessarily alone). Given the pasture location of the cows and a description of the paths that connect the pastures, find the pasture in which to place the sugar cube so that the total distance walked by the cows when FJ rings the bell is minimized. FJ knows the fields are connected well enough that some solution is always possible.```
and im thinking of a brute force sol
where i just try bfs from each pasture, and see which is the minimal
but my program (in py, ofc) has to run under a second so is there a more optimal algorithm i could use?
(ping 2 reply thx)
Looks like an optimization problem @eager hamlet ?
More specifically it seems like it could be an all-pairs shortest path problem, maybe look into Floyd-Warshall algo and see if that could be applied somehow?
ok then
out of Linked List, Binary Search Tree, AVL Tree, Hash Table, Min-Heap, which would take the longest time to search for an element?
Linked List
Actually wait
I'm a bit unsure of that
Linked List (unsorted), BST have worst-case time O(n) for searching, AVL is similar to binary tree but has properties that guarantee O(logn) complexity when searching. Hash table is O(1) on average but O(n) worst-case, and Min-Heap I believe is also O(n)
Hopefully this helps @fluid copper
@brisk swan I forgot to specify this was for average time. So linked list makes sense I think
Ahh I see
if one of these is even slower that linked list that would be extraordinary
😂
(unsorted) doesn;t even change anything
on average would hash tables be the fastest?
I guess so
Yeah, the unsorted was a mistake
In this case i is the index and x is the Node?
I believe so
If so, you save the next at the index, replace it with the node, then set the Node's next to the one you saved
you walk to the spot and splice in the node
@brisk swan i looked into floyd-warshall, and it looks like it has a complexity of n^3 which doesn't really work for me bc i have to be able to run around 800 pastures in under a second
how did web crawler bots even find websites to index
originally
like where did they get the urls
@eager hamlet Ah man that detail totally slipped me, sorry man. But it's still an all-pairs shortest path problem, maybe you can adjust other shortest-path algos to adapt to that constraint
ok then
@fiery cosmos take a few known webpages and collect all the links you find. Visit each unique link and repeat the process
Hi can anyone help me with some algorithm runtime questions?
hi can someone explain to me how a parser file is supposed to work
so, i'm doing this problem:```
Farmer John has discovered the secret to making the sweetest butter in all of Wisconsin: sugar. By placing a sugar cube out in the pastures, he knows the N (1 <= N <= 500) cows will lick it and thus will produce super-sweet butter which can be marketed at better prices. Of course, he spends the extra money on luxuries for the cows.
FJ is a sly farmer. Like Pavlov of old, he knows he can train the cows to go to a certain pasture when they hear a bell. He intends to put the sugar there and then ring the bell in the middle of the afternoon so that the evening's milking produces perfect milk.
FJ knows each cow spends her time in a given pasture (not necessarily alone). Given the pasture location of the cows and a description of the paths that connect the pastures, find the pasture in which to place the sugar cube so that the total distance walked by the cows when FJ rings the bell is minimized. FJ knows the fields are connected well enough that some solution is always possible.
PROGRAM NAME: butter
INPUT FORMAT
Line 1: Three space-separated integers: N, the number of pastures: P (2 <= P <= 800), and the number of connecting paths: C (1 <= C <= 1,450). Cows are uniquely numbered 1..N. Pastures are uniquely numbered 1..P.
Lines 2..N+1: Each line contains a single integer that is the pasture number in which a cow is grazing. Cow i's pasture is listed on line i+1.
Lines N+2..N+C+1: Each line contains three space-separated integers that describe a single path that connects a pair of pastures and its length. Paths may be traversed in either direction. No pair of pastures is directly connected by more than one path. The first two integers are in the range 1..P; the third integer is in the range (1..225).```
and my code is as follows: https://paste.pythondiscord.com/hitomoveji.py
however, it's too slow for this test case (under 1 second): https://paste.pythondiscord.com/zepuqoniga.py
any optimization tricks? (ping 2 reply thx)
it implements dijkstra's algo for each cow for each possible field with a heap for better node-getting
@eager hamlet did you try implementing it as Floyd-Warshall instead of doing Dijkstra's n times?
I'm still not sure how to factor in the "vertex weights".
ok ill try floyd warshall
floyd warshall gives you the shortest distance between all pairs of vertices.
https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/ this page has a Python implementation that's painful to read, but it might give you a place to start.
i once implemented it, i'll just copy paste from there
@oblique panther ok, now my new code is here: https://paste.pythondiscord.com/hodexotota.py
but now it produces a wrong output for this case: https://paste.pythondiscord.com/uzecekozif.py
I asked my coworkers what they think
Not at my laptop so I can't get to it rn
But the textbook that I use
Its implementation of Floyd Warshall usually initializes the matrix (in your code, initialDist) to infinity oh nvm i see u did that already
Oh u got it workin?
but it's too darn slow for this test case again https://paste.pythondiscord.com/zepuqoniga.py
oof
@eager hamlet did the instructor say what the target runtime complexity is?
@oblique panther 1 second (also it's just the usaco training pages)
That's not the same as runtime complexity
uh no then
For my next project, I need to write some AMD64 bytecode, basically do the job of an assembler, I tried to read the Intel documentation, but it was totally unreadable for someone that isn't used to, like me 😓 would you know a book or tutorial that would have a comprehensive guide to AMD64 bytecode?
Is it a terrible idea to start learning C# while continuing to do projects in python?
No
Thanks
Searching a binary tree for a value K has a lower bound of log n. Would searching for k same values have a lower bound of log C(n, k) (the combination)?
I'm looking for k K in an input of size n
Ahh
The first search would require log n computations. The next would require log n-1 computations. The k'th would require log n-k+1 computations. I believe this produces log C(n, k)
unless i'm wrong
why doesnt it know what direction is
fuck
how do i maker this thing move north
and south
and west and east
ugh
who can help teach me about something to do with manual system calls on a rasberry pi im interested in talking code theory if anyone is up for it pm please
is there a general case algorithm for determining uh.
let's say I have ten strings that, when hashed, have the same hash
(it's an extremely low-bit hash)
I have code which needs to get the correct string
so it needs a collision resolution table
it resolves collisions by having a table which has a character to check for, and the position to check it for
so if my strings were, for example, "apple, orange, banana, apricot"
the table might look like
(p, 3), (o, 1), (b, 1), (r, 3)
does that make sense?
what would an algorithm that can calculate that table look like, given any number of arbitrary strings?
the case for two strings is trivial but any higher than that, I'm not sure what approach to take
that can still result in a collision
uh, like "lia, lop, toa, tip"
this would be more general, it stores a substring, so it can store the whole string in the worst case
in either case the algoithm is brute force
hi, can someone help me ? I'm trying to iterate through a list of jsons, just like ```
[
{
1:"a",
2:"b"
},
{
3:"c",
4:"d"
}
]
[
{
"a":1,
"b":2
},
{
"c":3
}
]
but I get json.decoder.JSONDecodeError: Extra data: line 28 column 2 (char 954)
You are missing a comma after the first ]
You are missing a comma after the first
]
@north zealot same exception anyway
jsons can only have strings as keys
not integers
this is the wrong channel for it though
I want to calculate the distance between two points in n-dimensions. I'm mapping the operator.pow on a tuple (base), and want to apply the same exponent of 2. what's the most pythonic way of doing this?
example:
p1 = (0,0) p2 = (2,2) map( operator.pow, map(operator.sub, p1,p2), [2]*len(p1) )
This works, but I feel this looks somewhat ugly. Is there a better approach for defining the exponent of 2 for each base?
What about a plain old list comp?
[(v1 - v2) ** 2 for v1, v2 in zip(p1, p2)]
Also if you're thinking of doing a lot of things with vectors you should check out numpy
What about a plain old list comp?
[(v1 - v2) ** 2 for v1, v2 in zip(p1, p2)]
Since you're going for the distance you can just do this directly:
sum((v1 - v2) ** 2 for v1, v2 in zip(p1, p2))
Thanks @quasi oracle
In Python 3.8 you can use math.dist(p1, p2)
Is it possible to stop a python script from another python script? for example I am running script1.py and I want to terminate it with script2.py
You'll likely have to use shell commands to find and kill the process
What is the best resource for learning regression and classification in Python?,
What is the difference between predicate logic and temporal logic?
when I am done with the next milestone of my project, I will have a huge json
it has 5 million keys
with every key taking 3kb storage
= 15GB of storage
how do I deal with such large files? Like - I cant just load it into ram for example
maybe an other format is better suited?
it is a bit build up like that:
{
1: {
"a" = "b"
"list" = ["cat", "dog"]
}
}
out of the keys of the json, they have lists again.
I want to be able to find -for example- all dicts that have "cat" in subdict["list"]
it should be fast, so just iterating over every element is not doable
where do I get started?
Use case: I want to find all dicts that contain the searched string as fast as computationally possible.
exporting everything to sql would also be an option, would need to do research for that tho - but idk if that would be faster
please @ me so I see the reply
at this point you definitely want to use a database like SQL instead of loading files into memory to do a search
@median ridge If your data has to stay in the JSON string format, then the solution is streaming. I'm not sure on a specific library, you just need to have a look around for python streaming json libraries. Rdbaker is right though, and ideally you'd be storing your data in a better way - either MongoDB which is closer to json, or SQL
The details matter a lot on the specifics of your data - which makes it difficult for this server to help you with. But solutions I'd be investigating (in this order) would be: reformatting data to be relational SQL (Postgres, or MySQL), MongoDB (can leave your data closer to its current format), or streaming the file (last reosort)
This is the wrong channel though.
@royal kestrel Thanks for that tip about math.dist
Does anyone know why I get this error?
pool = {}
x = ContinuousEntityEvent(0,0,Point(0,0),lambda x:x+1)
pool[1] = {x}```
**TypeError: unhashable type: 'ContinuousEntityEvent'**
This is the class definition:
```python
class ContinuousEntityEvent:
def __init__(self, uid, startTime, startValue, model):
self.uid = uid
self.startTime = startTime
self.startValue = startValue
self.model = model
def getIter(self):
return self.Iterator(self.startValue, self.model)
class Iterator:
def __init__(self, startValue, model):
self.current = startValue
self.model = model
def __next__(self):
self.current = self.model(self.current)
return self.current```
i think u need a space
not sure tho
but
pool = {}
x = ContinuousEntityEvent(0, 0, Point(0, 0), lambda x:x+1)
pool[1] = {x}
@sharp onyx
@fiery cosmos Thanks, I'll give that a try
Hm, so the code as I have posted in here works. But the code in my codebase does not.
I think I uncovered a root of my problem, my classes were inheriting from an abstract class that inherited from module ABC. It seems that prevented the __hash__ function from being defined.
can anyone explain to me real quick what to do for my boolean algebra work
i dont understand what im meant to do
if you see this id appreciate even a short answer because my homework for computing is due at 11:30 today for my live lesson
Hey Everyone..
this is an example of rotations in AVL trees but i think author of the book made a mistake like if you see the picture (at the right) then right child of node = G is node = P.
And in the left picture it 's shown that node = G exist in the right subtree of P which means node G value is bigger than node P ..
So, it should be like this :
G
/ \
P C
/ \ / \
s1 s2 s3 s4
am i doing it right ?
thanks @last blaze. I thought this would be the right channel as it says "discussion of data structures as they relate to solving problems with python"
What would be the right channel then?
i dont understand what im meant to do
@fiery cosmos I have no idea when's 11:30 for you, but you should make a truth table for each expression and see if you recognize a pattern in the result
@balmy siren as far as I can tell you're right, but I haven't touched the subject in a long time
@quasi oracle yeah thanks man .. cause at first P is the root of a tree and G exist In it's right subtreee (which simply means, G is greater than P) but what the author does is, he rotates the tree in a wrong direction
Generally speaking when you rotate a search tree the order horizontally should stay the same.
E.g in your case it's s1 p s2 g s3 c s4, and that's how it stays after the rotation
@median ridge probably #databases. Possible #tools-and-devops . It doesn't necessarily fit nicely into any channel, but #databases should be fine
@median ridge By "data structures", the topic refers to abstract data structures like lists, dictionaries, trees, graphs, etc. and their computational properties, not just "a lot of data" in general.
But databases are designed to store and manage large amounts of data, so #databases is appropriate.
yeah, db was just 1 option I thought later of. I get the information as a json, so my first thought was to manage it in a json.
I later realized I forgot a 0 at the end, making it from 1.5GB (on the edge of managable to just load it into ram) to 15GB (not possible)
Hi there!
I have some data stored in a dictionary serialized as json; it has a structure something like: data={"category1":{"key":ammount},"category2":{"key":ammount}}
but when entering the data soem typos slip in. I wrote a short script to fix those typos from the command line
(while also keeping a list of know typos to fix them quicker)
I load the data, do a deepcopy and iterate over the keys, and 'fix them into' the deepcopy and at the end save the deep copy
is that considered an 'elegant' solution, or is there a better way?
(btw it is not really much data)
This isn't really computer science either. You could just ask this in a regular help channel.
Try one of the ones in the available category
ah okay, sorry
No problem
@lone umbra Firstly, this is off-topic for this channel, and secondly, we can't help solve homework and exams for you
ok cool
If you have general Python questions, we can help you with those
But not in this channel
Ask in one of the channels in the Available section
Can anyone tell me how to install a Linux subsystem
@hidden pebble what operating system are you using?
If you're on windows. Then #491524019825278977 has a guide pinned. Its quite old - but if it's still pinned, I assume it's still relevant
if you're on Mac, you could try the "multipass" thing from Ubuntu; it works pretty well
or you could just try VirtualBox
I wouldn't call that a "subsystem" but it'll let you run Linux
(not sure if this is the right channel) Trying to find a way to check if a json value is nil or 'subscriptable'. Right now im trying to use ```py
#I've done this
NoneType = type(None)
if i["Example"]["Example2"] == NoneType:
#do things
#I've also done this
if i["Example"]["Example2"] is None:
Why is that ^C is ignored by child threads? Google says it is ignored by main thread does that mean main thread will stop executing but child thread will not be affected by keyboard interrupt? I don't quite get it
import os
import threading
try:
os.unlink("/tmp/128ecf542a35ac5270a87dc740918404")
except FileNotFoundError:
pass
def symlink():
while True:
#do something
def run():
while True:
os.system("./maze0")
x = threading.Thread(target=symlink)
x.start()
run()```
I still get the output from run() even though I hit ^C a bunch of times. I think main thread doesn't care about it either
anyone know of an easy method to convert binary to hexadecimal
what exact data do you have, and what exactly do you want it to look like?
in other words, what is "binary"?
maybe this is what you want ```py
hex(int('10000110', 2))
'0x86'
but until you tell us, it's just a guess @fiery cosmos
@fiery cosmos one letter is 4 digits
A is 1010
4 is 0100
etc
and vice versa, 1000 is 8, 1011 is B
ik binary and hexadecimals im just shit at convertingn them
First convert this into decimal number:
= (1101010)2
= 1x26+1x25+0x24+1x23+0x22+1x21+0x20
= 64+32+0+8+0+2+0
= 106
Then, convert it into hexadecimal number
= (106)10
= 6x161+10x160
= 6A which is answer.
because this is the example i was taught but ik theres an easier way
@fiery cosmos there is. Pad the binary number on the left with leading zeroes until its length is a multiple of 4, then convert each 4 binary digits to their corresponding hex digit.
1101010
= 0110 1010
= 6 A
A hex digit can represent 16 different states, as can 4 binary digits - so each 4 binary digits can be translated to 1 hex digit.
ok thank you i was getting confused with the positional thing i thought that it was included in teh binary conversions aswell
@wild bronze yup the thread will be orphaned (no parent thread) and continue running for ever
You can set thread.daemon to true so that it exists with the main thread but this might cause data loss etc
You can also call thread.join() to block until the thread finishes. This ofc only works if you don't use while True
(not sure if this is the right channel) so im kinda a beginner in python, I'm coding a pong game and I can't fugure out what my mistake is. Prolly some stupid small mistake but can sum1 skim thru my code and tell me if they can catch what I did wrong? pls dm me if ur willing to help cuz it wont let me send the file here
Breadth First Search has a time compexity of O(|V| + |E|). Can this be considered polynomial?
@fiery cosmos you can use one of the available help channels. You can check out #❓|how-to-get-help on how to do it
ok
@fiery cosmos That depends on the graph. If it's a clique then the number of edges is polynomial in the number of vertices. If it's, say, a 2-regular graph, then it's linear.
If you're asking with respect to both V and E separately, then it's linear in each
Hi, I have an assignment I’m working on. I have some what an understanding but i would appreciate it if someone could look over my answers and give me a few pointers
Any guidance would be greatly appreciated, thank you!
If you want to express the whole runtime of something rather than it's big-O/theta/omega complexity, is that just T(n) = ...?
@forest hull is that question asking how many bits are present in a grid of that size?
Yes, I think so
So if I understand correctly, the grid is 512 by 16384, and each cell in the grid is 24 bits.
But if the dimensions of the grid are measured in bits, then the answer is different.
do you know which it is? I squeaked by in my hardware class.
For the question about the MAR
I think it just mirrors however many bits the memory address is (N)
At least that’s my understanding
I didn’t really take into account the dimensions of the grid. Although the following questions do ask about the grid
Hi!
I'm working on a hobby project to 'minmax' Upgrades for a little game I play.
this game has different facets so I can't peacefully 'minmax' a single value, so I made up some math.
But I'm unsure about pitfalls or shortcommings
can I post a screenshot of my idea typed up in LaTeX here?
Yes
here goes bad latex
I think the sum may be an issue here
yeah that won't work the way I set it up
let P = .... for a given "strategy" ...
do you mean game state?
or is it just a coincidence that they are both called S
also maybe add a set W of weights
yeah. The issue here is that the costs don't factor in correctly so it could only compare upgrades with the same costs the way its set up here
also A an upgrade should propably be something more like an ordered pair of game states
or a set of reachable gamestates from the 'current' gamestate. with each reachable gamestate having some sort of costs
no wait it works the way i set it up
an 'upgrade' changes the gamestate. the 'available' upgrades depend on the current game state
so you have a (in my case finite) subset of the set of upgrades over wich you would try to maximize
and yeah the word 'Strategy' is not well picked. But i do not really know how to express the concept i mean.
when calculating the complexity of algorithms dealing with graphs, would iterating over the edges or the vertices be considered O(n)?
Generally, you have two different ways of denoting the time complexity of graphs. O(K) is the number of edges, O(V) is the number of vertices/nodes
You need to be a bit more specific than just O(n) for graphs really
Though when analyzing complexity you should define what your variables mean anyway
Num2=6
Num3=10
for i in range(n):
for j in range(k):
x = i * i
y = j * j
z = i * j
for i in range(n):
w = Num1*i + 45
v = Num2*Num3
Num3 = 33
``` How to calculate big O of this snippet?
for i in range(n):
w = Num1*i + 45
v = Num2*Num3
```this part is smaller than the other one, you ignore it entirely
the other part is O(n*k), that would be the final complexity
instead of adding up, the highest complexity just wins
so it should be O(nk)
sure
result = 1
while n > 0:
result *= n
n-=1
return result
``` so then this should be O(n)?
yeah I'd say so
Thanks
@last blaze I always thought it was O(E) and O(V), or is that a German thing?
Edges are called "kanten" in german so O(K) would make sense
Can someone explain the role of inconsistent set in ARA* (Anytime A*)?
@last blaze I always thought it was O(E) and O(V), or is that a German thing?
@gusty grove
I have heard that as well actually. It does feel less common though
Have only ever used E
In NN are the weights attached to the node or attached to the link? (I know it is not python specific and more theory base)
@thick canopy the link because then the weight between each node can be specific to those 2 nodes, also best place to ask about NN is probably data science
if a problem can be decided in O(|V| + |E|) time, would it belong to class P?
ok thanks
if a problem can be decided in O(|V| + |E|) time, would it belong to class P?
@fiery cosmos yes
how do i download python on a chromebook
@upbeat magnet please see #❓|how-to-get-help and not post questions in channels that are completely unrelated to your question
Could someone explain to me why a turing machine with an added stack is not more powerful than a turing machine without one?
@pale wadi "more powerful" would mean that there are languages that a Turing machine with a stack can decide on, that one without cannot. Is that the case though? maybe you see a way in which the stack could be incorporated into the machine's track itself?
