- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Distant Barcodes in Python
Suppose in a warehouse, there is a row of barcodes. The i-th barcode is barcodes[i]. We have to rearrange the barcodes so that no two adjacent barcodes are same. So if the input is [1,1,1,2,2,2] so output is [2,1,2,1,2,1].
To solve this, we will follow these steps −
- make one map named d
- store the frequency of numbers present in the barcode array into d
- x := empty list
- insert all key-value pairs into x
- i := 0
- res := make a list whose length is same as barcodes, and fill [0]
- sort x based on the frequency
- while i < length of result
- result[i] := element of the last entry of x
- decrease the frequency value of the last entry of x
- if the frequency of the last element of x is 0, then delete that entry from x
- increase i by 2
- i := 1
- while i < length of result
- result[i] := element of the last entry of x
- decrease the frequency value of the last entry of x
- if the frequency of the last element of x is 0, then delete that entry from x
- increase i by 2
- return result
Let us see the following implementation to get better understanding −
Example
class Solution(object): def rearrangeBarcodes(self, barcodes): d = {} for i in barcodes: if i not in d: d[i] = 1 else: d[i]+=1 x = [] for a,b in d.items(): x.append([a,b]) i = 0 result = [0]*len(barcodes) x = sorted(x,key=lambda v:v[1]) while i <len(result): result[i] = x[-1][0] x[-1][1]-=1 if x[-1][1]==0: x.pop() i+=2 i=1 while i <len(result): result[i] = x[-1][0] x[-1][1]-=1 if x[-1][1]==0: x.pop() i+=2 return result ob = Solution() print(ob.rearrangeBarcodes([1,1,1,2,2,2]))
Input
[1,1,1,2,2,2]
Output
[2, 1, 2, 1, 2, 1]
Advertisements