I have just started using PriorityQueue module in python from Queue module but i am having a hard time to check if an element exists in the PriorityQueue or not. Below is my Code snippet.
from queue import PriorityQueue
q = PriorityQueue()
q.put(3)
q.put(2)
q.put(1)
ok = 4
if ok in q:
print("Found")
but i am getting the below error.
TypeError: argument of type 'PriorityQueue' is not iterable
Please tell me how to iterate and check if an element is present in PriorityQueue module in python.
Doubt 2 :-
In the above code snippet, PriorityQueue is MIN_HEAP by default, what syntax i should use i want a MAX_HEAP?
Priority queue is not iterable, so you have to pop out all the elements and then push them back to see if an element is inside. Another option is to use an array to keep track of the elements in the priority queue.
# Assume all the elements are in a range of 0 ~ 999
from queue import PriorityQueue
cnt = [0] * 1000
q = PriorityQueue()
q.put(3)
cnt[3] += 1
q.put(2)
cnt[2] += 1
q.put(1)
cnt[1] += 1
ok = 4
if cnt[ok]:
print("Found")
For Doubt 2, the simplest way to get max heap is to insert the negative of the element.
max_heap = PriorityQueue()
max_heap.put(-10) // 10
max_heap.put(-20) // 20
max_heap.put(-15) // 15
max_heap.put(-27) // 27
while not max_heap.empty():
print(-1*max_heap.get())
Related
def largestlowest(matrix):
largeset = 0
lowest = 0
for row in range(len(matrix)):
for col in range(len(matrix[row]-1)):
if matrix[col] > matrix[col+1]:
largest = matrix[col]
if matrix[col] < matrix[col+1]:
lowest = matrix[col]
else:
print("there is no min/max value")
return largest and lowest
print(largestlowest([[4,8,2,9,34,57,22,44], [1,2,8,9,1,2,55,3,22,4]]))
Don't forget to mention the language. I assume this is python. Also try to run and test the code before posting it. This code is not running at all.
This is the running version of the code you submitted in python:
def largestlowest(matrix):
largeset = 0
lowest = 0
for row in range(len(matrix)):
for col in range(len(matrix[row])-1):
if (matrix[row][col] > matrix[row][col+1]):
largest = matrix[row][col]
if (matrix[row][col] < matrix[row][col+1]):
lowest = matrix[row][col]
return (largest, lowest)
print(largestlowest([[4,8,2,9,34,57,22,44], [1,2,8,9,1,2,55,3,22,4]]))
Note that to access an element of a list you should call it by both row and column : matrix[row][col].
There are a few things wrong:
You go up to (len(matrix[row])-1) and therefore do not include the
last column.
Then you compare neighboring elements matrix[row][col] > matrix[row][col+1] instead of comparing all of them with the lowest and the largest.
You assign the lowest to 0, which will always be lower than all of your elements
return a and b will return a only
I recommend you search each step (e.g how to call a matrix element in python). You will find plenty of information online. Try to run the code as quickly as possible and solve the errors in the console.
Finally, the code that does what you want (I think):
def largestlowest(matrix):
if (not len(matrix)):
return ("Matrix should have at least one element!")
## assign largest and lowest to first element of martix
largest = lowest = matrix[0][0]
for row in range(len(matrix)):
for col in range(len(matrix[row])):
if (matrix[row][col] > largest):
largest = matrix[row][col]
if (matrix[row][col] < lowest):
lowest = matrix[row][col]
# return (largest, lowest)
return "Largest element of matrix: %d, lowest element of matrix: %d" % (largest, lowest)
print(largestlowest([[4,8,2,9,34,57,22,44], [1,2,8,9,1,2,55,3,22,4]]))
print(largestlowest([]))
Your code was actually comparing the wrong values:
if matrix[col] > matrix[col+1]: isn't comparing the current value to the largest, it is comparing it to the one after it. The same thing was happening for the small.
Also, you were handling your data incorrectly. matrix[col] is an array itself, not an individual element (at least, according to the example you gave).
The code below is commented and works. It outputs:
LARGEST: 57
LOWEST: 1
# Function
def largestlowest(matrix):
# Declaring biggest and smallest variable. Setting extraneous at first
largest = -10000
lowest = 10000
# Loop through every array in the matrix as you have defined it
for arr in matrix:
# Loop through each item in the array
for item in arr:
# If it is bigger than the largest, set the largest to be that value
if item > largest:
largest = item
# If it is smaller than the smallest, set the smallest to be that value
if item < lowest:
lowest = item
# Return the largest and lowest
return largest, lowest
# Example main function
def main():
# Define a test matrix (copied from your example)
matrix = [[4,8,2,9,34,57,22,44], [1,2,8,9,1,2,55,3,22,4]]
# Run the function we created
largest, lowest = largestlowest(matrix)
# Print out the results
print("LARGEST: ", largest)
print("LOWEST: ", lowest)
# Call the main function
main()
Let us take an first Queue which contain elements 1,2,3,4 in order so the first Queue becomes 1,2,3,4 front is 1 and rear is 4. We have one more empty Queue contains zero elements. How can we reverse this first Queue using another Queue which is empty ? (We cannot use third Queue for reversing).
I have tried to reverse a Queue using one more Queue but no solution comes in my brain.
So I expect the Queue to be reversed so that first Queue elements become 4,3,2,1 after reversing.
from tqdm import tqdm
def rotate(q, k):
move(q, q, k)
def move(q1, q2, k):
for i in range(k):
q2.append(q1.pop(0))
def reverse(q1):
q2 = []
for i in range(1, len(q1)):
move(q1, q2, len(q1) - i)
rotate(q2, len(q2) - 1)
move(q2, q1, len(q2))
rotate(q1, i + 1)
return q1
if __name__ == '__main__':
for i in tqdm(range(1000)):
rq = reverse(range(i))
assert rq == range(i)[::-1]
I need to evaluate prefix using a queue (not stack). for example:
+ 3 * 2 1
is equivalent to 3+(2*1) = 5.
I am thinking about to loop through the queue over and over using dequeue and enqueue. If the pattern "operator" + "number" + "number" if found, dequeue 3 times and enqueue the result until there is only a number left in the queue.
while size(q)>1
if elements are in this pattern: an operator is followed by 2 numbers.
operator <--dequeue(q);
number1 <--dequeue(q);
number2 <--dequeue(q);
int a = apply(operator, number1, number2 );
enqueue (q, a);
else if the element is a number or operator:
element <-- dequeue(q);
enqueue (q, element);
return dequeue(q);
My algorithm has 2 problems:
operators and numbers are 2 different types and need to be saved in one queue. how can I save a "+" in an int queue?
2 3 + is an invalid input, but it will eventually return 5. 2 and 3 will be enqueued to the right, it becomes + 2 3. If the input is invalid, how do I prevent it?
Many thanks
Answers-
1- No this is not the best algorithm to solve prefix input(Stack approach is better).
2- You can give a special number for each operator.(lets say -999 for '-').
Better approach(without stack)
try something like this recursive approach
Simple recursion:
int c=0;
Evaluate(input,current_position):
c++;
Read a token from input at current pos.
If the token is a value:
Return the value of the token
If the token is a binary operator:
if(current_position+2 exists)
Let first_argument = Evaluate(input,current_position+1)
Let second_argument = Evaluate(input,current_position+2)
Return apply(operator, first_argument, second_argument)
else
invalid expression.
if(c==len(expression)
valid exp
else
invalid exp
This is my recursive solution using a queue structure (Last in First out).
Method 2:
Each element will be dequeued from an old queue and enqueued to a new list. If the pattern is found, dequeue 3 times and enqueue the result to the new queue. If the queue length doesn't change, report invalid input.
Define:
1. Given an input string.
2. Recursive function: int prefix_eval( q )
Base case: if size(q)==1, return dequeue(q);
Create a new queue: new_q;
int old_qlen = q->qlen;
While(size(q)>0)
if q->data[0] is an operator, q->data[1] and q->data[2] are numbers.
operator <--dequeue(q);
number1 <--dequeue(q);
number2 <--dequeue(q);
element = apply(operator, number1, number2 );
enqueue (new_q, element);
Else:
element = dequeue(q);
enqueue(new_q, element);
If (old_qlen > new_q->qlen)
Prefix_eval(new_q);
Else
Report invalid input and return
Start:
Create a queue q;
Enqueue q with each token from the input
Prefix_eval(q);
Bubble sort
In the above URL it is clearly written that short bubble is a modification in bubble sort to reduce the number of passes.
So in my implementation of both the algorithms i have added a counter which counts the number of passes and surprisingly both are having same no. of passes.
Here is my code:
def bubbleshort(mylist):
flag= True
passnum= len(mylist) -1
counter = 0
while flag and passnum > 0:
flag = False
for element in range(passnum):
if mylist[element] > mylist[element + 1]:
flag = True
temp= mylist[element]
mylist[element]= mylist[element+1]
mylist[element + 1] = temp
counter += 1
passnum -= 1
return mylist, counter
def bubble(yourlist):
count=0
for i in range(len(yourlist)-1, 0, -1):
for swap in range(i):
if yourlist[swap] > yourlist[swap + 1]:
temp=yourlist[swap]
yourlist[swap]=yourlist[swap + 1]
yourlist[swap + 1]= temp
count+= 1
return yourlist, count
mylist = [20,30,40,90,50,60,70,80,100,110]
mylistx = [20,30,40,90,50,60,70,80,100,110]
sortedList, counter= bubbleshort(mylist)
sortList, count= bubble(mylistx)
print(sortedList,counter)
print(sortList,count)
Also if i pass same list to both the functions the the bubble function is producing zero counts but is still giving a sorted list.
So can anybody tell me what exactly is the purpose of modification when the no. of passes are same. Their maybe a chance that my implementation of counter is wrong that why i am getting wrong answers.
It really depends on the input list whether the two functions go through the same number of passes.
For example, an almost sorted list like [9,1,2,3,4,5,6,7,8] takes only two passes for the short bubble function while it always takes 8 (n-1) passes for the regular bubble function.
I was given this problem to solve with Ruby:
Compute the sum of cubes for a given range a through b. Write a method called sum_of_cubes to accomplish this task.
I wrote this:
def sum_of_cubes(a, b)
sum = 0
for x in a..b
c = x ** 3
end
sum += c
end
I got the value of the cube of b. What is wrong with this code? How can I solve this problem with a simple loop?
Thanks!
I would use Enumerable#reduce
def sum_of_cubes min, max
(min..max).reduce(0) { |a, b| a + b ** 3 }
end
A little explanation of what's happening here
We start with range (min..max) which is an Enumerable
irb> (1..3).is_a? Enumerable
=> true
Using the reduce instance method we get from Enumerable, we can use a block of code that gets called for each item in our (enumerable) range, and ultimately returns a single value.
The function name makes sense if you think "take my group of items and reduce them to a single value."
Here's our block
{ |a, b| a + b ** 3 }
We called reduce with 0 which is the initial value given to the block's a param
The return value of the block is passed to the block's a param on subsequent calls
Each item in the range will be passed to the block's b param
Let's step through and see how it works
(1..3).reduce(0) { |a, b| a + b ** 3 }
the first block call gets a=0 (initial value) and b=1 (first item in our range)
the return value of our block is 0 + 1 ** 3 or 1
the second block call gets a=1 (return value from the last call) and b=2 (the second item in our range)
the return value of our block is 1 + 2 ** 3 or 9
the third block call gets a=9 (return value from the last call) and b=3 (the third and last item in our range)
the return value of our block is 9 + 3 ** 3 or 36
the final return value of reduce is the last-called block's return value
in this case 36
You need to have sum += c inside the loop. And then return sum when done.
Here’s another way to calculate this. It doesn’t address your problems with your loop but I think it’s worth mentioning.
The sum of cubes of integers 13 + 23 + 33 + ... + n3 is given by the formula (n(n + 1)/2)2, so the sum of cubes of a given range min..max is therefore given by:
(max(max + 1)/2)2 - ((min-1)((min-1) + 1)/2)2
In code this could look like:
def sum_of_cubes_fixed min, max
lower = min - 1
(((max * (max + 1))/2) ** 2) - (((lower * (lower + 1))/2) ** 2)
end
This code avoids the loop, and so is O(1) rather than O(n) (almost – I’m hand waving a bit here, the time complexity of the multiplications and exponentiations will depend on the size of the numbers). For small sized ranges you won’t notice this, but for larger sizes the difference between this and the loop version becomes increasingly obvious. I haven’t done any strict benchmarks, but a quick test on my machine with the range 1 to 10,000,000 takes several seconds with the reduce method but is almost instantaneous with this method.
Normally I would just use reduce for something like this, but the structure of the task suggested that there might be a better way. With the help of Google I found the formula and came up with a more efficient solution (at least for large ranges).
(a..b).map{|i| i**3 }.inject(&:+) map and inject does the job, elegantly.
EDIT: Although it walks through the list twice ;)