#algos-and-data-structs
1 messages · Page 94 of 1
i'm creating a byte starting from 0, and building it with data
per BYTE
i need to set the next BIT after the first BYTE
so essentially
[bit, bit, bit, bit] [identifier] [bit, bit, bit, bit] [identifier] [bit, bit, bit, bit]
using struct.pack how would i do this?
essentially shifting each byte but assigning data in its spot
and what if the first set is 2bytes?
[bit, bit, bit, bit, bit, bit, bit, bit] [identifier] [bit, bit, bit, bit] [identifier] [bit, bit, bit, bit]
So I am doing a lot of graph theory research lately. I have seen all of these algorithms made for the identification of articulation points in these graphs. My question is, how can I find out not only articulation points, but how important a part is to a graph? Such as, giving score(s) for points that if removed, would cause major detours, ect.
Anyone know of anything they can point me to, or have any ideas? @ me when responding 🙂
Don’t have an answer but just did a project for data struct class and one of the methods was finding articulation points. Tough concept
maybe the degree of the articulation point can help?
if the degree is large then it is more important
What are some malicious file extensions to blacklist on my server?
exe scr js vbs bat sh
you could probably start with the ones that this server blocks
we block everything but what discord embeds and some things we use internally
i'm not sure exactly, you could try asking in #community-meta
Hi
Hello everyone
Guys where do you start in algos and dst?
like what algorithm should I learn to solve?
@autumn mason you could make a doubly linked list and explain the runtime complexity of each operation.
@oblique panther I hope it's not difficult Im just starting to learn them ))
doubly linked lists are a simple object-oriented implementation of a list.
and if you do it using dunder methods, you also get to learn more about those.
Hey, would you like links to some learning resources?
What is your end goal?
Well, I started to.learn python year ago and I want be confodent that I know I knoe it well
Unfortunately, I didn't do any algos and dst and do not know how to them
End goal I suppose is to develop that mindset(mentality) to solve complex problems on programming
Would love that
Khan Academy's algorithms course might be a good place to start: https://www.khanacademy.org/computing/computer-science/algorithms
Also check out the "where to go from here" section at the end for links to further resources.
It does use Javascript for some of the exercises. But the concepts are general and apply to any programming language.
If you'd like to solve the problems using Python instead and want feedback, just post your solution here.
can anyone reccomend me a good plagiarism checker algorithm for comaparing to two documents.
Thanks a lot
yes?
@pale fable Might be a good place to start looking https://towardsdatascience.com/the-best-document-similarity-algorithm-in-2020-a-beginners-guide-a01b9ef8cf05
If you want to know the best algorithm on document similarity task in 2020, you’ve come to the right place.
is there any site in which I can practice python algos for beginners(im a newbie in python)
I've been learning about linked lists, and I can see how insertion is very easy and simple, because you just input node in which to insert and data. But for to find the node after which you want to insert, you need to use things like linkedlist.root.next.next.next, or do while loops for to find the node with the value you want. So I dont understand how the insertion in linked lists is any better than in normal arrays
Cause you waste the time finding the node after which you insert
yes - finding things in a linked list is slower than finding them in an array. But inserting or removing elements is faster in a linked list than inserting or removing them in an array. An array is made up of contiguous memory, so if you've got an array containing people's names in alphabetical order:
students = ["Ashley", "Bret", "Carl", "Debbie", "Fred", "George", "Harold", "Iggy", "Javier"]
and then an "Eddie" joins the class, you need to figure out where to insert "Eddie" - index 4, after "Debbie" and before "Fred" - and then you need to make room for it. Even if the array already has capacity to hold 10 names (instead of the 9 it's currently holding), you need to move "Javier" from index 8 to 9, then move "Iggy" from 7 to 8, then move "Harold" from 6 to 7, then move "George" from 5 to 6, then move "Fred" from 4 to 5, then you can put "Eddie" in 4.
with a linked list, you don't have to move all of those later names - you just make "Debbie" say that "Eddie" is next, and make "Eddie" say that "Fred" is next, and you're done.
so, yes - iterating over the first part of the list to figure out where to stick the new name is much faster with an array than a linked list, but actually inserting it once you've found the spot is much faster with a linked list than an array.
is this the channel to ask about dirs and paths
nope it is to ask abt algos
alright
well i could not find it I am new here so...
oh ok
maybe u could ask the owner/admin or mod
I have a 2D array like [[Joe, Sim, Pal], [Lary, Joe, Sim], [Howard, Pal, Joe,], [Joe, Howard, Pal]]
I want to print that every list that contains JOE at position 0 i.e first position
Output : [Joe, Sim, Pal] , [Joe, Haward, Pal]
How can I iterate in a 2D array ?
you can write:
if arr[0] == 'Joe':
print(arr)```
or in a more Pythonic way:
print([arr for arr in arr2D if arr[0] == 'Joe'])
I tried this. But it gives int not iterable error
Then your input is probably wrong
Oh now I get it @lean dome Thank you very much!
I have shifted from C++ to Python. Suppose we are in a recursive function ( i.e dfs) and we are in a specific instance of that function. I need to store something so that I can use it later. I only need that info and the info can be found in that specific instance. C++ for example I would assign the info to a global variable. But how do I do that in python
hello buddys im new member.. anyone here can tell the rules for asking in this server
i want to find out recursively the i-th element of a list
def element_at(xs, i):
if i == 0:
return lista[0]
else:
return element_at(xs[1:], i - 1)
i m trying something like this but it shows the first element of the list everytime
what i do wrong?
what is lista
If you want to store a list, you can just append it to a list variable defined outside the function once the condition is met, without need of using the global keyword
Does it give better performance or is it good practice to delete nodes with del after removing the from a linked list?
it makes no difference because using del doesn't force garbage-collect the object.
And is there anything that would do that?
nope
Oh ok
It would actually be a huge change to the language to add that
because the interpreter assumes that objects exist until it decides to delete them
and if you let the user decide when to force delete something, tons of code would have to be re-written to account for the loss of that earlier assumption.
!e
thing = 'hello world'
del thing
print(thing)
@oblique panther :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | NameError: name 'thing' is not defined
@lean glade this is a NameError because del thing had the effect of making the name "thing" no longer point to anything. We don't know if any memory was actually deallocated.
am I boring you now?
But can the interpreter later decide to garbage collect the object?
yes, the interpreter will always garbage collect everything by the end of the program, even if that's the last step.
But that may amount to useless stuff just being stored in your memory
Causing problems
there's a procedure it uses to decide when it's safe to delete something
And is it like ultra-conservative when doing that procedure?
I don't know how you'd quantify how conservative it is. It uses reference counts
so as long as there's a reference left to an object, it won't get deleted. But once the reference count reaches zero, it will be deleted at some point.
there's also a funky algorithm that detects circular references
And if I del'd the only reference to that object, it will destroy it?
Or variable
Maybe there are more references
if you del the only reference to an object, the reference count for that object will reach zero, and then it will get garbage collected in the future.
I'm not sure how to quantify how far into the future that is.
I think it might be every time you exit a scope. Like when you return from a function, it might be that that's when everything for that function gets deleted. Or something like that.
the only thing you can really say is "on the next pass of the gc"
Sorry, I meant, does an independently created object, like a list, get destroyed when you del it? cause the variable name was the only reference to it, unless there's other reference somewhere else
the del keyword ultimately doesn't delete anything. it's a bit of a misnomer.
it doesn't get gc at the exact time you del, but there are no longer any references, so it will get gc in the future
you can manually run the gc
Really? how?
I doubt that's worth doing
that would be an interesting experiment
create a linked list with a million elements
and call the garbage collector after each deletion
Yeah
import gc
import time
from collections import deque
class catchtime:
def __enter__(self):
self.t = time.time()
def __exit__(self, type, value, traceback):
print(time.time() - self.t)
class GarbageDeque(deque):
def pop(self):
super().pop()
gc.collect()
def test(cls):
d = cls(range(1_000_000))
with catchtime():
while d:
d.pop()
test(deque)
test(GarbageDeque)
@lean glade @agile sundial first one ran very quickly
second one is still running
wild
so apparently, calling the garbage collector is expensive
hm, it has to check each object that it's tracking
Yeah, noticed when doing that with what I have
theoretically objects that it has checked before are pushed up a level, and are checked less frequently
There are kind-of two levels to the garbage collection: reference counting, and a more advanced GC that can deal with mutual reference.
An object should be garbage-collected when it becomes unreachable. No references is a sufficient but not necessary condition for unreachability.
Ok
km_cao is the number 3, and so it doesnt have the method fit_predict.
how can I duplicate elements from an array in a recursive way?
def duplicate(xs):
if len(xs) == 1:
xs.extend([xs[0]])
return xs
else:
return duplicate(xs[1:])
i tried something like this but i didn t solve anything
i tried to find a formula or smth but i didn t find anything
Duplicate like, from [3,4] to [3,4,3,4]?
solved it
You can for example use a non-recursive function that creates a list (or any other data structure) and passes it to the recursive function
For example, here we are searching for all positive values from a binary tree
if tree is None:
return
else:
if tree.val >= 0:
pos_vals.append(tree.val)
rec(tree.left)
rec(tree.right)
def get_pos_vals(tree):
pos_vals = []
rec(tree, pos_vals)
return pos_vals```
hey, I think that when mentioning that you found the solution, it's better to briefly explain what you did
I used concatenation
def duplicate(xs):
if len(xs) == 0:
return []
else:
return [xs[0], xs[0]] + duplicate(xs[1:])
how can I recursively delete an element from a list? I don t have any ideas on that since I can simply xs.remove() it. I was thinking about slicing the list or something, but it doesn t look like a great idea
Your solution works, but you have to know that it's kinda slow, because at each call, you're recreating the whole array, [xs[0], xs[0]] + duplicate(xs[1:]) costs O(n), so your solution runs on O(n²)
i know it s slow, but my teacher wanted recursion
A better solution would be to create another list, then you append each element twice
Yes you can do it recursively
if i == len(xs):
return
else:
dup.append(xs[i])
dup.append(xs[i])
rec(xs, dup, i+1)
def duplicate(xs):
dup = []
rec(xs, dup)
return dup```
are you allowed to use the method that deletes the element at a specific index?
I am allowed to do what I want, the condition is that the function is recursive
so here xs is empty
you can for example use recursion to search for the indexes where you can find your element and delete
What do you mean?
well you append in xs, so i suppose xs is an empty list?
I'm appending in dup not in xs
was talking about the first function
let me read my problem again
yes I'm appending in dup, it's written dup.append(xs[i])
so, he wants a recursive function that deletes the nth element from a list and it shows the deleted element and the list without the nth element
remove_at([1,2,3,4,5,6], 2) --> (3, [1, 2, 4, 5, 6])
so i know the index of the element that i wanna delete
and this is why I m confused, because i can simply return (xs[index], xs.remove(xs[index]))
shift all elements to the left starting from that index then pop to remove the extra element at the end
i was talking about a method for shifting
just xs[i-1] = x[i]
hmm, yeah, that'll do
tell us if you couldn't do it
save it somewhere before you start shifting
i have an index out of range error
try to find the reason
it s because the way i save that element
but i don t know why, it doesn t delete right
bring code
def remove_at(xs, ind):
if ind >= len(xs):
return xs
else:
xs[ind - 1] = xs[ind]
return remove_at(xs, ind + 1)
[1,2,3,4,5], 2 -> [1,3,4,5]
it should be
[1,2,4,5]
oh
it duplicates the last element also
oh, forgot to pop
wow i can t pop
out of range
def remove_at(xs, ind):
if ind == len(xs) - 1:
xs.pop(ind)
return xs
else:
xs[ind] = xs[ind + 1]
return remove_at(xs, ind + 1)
i still don t know why do i have an out of range error
oh, solved it
it s pop(ind)
you make pop on the index or on the value?
just call it without params, it will remove the last element
is it ok if i put 50 messeges here so i can voice chat?
is it useful to add an attribute to a linked list which holds the last node? or should I just go for a doubly linked list?
last like previous?
No, for appending
okay but by "last node" do you mean the previous node or the last node of the linked list?
The last node of the linked list, for appending
yes it's useful
Ok thx
To what specifically?
to take in consideration your tail attribute
def remove_at_secundar(xs, ind):
if ind == len(xs) - 1:
xs.pop(ind)
return xs
else:
xs[ind] = xs[ind + 1]
return remove_at(xs, ind + 1)
def remove_at(xs, ind):
valoare = xs[ind]
tuple = (valoare,)
if isinstance(xs, list) == True:
return tuple + (remove_at_secundar(xs, ind),)
print(remove_at([1,2,3,4], 2))```
i have these 2 functions, one that removes recursively the element on the index ind, and the one that should make a tuple with the element that I removed and the list without that element.
it should print (3, [1,2,4])
why is it (3, (4, [1, 2, 4]))?
Oh right sure
for example, when deleting a node by index or by value, you have to make sure that if the last node gets deleted, then it updates the tail
But now that I think about that, I would need to recalculate what is the last node each time I remove the last node
yes that's a problem, you don't have .prev reference
Yeah, hmm, I think i'll just move on to implementing a doubly linked list now. Anyway not making them for any real use
you're performing mutual recursion
remove_at_secundar is calling remove_at
yes
it should call itself
i cannot print the number that i delete in the remove_at
because it s recursion, it will never be that element*
the index is incrementing
and few things to know:
== True isn't necessary in a condition
here you're making sure that xs is a list, so you are not sure that your input is valid, in that case, you still have things to check (that ind is a number and that it's not out of list)
if ind == len(xs) - 1:
xs.pop(ind)
return xs
else:
xs[ind] = xs[ind + 1]
return remove_at_secundar(xs, ind + 1)
def remove_at(xs, ind):
valoare = xs[ind]
return (valoare, remove_at_secundar(xs, ind))```
https://www.codewars.com/kata/5a667236145c462103000091/train/python
so looking at the comments, there's most likely a dp solution, but i don't know what that is
it's not like you can get from 1 to 2 because some values aren't possible, so idk how to "jump over" those values
so any help? (ping 2 help thx)
i cannot find my mistake
look at your remove_at_secundar function, it's calling remove_at, not remove_at_secundar
ohhh
Is there a way to consistently match groups of words that works faster or better than levenshtein distance. I'm working with fuzzywuzzy.
I having difficult matching a company name to similar name in a group of company names.
result = process.extractOne(x, clean_comp_list)
I have a list of over 6k names that I am matching against. So each match takes at least 9 seconds to make
you mean Levenshtein distance right?
Lol ya
you implemented it by yourself or you're using a lib?
I found this
@wispy hare Ya I can't use the C+ library python-levenshtein
I'm using the code on an academic system where I can't use visual studios
If you know of a way to get this library without installing visual studios I'd like to know
you don't need visual studio, I think that you just need to pip install python-Levenshtein then you can use it
Nah I'm getting a error message saying that I must install it
building 'Levenshtein._levenshtein' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
----------------------------------------
Ya but I can't install it because I'm not using visual studio's IDE and I'm going to be running the code directly into a interpret
@wispy hare
oh, I don't know much about packages problems then, check the right server and ask this question there
What would be the right server?
Maybe python-general
Ok thanks
you're welcome
Given a long list of json objects and a key-value pair to search for, what is the most efficient way of searching for that key-value pair in the long list of json?
hi everyone, the round() function is being a piece of shit. i'm really angry lmfao
this is what i have written
for num in list:
print(round(num, 3))```
roundlist(liberalMindZScores)
the goal is to round every number in the list to three decimal places
when i run, i get this error
```---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-66-fcef4bcaa5f3> in <module>
3 print(round(num, 3))
4
----> 5 roundlist(liberalMindZScores)
<ipython-input-66-fcef4bcaa5f3> in roundlist(list)
1 def roundlist(list):
2 for num in list:
----> 3 print(round(num, 3))
4
5 roundlist(liberalMindZScores)
TypeError: round() takes 1 positional argument but 2 were given```
and the most fucking annoying thing is it was working like ten minutes ago
and nothing changed
Did you define a function named round?
Hello, I need help.
Im new to algorithms and my teacher told me to make a simple duplicate number algorithm.
She told me to use the "hare and tortoise" thingy.
Btw the language is python.
That's this algorithm: https://medium.com/@tuvo1106/the-tortoise-and-the-hare-floyds-algorithm-87badf5f7d41
Ok
I created this function for a tic-tac-toe game I'm working on but I'm wondering if there is a much simpler way to do all this? https://pastebin.com/TYS9RVg7
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
if square_array is [[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9,10,11,12], [13,14,15,16]]
you want to get [1, 6, 11, 16, 4, 7, 10, 13] right?
if yes then just def get_diag_rows(square_array): n = len(square_array) diagonal = [square_array[i][i] for i in range(n)] antidiagonal = [square_array[i][-i-1] for i in range(n)] return diagonal+antidiagonal
import numpy as np
def tester():
np.seed(100)
return np.random.random((4, 7))
```Im trying return numpy random array but seed the numpy random number generator with the see `100` , how do I do so ?
Wrote about implementing a list equivalent of Python's defaultdict https://blog.matthewbarber.io/2020/12/08/defaultlist/
Its np.random.seed(100)
#data-science-and-ml will be of help to you
is anyone doing advent of code here?
@unreal forum #782715290437943306
this shell works but in the wrong way
def shellSort(l):
interval = len(l)//2
while interval >= 1:
for i in range(len(l)-interval):
for j in reversed(range(0, i+1, interval)):
if l[j] > l[j + interval]:
l[j], l[j + interval] = l[j + interval], l[j]
else:
break
interval //= 2
return l
anyone well versed with java?
@vast whale you can join the Together Java discord to talk about that.
thanks
hashmap = {} here it is
HashMap<Integer, String> public static void hashmap = new stream(hashmap).collect(hashmap);
Anyone here have experience with Tesseract?
I implemented a Linked List and Doubly Linked List, and it would be great if somebody could give me feedback on stuff that could be changed or optimized. Many of the methods come from methods of a list.
LinkedList: https://hastebin.com/veronovike.rb
DoublyLinkedList: https://hastebin.com/yowitarozi.lua
Why can't Tesseract convert these images to a string with '0'? Tried changing dimensions, sharpness etc.
Oh I like that, I think it should be pinned somewhere
Idk if in this chat, but maybe elsewhere
Hi guys, I need help with this problem, I'm new to Python and I don't remember what the solution will be
xd
really? xD
We do not really appreciate using that word here, even if it is meant for yourself.
oh sorry
no worries, just wanted to let you know
Ahh that makes sense, thank you. I didn't realize that the index for the 1st diagonal was the same for each iteration like that. I am just learning list comprehension so this is sexyy af ```py
antidiagonal = [square_array[i][-i-1] for i in range(n)]
you're welcome!
Hi Someone please help with this targetSum problem,
I am given an array of numbers and a target, and i have to find out if any or number from numbers array can sum up to target (number from numbers array can be repeated)
I wrote this dp approach
def canSum(targetSum, numbers, memo={}):
if targetSum in memo:
return memo[targetSum]
if targetSum == 0:
return True
if targetSum < 0:
return False
for i in range(len(numbers)):
remainder = targetSum - numbers[i]
if canSum(remainder, numbers, memo):
memo[targetSum] = True
return True
memo[targetSum] = False
return False
print(canSum(7, [2, 3]))
print(canSum(7, [5, 3, 4, 7]))
print(canSum(7, [2, 4]))
print(canSum(8, [2, 3, 5]))
print(canSum(300, [7, 14]))
it prints
True
True
True
True
True
but for 3rd and last test cases it should return False, which it does if i run it separately, then why is it not working with multiple testcases?
!mutable
Mutable Default Arguments
Default arguments in python are evaluated once when the function is
defined, not each time the function is called. This means that if
you have a mutable default argument and mutate it, you will have
mutated that object for all future calls to the function as well.
For example, the following append_one function appends 1 to a list
and returns it. foo is set to an empty list by default.
>>> def append_one(foo=[]):
... foo.append(1)
... return foo
...
See what happens when we call it a few times:
>>> append_one()
[1]
>>> append_one()
[1, 1]
>>> append_one()
[1, 1, 1]
Each call appends an additional 1 to our list foo. It does not
receive a new empty list on each call, it is the same list everytime.
To avoid this problem, you have to create a new object every time the
function is called:
>>> def append_one(foo=None):
... if foo is None:
... foo = []
... foo.append(1)
... return foo
...
>>> append_one()
[1]
>>> append_one()
[1]
Note:
• This behavior can be used intentionally to maintain state between
calls of a function (eg. when writing a caching function).
• This behavior is not unique to mutable objects, all default
arguments are evaulated only once when the function is defined.
ugh, i hate how long that is
Oh, didn't know that kwargs will create a new object
@agile sundial thanks you so much!!!, it resolves my issue
hello everyone
l = len(seq)
for x in range(l - 1): # we subtract 1 from length because we
# can't make comparison on the last element of
# the list because there is no numbe after it
x += 1
for i in range(0, l - x - 1): can anyone explain to me this step?
i += 1
if seq[i] > seq[i + 1]:
seq[i], seq[i + 1] = seq[i + 1], seq[i]
return seq```
guys I need help understanding this
as you can see this is bubble sort
in the line for i in range(0,l-x-1) i want to know in details what it does
thanks in advance
did you try to visualize how bubble sort works on an array?
yes i did
the thing is
I know what first for loop does
and the one after it kind of confuses me
like what l-x subtracts?
the first iteration does n-1 comparisons right? (n is the length)
yes
the second iteration does n-2 comparisons only, because the last element is already in the right place
hmmmm
then the next one does n-3 comparisons only, because the last 2 elements are in the right place (they are already sorted)
nope no problem man
just tryna understand that)
Hello friends, I want to ask you, how can I improve this code of my first python app? (it's a calculator and the variables are in Spanish)
it's made with tkinter
class Solution:
binary = ""
output = 0
def converttodecimal(self,string):
decimal = 0
count = len(string)-1
for i in string:
decimal = decimal + (int(i) * (2**count))
count -= 1
return decimal
def getDecimalValue(self, head: ListNode) -> int:
if head.next == None:
self.binary = self.binary + str(head.val)
return self.converttodecimal(self.binary)
self.binary = self.binary + str(head.val)
head = head.next
self.getDecimalValue(head)
this keeps returning None
when it should return 5
i dont understand why this statement in the above code does not work:
return self.converttodecimal(self.binary)
heres the question:
can someone pls help me out?
thanks!
Nope, sorry, I'm just logging off.
You could try opening a help channel, if you don't get a response here.
Best not to directly ping helpers though.
hey guyz,
i m doing DS and algo, would anyone like to team up?
i am writing search algorithms in python for practice but how can i calculate the big o complexity of my code?
does that just run a bunch of tests and run regressions?
@vapid dirge use master's theorem or you can actually do it manually as well it just takes more time
how can i decrease the complexity of this
def func_30(n):
return_list = []
for i in [16, 8, 4, 2, 1]:
if n >= i:
n -= i
return_list.append(i)
return return_list```
you can't
oh
what is the complexity right now
what's n
the number of inputs
wait
so its o(1)?
since the output is always one?
public santa void main?
so the number of times is linear
no
yep
what's it supposed to do?
the code
its supposed to take a number
and give the numbers from the powers of 2 that give this when added up
for example
5 gives [4,1]
that's the best way then
Yay, thnx for the help
idk if this is the right channel or not but I'll put it here bc technically it's a linked list ig
so I'm writing a undo button for a thing I'm working on but for a thing
the code for the main thing is
if keys[pygame.K_LSHIFT] and keys[pygame.K_LCTRL] and keys[pygame.K_z]:
if state-1 > 0:
state -= 1
dots = states[state]
elif not keys[pygame.K_LSHIFT] and keys[pygame.K_LCTRL] and keys[pygame.K_z]:
if state+1 < len(states):
state += 1
dots = states[state]
also earlier in the code I do states.insert(0,dots) every time there's something that'd make it change
also did
for s in states:
if not s == dots:
print('true')
to test it and it never returned true
wait nvm 
I think ik what the problem is
nvm
I thought the problem was that I was doing states.insert(0,dots) so I did
states.insert(0,'replace')
states[0]=dots
so it would just be what dots was atm not always dots
A factory is running a production line that requires two operations to be performed on each job: first operation "A" then operation "B". Only a certain number of machines are capable of performing each operation.
Figure 1 shows the organization of the production line that works as follows. A type "A" machine takes a job from the input container, performs operation "A" and puts the job into the intermediate container. A type "B" machine takes a job from the intermediate container, performs operation "B" and puts the job into the output container. All machines can work in parallel and independently of each other, and the size of each container is unlimited. The machines have different performance characteristics, a given machine requires a given processing time for its operation.
Give the earliest time operation "A" can be completed for all N jobs provided that the jobs are available at time 0. Compute the minimal amount of time that is necessary to perform both operations (successively, of course) on all N jobs.
PROGRAM NAME: job
INPUT FORMAT
Line 1: Three space-separated integers:
N, the number of jobs (1<=N<=1000).
M1, the number of type "A" machines (1<=M1<=30)
M2, the number of type "B" machines (1<=M2<=30)
Line 2..etc: M1 integers that are the job processing times of each type "A" machine (1..20) followed by M2 integers, the job processing times of each type "B" machine (1..20).
SAMPLE INPUT (file job.in)
5 2 3
1 1 3 1 4
OUTPUT FORMAT
A single line containing two integers: the minimum time to perform all "A" tasks and the minimum time to perform all "B" tasks (which require "A" tasks, of course).
SAMPLE OUTPUT (file job.out)
3 5```
ok so
i can just greedily figure out
all the minimum finishing times for each task to go through the A production line
but a similar greedy method won't work for b
is there like
some other greedy method? (ping 2 reply thx)
also nvm about my question I just loaded/dumped it with pickle and it worked
expression = '48'
decimal = lambda expression: sum(list(x*(2**y) for y, x in enumerate(map(int, expression))))
def octal(base_value):
values = []
while True:
if int(int(base_value)/8) != 0:
values.append(0)
base_value = int(int(base_value/8))
else:
values.append(int(base_value))
break
return values
print(octal(decimal(expression)))
Anyone know why this gives [0, 2]?
because, when it first divides 48 by 8, the answer would not be 0, so it appends 0 to the values, and base_value should be 6 as 48/8 is 6.
Then it sets the base_value as 6, and the loop happens again,
6/8 == 0, so it should append 6 to base_value and break, but somehow it appends 2
anyone know what's wrong here
eh, that aint the problem here is it?
i did reassign it base_value = int(int(base_value/8))
how is it no tthe divided one?
what is decimal supposed to do?
what do you mean by "base value"?
the argument
decimal("48") is 20, and I can't figure out what that's supposed to mean.
!e
You are not allowed to use that command here. Please use the #bot-commands channel instead.
Any really good youtube channels pertaining strictly to algorithms and data structure type puzzles based on algorithms?
@foggy phoenix #discord-bots
Corey Shafer is pretty good. I also recommend computerphile. But these channels also make content other than algorithms and data-stuctures. I highly recommend them
hi guys got any tool can help to auto buy the things ??
like in lazada , amazon
kindly like can help to buy in the limited time
I don't think you can buy things through amazon through a python bot.Won't there be one-time-password sent to phone to verify.Even if you login there will a recaptcha that identifies if you're a bot or a human.It's gonna be difficult.I don't know any tool sorry.
This is for aoc's question 1 today. I figured this would be a better place to ask than in the channel, since it has more to do with python itself than aoc.
So, I have two programs for part 1, which was essentially The Game Of Life.
The 1st code is spaghetti code and has conditional checks for every type of cell I could be on in the matrix- corner, edge or other
The 2nd code, I instead used the dirs = [(-1,0), (1,0), ....] trick and eliminated redundant code.
I barely changed any other logic, infact I was trying to refactor and optimise it(For example maintaining a boolean to detect if there was a change in the matrix rather than doing an O(N^2) equality check).
But I don't understand why the first dirty code runs in 2.5 seconds on an average, while the second one with functions takes ~7 seconds
This is the dirty but fast code -
https://paste.pythondiscord.com/origemexes.go
This is the slow but refactored and optimised(???) code:
https://paste.pythondiscord.com/fagewoqene.properties
I initially thought maybe the function calls could be the bottleneck, so I removed the function calls and wrote it in a procedural manner, time reduced from ~7.2 sec to ~6.8
But that's still nowhere close to the less than 3 seconds that the dirty code gives.
So, could someone explain what's up with python?
probably some optimizations related to python calling C
hm, what do you mean?
hi can anyone help me with my coursework?
ill get you a discord nitro
pls dm me :))
!rule 6 @compact fog
6. No spamming or unapproved advertising, including requests for paid work. Open-source projects can be shared with others in #python-general and code reviews can be asked for in a help channel.
unapproved advertising, including requests for paid work.
Hi I'm trying to create an algorithm to find the row and index of the n'th letter in a series of rows such as this.
This is a simplified version of the problem.
There would be random data in each of these indexes, but the lettering from a-Z is their order.
Its constructed by removing every other letter in a-Z, and putting them into the next row. Then the next row you remove every other letter and put it in another row, and so on.
I've managed to get an algorithm to determine the exact row to check. I've also found a very close solution to getting the index in that row, but it's having a few mistakes.
This sequence is very close to getting the index correct, but any index a multiple of 8 returns around an index or two short in my test case: https://oeis.org/A003602
Do you guys think it's possible to have a straightforward function that returns the nth piece of data in this without iterating through it all?
also I found that the row order for n rows is this sequence: https://oeis.org/A033564
Since this is so close I feel as though it is possible
wait actually I tested on a large-scale case and it seems to work perfectly fine 🤔
:incoming_envelope: :ok_hand: applied mute to @fiery cosmos until 2020-12-11 19:50 (9 minutes and 58 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
:incoming_envelope: :ok_hand: applied mute to @novel cargo until 2020-12-11 21:30 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
hey guys, how do i determine the time complexity for specific sorting algorithm?
for instance, how do i determine the time complexity for Selection and Merge sort?
import string
lowerbet = string.ascii_lowercase + '_'
"".join([lowerbet[randint(0,len(lowerbet))] for n in range(randint(4,12)
) ])
why does that work? And...
words = ['test' for m in range(10)]
works
but:
["".join([lowerbet[randint(0,len(lowerbet))] for n in range(randint(4,12)
) ]) for m in range(size)]
yields IndexError: string index out of range
for me a different error is shown
Traceback (most recent call last):
File "D:\programming projects\python programs\trial.py", line 3, in <module>
lowerbet = ["".join([lowerbet[randint(0,len(lowerbet))] for n in range(randint(4,12))]) for m in range(size)]
NameError: name 'size' is not defined
it should only indexerror if randint(0, len(lowerbet)) == len(lowerbet), so you might want to change that to randint(0, len(lowerbet) - 1) or randrange(0, len(lowerbet))
or just change it completely to random.choice(lowerbet)
Idk if this belongs here bnut how woulod i set a np array with no deffiended shape
i'm trying to find the len() of an itertools.combinations(), but my kernel keeps getting "killed" because the number is just too big... (im guessing its ike 350,000 combinations or so). Anyone have suggestions how i can counter this?
^ already answered in another channel
any tips on analyzing how a recursive function works? like visualizing through diagram or table or any other way
you have to visualize the evolution of the call stack and the recursion tree
[Solved]
looks like it's not in the correct directory
Hello everybody I have a question concerning datastructurs in Python ! How do you know about data structure like XOR, List, etc... Thank you for reading me and respond to it 😉
do you mean shuffling an array, or sorting by guessing permutations
shuffling an array randomly and hoping we get the sorted list
then melio's explanation was right
that is if we make sure we don't repeat the last permutation right?
but if we don't check if the permutation has already been permuted
is it infinite then?
The complexity of walking through all permutations is O(n! * n):
(a, b, c, d):
(a, b, c, d)
(b, a, c, d)
(b, c, a, d)
(b, c, d, a)
...
because you look through each of them (and there are n! permutations), and see if it's sorted (which is O(n)).
Factorial of n, written as n!, is the product of all natural numbers from 1 to n, e.g. 5! = 1 * 2 * 3 * 4 * 5 = 120
The time complexity of randomly sorting an array is O(infinity) or something like that. Doesn't really make sense to talk about the complexity of that algorithm, since it's pretty silly 🙂
Yes.
yes, because if for example your array has 5 elements, then the first element of the permutation has 5 possibilities. The second element has only 4 possibilities, because we already used the 5th one for the first element. Then the third element has only 3 possibilities, because we used the two other ones in the first two elements
and it continues like that 5 * 4 * 3 * 2 * 1 (in a general way: n * (n-1) * (n-2)*...21), and this product represents n!
That's a slightly better drawing 😅
lol, thnx, that tree helped me understand it so much better
you're welcome!
try to write (or at least understand) the algorithm that generates all the permutations of a string/array
yeah im currently trying to do that
For https://www.reddit.com/r/learnmachinelearning/comments/fmx3kv/empirical_example_of_mcts_calculation_puct_formula/ , what python data structure should I use for monte-carlo tree search ?
Any recommendations ?
try to explore this website: https://www.programiz.com
Learn to code in Python, C/C++, Java, and other popular programming languages with our easy to follow tutorials, examples, online compiler and references.
some DSA lectures are available there
Is there a high performance tree library in python? I've tried anytree and treelib so far, and while treelib is a lot faster than anytree, constructing the tree still takes almost as long as parsing the data for it. For context: I'm trying to create a directory tree from a TLV-mapped VFS file with around 50k entries (directories and files). Is there a better way to do this? I probably don't need most features of these libraries for my purposes. Should I make my own tree implementation? Curious to hear your thoughts on this.
i think scipy or some other math lib allowed you to make a kd tree
Hello everyone! Can anyone help me with one dp task?
Doesn't seem like a good fit if I have some directories with hundreds of entries
Hey guys , just a general question , I am a beginner in web dev and i dont know any DS and Algo (except the basic ones) , so should i stop for a bit and learn those before continuing or should i learn them as i encounter need for them
Also , what language should it be in ?? I am ol with c,cpp,python , javascript
Thank u. Appreciate that
is this an example of post-order traversal?
def common_ancestor(root, p, q):
if root is None:
return None
if root == p and root == q:
return root
x = common_ancestor(root.left, p, q)
if x is not None and x != p and x != q: # found common ancestor
return x
y = common_ancestor(root.right, p, q)
if y is not None and y != p and y != q:
return y
if x is not None and y is not None:
return root # this is the common ancestor
elif root == p or root == q:
return root
else:
return y if x is None else x
Idk if that was said sarcastically or not
def sort(l):
for i in range(len(l)):
right_idx = len(l)
while True:
if right_idx == i:
break
for j in reversed(range(i+1, right_idx)):
if l[i] > l[j]:
l[i], l[j] = l[j], l[i]
break
right_idx -= 1
return l
does this sorting algorithm exist
Looks like selection sort to me. https://en.wikipedia.org/wiki/Selection_sort
why do i keep on making sorts that seem new but are just weird variations of already existing sorts XD
however this one is slightly faster than selection sort
how slight lol
Use range(right_idx-1,i,-1) instead of reversed(range(i+1,right_idx))
and while right_idx > i: instead of ```py
while True:
if right_idx == i:
break
And don't use the letter 'l' as a variable name, it's confusing
I don't agree with that as a general rule, but in this case left_idx would be a better name.
http://codeforces.com/contest/847/problem/B
any help? O(n^2) is too slow
the problem tag says binsearch but i have no idea how to implement that lol
If there's a way that this could be solved using a binary search, I'm not seeing it.
it can, however, be done in a single pass over the input data, instead of in multiple iterations. And that would probably let you make something fast enough.
something like:
results_lists = []
for e in input_numbers:
for result_list in result_lists:
if e > result_list[-1]:
result_list.append(e)
break
else:
# Smaller than the highest value in every list
result_lists.append([e])
i mean that'd still be n^2
ah, there is a place where you could use a binary search there, if that's not fast enough.
each of those sublists winds up being sorted in descending order by the highest value. You can binary search through result_lists to find the earliest one where the element is greater than the max of that list
Yo so can someone help me with this problem I have a for loop that runs a unknow amount of times and each time it calls a funtion with is going to return a list of ints and each time i need it to append a np array but in a new layer (so instead of it being 1111 it would be ```
1
1
1
1
maybe run another for loop that appends it to the array?
that is, let's say you've got 10 result lists. You can iterate over them one at a time to figure out which one to append to, but it would be more efficient to check last element of the 5th one. If your number is lower than that, it must be lower than the highest element of the 1st through 4th as well. If it's higher than that, it must be higher than the 6th through 10th as well. So you can narrow down your search space from there, and check the 3rd or the 7th.
wait
how do we know
that the results'll be sorted by last element
at any step in the iteration
results_lists = []
for e in input_numbers:
for result_list in result_lists:
if e > result_list[-1]:
result_list.append(e)
break
else:
# Smaller than the highest value in every list
result_lists.append([e])
Because at every step in the iteration, we append the new item to the earliest result list where it's greater than the current max element.
A natural consequence of that is that the first list will always contain the largest number encountered so far, and the second list will always contain the largest number that was excluded from the first list, and the third will always contain the largest number excluded from both the 1st and 2nd...
That was actually a fun little problem - binary search requires a sorted input, so at first I couldn't see how it could possibly apply here
it's neat that there's a way to apply it here, thanks to building up a sorted set of result lists 🙂
yeah
i was thinking
like that too
the cloest thing i could do
was sort it each time after
FWIW, if it's not immediately obvious, your worst case input will be 200,000 values that are sorted from most to least.
if your input is 5 4 3 2 1, then your output is 5 separate one-element lists.
so, if you're timing this yourself, test your performance of different versions against that input to see how they stack up against one another.
@lean dome thanks, the algo worked! wanna see my code?
sure
nice 🙂
Nah I meant the letter L as name for the list
And yeah ik im answering late
hey, anyone know why i & -i returns the greatest power of 2 less than i
and why doesn't it work for larger numbers
def happines(check_array,set_a,set_b,set_c):
happy = 0
for i,j in zip(set_b,set_a):
if i in check_array:
happy += 1
if j in check_array:
happy += 1
for k in set_c:
if k in check_array:
happy-=1
print(happy)
time complexity of this code?
what do you think
It's not certain, but I don't think so
Consider the worst case of if j in check_array
Judging by its name, check_array is likely a list. Therefore, in could do a linear search through the entire list.
And such search is being done for every item iterated
Furthermore, the loops iterate over different objects. Therefore, excluding the previous consideration, it's not just n but rather a sum of two variables representing their lengths.
Code:
fmt = '{:<4} {:>10}\n'
a+=fmt.format(row[0],row[1])
Output:
StrA 50
StrAStrBStrCStrD 12```
**How to get the output like this (equally aligned)?**
```yaml
StrA 50
StrAStrBStrCStrD 12```
hi
hello
increase key heap implementation code is here
please help with testing case for increase key
i have these two
does anyone have exercises divided by algorithm and data structure topic?
Idk where is the best place to ask this question but i thought this would be a good place. How do you determine whether an algorithm is P, NP, NP-complete or NP-hard. I've currently made a program that can only possibly be solved in exponential time, and can also only be verified in exponential time. Does this mean its NP-hard?
hackerrank.com used to be ok, don't know now.
https://codeforces.com/problemset/problem/1461/E
so uh
this basically boils down to quickly simulating py for _ in range(t): if k <= u - y: k += y k -= x if not l <= k <= r: print('NO') break else: print('YES')
any help?
an idea would be to use integer divison
to simulate until he can't add any more, than divide for the time until he has to add some water
so the level sort of fluctuates between 2 extremes
I think there's a purely mathematical answer here; I don't think you need the loop.
If the amount withdrawn each day matches the amount that can be deposited each day, then the only way to lose is if there's not enough room to make a deposit on the first day, and making a withdrawal drops below the lower bound.
If the amount withdrawn each day is one greater than the amount that can be deposited each day, then:
- if you cannot make a deposit on day 1 and the amount to withdraw puts you too low, you lose immediately
- if you cannot make a deposit on day 1 and the amount to withdraw is OK, you lose after
k-ldays - if you can make a deposit on day 1 you lose after
k-l+1days
I'm pretty sure this can be generalized to a formula that works for all possible inputs...
if it does need to be done iteratively, note that you can stop as soon as you hit any number you've already seen before. If it's possible to get from some number back to that same number, you can do that any number of times indefinitely.
So curious if a dictionary of sets would be the best. I have a giant csv and I want to pull out ports and hosts, which I can do. But now I want to store all hosts (keys) with the ports (values) and do it the fastest way possible, without any duplicates... Any suggestions?
multiple ports per host? a dictionary keyed by host with sets of ports as values sounds entirely reasonable.
Hello, i'm trying to add 2 lists to each other, however if any value in the list is a permutation of another, the value to which the permutation belongs, has to be added to another list, and the permutation has to be removed from the initial list.
EG. ['123','321','459','945'] should turn into ['123','459']
you could use a set of sets
so if i add ['123','321','459','945','552'] and ['525','667'] the result should be : ['123','459','552',667] where the other list should be ['123','459','552']
my problem comes in where i need to remove the permutation, currently my for loop loops through every permutation, if it finds it in the list removes it, but i need to keep the first one
need something like this?:
In [57]: split_duplicates(['123','321','459','945','552'])
Out[57]: (['123', '459', '552'], ['321', '945'])
oh, the duplicates should be the original items
yes, and im having a hard time, removing every permutation, but keeping the original item
In [60]: split_duplicates(['123','321','459','945','552'] + ['525','667'])
Out[60]: (['123', '459', '552', '667'], ['123', '459', '552'])
i think i got there
i did this by keeping track of "seen" permutations in a dictionary
using frozenset, though you could use other data structures
hmm, ive nevr really worked with sets, nevermind frozensets, so if you keep track of all the permutations you see, how do you make sure you dont remove all of them? since the permutations of "123" includes itself
well, frozensets are just sets that are hashable meaning you can use them as keys in a dict
i started here:
seen = {}
unique = []
duplicates = []
for item in my_list:
as_set = frozenset(item)
we check if it's in seen, if not then we append it to unique and add the permutation to the dictionary like so: seen[as_set] = item
if it is in seen then we just append seen[as_set] to duplicates
so would my_list be the lists you add, or a list of each items permutations?
my_list is what i passed to the function
oh i see, this last code part is inside the split_duplicates function?
yep
okay so i'm trying to wrap my head around it but i feel kind of stupid
seen = {}
unique = []
duplicates = []
list1 = ['123', '321', '459', '945', '552']
list2 = ['525', '667']
def split_duplicates(duplist):
for item in duplist:
list1permutations = [''.join(p) for p in permutations(item)]
for permutation in list1permutations:
as_set = frozenset(permutation)
if permutation not in seen:
unique.append(permutation)
seen[as_set] = permutation
else:
duplicates.append(seen[as_set])
split_duplicates(['123', '321', '459', '945', '552']+['525', '667'])
print(unique)
print(duplicates)
unique should be the 2 lists added, but with each items permutations removed? and then duplicates should be the permutations that we kept?
you don't need the loop on the outside
def split_duplicates(my_list):
seen = {}
unique = []
duplicates = []
for item in my_list:
as_set = frozenset(item)
if as_set in seen:
duplicates.append(seen[as_set])
else:
unique.append(item)
seen[as_set] = item
return unique, duplicates
oh from what i can see it works perfectly, thank you for your help! i just want to ask a few questions so i fully understand what we do. So as_set is basically a tuple of our list item? except it stays an item(i'm still looking for a proper explanation online on frozenset())?, if as_set is not in seen, we create a dictionary entry(dictionary because they cant have duplicates?) why do we add item to unique and not as_set?
a set only cares about the elements inside the set --- the order doesn't matter
In [61]: set("123") == set("321")
Out[61]: True
so we make a set or frozenset of the item, because we don't care about the order of the numbers
we use a frozenset so we can use it as a key to our dictionary, where we store the original item that made the set as a value
it's not like a tuple at all --- tuples care about the order of the elements
it's hashable
so we can use it as a key to a dictionary
normal sets are mutable and not hashable
OOH, so frozenset(X) will be equal to all values in the permutations of X?
basically
In [62]: set("123") == set("132") == set("213") == set("231") == set("312") == set("321")
Out[62]: True
if sets are so useful, why have i never seen them in any python tutorials, thank you again for your help
it's a data structure you usually don't use as a beginner
maybe
@hollow isle did you have some question that's related to the channel topic?
maybe you can try #discord-bots
how is it related to algorithms and data structures?
basically I'm getting a 400 Bad Request though all my dictionaries etc are right and need assistance
if you have a suggestion as to a better place to ask, go ahead and tell me
asked in #web-development and 2 other servers waited an hour got no response , thought it'd be slightly relevant to data struts cos i clearly messed up some dict values thats why asked here
maybe open a help channel, the code snippet seems to be missing a lot of relevant code
what do you think i'm missing? i can provide
and wdym open a help channel, how and where
oh ty LOL since Selenium is a module, all this while i been thinking there were modules called potassium fluorine etc LOL im so dumb thanks
Hi, I'm trying to implement a MinMax Algorithm (recursively) but I'm facing this annoying error related to recursion:
RecursionError: maximum recursion depth exceeded in comparison
This my code:
import math as m
list = [11 , 4 , 8 , 9 , 2 , 7 , 17]
list.sort()
def MinMax(A , low , high):
if (high - low) == 1:
if A[low] < A[high]:
return A[low] , A[high]
else:
return A[high] , A[low]
else:
mid = m.floor( ( low + high ) / 2 )
x1 , y1 = MinMax(A , low , mid )
x2 , y2 = MinMax(A , mid + 1 , high)
x = min( x1 , x2 )
y = max( y1 , y2 )
return x , y
print('sorting ...')
print(list)
mm = MinMax(list , 0 , len(list)-1)
print(mm)
anyone can help me with that ?
hey, am new to coding and i would really like to know how are algos are made in python. Would you guys have any documentation or good youtube videos where i could find answers ?
Could someone explain in some relatively layman's terms what a shunting-yard algorithm is?
It's an algorithm for resolving associativity and precedence in a mathematical expression
In other words, figuring out that a + b * c represents multiplying b by c and then adding a to the product, and not adding a to b and then multiplying the sum by c
Mhmm, I see. So it's basically a way to produce operator precedence?
Essentially but with reverse polish notation
Well, RPN is a potential output from it, but so is any other unambiguous parse tree
It's a way to figure out what operators should be called with what operands, given that the operators' associativities and precedences are inputs to the algorithm.
If it were parsing Python, for example, you would tell it that + is left associative (meaning that a+b+c is evaluated as (a+b)+c) and that ** is right associative (meaning that a**b**c is evaluated as a**(b**c), and that + has lower precedence than **, and it would then tell you that a+b+c**d**e is evaluated as (a+b)+(c**(d**e))
And RPN is a useful human readable way of representing that final result without any ambiguity.
Hi, may I know if anyone is familiar with SLAM algorithm?
yup! i havent done a lot of work with it, what do you want to know?
Is there a way to add code snippets to word document that it isnt a image but wont be counted as word count ?
Hello, i'm trying to get the value in a 2D List, by passing in the index of the item i want, as i understand 2dlist[0,0] returns the first value in the first list
that would work for numpy arrays
for lists it needs to be _2d_list[0][0]
(you can't start the name of a variable with a numeric character)
a numpy array/matrix is one object, no matter what shape it is. But if you have nested lists, you're actually doing two separate lookup operations.
on two separate objects.
think of it as (_2d_list[0])[0]. That's what the order of operations is
Is that more information than you wanted? 😄
yes that's perfect thank you
.
I need a hash set data structure that's ordered and supports O(1) indexing. Is there anything like that?
There's this https://github.com/niklasf/indexed.py
It's pretty close except it's a dictionary not a set. I could use it and just set a dummy value for every key.
A (unordered) set is implemented with a dictionary by the way
What you're searching for is probably an ordered set
which can be implemented with a self-balancing binary search tree
Usually this is implemented using something like a set plus a linked list, from what I've seen. If I understand what you need.
Like, OrderedDict is a dict plus a linked list, so you could build an OrderedSet the same way
I'm looking at an ordered set implementation right now
They seem to keep the index as the value in a dict
But that's a problem cause they have to do this https://github.com/LuminosoInsight/ordered-set/blob/master/ordered_set.py#L276
What's the overall goal? This seems like a strange data structure to need.
I have media files and each file has streams (audio, video, subtitles, etc). For each file I need to add all its streams to a ordered set and then remove some items that are excluded. After some items are removed I need to look up the index of certain streams.
Hm, why not just a dict mapping stream to index? You would read each stream from your media file, keeping a counter. Each read stream would be added as a key to the index, with the counter as the value. You'd remove the entries that are excluded (or never add them), and then you'd look up the index of your certain streams with regular dict lookups
Because when I remove items the indices need to be updated
And I don't want to loop through the entire data structure decrementing indices
So are you removing streams, and trying to write the kept ones back in the original order?
That being said, i think i can avoid this by getting the streams that should be excluded, then getting all streams, then adding them to a dict 1 at a time while ignoring those that were originally fetched for exclusion.
I originally didn't think I could get the excluded streams that's why i was over complicating this
In Python 3.7 or higher, dicts preserve insertion order. You can do what I said, adding every stream, them removing the ones that should be removed, then iterate over the dict with enumerate. For each stream encountered, the value is its old index, and the enumerate counter is its new index
I see what you mean. Just do one more iteration to correct the indices after things are removed
Does anybody have experience using the struct.unpack and pack modules?
Sure, what about them?
Would using the open() and read() functions be better in this case to use for parsing hex rather than the unpack()?
it seemed to work, so just wondering why even bother using unpack()
That approach only works for values between 0 and 255. It would print 0 instead of 256.
Which is to say, you don't need struct.unpack to read one byte out of a byte string, but you do need it to read a multiple byte long integer. (Well, not need it, but it makes the job easier)
It looks like status_byte and partition_type actually are only one byte, but sector_address is a 4 byte unsigned integer, which means that to correct your code you'd need to do ```py
sector_address = int.from_bytes(chunk[0x1BE + 8 : 0x1BE + 12], "little")
this makes a lot more sense, 'rb' could read only the smaller ints, but this one is larger so it needs a range specified
thanks for explaining that
"rb" gets you the ability to see the value of each byte, but when a value is composed of multiple bytes, interpreting it takes more work.
would this also work the same:
unpack('<i', chunk[0x1B8:0x1BC]
and just set that to sector_address
that would read an entirely different value - one is the 4 byte unsigned integer starting at 0x1BE, the other is the 4 byte unsigned integer starting at 0x1B8
so just use [0x1BE + 8 : 0x1BE + 12] isntead?
yes
and i should be I, I think
because, as far as I can tell, the number is unsigned, not signed.
Can someone help me with this linear regression algorithm im trying to write ? The step size isn't converging for some reason and I dont know why.....
class LinearModel(object):
def __init__(self, x, y, learning_rate=0.01):
self.learning_rate = learning_rate
self.X = x
self.Y = y
self.coeffs = np.zeros(x[0].size)
def gradient(self):
"""
Calculates the gradient
:return:gradient as a numpy array
"""
labels = self.Y
features = self.X
gradient = np.array([])
dw = 0
for f in range(len(features[0])):
for i in range(len(labels)):
dw += (labels[i][0] - np.dot(self.coeffs, features[i])) * features[i][f]
dw /= len(features)
gradient = np.concatenate((gradient, np.array([dw])), axis=0)
return gradient
def step_size(self):
"""
Calculates and returns the step size
:return: step_size
"""
step_size = self.learning_rate * self.gradient()
return step_size
def fit(self):
"""
Find values of the coefficients that minimize the loss function, LSE
:return: void
"""
for _ in range(12):
self.coeffs -= self.step_size()
print(self.step_size())
def predict(self, x):
"""
Predicts using linear regression algorithm
:param x: Features
:return: Predicted label
"""
return np.dot(self.coeffs, x)
What do you think of the use of Enum like such:
from enum import Enum
class Day(Enum):
Monday = 'mon'
Tuesday = 'tue'
Wednesday = 'wed'
Thursday = 'thu'
Friday = 'fri'
Saturday = 'sat'
Sunday = 'sun'
simply change
self.coeffs -= self.step_size()
to
self.coeffs += self.step_size()
Help
First of all, take selective screenshots with windows+shift+s
that seems like a test
You are asked to type the answer where it says "Type the answer here..."
sry I had to...
im currently learning python and im trying to make a basic "command prompt" but whenever the code runs and i type lets say start it stops the program how do i make not end the program once it is executed
basically the program keeps running after its executed
how do i do that
you can pause it for a certain amount of seconds:
#code
time.sleep(120) #stops for 2 minutes```
i dont want that i just need it to not stop
or you can wait for the user to press Enter
input('press Enter to continue')
i need them to input so it can execute
@spare pivot try an infinite loop
how do i do that?
Ex : while 1: your code
Go ahead
im not sure what to put in the while
oh so i should make a boolean variable or lets say i = 1 then while i == 1:
Or while command ! = 'exit' : cuz u want to exit the program after the exit command is given right
Then put the input inside the while loop
Thank you it works!! But isn’t the direction supposed to be the opposite to the gradient for steepest descent ?
@peak wave it checks all numbers from 2 upto x and sees if they are divisible. if x%i is not 0, then it returns false.
since 0 is treated as false
lol
lets say I wanted to create a program that reads different files and the file names were all identical except for they all had a number between 1-20 how would i do that
@cyan nova you can make a use of fstrings when describing the file name.
for example : suppose, if you've files -> test1.py, test2.py, test3.py....... then you can make the string like this
i = 1
while i <= 20:
try:
with open(f'test{i}.py', 'r') as file:
print(file.read())
except Exception as err:
print(err.args[0]) # or use args[1]
i += 1
possible exception could be FileNotFoundError()
i = 1
while i <= 20:
with open(f'test{i}.py', 'w') as file:
file.write('test'))
i += 1
``` Works with write at least @balmy siren
but what if file5.py doesn't exist ?
yeah you can perform any operation read, write or whatever.. but he asked for read, so i used that
also, write will overwrite the previous contents of file
test
test
test
test
2 # file 5
test
test
test
test
... etc
``` output when run with file5 deleted
2 is the result of print(err.args[0])
using mine code ?
yeah
I generated the files and then used your code to read them after deleting the 5th file
yes, you can make a simple print statement there..
all the files should need to be exist in the system already
otherwise it will give you an exception
Then it works right? the program finished fine after it hit the except statement
no no no, if any file doesn't exist then whatever is assigned under except statement will perform, once it is done then control goes to the next line or whatever is after try....except block i.e., i+=1
Dreams of those who do not learn software: 01010101 ehe heçkırım ehe
in reality:
import random
x = random.randint (1, 100)
print (x)
pc: you wrote a program from bravo python that writes between 1 and 100 numbers
anyone who is familiar with searchalgorithms, linear, binary, jump, interpolation, exponential? I need some help since I have to send an assignment in a couple of hours, if you can, pls call or pm me
What do you need?
its that ive made linear, binary, jump and interpolation search. Im trying to check time on all of them and see which one is faster by testing for hte same list, but it gives me 00.00.00 on some of them
sry let me send the list first
l = list(range(0,100000000))
so thats my range
you can fit that in memory?
wdym you got lucky
idk man
well
can you possibly hop on a call
much easier to explain
im shit at writing in english
i can't
ok :/
Are you want to compare execution times?
i have
just wanted to screenshare
cause i have to write a whole lot before i get my point out
therefor its easier on voice chat
I don't have mic 😞 drivers broke it
i can try to explain it here, but if you want to, we can voicechat 😄
well can i screenshare then and you can type 🙂
takes ages for me to explain , sry
DLower = datetime.strptime(DLower,'%Y-%m-%d')
Date = DLower
Print(Date)``` When I print the variable Date it also includes the time, how would I get rid of this??
@stable pecan really sorry to @ you, but i have a question regarding the algorithm you helped me with, the list contains bot 007 and 770, and 007 is being flagged as a duplicate due to 770 being in seen, i thought the sets look if all the values in the string match?
in that case you might want to use collections.Counter instead of set
though you'd have to create a hashable version --- which you could do by sorting the items
so using collections.Counter, somethign will only be flagged if a permutation of it has been seen?
yeah, i assumed all the items in the strings would be different
In [1]: from collections import Counter
In [2]: Counter("007") == Counter("070")
Out[2]: True
In [3]: Counter("007") == Counter("770")
Out[3]: False
so i can replace frozenset with Counter and it should be fine?
well, you have to do a little more work actually, because Counter isn't hashable
can you post the code as it was
yes sorry i should have mentioned, its explicitly to remove duplicate permutations, and mark them
def split_duplicates(my_list):
seen = {}
unique = []
duplicates = []
for item in my_list:
as_set = frozenset(item)
if as_set in seen:
duplicates.append(seen[as_set])
else:
unique.append(item)
seen[as_set] = item
return unique, duplicates
from collections import Counter
def split_duplicates(my_list):
seen = {}
unique = []
duplicates = []
for item in my_list:
as_multiset = tuple(sorted(Counter(item).items())) # Transform Counter into a tuple so it's hashable
if as_multiset in seen:
duplicates.append(seen[as_multiset])
else:
unique.append(item)
seen[as_multiset] = item
return unique, duplicates
I think this will take care of it
thank you so much for your help, this time we are? sorting the items, counting the and putting them into a tuple? would that flag 321 if 213 has been seen?
In [7]: split_duplicates(["213", "321"])
Out[7]: (['213'], ['213'])
splits it up, and even replaces it with the original permutation
what Counter does is count the occurences of each letter in the string
In [8]: Counter("123")
Out[8]: Counter({'1': 1, '2': 1, '3': 1})
so two Counters are equal if the counts are equal
In [9]: Counter("123") == Counter("321")
Out[9]: True
ohhh i see, how are you so quick to solve things i mush my brain over?
maybe practice
once again ,thank you a ton for helping, and if you could maybe recommend where i can practice this kind of problem-solving?
codewars maybe
but i would also bookmark the itertools and collections pages
if you get familiar with these two libraries, few problems will stand in your way
codewars isn't a paid subscruption correct?
alright, thank you i'll definitely check on the documentation and look at codewars
maybe look up some Raymond Hettinger talks if you like watching videos: https://www.youtube.com/watch?v=OSGv2VnC0go
Raymond Hettinger
Learn to take better advantage of Python's best features and improve existing code through a series of code transformations, "When you see this, do that instead."
that's a good way to get familiar with some python
ooh thank you, ill watch it too^^
that talk is a bit old (print statement doesn't work like that anymore!), but still has useful stuff in it
ah is it back in python2? but that's fine, fortunately I've mastered the print() function , thank you a ton
np
hey, I have a quick question. I'm trying to implement a rotate-lines-along-axis function for the project I'm working on. I made a function that takes a 3 x n input array of points, and returns the rotated points the same way
However, I'm starting off with the points belonging to my Line class (supposed to represent Fibres), which has a start and end point and ideally I need to rotate up to a 1000 or more lines at a time. I can more or less nicely list comprehend and reshape the points into the input array, but what would be a nice way to funnel the rotated points back into the class instances?
Hi guys, so i want to cast this string for example '2.56400' to float and when i print it iget this result 2.564 it's correct i know but instead i want this result 2.56400, how i can keep zeros, any ideas
you need to keep it as a string
floats don't have the concept of trailing zeroes
or you could use the Decimal class
or you could format it when you want to print it
!e print(f'{1.23:.4f}')
@brave oak :white_check_mark: Your eval job has completed with return code 0.
1.2300
@brave oak i ve tried that but i want to return float type not string type, thnx anyway
Hello, i have an open help channel (help-lithium) in case someone here has some time to spare
ops wrong channel
@deep phoenix did you mean stuff things like !@#$%^&*,.'? ?
yup
well if word[0] isnt a letter, maybe add word[0] instead of its translation
@pallid phoenix
def pig(word):
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #no space
VOWELS = "AEIOU"
INTERPUNCTION = ",.!?:"
i = len(word)
if word[0] in VOWELS and word[i] in INTERPUNCTION: # Easy case. "IS" becomes "ISYAY" INTERPUNCTIE
return word[0:i-1] +'ay' + word[i]
elif word[1] in VOWELS and word[1:i] in INTERPUNCTION: # Consonant followed by vowel. "BIN" becomes "INBAY" INTERPUNCTIE
return word[1:i-1] + word[0] + "ay" + word[i]
elif word[0:i] in INTERPUNCTION:
return word[2:i-1] + word[0:2] + "ay" + word[i] #"STOP" becomes "OPSTAY" INTERPUNCTIE
elif word[0] in VOWELS: # Easy case. "IS" becomes "ISYAY"
return word +'ay'
elif word[1] in VOWELS: # Consonant followed by vowel. "BIN" becomes "INBAY"
return word[1:i] + word[0] + "AY"
else:
return word[2:i] + word[0:2] + "ay" #"STOP" becomes "OPSTAY"
this doesn't work
the first 3 if statements don't get used at all eventhough it should
what word did you test it with?
and it should be?
INBAY.
you could just take all the punctuation out of the string and add them back later
"just"
well, yeah
why not create a new word instead of editing the old one? so do neword.append(word+ay) neword.append(word[i]) note, only testing the last index of the word wont account for something like I'm
well its quite simple in my opinion, if the ltter meets condition-translate it and add it, if its a special character, add it without translation?
correct seems to be larger than the index range
I don't understand
when you look for the index of word, you use word[correct], and correct is either too small or too big, and index equaling correct does not exist(sorry i'm bad at explaining)
So I have a dictionary that has multiple different keys named the same thing. I have the value of one of them and I need to get when that variable occurs so that I can grab other repeated variables that occur around it.
Like there is a owner and I have the owners name but there are multiple different owners stored in the same dictionary.
and then where the owner I need is stated, there are also other bits of information like name for example, which there is also multiple of.
so then say I wanted to get the name for a specific owner, how would I do that?
how do send code like this
where others can copy and paste
in discord
a dictionary can't have multiple keys with the same name
So i am making this thing where theres 2 tiles and a player the path tile (🟫) and the off-map tile (⬛) and the player (🤠) so basically i want to randomly generate a path for the player.
Which is better?
- Locating the last path tile and finding the possible options for a new path tile to be placed.
- Randomly generating the whole path.
:incoming_envelope: :ok_hand: applied mute to @calm spade until 2020-12-20 08:59 (9 minutes and 58 seconds) (reason: discord_emojis rule: sent 72 emojis in 10s).
!unmute 470866478720090114
:incoming_envelope: :ok_hand: pardoned infraction mute for @calm spade.
Sry i didnt know
An image would be better, i guess 🙂
I'll just repost so that you don't have to spell it out again
Thanks sm
[[0,2,0,0,0,0,0,0,0,0,0,0],[0,1,0,0,0,0,0,0,0,0,0,0],[0,1,1,0,0,0,0,0,0,1,1,0,0],[0,0,1,1,1,1,0,0,0,1,0,0],[0,1,1,0,0,1,1,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,0,0]]
What do you consider the last path tile here?
Right, but the layout ends in two spots in your example
So i ment like i place tile by tile
So player then the tile under it then from there u'd have 3 possibile options
The next tile
The previous tile
And the under tile
In my example its the under one
Down*
Next as in right?
repeat
Like that
And repeat until the amount of tiles i choose has been placed
It works on my head but idk how to implement it 😂
So you want to just randomly make decisions until you visited enough unique tiles?
Exactly
You need to set some rules, like don't immediately go towards the wall, don't go right 3 times etc
Well after i figure out how to actually place a tile then those can be done
Use random to choose a random shift, left right or forward. The shift can re represented by a tuple containing a value that each index should be shifted by.
You are using a nested lsit to represent the board?
Right, I think I understand what you mean now. I would start with the first option
Okay but... How do i make it ? 😂
By last I guess you mean the latest tile you visited
nested lsit?
is there like a number of tiles to visit or something?
[[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']]
Won't it be easier by integers?
so the player starts at a certain cell (i, j) then randomly traverses a path of k tiles right?
Yup the player is always the second object at the first row
Then i'd have three options (left, right, down)
And so on until i placed the number of tiles i need
I mean if like the path tile is 1 and player is 2 and the other tiles are 0
That'd be easier to work with right?
Oh yeah use whatever value you want in the list
Oh ok i thought you wanted me to make them into strings
path = 1
[['0', '0', '0'],
['0', '0', '0'],
['0', '0', '0']]
``` ```py
board[0][0] = path
``` ```py
[['1', '0', '0'],
['0', '0', '0'],
['0', '0', '0']]
aha i was doing it like
[[0,0,0],
[0,0,0],
[0,0,0]]
It makes it easier to read :p
Ye kinda
so how how about...
I know how to add / remove and loop over the nested list and stuff
But what i dont know is
How do i track the last path
And check the posibile decisions
And add the next tile
And repeat that
tile = 1
start = (0, 0)
up = (-1, 0)
down = (1, 0)
left = (0, -1)
right = (0, 1)
r, c = start
board[r][c] = tile
``` then you can manipulate the r and c
That is part of it maybe
But i'd have to create the entire layput with this
But the decision making is gonna be a challenge
You can use the random module to randomly shift the position around
Yeah i know
check if the box has a tile path
I think a simple solution would be to just try random spaces like that
You could also check to see if placing a tile would cause that tile to touch another, which you could then avoid by choising a differnt tile
lmao how?
when you visualize the final state of the gird, the path isn't clear
hahaha
layout = [[0,2,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]]
for row in range(0,len(layout)):
for col in range(0,len(layout[row])):
if row == 0: pass
``` this is as far as i can go
...
you need to make sure the next move doesn't touch a path tile
I did it