#algos-and-data-structs
1 messages · Page 80 of 1
something along the line of```python
value = (current-upgraded)/(current*costs)
where current and upgraded arent too different, but can grow huge, and costs could also go up a lot. also upgraded may be equal to current
I don't think python has much specific to say about that@prime flame
you might be able to use Decimal, which guarantees exactness at the cost of memory usage (and perhaps slowness)
I don't think that would work. the values for current and upgraded will come from a supplied function wich somehow assigns a value to a game state
I think I'll just drop that approach for now. the target would have been to 'combine' two different functions by weighting their value as defined above
(wich I'm also unsure about if it would work as I would expect...)
res = [[]]
for i in [tuple(i) for i in args]:
res = [x+[y] for x in res for y in i]
return res
print (product([1,2],[1,2]))```
thank you python
this is a readable cartesian product code
@turbid path might as well do
def product(*args):
return list(itertools.product(*args))
print(product([1,2],[1,2]))
👍
Is it better to have multiple packages or less? Or is this a personal opinion?
As many as you need? the number of imports is negligible for the average program as long as you keep your namespace clean
Also not particularly comp sci related 😅
How can I use an array as a member in a class?
I defined this class:
class Overlay:
def __init__(boxes, strings):
self.boxes = []
self.strings = []
I tried to initialize one like this:
overlay = Overlay([], [])
But I get TypeError: __init__() takes 2 positional arguments but 3 were given
I basically want to treat it like an object
you forgot self
I want to append other class objects into the arrrays
💐
If im trying to create a DFS its valid to insert each item in a list then pop that item out right?
some actual code
nodes = ['A','B','C','D']
def DFS():
global nodes
node = nodes.pop(0)
children = node.get_children()
for child in children[::-1]:
nodes.insert(0,a)
if nodes == []:
return
else:
DFS()
DFS()```
that's how I do a breadth first search
depth first, I think you can just use recursion
im inverting the list
so if A had children 1,2,3, would the new nodes be
[1,2,3,B,C,D] then we pop 1 and if one has no children we recall and pop 2
etc..
@sly vale the order of immediate children makes no difference. You insert to the beginning and pop from the beginning, so it works like a stack, though I imagine not the most efficient one, so in theory this should get you DFS. However I'm not sure why you're mixing a stack with recursion when either one or the other would give you a complete solution
Hi guys, I'm a bit new to data structures. I'm trying to reverse a doubly linked list in Python - simply by swapping the head and the tail using
self.head, self.tail = self.tail, self.head
Any idea whether this is just..wrong or is there something in my code for traversal (from start or end) that is erroneous?
I created a list, reversed it and then tried traversing it again and I'm getting an error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-102-65d98c8b6d59> in <module>
----> 1 mylist.contentsFromStart()
<ipython-input-94-7df8fc721289> in contentsFromStart(self)
23 elements = []
24 current = self.head.next
---> 25 while(current.next!=None):
26 elements.append(current.data)
27 current = current.next
AttributeError: 'NoneType' object has no attribute 'next'
The problem is that self.tail.next is None
You make it the head, but it doesn't help with the links in your list
So now the head is pointing at None
I was thinking self.head and self.tail are both objects of the class. So swapping them should swap their previous and next values too right?
From what I think my mistake is, according to what you said, is that the self.head.next and self.tail.previous point to None instead of the list elements. Am I correct?
Correct. An easier solution would simply be to swap only the data they hold
self.head and self.tail have no data values though, they're both None...
Oh you want to reverse the whole thing
Yes yes
Then no, swapping the head and tail won't do it. Make yourself an example on a piece of paper and look at the reversed version vs the result of what you did
Okay, I'll have a look. Thank you very much!
Also are you making the head and tail hold None by definition? Because there's nothing preventing them from holding a value just like any other node
Yes, while initializing the node class, the default value that any created node takes is None. So since I haven't created the head and tail nodes by giving a parameter of some value, their value is None
class node:
def __init__(self, data = None):
self.data = data
self.next = None
self.previous = None
class ll:
def __init__(self):
self.head = node()
self.tail = node()
self.tail.previous = self.head
self.head.next = self.tail
Like so
I'd set the head and tail of an empty list as None, instead of an empty node
Oh, yes that makes sense
@sly vale the order of immediate children makes no difference.
@quasi oracle so it doesn’t matter if which child I search as long as once I get those children I add it to the stack
Yes that's right. BFS / DFS just says what the distance of the next traversed node should be from the root
In DFS you get as far away as you can, in bfs you stay as close as possible, from the nodes still not visited
Though in binary trees you traditionally visit the left child first
Yea that makes sense thanks
can i use python to discover vulnerabilities?
Hi, can somebody help me to solve this question?
shuffle.py Write a function that takes a word, splits it in half, recombines it in the reverse order, and then returns it.
from math import floor
s = "antilope"
s[:floor(len(s)/2)]
that would be half
@tribal plume
yikes
define a function largest(n) ): that recursively finds the largest digit in the number stored in n,
and return it. Can someone help me with this
the last digit of a number: n % 10
all the other digits: n // 10
then you find the largest digit in the n // 10
then you have 2 candidates, return the larger one of them
the problem is this is my school's assignment and i cannot use a loop or max function i have to do it using recurssion only so how should i find the largest digit of n//10
max function? just do it by hand
out of 2 numbers, which is what you have, 2 candidates
it's the complete algorithm I gave, pretty much just write exactly that
largest(n)
well not n, but it's largest(something)
now you make what they call a base case
at the start
how can you detect if n has 1 digit?
I guess you can aslo detect if it's 0
more boring
i am really sorry but i am just a beginner and i am not getting whatever u r trying to say so will u mind sending the source code .... no need to put a check if n has 1 digit or n is 0 i will do that
I was going to ask you to send yours
yikes
@runic tinsel Why do you say yikes when I am posting the solution to a question?
I reacted like that because it crashes
What crashes?
the code you sent crashes
hmm it shouldn't
so it's like objectively embarassing
There, corrected it. However, you should check your attitude
You could tell me without being a giant ass about it
Everyone makes mistakes, especially when giving a quick example
And besides, you didn't have the approach right with your answer, so maybe it's not up to you to point fingers
nah, that would be self-reflection
def largest(n):
largest = 0
while (n):
r = n % 10
largest = max(r, largest)
n = n // 10
print(largest)
this is what i have done
but cant do that because loop is not allowed
@runic tinsel can u help me now what should i do?
i am allowed to print
that's why it's a surprise, you didn;t know
you're not allowed to print the answer, that's not how it works
a function returns the answer
def largest(n):
largest = 0
while (n):
r = n % 10
largest = max(r, largest)
n = n // 10
return(largest)
is it ok now?
it's usually without () but that's minor
def largest(n):
if n is 1 digit return n
r = n % 10
n = largest(n//10)
return the r or the n, the larger one
yeah thats because i replaces print with return so forgot to remove it
ok
def largest(n):
if n <10:
if n>r:
return n
else:
return r
r = n % 10
n = largest(n//10)
is this u want me to do ?
yeah but not in this order
that part where you return the larger one, it's at the end
if n <10:
return n
```and that's the base case
@junior locust congrats, that's it
Thanks for ur help
I'm trying to wrap my head around kd trees, but can't seem to get the searching part
Just out of curiosity, are you using kd trees from scipy, scikit, or your own implementation?
def dfs_recursive(graph, vertex, path=[]):
path += [vertex]
for neighbor in graph[vertex]:
if neighbor not in path:
path = dfs_recursive(graph, neighbor, path)
return path
adjacency_matrix = {1: [2, 3], 2: [4, 5],
3: [5], 4: [6], 5: [6],
6: [7], 7: []}
print(dfs_recursive(adjacency_matrix, 1))```
I have a question as to the order in which this is traversed
it goes from 1 -> 2 -> 4-> 6-> 7
which makes sense
however then it goes back up and the next thing it executes is 6
is that because the
for neighbor in graph[vertex]:
if neighbor not in path:```
hasnt finished running yet?
so it finishes checking that right
then it returns path for that value then it jumps to 4: for neighbor in graph[vertex]: if neighbor not in path:
then 2 etc...
i def like using stacks better for DFS
What exactly do you mean "next thing it executes is 6"
As you said 1 -> 2 -> 4-> 6-> 7 makes sense
Then since 7 has no children, you go back up the tree, back to where you came from, so 6
6 has no more children, so you go back up to where you came from, 4, once again no other children, so you go back up to 2
2 has another child, 5. You now go to 5. 5 has one child, 6, but you've already visited it so you return back up to 5.
5 has no other children, so you go back up to 2
2 has no other children, go back to 1
1 has another child, 3 go into it. 3 has a child 5, which is already seen, go back to 3. 3 has no other children and the traversal is complete
Do note that since you have path=[] repeated calls to this function will start showing incorrect results due to how list.__iadd__ is implemented
Default values are evaluated only once and path += [vertex] adds to that empty list
You can see this in effect if you change the function to be ```
def dfs_recursive(graph, vertex, path=[]):
path += [vertex]
return path```temporarily, then call it twice with the same arguments
in other words the first time we called 6 it checks for 7 then after 7 is done running the for loop for 6 hasto still finish
yes
The loop that 6 started called 7 inside it
7 finishes so the loop is continued
the loop terminates as there is no more items and the same effect cascades up the entire tree
Ok that’s what I thought thanks
Oh scipy has kdtrees? I'm implementing my own though as I'm going to make another in a different language
Just saw that it's open-source, I'll be looking at how they do it. thanks
Hi
my problem is quite simple
top_list = []
top_val = -1
second_list = []
second_val = -1
for x in user_dict:
cost = user_dict[x]["redemption_costs"]
if cost > top_val:
second_list = top_list
top_list = [x["user"]]
second_val = top_val
top_val = cost
elif cost == top_val:
top_list.append(x["user"])
elif cost > second_val:
second_list = [x["user"]]
second_val = cost
elif cost == second_val:
second_list.append(x["user"])```
user_dict is a dict that looks like
{
"some_random_numbers": {
"user": user,
"redemption_costs": 0,
"days_redeemed": [False for x in range(process_time)]
}
}
Is there a faster way to do this?
@grave rover you forgot to mention what the problem was fam
this is currently o(n) right?
Oh 
I have to get 2 lists, the users with the highest and the second highest "redemption_costs"
optimization of the code, aight headin out
XD
i dont think there is a o(logn) solution
but i dont know.
or simply a better way to do it.
If the point is to go over each element in the dict, then it has to be O(n) at least
Though I'm honestly not sure what the goal is
are you trying to make two lists are just grap the top two users by redemption costs
i see, you can do this with less code if you use standard library Counter, or heapq
from heapq import nlargest
user_to_costs = {sub['user']: sub['redemption_costs'] for sub in user_dict.values()}
first, second = nlargest(user_to_costs.values(), 2)
firsts = [user for user, costs in user_to_costs.items() if costs = first]
seconds = [user for user, costs in user_to_costs.items() if costs = second]
hello
@stable pecan is that faster?
What you have is O(N), AFAICS, @grave rover - it makes one pass through the list and inspects each key only once.
Yes I know
it isn't faster! but it's easier to read, at least for me
hey guys, this is not realated to python but can anyone explain what two way logic is?
I can only find a small handful of papers that use that term after a quick search - where did you see it? How did they define it? @pastel siren
Yeah I’m not so sure either, I guarantee my lecturer wouldn’t know either.
Would someone know a good paper about parser engines, like regex engines?
Thanks!
Hi guys
can someone explain me big and little endians? I googled it and figured out it's the order of the bytes, for example a big endian is ordered from the most important byte to the least one
But what the most important byte should be?
To make things simple, the most significant bit is the bit that carry that yield the most numbers when you convert to base 10
For example, 0b001
If the most significant bit is the right bit, you have 0 * 4 + 0 * 2 + 1 * 1 = 1 in base 10
If the most significant bit is the left bit, you have 1 * 4 + 0 * 2 + 0 * 1 = 4 in base 10
so which is better to use?
There sin't really any better one, that depends on the arch you're working on
top_list = []
top_val = -1
second_list = []
second_val = -1
for x in user_dict:
cost = user_dict[x]["redemption_costs"]
if cost > top_val:
second_list = top_list
top_list = [x["user"]]
second_val = top_val
top_val = cost
elif cost == top_val:
top_list.append(x["user"])
elif cost > second_val:
second_list = [x["user"]]
second_val = cost
elif cost == second_val:
second_list.append(x["user"])
Hi Guys!!! There was such a problem: installed the library pillow, started PyCharm, created a new project on the python file and try to start the library pillow with the pip command (pip3) install but the following error appears: "pip" is not internal or external
command, executable program or batch file. The library itself is installed in my lib -> site-packages. My python version is 3.8.2. If anyone has this problem or knows how to solve it, write to me
Hello, so recently I've been working on a project a simple cookie clicker game to get my started with programming. I have started to make it but ran into a problem ( I am using tkinter to make this ) how would I display variable (e.g variable named Cash) in a Label and it loops like every 1 second to update the Label for the user gui.
- Thanks!
with connections.scdb() as db: dataset = db.fetch(sql) for item in dataset: pk = item['BARCODE'] self.__barcodes[pk] = item pk = item['SAMPLE_ID'] self.__samples[pk] = item pk = item['IDENT'] self.__num_samples[pk] = self.__num_samples.get(pk,0) + 1
Regarding this code which I have had passed to me, I wonder about the assigning of item. Would barcodes[pk] and samples[pk] point to the exact same element in memory, or is it two separate instances?
Hello guys please i need your help here
Describe the difference between objects and values using the terms “equivalent” and “identical”. Illustrate the difference using your own examples with Python lists and the “is” operator.
Describe the relationship between objects, references, and aliasing. Again, create your own examples with Python lists.
Finally, create your own example of a function that modifies a list passed in as an argument. Describe what your function does in terms of arguments, parameters, objects, and references.
Create your own unique examples for this assignment. Do not copy them from the textbook or any other source.
I dont think helping with graded assignments is allowed here
Hi guys, is anyone here familiar with tesseract ? I am sort of new to python, but i am familiar with other languages,
when i try to get the text off this image I just get "AN afi" not even a number, i tried to invert the image but still got a similar result, any ideas?
import pytesseract as tess
from PIL import Image
import PIL.ImageOps
# inverted_image = PIL.ImageOps.invert(img)
# inverted_image.save('new_name.png')
img = Image.open("text.png")
text = tess.image_to_string(img)
print(text)
here is the image
Hi there guys!
I am trying to count a row from a csv file and see the frequency of "apples, bananas and oranges in the file. Any pointers, i am stuck
@marsh bone Try following this tutorial and applying the methods to your image: https://nanonets.com/blog/ocr-with-tesseract/
Some other links which may help:
https://return2.net/python-tesseract-4-0-get-numbers-only/
https://stackoverflow.com/questions/46574142/pytesseract-using-tesseract-4-0-numbers-only-not-working
https://tesseract-ocr.github.io/tessdoc/ImproveQuality
perfect I will follow up later when i try it!
can I just have an object's __hash__ be its memory address ?
Doesn't sound very useful @exotic aspen
equal objects should have equal hashes, but no two objects are going to have the same memory address
maybe they're all singleton objects
does anyone here know how to use a lexer to create a grammar tree?
my remaining brain cells are currently getting nuked by a lexer
<@&267629731250176001>
!ban 516040052237664256 the content you've posted is absolutely unacceptable and not tolerable here at all.
:incoming_envelope: :ok_hand: applied ban to @atomic granite permanently.
thanks @feral shale
after I raise an error, how do I get it to immediately terminate at that line ?
I raise an error, but it still performs the next line after the raised error
Make sure you don't have any weird syntax issues, raise terminates control flow in the function
Question. I'm started this OSSU curse and there is a lots of new code to learn and my problem is i cant exactly remember to all codes. Is this ia big problem? Should i stop and check it out again? i make a lot of notes about codes and how to use them so whenever i have to do an assignment i know what i need to use but maybe i just forget a little part of the code but i just open my notes check it and write the code. So what do you think?
(Sorry for my english)
is there a succinct way of doing something like this:
checking if there's an object with a particular value in a set
like usually how we do if a in set or if a not in set, but I wanna do something like if a.val not in set, where the elements in set are assumed to all be objects of the same class as a
i'm not exactly sure what you want, but you can give the objects a __hash__ based on the val attribute
what is the advantage of doing computer science for GCSE
@knotty shore doing it for GCSE in particular or just doing it in general? An advantage of computer science is that it teaches you how to approach complex problems and find ways to break that problem up and tackle real world issues, it also can teach you about how computer systems work in good detail which is good knowledge to have in a world where technology is now used in almost every industry
can anyone help me with a c language program
#include <stdio.h>
int main()
{
float sp = 0;
printf("Enter the selling price:");
scanf("%f",&sp);
float gain_or_loss_per = 0;
printf("Enter the gain or loss percent:");
scanf("%f",&gain_or_loss_per);
float gain_or_loss = 0;
printf("Enter if it is gain or loss:");
scanf("%f",&gain_or_loss);
printf("%f",gain_or_loss);
char gain_or_loss1 = 0;
gain_or_loss == gain_or_loss1;
char gain = 0;
char loss = 0;
if (gain_or_loss1 == gain)
{
float cp1_with_gain = 0;
cp1_with_gain = 100+gain_or_loss_per;
float cp2_with_gain = 0;
cp2_with_gain = 100/cp1_with_gain;
float cp3_with_gain = 0;
cp3_with_gain = cp2_with_gain*sp;
printf("The cost price is:");
printf("%f",cp3_with_gain);
}
else if (gain_or_loss == loss)
{
float cp1_with_loss = 0;
cp1_with_loss = 100-gain_or_loss_per;
float cp2_with_loss = 0;
cp2_with_loss = 100/cp1_with_loss;
float cp3_with_loss = 0;
cp3_with_loss = cp2_with_loss*sp;
printf("The cost price is:");
printf("%f",cp3_with_loss);
}
else
{
printf("Please only write gain or loss. If you have write anything else .Please change the same");
}
return 0;
}
pls if anyone can help me
the problem is that gain_or_loss variable is not taking any value and if i assign it with 'char'. it doesn't ask for input
This is a Python server
well but the channel is computer science. isn't it ?
#bot-commands
@quasi nebula you need to make it a char*
and then convert using atof
this is why you use python duh
🤭
!tempban 676888464351821867 7d that type of language is not appriciated here, take som time to read our rules again
:incoming_envelope: :ok_hand: applied ban to @bleak bear until 2020-05-27 17:47 (6 days and 23 hours).
Hey guys, is there a way to convert old pcs into private servers
Yes.
Hey when doing a minmax search without progressive depending you only evaluate the board state at the depth limit correct?
however if thats the case how do we check for both minimizer and maximizer? do i just check each individually
I can share my code but there are alot of objects/function from different modules
Somebody could help me with this?
I'm trying to get a list as an input
for my my function
I tried putting the input without the ' '
But it didn't run 😦
I tried strand (T, A, G)
def strand (dna):
symbols = dna
return symbols
strand(['A','B','C'])
Oh I see
So, the list brackets shouldn't be used it the definition
But when invokating the function.
yes also no return print
print returns nothing, so your function would return nothing in that case
It worked, thanks brzing
*brzig
But if I don't put print how are the results are being displayed?
Does the "return" substitutes the print when invoking?
Oh, I think I get it
print the function
Only use print when using the funciton
yea print tells us something return tells the computer something
great to hear!
of course
Hey when doing a minmax search without progressive depending you only evaluate the board state at the depth limit correct?
however if thats the case how do we check for both minimizer and maximizer? do i just check each individually? I can share my code but there are alot of objects/function from different modules
prog = re.compile(r'(')
#word is an array of characters
word = list("(one(()))")
#loop thru the list of chatracters and match it
count = 0
for char in word:
if prog.match(char, pos=len(char) ) != None:
print('there is a pair of parentheses')
count = count +1
else:
print('there isn\'t any' )
hey guys im trying to find a pair of parentheses present in a string
here is the following code that i wrote but im gettin an error can anyone help
if anyone has the time, i need help with some python code... it has to do with widgets, pillow, and a csv file
well first off you dont need regex to find parentheses
Hey everyone..
last night i was doing hash tables and today i got a new task to design a Hash Map.. so i checked it on google and i see that people were using a dictionary for implementing Hash.. it's like they put (key, value) pair in a dictionary
dict[key] = value
Do i need to do the same or is there any other ways of implementing Hash Map ?
hey y'all
i want to learn discrete math. but, i'm currently in physics degree, so i don't get that topic. Can you suggest me books or courses that good to learn discrete math?
and sorry for my bad english
@balmy siren well a dictionary is a hash map. it lets you look something up (value) by checking the hash of the key (key) -> key:value pairs
could someone explain to me how confidentiality of a document can be achieved when a sender sends the document to a receiver using asymmetric cryptography?
what is unittest actually?
How to translate bytes to human readable text ?
import scapy.all as scapy
from scapy.layers import http
def sniff(interface):
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet)
def process_sniffed_packet(packet):
print(packet)
sniff("Realtek 8821CE Wireless LAN 802.11ac PCI-E NIC")
im getting packets like these
How can I sort this with xps?
"701465933041893427": {
"435394854017826817": {
"xps": 3140,
"level": 8,
"last_message": 1588350254
},
"660702877546840075": {
"xps": 1685,
"level": 7,
"last_message": 1589561109
},
"702722966039035965": {
"xps": 585,
"level": 4,
"last_message": 1587915578
},
"703469461927362613": {
"xps": 40,
"level": 0,
"last_message": 1587792479
},
"614120525761085450": {
"xps": 95,
"level": 1,
"last_message": 1587878540
},
"693401671836893235": {
"xps": 0,
"level": 0,
"last_message": 0
}
}
What's XPS? @uncut jetty
I made it
I don't understand what you want to do
He wants to get the Id or whatever that contains the largest xps
max(dict.values(), key=lamda value: value["xps"])
Something like that
Oh you want sorted not max
So replace max with sort
lol, NaN to go!
That was big
I would have had no idea what that meant had I not learned Numpy the other dya
'learned Numpy' I mean, I'm still clueless
but I can fill those NaN's
Thanks for listening!
Just saw this and it reminded me of that
Is anyone actually using the coding generator from OpenAI to code for us? Like is it out yet :laugh:
Ok, I might have a few of the details wrong on this so if anyone finds flaws then let me know. But for @pseudo cliff:
Asymmetric cryptography uses a pair of keys for both encrypting and decrypting messages: a public and private key. Messages encrypted with the public key can be decrypted with the private key, and messages encrypted with the private key (bad idea) can be decrypted with the public key.
Given two users Alice and Bob who are communicating with each other, Alice would have Bob's public key and vice versa. Alice would encrypt her message for Bob using Bob's public key, and when Bob receives the encrypted text he would be able to obtain the original message by decrypting with his private key.
With asymmetric cryptography, someone with the public key is able to encrypt a message, providing confidentiality, and then only the person in possession of the private key is able to decrypt it.
I m not sure if this question fits here.
But i would like to create a blog for my personal use so that i can keep track of all the new things and concpets I learn about.
Like a section for new general concepts of programming a section for all the math a learn through and so on
So what will be the best way to initiate this approach and what r ur views on it?
@elfin pecan I tried that many many years ago and I couldn't force myself to keep it updated. Nowadays I keep track of my projects using gitlab (you can use any git alternative you want of course). Imo it is way easier. Build an implementation of a concept that you have learned. Document it thoroughly because you will forget about it. Then you can use it as a perfect cook book.
@shell abyssOkay cool, that sounds like a better appraoch to my problem.Thank you for your advice.
@elfin pecan No problem, hope it helps 🙂
how would you guys go about training a nn to play tictactoe ?
should it learn from its mistakes or feed it tons of data ?
former one would be neater i think
Where is the correct place to put a class (readonly/final, private) string?
Where is the correct place to put a class (readonly/final, private) string?
@floral sundial
Python doesn't have those.
ok, lemme rephrase then: what is the best way to make a string, loosely tied to a class, that wont be duplicated multiple times in memory, and can't be modified during runtime
well no string can be modified at runtime, so you don't need to worry about that
make it a class attribute I guess
You could make it a property and have the setter raise an error
ah, thanks. ill take a look into that then
Fwiw, this isn't the right channel. #python-discussion would be better I think
is there a better/quicker way of creating a random 32-digit integer other than
random.randint(10**32, 10**33-1)``` ?
You are not allowed to use that command here. Please use the #bot-commands channel instead.
can someone help me understand what ASCII and UTF-8 mean while encoding. What is it used for and why do we need it. This topic is so confusing to me
@raven socket
x=random.randint(0, 10**33-1-10**32)+10**32
I think this runs fast
import timeit
one='''
import random
x=random.randint(0, 100000)
'''
print(timeit.timeit(one, number=10000))
two='''
import random
x=random.randint(10**32, 10**33-1)
'''
print(timeit.timeit(two, number=10000))
three='''
import random
x=random.randint(0, 10**33-1-10**32)+10**32
'''
print(timeit.timeit(three, number=1000))
timeit script
can someone help me understand what ASCII and UTF-8 mean while encoding. What is it used for and why do we need it.
@foggy mural
At some level, computers only deal with numbers. In order to deal with text, we assign numbers to letters, and it works fine as long as everyone agrees on which letter gets what number. One of the early encodings, ASCII, defined a mapping for 128 characters to the numbers 0 through 127. That covered every English digit and letter (upper and lowercase) and most common punctuation, and a bunch of other stuff. For a while that was enough, because programming languages were being used by English speakers, or people who could type text that looked like English by dropping some accent marks. Later, people from other countries wanted to be able to have computers render their text, so a bunch of incompatible encodings were developed - many were compatible with ASCII for the numbers 0 through 127, and used 128 through 255 for local characters. That worked OK, except Asian languages often have thousands of characters, so they need an entirely different approach. Unicode is that different approach - it's a mapping of every character used by any language on Earth to a unique number. UTF-8 is a mapping of those Unicode numbers representing characters to a particular binary representation.
And https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/ can explain that in more detail.
ok thanks so much
@foggy mural also http://reedbeta.com/blog/programmers-intro-to-unicode/
Pixels and polygons and shaders, oh my!
import numpy as np
import matplotlib.pyplot as plt
def euclidean_distance(query, data):
euclidean_distance = np.sum(np.power(data-query,2),axis=1)
return euclidean_distance
def fuzzy_cmeans(data, n_clusters=15, n_iterations=100):
n_instances, n_features = data.shape
#cluster intiliazation
clusters = np.zeros((n_clusters, n_features))
dist_inst_cluster = np.zeros((n_instances, n_clusters))
for i_instances in range(n_instances):
dist_inst_cluster[i_instances,:] = np.random.dirichlet(np.ones(n_clusters), size=1)
for i_clusters in range(n_clusters):
clusters[i_clusters,:] = np.average(data,weights=np.power(dist_inst_cluster[:,i_clusters],2),axis=0)
for i_iter in range(n_iterations):
for i_instances in range(n_instances):
##### code implementation ####
for i_clusters in range(n_clusters):
clusters[i_clusters,:] = np.average(data,weights=np.power(dist_inst_cluster[:,i_clusters],2),axis=0)
return clusters, dist_inst_cluster
```
i am so stuck any ideaaas
@dense meteor i think when calculating euclidean distance u got to sqrt at the end after you take the sum of the values squared
I've managed to unearth a laptop that used to have ransomware on it from years ago. Tried to boot it up and the lights are on, but it automatically opens the CD drive with nothing displaying on the screen. Does this mean the BIOS or OS have been wiped and I'll need to flash one onto it?
if it had ransomeware, it's probably safest to wipe it either way.
is the value returned by a perlin noise function where all inputs are integers always 0?
Shouldn't be
then my understanding of the algorithm is wrong
oh just the dotproduct there is zero
It's a laptop so it'll prove difficult to wipe.
Still I'll make sure to once I get a docking station.
!off-topic
Off-topic channels
There are three off-topic channels:
• #ot0-psvm’s-eternal-disapproval
• #ot1-perplexing-regexing
• #ot2-never-nester’s-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Is this not still related?
Discussion of general computer science, algorithms, data structures, and maths as they relate to solving problems with Python.
I don't see "identify hardware" there
Is looking at the Train vs Validation loss enough to paint a picture on how accurate your model will be or do you have to look at RMSE to conclude how good your model really are??
Probably a question better suited for #data-science-and-ml
Can you set the return from a function directly to a variable?
Sounds pretty normal
yeah I can't figure out how to do it, anyone know how?
foo = round(1.5)
do y'all know of any good free online courses for discrete math? I've been looking for a few days and can only find traditional courses for a fee, free courses with poor ratings, and free courses that look kind of like discrete math course but not completely
Maybe this will help u guys out
This video shows how to debug in VS code.
Mingw compiler download link: https://osdn.net/projects/mingw/downloads/68260/mingw-get-setup.exe/
Like, subscribe and share. Give suggestions in comment for next video :)
Hey Everyone,
If anyone needs to do a particular course on Coursera, then you can register here for getting the Premium License to access the curated course in the organization catalog.
You can register under the Non MIT-WPU section & can share it with anyone who's interested for the same.
link: https://thescriptgroup.in
This in an Initiative taken by The S.C.R.I.P.T Group to provide courses to other Institutions where this program has not been introduced.
Leading Tech-Driven club of MIT-WPU
@hidden merlin thank you!! very useful link
what is an "unordered list"?
In my experience, lists are ordered
do you mean the order isn't what you expected?
Or do you mean the result is a set, not a list?
I'm creating a list here
yes, so it's starting with like 3001 and then instead of 3002 it goes to 3005
so the order is not what you expected?
I'd guess it's because the various threads or subprocesses don't all finish in exactly the same order in which you started them.
some take a little longer than others, for more or less random reasons, having to do with whatever else your computer is doing at the moment
sorry im not super familiar is the pool command required it would seem to me that pool would cause the sudo randomness but i may not understand it well enough to say for certain
actually pool has a function where you can make the list unordered pool.imap_unordered()
@near cloud I think the fix is "don't worry, be happy" 🙂
lol
if you want, I guess you could sort the results by the order in which you started the process
I've never even heard of imap; maybe I'd better read about it now
actually this is a little confusing because sometimes using unordered function gives order list
and using ordered function gives unordered function
lol
also it's confusing because the docs for imap_unordered strongly imply that plain imap will indeed preserve the order
yes that's the confusing part
and some time, and it happen to me, if I use imap_unordered it will give order list
but if I only use imap() it won't
may i ask what you are trying to accomplish with this code, i assume its a small part of a much larger mechanism... if you simply need to list the items from least to greatest i believe there is a way to slice the list and rearrange i apologize though i cannot remember the method its been a while since i read that
hmm, mine seem ordered
really?
import multiprocessing
def double_and_add_one(x):
return x * 2 + 1
if __name__ == "__main__":
with multiprocessing.Pool(processes=4) as pool:
results = pool.imap(
double_and_add_one,
range(100),
chunksize=10
)
print(list(results))
# [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 101, 103, 105, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199]
i would definitely consider another technique most brute force attacks can be circumnavigated by finding an open back door rather than crashing in the front door... might be worth doing more recon. good luck with your project though 😄
no no, this is a ctf challenge actually
so he just want you do bruteforce the date, so you need to find the server date and try to bruteforce based on that
which you can find the server date with curl --head <url>
and based on that you can bruteforce the rest
does your ctf have a link?
I could just do it without pool
but I need to make things faster
@near cloud I think the fix is "don't worry, be happy" 🙂
@stark bridge for you information, doing it using unordered list actually solved the challenge for me, so you don't really need it ordered, but I'm just curious
I am too; when I tried it, imap returned things in order, even after I added a random sleep to the function.
and imap_unordered clearly showed the ordering was mixed up.
maybe the http request is doing something
or maybe my vm is doing something weird here
I'm actually printing it, and it still unordered, I'll try another vm and see
@stark bridge I can confirm requests lib is the reason here
weird
Can we talk about how operating systems work here?
Or is that considered off-topic in the channel?
🤷
Hello all
I hope it is not off-topic or not allowed but I made this youtube video today https://youtu.be/mc6rQSW3NRo
Topological Sort is a common pattern in coding interview questions. In this video I describe the algorithm for finding a valid topological sorting given a graph as well as the space and time complexity. I also write the code in python and explain it step by step.
p.s. I made...
ok so I am trying to get a minmax search algo to work I have generated all the game states in the proper DFS order in a list but im not sure how to now get the values from the list...
sorry im just so frustrated cause im almost there but i cant quite finish it
Im currently learning C, but next year I will learn python at school. So my question is: will it an advantage to already know a language or how a pointer works, or will it be a disadvantage because I will do some mistakes such as syntax mistakes
the main advantage will be knowing programming already. You will need to get used to not having to manage memory
i've tried python one time, and i was doing a lot of mistakes like typing printf instead of print, or adding ; at the end
roughly does python look like C?
if you squint really hard and ignore all of the parts that are entirely different
😆
python is a more complicated language than C, but easier to actually write code in, as a lot of things are already handled for you
thank you ❤️
@timber harness
bruh
Hello!
the channels with the green checkmark
Oh okay. Sorry I'm new here
is anyone familar with minmax search i could really use some help
somone knows something about artificial neural networks?
and if i give him my code, can he tell me what i do wrong?
Here is a video if u r interested in competitive programming:
https://youtu.be/dFb6-Uct3Tw
This video discusses about basics of vector and important functions of algorithm library which is super helpful in competitive programming. If you guys want more of this then give a thumbs up. For more helpful videos on Maths tricks and programming subscribe to my channel :)
...
Hopefully this doesn't mean spamming in here
Does anyone here use pygame?
hi, coming from C++ and used to using our STL, like vector, list, unordered maps, hashs, what is the equivalent of the STL in python
just the various stuff you can import that comes with python
of course python has nothing remotely resembling templates
C++ templates are a bizarre hack
@wintry merlin - Python's dict and C++'s std::unordered_map are both hash maps. Python's list and C++'s std::vector are both dynamic arrays. Python's collections.deque and C++'s std::deque are both doubly linked lists of dynamic arrays. I can't think of anything analogous to std::list or its singly linked variant - I don't think Python ships with a linked list individual elements.
and the builtin set type is analogous to std::unordered_set
Hi all, working on leetcode and having issues with loops when dealing with list[i + 1]. For ex: I want to check
i = 0
while i < len(nums):
if nums[i] == nums[i + 1]:
# Do something
and my issue is where IndexError: list index out of range. I understand why thats the problem, but how do i go about that everytime i do something with list[i + 1]
you either need to stop before the last element, or start after the first, @indigo tiger - so, either make your while i < len(nums) - 1 or start at i = 1 and check if nums[i - 1] == nums[i]
See #❓|how-to-get-help if you need more than that.
Thanks! @lean dome
here's a general computer science algorithm :)
if is_possible_to_occur(bad_thing):
bad_thing_will_occur = check_for(bad_thing)
if bad_thing_will_occur:
dont_do_bad_thing_and_show_an_error_instead()
that should apply to your i+1 case, along with many others
!e
You are not allowed to use that command here. Please use the #bot-commands channel instead.
This is my way to find two the greatest numbers in list.
def two_largest(A): ... max1, max2 = 0,0 ... for number in A: ... if number>max1: ... max2 = max1 ... max1 = number ... elif number>max2: ... max2=number ... return max1,max2
@proven sparrow you can also do:
A.sort(reverse=True)
max1, max2 = A[:2]
you can also use nlargest from the heapq module
@proven sparrow you can also do:
A.sort(reverse=True) max1, max2 = A[:2]
@latent wasp What about time complexity?
you can also use
nlargestfrom the heapq module
@stable pecan Isn't it O(nlogn) time complexity?
i don't know if it assumes a heap or not
or if it sorts or not
no, it just makes a single pass https://github.com/python/cpython/blob/3.8/Lib/heapq.py#L461
@stable pecan hm... it says Equivalent to: sorted(iterable, key=key, reverse=True)[:n] So it sorts beforehand. The best sorting algorithms are nlogn.
functionally equivalent to --- the implementation is more sophisticated
which i linked
ok
# X_OFF and stuff are set here
def transform(self, x, z):
camera = self.fsys.camera
# TODO: use Ortho Indoors
camPos = camera.lookat.camPos
target = camera.lookat.target
forward = vmath.unit(vmath.sub(target, camPos))
right = vmath.unit(vmath.cross(forward, camera.lookat.camUp))
up = vmath.unit(vmath.cross(right, forward))
p = vmath.sub(vmath.vec(x, target.y, z), camPos)
aspect = camera.persp.aspect
tanFov = camera.persp.fovysin / camera.persp.fovycos
IR3 = vmath.dot(forward, p)
IR1 = vmath.dot(right, p)
SX = X_OFF - (IR1/(-IR3 * aspect * tanFov)) * X_OFF
IR2 = vmath.dot(up, p)
SY = Y_OFF + (IR2 /(-IR3 * tanFov)) * Y_OFF
return (SX, SY)
```The method takes in-game coordinates and converts it to on-screen coordinates, and now I need to write the inverse of this function. Any ideas? (vmath is a small lib I use for vector math)
basically, figure out the x and z passed to this function based on the SX and SY. camPos, target, forward, right and up will have the same values for this, same with aspect and tanFov
but when it comes to such complex vector math my brain just stops working
Heyo
At re:Invent 2019, AWS shared the fastest training times on the cloud for two popular machine learning (ML) models: BERT (natural language processing) and Mask-RCNN (object detection). To train BERT in 1 hour, we efficiently scaled out to 2,048 NVIDIA V100 GPUs by improving th...
def invert_dict(d): inverse = dict() for key in d: val = d[key] if val not in inverse: inverse[val] = [key] else: inverse[val].append(key) return inverse
so, I am rather new to Python and coding as a whole, and I got stuck on this here function. Simply I want it to create a reverse dictionary of a dictionary argument that returns a list of values for each key. But I cannot for the life of me wrap my head around how to workaround the fact that the funcion needs to work with lists mid-execution. Anyone be so kind to give me a hand?
@half vine Won't be possible, as lists cannot be used as keys due to them not being hashable afaik
you could try using sets instead maybe?
is that it, that values can be lists?
I know that, but I have seen that some one managed to make this function turn this:
{“London city”:[“ChelseaFC”, “West HamFC”,”FulhamFC”]}
into this {“ChelseaFC”:[“London city”], “West HamFC”:[“London city”],”FulhamFC”:[“London city”]}
by modifying it
I'm trying to figure out what did they change
oh ok
the values will be lists guaranteed, got it
def invert_dict(d):
inverse = dict()
for key in d:
for val in d[key]:
if val not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
return inverse
that's doing something
anyone idea how I can see whether my computer fan are on or off ? I want to control the fan speed via python
anyone here? I need desperately help
i need help with f sharp, i can pay too
Wow
Rate my video. Its on std::map in c++:
This video discusses about map in C++ and important operations on it. If you guys want more of this kind of video do give thumbs up, it motivates to make more of this. For more helpful videos on programming and Maths tricks check out my channel.
Any suggestions ?
Any subjec...
Is learning graph theory worth it
I'm a high school student
It seems pretty long
on python is there a command to clear output? I'm using Jupyter notebook to code
Anyone know how to use the remind.reminder module? i know how it exists, but i can't find any info or the documentation for it.
@queen orchid depending on your os you can try os.system("cls") or os.system("clear")
that will clear the terminal output
Hey ya'll, I found this thread on StackOverflow about implementing data structures for collision detection, and one user talked about "loose grids". In their implementation, which is in C++, they're using indexes instead of object pointers. Is there a difference in speed and memory in keeping indexes instead of the object pointer itself? Especially in a dynamically typed language like Python?
Also here's the link for the thread: https://stackoverflow.com/a/48384354
Well C++ gives you control over if the object you have is a pointer or not
Python doesn't
So the question is, is storing a bunch of objects in one unified array faster than a bunch of objects with references
If we can see python's list object
assert(self->ob_item == NULL);
assert(size > 0);
PyObject **items = PyMem_New(PyObject*, size);
if (items == NULL) {
PyErr_NoMemory();
return -1;
}
self->ob_item = items;
self->allocated = size;
We can see that the list is actually a list of pointers for PyObject
So regardless of what we do in python, we'll ultimately just end up with a list of pointers instead of a list of objects
So theoretically, this would just be outright slower than having a bunch of addresses, because you now need to dereference the array pointer, index the array, and also dereference the object pointer
And most dynamic typed languages follow a similar design I believe
I can't think of an immediate example that doesn't at least
This implementation is also specific to CPython Interpreter
I see, so all the arrays in Python are just pointers
No the objects themselves are pointers
So you make an array
Or a python list object
Inside this object is a pointer to the internal array
This internal array will be declared of type PyObject ** as we can see above
It's a pointer to a pointer
So we have PythonList Object -> Internal Array -> some index -> PyObject pointer
So anything in python isn't stored in the array, we just store a bunch of pointers/references in the array for each of our PyObjects
I can't stress enough how much these speed differences don't matter in a language like Python though, they're cool little points to explore about how the language works, but generally you should not be thinking about this when writing code
Then there would be less instructions just storing the pointer/reference than indexes?
Yes the speed probably would be negligible, I just find it interesting to know how it works for Python
compared to another language
Then there would be less instructions just storing the pointer/reference than indexes?
I don't know what you mean by this
I don't know if this is the right section of the python server to ask questions but what are recommendation algorithms?
Yeah but I don't really understand xdd
If you google popular examples like how Netflix recommends movies, or how spotify recommends music it thinks you'll like (A seminar was run at my university on this and was very interesting)
Well it's hardly a simple topic
Ah ok ok thank you!
Oh sorry, I am talking about storing the index instead, rather than the object directly in a data structure (like a Quadtree) which points to an element in an array in Python
// Storing indexes
node = Node([0, 2, 5, 7])
// Storing references themseleves
node = Node(elements[0], elements[2], elements[5])
Yes but what I'm saying is due to how python works underneath your array is already a list of references
not the actual objects
So indexing the array = object lookup
reference from element = object lookup
It won't make a difference 🤷♂️
Infact indexing might even be slower, because that list of integers will need to perform the additional lookups on the int objects too
So these aren't the sort of optimizations we make in Python
Because we can't
The underlying implementation will always be dereferencing at least one pointer
Also even in langauges like C/C++ dereferencing a pointer shouldn't be that slow :b
pointer deref is often free in C/C++
Well, a consecutive array can still be faster because reading stuff in sequence is faster than randomly, and something something cache magic.
But that's impossible with Python objects, since they all occupy different amount of space.
You could store them consecutively, but then accessing an element by index would be O(n)
You can't store objects at all, not in any meaningful sense of the word. Each Python object is independently allocated, and storing an object in a list is actually storing a reference (i.e. pointer) to it. There's an indirection either way, that is.
is there a clean way to split a shorthand list comprehension over >1 line?
my_filter = request.params.get('status') # boiler just for this example
my_shard = get_shard(my_pool, shard_id) # boiler
my_commands = [command for command in my_shard['ommands'] if command['status'].lower() == my_filter.lower()] # can I linebreak?
I am looking to reduce line length <80
Thanks in advance
Well, list comprehensions naturally break in a few places
a = [
my_long_function(i+15 % 32)
for i in long_function_2()
if matches_long_3(i)
and matches_long_4(i, another_var)
]
But I'd advise that 80 chars is probably a narrow line limit and 100/120 is more practical, and I'm not sure that one should be broken up just for style concerns
okay thanks. your example made it much more clear what the structure of a list comprehension can look like.
I am new to Python so I am just following Google's stylesheet which recommends 80chars
Thanks for the guidance, your time is appreciated
👍
Anyone have an idea about an ideal way to store a trie into a database maybe I should use #databases ?
!rules 6 @fiery cosmos We do not allow advertisement here. If it were a tutorial on python, maybe, in #303934982764625920 .
6. No spamming or unapproved advertising, including requests for paid work. Open-source projects can be showcased in #show-your-projects.
Would anyone be able to help with a quick question about inputs?
for _ in range(int(input())):
N, K, P = [int(_i) for _i in input().split()]
S = []
for _i in range(N):
S.append([int(__i) for __i in input().split()])
# Test Cases
# 2
# 2 4 5
# 10 10 100 30
# 80 50 10 50
# 3 2 3
# 80 80
# 15 50
# 20 10```
So when I run the code with this test data it goes through the first iteration and then asks for another input before ending. I'm trying to make it so I don't have to to do the second input and it just takes the data I've put in.
Use a variable for the input, before the loop?
Do you mean the first input? python T = int(input()) for _ in range(T): Like this?
For instance, and the other one if it doesnt change?
Ahh sorry I'm really tired could u elaborate?
Does N, K, P change in every iteration of for _ in range(int(input())):?
Can I post a gif of it in here?
Probably
So after inputting the data the first instance of S prints and then I have to press enter before the next one comes up. Is there any way I can have them both print without having to hit enter in the middle? https://gyazo.com/2777085bdb8bf5399e93d409705e0328
Sorry if its not clear
What are you inputing there?
Its test data from this problem https://codingcompetitions.withgoogle.com/kickstart/round/000000000019ffc7/00000000001d40bb
You could either hardcode the test data, or have it query for the numbers before running the loops
Hey guys,
I'm reading graphs now and just want to know the difference between graphs in Discrete mathematics and the one in data structure
should i go for Discrete mathematics first before studying graphs in DS&Algo.
@balmy siren I feel like discrete mathematics is quintessential to learning data science and algorithms
It helps you shape the problem and the situation better
@latent wasp thanks for replying
yeah you're right about shape the problem and understanding the problem better mathematically. So, should i go for graphs in Discrete because it will help me in understanding the mechanics of graphs better and then i can implement it in python.
Hi guys, we at The SCRIPT Group have launched our podcast finally, we're calling it
"Pretty Epic"
Find the first episode on https://youtu.be/qRqhR0JQtcU
We're open to topic suggestions for our next episode, and it doesn't necessarily need to be tech!
Just send me your topic suggestion on 8452047071 and if it's epic enough, we'll take it up in the next episode.
Don't forget to like, share and subscribe❤️
#prettyepic #thescriptgroup #stayathome
Pretty Epic is a podcast where members of The SCRIPT Group, a tech-driven community talk about "epic" stuff happening around the world, and how they matter.
Have epic stuff to suggest for our future episodes?
Join our community on: ht...
Hey, can you give me an example for two algorithm with the first having better time complexity in the worst case, but worse complexity in the best or average case ?
quicksort vs merge sort is a common example
they have the same best and average cases 🤔
Another question, how can i calculate the probability of the best case, average case , and worst case?
depends on the algorithm
for example, for quicksort you have to calculate in which case the algorithm makes the least and most comparisons
I have an algorithm question. Basically, we are given an array called foodTimes.. foodTimes [i] tells us how many food i we have left. A customer try the food one by one. After eating one food, the customer will move to eating next food. And by next food, i mean next available food, a non-zero food. We are also given k, which tells how many times the customer can eat. The task is to find next food the customer will eat after he has eaten k times.Also if there are no food left, then return -1.
Example: foodTimes = [3, 1, 2], k= 4, then
Eat food 0, foodTimes = [2,1,2], k=3
Eat food 1, foodTimes = [2,0,2], k=2
Eat food 2, foodTimes = [2,0,1], k=1
Eat food 0, foodTimes = [1,0,1], k=0
After k times, the customer will eat food 2, since there is no food 1 left, we skip to food 2.
Here is my solution
def solution(food_times, k):
answer = 0
i = 0
numOfZeros = 0
while k > 0:
# reset number of zeros when at first i
if i == 0:
numOfZeros = 0
# if there ares still remaining food i
if food_times[i] > 0:
# reduce the number of that food
# and the seconds
food_times[i] = food_times[i] - 1
k = k - 1
else:
# otherwise, add number of zero food
numOfZeros = numOfZeros + 1
# if we are at the end of the list and there are no more food left
if i == len(food_times)-1 and numOfZeros == len(food_times):
return -1
# go to next food
i = i + 1
i = i % len(food_times)
# go to nearest non-zero food to the right
# if we reach the end, return back to beginning
while food_times[i] == 0:
i = i + 1
i = i % len(food_times)
# answer is the last i we are standing on
# return i
answer = i
return answer
print(solution([3, 1, 2], 4)) # 2
But I was told my solution is not efficient enough
Probably not going to have the easiest time getting help for not Python on a Python server
depends on the algorithm
can you recommend a good resource to read for that?
he can change function to def. and problem is solved xD
@bronze gazelle I mean, the language doesn't matter, I am looking for an improvement, or another algorithm
maybe using different data strucutre
def solution(food_times, k):
answer = 0
i = 0
numOfZeros = 0
while k > 0:
# reset number of zeros when at first i
if i == 0:
numOfZeros = 0
# if there ares still remaining food i
if food_times[i] > 0:
# reduce the number of that food
# and the seconds
food_times[i] = food_times[i] - 1
k = k - 1
else:
# otherwise, add number of zero food
numOfZeros = numOfZeros + 1
# if we are at the end of the list and there are no more food left
if i == len(food_times)-1 and numOfZeros == len(food_times):
return -1
# go to next food
i = i + 1
i = i % len(food_times)
# go to nearest non-zero food to the right
# if we reach the end, return back to beginning
while food_times[i] == 0:
i = i + 1
i = i % len(food_times)
# answer is the last i we are standing on
# return i
answer = i
return answer
print(solution([3, 1, 2], 4)) # 2
that is the same code but with hightlights
@steep wave thanks
I'm thinking of doing OSSU anyone done it?
Your locale is set to UTF-8, and that string contains non-UTF-8 data. To decode it you'll need to know what encoding was used to encode it, @past flare
i kind of need advice I just started Data Structures in python i don't know how to memorize the algorithms i don't know how to become better in that can anyone help me
just getting started with data structures
do you have a textbook? a lot of the the examples involve making small code tweaks, those are good to get started before moving on to harder problems
no can you recommend an one in web page
This big O cheat sheet is pretty handy
if you'll need to recall algorithms for a test, practice performing the algorithm manually with pen and paper
otherwise just learn the names of the algorithms and what they do and look the details up when you need it
like manual tracing?
ya
the MIT opencourseware lectures, the board notes are in pythonesque psuedocode
If you want something a bit longer, there's a course in the pins
if you want a textbook
like a PDF
CLRS is the Truth
that's nice thanks for that
@feral wadi you can also refer to this: https://runestone.academy/runestone/books/published/pythonds/index.html
An interactive version of Problem Solving with Algorithms and Data Structures using Python.
It'll equip you with basic and intermediate data structure and related algorithms
Can anyone say me how do i install pyplot?
Because when i run plotly.pyplot it gives an error
After i download it
do you need matplotlib
and import it into your project
im working on a ethical hacking project so i need someone to make me hulk ddos tool into a exer
@me
exe
does anyone know of a way to extract the icon from a file in python?
and save it to a file?
in windows 10?
!rule 5 @TROLLIE#6481 even if it is an "ethical" project, we don't allow those
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.
seems weird to use lists for this since the left, right, parent, and value are all "single" items
hi, I am working on segregating webpages based on the responses, I have to segregate them based on 10 HTTP responses, what would be better to use, switches or if-else statements? or there is more pythonic way of doing it
I am sorry, I will more precise. I have them in a dictionary. A json file which has the data as {'url':'', 'http_response':'404'}. Now i am trying to run some function, which checks them on the basis of what response code the have. so would using if dict[port] == '404': do this elif dict[port]=='200'...... or using a switch case instead of if-elif.
hi i need help with my code it says invalid syntax
python has no switch-case
what do i do
you use dictionaries for the same things
{
'404': some_function,
'200': other_function
}
that is python 2 code, if you are following a tutorial, use a python 3 tutorial
ahhh I see. I mistook this post for making me believe python has one. https://data-flair.training/blogs/python-switch-case/
please do not use b]
b], what?
hi i need help with my code it says invalid syntax
@dull owlprint(character + "text")I would suggest going this way,print(f'{character} walked down the street')
actually dont use either of these
just use if/else
oh i see you already have a dict of functions
im new so whats the f for
then use a dict of functions, yes
Thanks. @loud trail and @mint jewel
im new so whats the f for
@dull owl https://realpython.com/python-f-strings/ -> should be helpful.
thanks
seems weird to use lists for this since the left, right, parent, and value are all "single" items
@loud trail ikr? that's what confused me so much, it was a task for friend's uni. here is how solution looks like
what in the world
why would you do that
ok i guess it's like, the whole tree?
instead of individual nodes?
but the whole notion of left and right breaks down then
super simple question:
Given a Trie data structure, most people describe it as having a search up time of finding if a word is in the Trie or not as O(n) where n is the length of the word searched up, shouldn't it be O(n * m) where n is the length of the word and m is the number of unique characters possible for all the children of a node?
correct me if I'm wrong but I think it depends on how the trie is implemented
if you're storing child nodes in an array then yes, but if you're storing in an dictionary the lookup time for child node can be O(1)
another point to make is that O(mn) is still O(n) if m is a constant. I.E if we're talking about english words then m = 26 so O(26n) is still O(n)
Well even if it's an array, you would just use a 26-long one and lookup by character value giving constant time lookups.
can someone look at my java code and tell me why it won't run?
No, this is a Python server, sorry. There are plenty of other generic programming servers that can probably help.
You could try to ask off-topic though, but a specialized server would be better yeah
Hi guys, I need to sum up approx. 23 columns from a panda dataframe imported from a csv file
how do I go about doing it?
this would be appropriate in #data-science-and-ml
what do you mean sum.. do you mean total of all rows or total under each column?
hello! , i have to do a method so i can check if two nodes of a binary search tree are cousins, is there aynone who could help me ? since i dont know how to even start , thank you
Hey guys im implementing graphs in python
and i was wondering
is a graph still directed if for example we have [A -> B] and [B -> A] but also a bunch of one-directional connections?
such as [B -> C], [C -> D]
because for a graph to be undirected, its connection is always 2ways [A - B] etc
but i didnt know whether a graph is still directed if there is at least one double connection.
So, can we see a double connection as simply two directed connections to each other?
Cool, and to be clear, a graph is still directed, even if there is one or more occurences of a double connection between two different nodes?
Yes
ok thanks 🙂
ahhh I see. I mistook this post for making me believe python has one. https://data-flair.training/blogs/python-switch-case/
What I want to know is why they didn't mention using a dict?
Also I've never once wanted to use a switch case.
At least, I've never thought "Oh golly, I sure wish Python has switch cases; guess I'll emulate one with a dict!"
Hi I have a basic python question. How do I return from a nested function? Let’s say I have a function that calls another function. And Theres a condition in the inner function that I want to return from both functions. Is there a way to do that?
No, not directly
You can return a value which indicates to the outer function that it should also return
e.g. return None, and then the outer function will also return if it sees the inner function returned None
This is of course assuming that the outer function is calling the inner function
If you're passing it off elsewhere then it's not possible afaik
Well, maybe if you like set a variable in the outer function's scope, but that's really really confusing control flow.
Isnt it used in the military?
what
http://puu.sh/FSXVY/80bcbc9dcd.png
Hey Guys, I have a question regarding global variables.
As seen in the screenshot, I want to set the "url"-variable in the main function, and after that, call a Scrapy-Crawler from the same function.
However, even though I set the global url before, it says that its empty in the Crawler-Class.
//Edit: I found a workaround, would still be interesting to know, but its not urgent
How do I get that url there?
Hey guys, I have a JavaScript base question, how do I grab a an index link that will allow me to run a parallel index numbers from 1 instead of zero
Any pc simulator or a tool like that which can make me aware of all kinds of different hardware used in pc building?
What do you mean aware? If you want to monitor your hardware you can use HWMonitor. If you want to learn about pc-building and what hardware you need there are many videos on youtube that teach you this in a better way than reading about it on discord
Any pc simulator or a tool like that which can make me aware of all kinds of different hardware used in pc building?
@elfin pecan well i think you just got to really know the parts? if not just buy a built in pc. Youtube, google and everything is available online
So any specific youtube channels you guys would like to suggest?
Linus Tech Tips
I like Maru and Hana, but ... it's not particularly python-related 🙂
but it doesn't
>>> dates = {
'1':{'a':0,'b':0},
'2':{'a':0,'b':0},
'3':{'a':0,'b':0},
'4':{'a':0,'b':0},
'5':{'a':0,'b':0}
}
dates['5']['a'] += 1
... ... ... ... ... ... >>> >>>
>>> pp(dates)
{'1': {'a': 0, 'b': 0},
'2': {'a': 0, 'b': 0},
'3': {'a': 0, 'b': 0},
'4': {'a': 0, 'b': 0},
'5': {'a': 1, 'b': 0}}
>>>
your problem is that you don't have five separate dicts as your values; instead you're using the same one
>>> a_b = {'a': 0, 'b': 0}
>>> dates = {
'1':a_b,
'2':a_b,
'3':a_b,
'4':a_b,
'5':a_b
}
... ... ... ... ... ... >>> dates['5']['a'] += 1
>>> pp(dates)
{'1': {'a': 1, 'b': 0},
'2': {'a': 1, 'b': 0},
'3': {'a': 1, 'b': 0},
'4': {'a': 1, 'b': 0},
'5': {'a': 1, 'b': 0}}
>>>
@next aspen you want to access the preview icon of a folder?
@north zealot sorry im late, but what im trying to do is get the preview icon of the file/folder for a file explorer type thing.... but I have no clue on how I can do that
Is there a math module that does not require cpython?
My problem is that the current math module uses the GIL and isn't kind to threads.
For example
math.factorial(1000000) will freeze all threads
maybe you could do that computation in a subprocess
Or can I use multiprocessing?
I'm running it in an ThreadExecutorPool
I fucking hate the GIL
@exotic hatchalright! Thanks!
up in the available channels like #help-corn
edit:sorry im dumb and dont know the rules @fiery cosmos
@fickle seal #web-development
Hi everyone. I'm preparing for coding interview. Does anyone want to join me to solve puzzles at kattis.com|hackerrank together and discuss it?
that usually means "help me prepare for my interview for free and answer questions I have"
For me it means "to have an ability to discuss|explain solution"
that usually means "help me prepare for my interview for free and answer questions I have"
@hollow stump
I mean. You say that as though it's a bad thing, but helping others is kinda the point of this discord
hey guys, im in year 12 doing alevel computer science. i have a test tomorrow. ive never really revised properly so my question is how i should go about learning 6 sections for the test
what are those 6 sections you are trying to learn
programming techniques, software developement, exchanging data, networks and web topologies, data types and boolean algebra
each topic is pretty broad. do you have list of books, articles and so on you should use for preparation?
did you go listen to lectures and do the exercises?
That's usually enough to pass, if you really did the exercises yourself that is.
There's no magical shortcut to learning this in a day obviously.
I'd recommend you skim through the chapters, mark stuff you don't understand yet and try working on that while you still have time.
Going on discord is kinda detrimental to effective learning as well
Shutdown all social media stuff while you're learning
i havent done very well in test scores this year because im much more interested in programming so ive missed out a lot of the theory work in lessons
and the reason im here asking is because i revised for hours yesterday for my math test i did today on every topic that it covers but i did badly because all the questions were on the parts i least expected
so im not really sure which sections come up the most for the test
well that's the whole point
If you knew in advance you'd not learn everything
But they cannot put everything on the test
So, unless you're well prepared for all topics of your lecture, you can't be sure to pass easily.
this is just new to me because for my gcses i just half-ass revised in the morning on the way to school and passed everything with ease
If you keep up with the exercises during the semester and start preparing for exams ahead of time you'll get passing grades again
Yeah, that doesn't work in uni/college
usually
Don't worry though, many students make this mistake at first
unrelated question but do you think it would matter for me in the future if i wanted to work in software developement (front and backend web developement for example) if i wasnt good at the theory side of computer science
Yes it would
probably a dumb question but why do i need it
The theory is your toolbox
If you only have a hammer in your toolbox you're going to face problems
And learning the theory prepares you to dive into more theory where needed
i just dont really see where i would need these topics im learning because in all my programming projects they havent helped me at all
The main goal is that you learn to teach yourself new stuff
and in my class im one of the bottom in tests but im one of the best on the coding side
Well, without an understanding of runtime complexity you can't really produce efficient code
i guess the only thing ive found to be important in theory that i used in my projects is database normalisation
well, obviously you'll learn stuff you won't use
but it is helpful, to be able to wrap your head around the theory
that's the main ability you're training with this
So you can understand the theory that is necessary for what you're doing right now
i guess i jsut have trouble in computing with the way they teach the subject too
it's often pretty removed from practical application, yes.
even the software based questions i dont do too well in because most of my knwoledge is self taught
which really confuses me sometimes
thanks for explaining this btw
do you work in software development?
You're welcome
No, I'm a math student with computer science as a side subject.
I've done a lot of programming in my free time though
i do math too but its a lot harder than last year
same
i only really get computer science from working on projects so lesson work is tough
what kind of programmes do you work on out of curiosity
right now, actually none
in general
I was most active in game hacking
so, reverse engineering and writing software that exploits whatever I figured out about the game
thats cool ive never done anythign like that
took ages to get into
i mostly worked on simple python programmes like console games but recently ive been really into databases and web development
You have to learn assembler for your platform, you have to dive very deep into operating system stuff
yeah, I also did webstuff later, but the project I was part of never went anywhere, with me as the only backend dev and the frontend devs never submitting anything but the landing page
so the project never got to a point where it could've been released
the closest ive been to hacking is making a programme that uses google search to find peoples' repls with certain names such as 'key' and checks the code for any variables called key or whatever then seperates the variable with its value and stores it in my file, then used it to gain access to twitter accounts or discord accounts
it was an interesting experience though, learned a bit about issues that can crop up when you work with a team of people
ive never worked on a project with more than 2 people so that sounds interesting
and it taught me that people don't read manuals
is it common for programmers to get really into a project but never finish it through because you find something new or is that just me
if you don't have any incentive to finish the project anymore, of couse it will stall, so it's pretty normal.
But it can also be more general problem
If you leave work unfinished a lot in general
yeah its pretty general
Yeah, scheduling planning and sticking to your plans
all great abilities which school doesn't teach
like for example im around halfway through my programming project which we havea year to complete within the first 2 weeks but i got bored so i made a chatroom site
my inability to properly lay down plans is often troubling to me, but I'm working on it 😅
yeah im very bad at planning
especially with coding
i work best when i just get into my zone and code for hours straight no breaks
so its tough to try note down how i made the code for the written side of the project
A general strategy that applies to all problem solving is to subdivide a project into smaller taks that can be finished in one sitting
in a software project you usually start out with a rough draft
you write down what kind of data you have to handle, what your application does with it etc
i do that already but its subconsciously if that makes sense
in an abstract informal way
having something written on notes or a blackboard can help you sort through things
and it can give you a guiding structure to approaching the task
i do that when im working with complex databases
i usually write in a notes file how i want the database to be formatted first
another question if you dont mind, can i use projects ive made as part of a resume of some sort when applying for a job
You definitely can
But your repositories for that purpose should be in tip top shape
what do you mean by that
You should make sure your code meets certain criteria they may be looking for
right
and the projects you list should have some relevance to the job you're applying for
Hello, I am a complete beginner at everything related to programming, I was just wondering if it is possible to make something that clicks on a button on a website whenever I get a notification from discord? If so would it be good to use Python ?
im not even sure if my projects are good enough to use though. im never really happy with the result
I get what you mean, there's always something that bugs you about old projects
even in a larger scale, im just not happy with what im able to do or not do
well, nobody is born a perfect coder 😉
Just keep learning as you go and do your best.
That's really all that matters, the rest is kinda up to chance.
thanks
ill keep doing what im doing i guess
Good luck, I'll get back to my studies now 🙂
me too thanks again
it might be small but can anyone help me understand what the question is asking
the bottom question*
What is required in the HTML code above to make the selectors show styles on the website
i think they mean to ask "how do you get the css to apply to the html?"
i still dont understand what thats actually asking
like does it mean link the external css file??
i agree
write the lines where the css selector on the left applies
Hello guys, do you have datasets for network security or malware? It will be very helpful if you have it and are willing to share it with me
can someone write the code for this question
The current high score for a videogame is 101500. Prompt the user to enter a score. If the new score beats the high score, change the high score AND output a congratulatory message. However, if the new score does not beat the current high score, ask the user to try again.
please dm me the answer
Hi guys, is searching through a Binary Search Tree ALWAYS faster than searching through a list in Python?
It seems to be so
please help me out guys
Bro that sounds like homework @oblique tusk
@fair plover if the list is sorted, then binary search is same speed as binary tree search
and python’s builtin ‘in’ operator is written in c, so it is faster than even binary search
Not necessarily.
is there a channel to discuss security?
If the list is big enough, binary search is of course faster.
@amber loom Especially if the comparison operation is custom.
❤️
If you have a list of 1048576 elements, linear search will have to do 1048576 comparisons, and binary search would have to do about 20*2 = 40 comparisons, so it's obviously faster.
@austere sparrow yeah you're right, but c is in general 10^2 to 10^3 times faster than python for calculations, and also to do binary search, you have to sort, which is O(n log n)
Well, assuming the lists are sorted.
And assuming that the list contains numbers or strings, the 100 figure might be accurate.
But if the comparison operator is defined in Python, it doesn't matter how fast C is
Also, always is a strong word
wdym?
Big o and whatnot being asymptotic
That's why I said "for big enough inputs"
What I mean is like, the question could be a 'trick' question
Due to how binary search works, it doesn't degrade into a worst case complexity on any inputs.
Something to keep in mind if it's homework or smth
can anyone just help tho
@oblique tusk it's pretty simple do a variable named 'currentScore' that equals to 101500 and create another variable named 'userScore'
Then do a print() and take the input of the user and assign it to userScore
And if userScore > currentScore:
currentScore = userScore
else:
Print("retry")
Sorry for the late response
and python’s builtin ‘in’ operator is written in c, so it is faster than even binary search
@amber loom
in has to call __eq__ as many times as there are elements in the list, and if eq isn't defined in C for either type, then that's executing python code.
Except when __contains__ uses hashing
I think
As far as the runtime complexity goes, not for which language is implementing the operation
Anyway, even though an O(n) operation being performed in C is going to be fast even for especially large values of n, eventually a O(logn) operation in python will be faster.
honestly it depends on the context, for sorted lists binary search is always faster, but otherwise just use 'in'
o(n log n) for sort is almost always slower than o(n)
Well yes, nlogn is a slower runtime in general.
@oblique panther to be fair, python's builtin sort is timsort, which is heavily optimized for average case, and also is written in hand-optimized C
I'm not sure what we're debating at this point.
Personally I would never seek out or hand-implement a binary search for checking if a data structure that I didn't write contains a certain value.
Is there actually an in-place sort with a better worst case than O(nlogn)?
Depends on the method of computation
If youre using comparisons of two elements, no
see: radix sort
I havent read the conversation im not sure of the context dont know if this is useful
I think it was a conversation where we both wanted to state things that we know about runtime complexity, regardless of relevance. At least that's how I was approaching it.
Are there examples of the stdlib implementing features that use things like Trees, Searches, etc...?
Yeah, more things like heapq would be interesting.
I think 99% of my workflow is lists, generators, dicts. Usually when they get more complex than that, there's a library that does the "cs thinking" part for me lol
For example, I don't think I've ever used heapq in anything ever. **outside of leetcode
There's also bisect module for a binary search algorithm
Do you have any recommendations for intuiting the algorithms and knowing how to apply which strategy when? I think my CS fundamentals are weak
honestly i dont really find myself in a situation normally where a sophisticated data structure is that useful
aside from graph stuff
search algorithms are kinda just "remember some of them well enough that you think of them later" i think?
or at least how to find them again
My perspective is mostly for interviews. There's usually a data structure or algo question. You usually have to explain what it is, why you picked it, etc...
Also, usually they're efficiently coded in some 3rdparty library already. If I had to code it, it wouldn't be obvious to me (but I would like it to be). Some things are visually intuitive, but not code intuitive if that makes sense
If you need to worry about performance, it may be worth writing in a different language. Python is real slow for CPU-bound stuff
oh yeah interviews
uh in that case like idk, dynamic programming and binary trees i spose?
if you want to really brute force it just crank out 200 leetcode problems
and you're p much set
yeah, my background is not in CS, so I'm not familiar with the common approaches. Most of the stuff I just learned on my own because it was relevant to whatever I was doing. >> weak theoretical understanding
theoretically/optimally you wont be getting problems that are genuinely just "know a specific algorithm and reproduce it"
it does sometimes happen
Most leetcode easy is np. Medium and hard are hit or miss. My solutions also never look anything like the most efficient ones in the discussion 😛
honestly leetcode problems are pretty similar to generic interview questions in my experience
like of varying difficulties
the more interesting ones are cool, but it's hard to really prepare for those specifically
some companies are heavier on the theoretical background though
esp for new grads
with less internship experience
in which case you want like
your "Standard platter"
of like idk
I am probably at E4
tree traversal, stacks and queues, object oriented stuff, some kinda 2d/3d grid stuff, hashes, big o, sorts, recursive fuckery with strings, and DP ™️
I think my actual day-to-day is fine, but the theoretical components common in interviews are not 😛
is it worth going through a data structures / algo course? I honestly find them really boring
..facebook?
i dont really know most of the big tech company tier names too well tbh
the real problem with theoretical shit is that it's like 99% of the time never touched on but then that 1% of the time it balloons into a massive bug-ridden, occasionally nearly-intractable headache because you are unsuccessfully emulating some big brain guy that already came up with the algo
when it would have been really helpful to go "Wait a minute, i could just blah blah it"
99% they also show up in one or more of the interviews 🙂
ah well and also interviews
