- 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
Program to find a sublist where first and last values are same in Python
Suppose we have a list of numbers called nums, we have to find the number of sublists where the first element and the last element are same.
So, if the input is like nums = [10, 15, 13, 10], then the output will be 5, as the sublists with same first and last element are: [10], [15], [13], [10], [10, 15, 13, 10].
To solve this, we will follow these steps −
num_sublists := size of nums
d := an empty map
for each n in nums, do
d[n] := d[n] + 1
for each number k and corresponding frequency v of elements in d, do
if v is not same as 1, then
num_sublists := num_sublists +(quotient of (v-1) *(v) /2)
return num_sublists
Let us see the following implementation to get better understanding −
Example
from collections import defaultdict class Solution: def solve(self, nums): num_sublists = len(nums) d = defaultdict(int) for n in nums: d[n] += 1 for k,v in d.items(): if v != 1: num_sublists += (v-1)*(v)//2 return num_sublists ob = Solution() nums = [10, 15, 13, 10] print(ob.solve(nums))
Input
[10, 15, 13, 10]
Output
5
Advertisements