Write a Python program that prints the maximum value of the second half of the list

Python program to find second largest number in a list

Given a list of numbers, the task is to write a Python program to find the second largest number in the given list.
Examples:

Input: list1 = [10, 20, 4] Output: 10 Input: list2 = [70, 11, 20, 4, 100] Output: 70

Method 1: Sorting is an easier but less optimal method. Given below is an O(n) algorithm to do the same.

Python3




# Python program to find second largest
# number in a list
# list of numbers - length of
# list should be at least 2
list1 = [10, 20, 4, 45, 99]
mx=max(list1[0],list1[1])
secondmax=min(list1[0],list1[1])
n =len(list1)
for i in range(2,n):
if list1[i]>mx:
secondmax=mx
mx=list1[i]
elif list1[i]>secondmax and \
mx != list1[i]:
secondmax=list1[i]
print("Second highest number is : ",\
str(secondmax))
Output Second highest number is : 45

Method 2: Sort the list in ascending order and print the second last element in the list.

Python3




# Python program to find largest
# number in a list
# list of numbers
list1 = [10, 20, 4, 45, 99]
# sorting the list
list1.sort()
# printing the second last element
print("Second largest element is:", list1[-2])
Output

Second largest element is: 45

Method 3: By removing the max element from the list

Python3




# Python program to find second largest
# number in a list
# list of numbers
list1 = [10, 20, 4, 45, 99]
# new_list is a set of list1
new_list = set(list1)
# removing the largest element from temp list
new_list.remove(max(new_list))
# elements in original list are not changed
# print(list1)
print(max(new_list))
Output 45

Method 4: Find max list element on inputs provided by the user

Python3




# Python program to find second largest
# number in a list
# creating empty list
list1 = []
# asking number of elements to put in list
num = int(input("Enter number of elements in list: "))
# iterating till num to append elements in list
for i in range(1, num + 1):
ele = int(input("Enter elements: "))
list1.append(ele)
'''
# sort the list
list1.sort()
# print second maximum element
print("Second largest element is:", list1[-2])
'''
# print second maximum element using sorted() method
print("Second largest element is:", sorted(list1)[-2])

Output:

Enter number of elements in list: 4 Enter elements: 12 Enter elements: 19 Enter elements: 1 Enter elements: 99 Second Largest element is: 19

Method 5: Traverse once to find the largest and then once again to find the second largest.

Python3




def findLargest(arr):
secondLargest = arr[0]
largest = arr[0]
for i in range(len(arr)):
if arr[i] > largest:
largest = arr[i]
for i in range(len(arr)):
if arr[i] > secondLargest and arr[i] != largest:
secondLargest = arr[i]
return secondLargest
print(findLargest([10, 20, 4, 45, 99]))

Output:

45




Article Tags :
Python
Python Programs
Python list-programs
python-list
Practice Tags :
python-list
Read Full Article

Find the maximum elements in the first and the second halves of the Array

Given an array arr[] of N integers. The task is to find the largest elements in the first half and the second half of the array. Note that if the size of the array is odd then the middle element will be included in both halves.
Examples:

Input: arr[] = {1, 12, 14, 5}
Output: 12, 14
First half is {1, 12} and the second half is {14, 5}.
Input: arr[] = {1, 2, 3, 4, 5}
Output: 3, 5

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: Calculate the middle index of the array as mid = N / 2. Now the first halve elements will be present in the subarray arr[0…mid-1] and arr[mid…N-1] if N is even.
If N is odd then the halves are arr[0…mid] and arr[mid…N-1]
Below is the implementation of the above approach:

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to print largest element in
// first half and second half of an array
void findMax(int arr[], int n)
{
// To store the maximum element
// in the first half
int maxFirst = INT_MIN;
// Middle index of the array
int mid = n / 2;
// Calculate the maximum element
// in the first half
for (int i = 0; i < mid; i++)
maxFirst = max(maxFirst, arr[i]);
// If the size of array is odd then
// the middle element will be included
// in both the halves
if (n % 2 == 1)
maxFirst = max(maxFirst, arr[mid]);
// To store the maximum element
// in the second half
int maxSecond = INT_MIN;
// Calculate the maximum element
// int the second half
for (int i = mid; i < n; i++)
maxSecond = max(maxSecond, arr[i]);
// Print the found maximums
cout << maxFirst << ", " << maxSecond;
}
// Driver code
int main()
{
int arr[] = { 1, 12, 14, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
findMax(arr, n);
return 0;
}
Java




// Java implementation of the approach
import java.io.*;
class GFG
{
static void findMax(int []arr, int n)
{
// To store the maximum element
// in the first half
int maxFirst = Integer.MIN_VALUE;
// Middle index of the array
int mid = n / 2;
// Calculate the maximum element
// in the first half
for (int i = 0; i < mid; i++)
{
maxFirst = Math.max(maxFirst, arr[i]);
}
// If the size of array is odd then
// the middle element will be included
// in both the halves
if (n % 2 == 1)
{
maxFirst = Math.max(maxFirst, arr[mid]);
}
// To store the maximum element
// in the second half
int maxSecond = Integer.MIN_VALUE;
// Calculate the maximum element
// int the second half
for (int i = mid; i < n; i++)
{
maxSecond = Math.max(maxSecond, arr[i]);
}
// Print the found maximums
System.out.print(maxFirst + ", " + maxSecond);
// cout << maxFirst << ", " << maxSecond;
}
// Driver Code
public static void main(String[] args)
{
int []arr = { 1, 12, 14, 5 };
int n = arr.length;
findMax(arr, n);
}
}
// This code is contributed by anuj_67..
Python3




# Python3 implementation of the approach
import sys
# Function to print largest element in
# first half and second half of an array
def findMax(arr, n) :
# To store the maximum element
# in the first half
maxFirst = -sys.maxsize - 1
# Middle index of the array
mid = n // 2;
# Calculate the maximum element
# in the first half
for i in range(0, mid):
maxFirst = max(maxFirst, arr[i])
# If the size of array is odd then
# the middle element will be included
# in both the halves
if (n % 2 == 1):
maxFirst = max(maxFirst, arr[mid])
# To store the maximum element
# in the second half
maxSecond = -sys.maxsize - 1
# Calculate the maximum element
# int the second half
for i in range(mid, n):
maxSecond = max(maxSecond, arr[i])
# Print the found maximums
print(maxFirst, ",", maxSecond)
# Driver code
arr = [1, 12, 14, 5 ]
n = len(arr)
findMax(arr, n)
# This code is contributed by ihritik
C#




// C# implementation of the approach
using System;
class GFG
{
static void findMax(int []arr, int n)
{
// To store the maximum element
// in the first half
int maxFirst = int.MinValue;
// Middle index of the array
int mid = n / 2;
// Calculate the maximum element
// in the first half
for (int i = 0; i < mid; i++)
{
maxFirst = Math.Max(maxFirst, arr[i]);
}
// If the size of array is odd then
// the middle element will be included
// in both the halves
if (n % 2 == 1)
{
maxFirst = Math.Max(maxFirst, arr[mid]);
}
// To store the maximum element
// in the second half
int maxSecond = int.MinValue;
// Calculate the maximum element
// int the second half
for (int i = mid; i < n; i++)
{
maxSecond = Math.Max(maxSecond, arr[i]);
}
// Print the found maximums
Console.WriteLine(maxFirst + ", " + maxSecond);
// cout << maxFirst << ", " << maxSecond;
}
// Driver Code
public static void Main()
{
int []arr = { 1, 12, 14, 5 };
int n = arr.Length;
findMax(arr, n);
}
}
// This code is contributed by nidhiva
Javascript




// javascript implementation of the approach
function findMax(arr, n)
{
// To store the maximum element
// in the first half
var maxFirst = Number.MIN_VALUE
// Middle index of the array
var mid = n / 2;
// Calculate the maximum element
// in the first half
for (var i = 0; i < mid; i++)
{
maxFirst = Math.max(maxFirst, arr[i]);
}
// If the size of array is odd then
// the middle element will be included
// in both the halves
if (n % 2 == 1)
{
maxFirst = Math.max(maxFirst, arr[mid]);
}
// To store the maximum element
// in the second half
var maxSecond = Number.MIN_VALUE
// Calculate the maximum element
// int the second half
for (var i = mid; i < n; i++)
{
maxSecond = Math.max(maxSecond, arr[i]);
}
// Print the found maximums
document.write(maxFirst + ", " + maxSecond);
}
// Driver Code
var arr = [ 1, 12, 14, 5 ];
var n = arr.length;
findMax(arr, n);
// This code is contributed by bunnyram19.
Output: 12, 14

Time Complexity: O(n)

Auxiliary Space: O(1)




Article Tags :
Arrays
Mathematical
Constructive Algorithms
Practice Tags :
Arrays
Mathematical
Read Full Article

Python | Create two lists with first half and second half elements of a list

Here, we are going to learn how to create two lists with first half and second half elements of a given list in Python?
Submitted by IncludeHelp, on August 03, 2018

Given a list, and we have to create two lists from first half elements and second half elements of a list in Python.

Example:

Input: list: [10, 20, 30, 40, 50, 60] Output: list1: [10, 20, 30] list2: [40, 50, 60]

Logic:

  • First take list (Here, we are taking list with 6 elements).
  • To get the elements from/till specified index, use list[n1:n2] notation.
  • To get first half elements, we are using list[:3], it will return first 3 elements of the list.
  • And, to get second half elements, we are using list[3:], it will return elements after first 3 elements. In this example, we have only 6 elements, so next 3 elements will be returned.
  • Finally, print the lists.

Program:

# define a list list = [10, 20, 30, 40, 50, 60] # Create list1 with half elements (first 3 elements) list1 = list [:3] # Create list2 with next half elements (next 3 elements) list2 = list [3:] # print list (s) print "list : ",list print "list1: ",list1 print "list2: ",list2

Output

list : [10, 20, 30, 40, 50, 60] list1: [10, 20, 30] list2: [40, 50, 60]

Using list[0:3] and list[3:6] instaed of list[:3] and list[3:]

We can also use list[0:3] instead of list[:3] to get first 3 elements and list[3:6] instead of list[3:] to get next 3 elements after first 3 elements.

Consider the program:

# define a list list = [10, 20, 30, 40, 50, 60] # Create list1 with half elements (first 3 elements) list1 = list [0:3] # Create list2 with next half elements (next 3 elements) list2 = list [3:6] # print list (s) print "list : ",list print "list1: ",list1 print "list2: ",list2

Output

list : [10, 20, 30, 40, 50, 60] list1: [10, 20, 30] list2: [40, 50, 60]
ADVERTISEMENT

By considering length of the list

Let suppose list has n elements, then we can use list[0:n/2] and list[n/2:n].

Consider the program:

If there are ODD numbers of elements in the list, program will display message "List has ODD number of elements." And exit.

# define a list list = [10, 20, 30, 40, 50, 60] # get the length of the list n = len(list) # condition to check length is EVEN or not # if lenght is ODD, show message and exit if( n%2 != 0 ): print "List has ODD number of elements." exit() # Create list1 with half elements (first 3 elements) list1 = list [0:n/2] # Create list2 with next half elements (next 3 elements) list2 = list [n/2:n] # print list (s) print "list : ",list print "list1: ",list1 print "list2: ",list2

Output

list : [10, 20, 30, 40, 50, 60] list1: [10, 20, 30] list2: [40, 50, 60]

Python List Programs »

Python | Create three lists of numbers, their squares and cubes
Python | Iterate a list in reverse order

ADVERTISEMENT


Preparation


Aptitude Questions MCQs Find Output Programs

What's New

  • MongoDB MCQs
  • Java MCQs
  • C# MCQs
  • Scala MCQs
  • Blockchain MCQs
  • AutoCAD MCQs
  • PHP MCQs
  • JavaScript MCQs
  • jQuery MCQs
  • ReactJS MCQs
  • AngularJS MCQs
  • JSON MCQs
  • Ajax MCQs
  • SASS MCQs
  • HTML MCQs
  • Advanced CSS MCQs
  • CSS MCQs
  • PL/SQL MCQs
  • SQL MCQs
  • MS Word MCQs
  • PL/SQL MCQs
  • SQL MCQs
  • Software Engineering MCQs
  • MIS MCQs
  • Generally Accepted Accounting Principles MCQs
  • Bills of Exchange MCQs
  • Business Environment MCQs
  • Sustainable Development MCQs
  • Marginal Costing and Absorption Costing MCQs
  • Globalisation MCQs
  • Indian Economy MCQs
  • Retained Earnings MCQs
  • Depreciation MCQs
  • Partnership MCQs
  • Sole Proprietorship MCQs
  • Goods and Services Tax (GST) MCQs
  • Cooperative Society MCQs
  • Capital Market MCQs
  • Business Studies MCQs
  • Basic Accounting MCQs
  • MIS Executive Interview Questions
  • Go Language Interview Questions
ADVERTISEMENT

Top Interview Coding Problems/Challenges!

  • Run-length encoding (find/print frequency of letters in a string)
  • Sort an array of 0's, 1's and 2's in linear time complexity
  • Checking Anagrams (check whether two string is anagrams or not)
  • Relative sorting algorithm
  • Finding subarray with given sum
  • Find the level in a binary tree with given sum K
  • Check whether a Binary Tree is BST (Binary Search Tree) or not
  • 1[0]1 Pattern Count
  • Capitalize first and last letter of each word in a line
  • Print vertical sum of a binary tree
  • Print Boundary Sum of a Binary Tree
  • Reverse a single linked list
  • Greedy Strategy to solve major algorithm problems
  • Job sequencing problem
  • Root to leaf Path Sum
  • Exit Point in a Matrix
  • Find length of loop in a linked list
  • Toppers of Class
  • Print All Nodes that don't have Sibling
  • Transform to Sum Tree
  • Shortest Source to Destination Path

Comments and Discussions!



Please enable JavaScript to view the comments powered by Disqus.
ADVERTISEMENT

Python program to find second largest number in a list

In this tutorial, we will write a Python program to find the second largest number in a list. List is an ordered set of values enclosed in square brackets [ ]. List stores some values called elements in it, which can be accessed by their particular index. We will be following various approaches to find the second largest number in a list.

For a given list of numbers, the task is to find the largest number in the list.

Input: [11, 5, 2, 8, 4, 19]

Output: 11

Input: [2, 11, 18, 23, 6]

Output: 18

Find Maximum Value in a List in Python

Python Python List

Created: November-16, 2020 | Updated: December-10, 2020

This tutorial will demonstrate how to find the maximum value in a list in Python.

A few scenarios and data types will be covered, from a simple integer list to a more complex structure such as an array within an array.

Python program to find the second largest number in a list

PythonServer Side ProgrammingProgramming

In this article, we will learn about the solution to the problem statement given below.

Problem statement− We are given a list, we need to display the second largest number in a list.

There are three approaches to solve the problem−

Python Program to Create Two Lists with First Half and Second Half Elements of Given List

  • Python program to create two lists with first half and second half elements of a given list.
  • Python program to create two lists with first half and second half elements of a given list using range slicing.

1: Python program to create two lists with first half and second half elements of a given list

use the following steps to write a python program to create list in first half of the elements with the second half of the elements:

  • Define a list.
  • Take input how many element in list from user.
  • Iterate for loop and use input() function to allow user to input element.
  • Append elements in list by using append() method.
  • Divide list length number by 2 and store in variable.
  • To get first half elements usinglist[:num] and store list1.
  • To get second half elements usinglist[num:] and store list2.
  • Print list1 and list2.
# write a python program to create two lists with first half and second half #elements of a given list. NumList = [] Number = int(input("How many elements in list :- ")) # condition to check given number is even or odd if( Number%2 != 0 ): print("This program will not accept odd number.") exit() for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element :- " %i)) NumList.append(value) #number half num = int(Number/2) # Create list1 with half elements (first 3 elements) list1 = NumList[:num] # Create list2 with next half elements (next 3 elements) list2 = NumList[num:] # print list (s) print("list : ",NumList) print("list1: ",list1) print("list2: ",list2)

After executing the program, the output will be:

How many elements in list :- 6 Please enter the Value of 1 Element :- 1 Please enter the Value of 2 Element :- 2 Please enter the Value of 3 Element :- 3 Please enter the Value of 4 Element :- 4 Please enter the Value of 5 Element :- 5 Please enter the Value of 6 Element :- 6 list : [1, 2, 3, 4, 5, 6] list1: [1, 2, 3] list2: [4, 5, 6]

2: Python program to create two lists with first half and second half elements of a given list using range slicing

use the following steps to write a python program to create list in first half of the elements with the second half of the elements using range slicing:

# write a python program to create two lists with first half and second half #elements of a given list. NumList = [] Number = int(input("How many elements in list :- ")) # condition to check given number is even or odd if( Number%2 != 0 ): print("This program will not accept odd number.") exit() for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element :- " %i)) NumList.append(value) # divide by 2 the length of list n = int(Number/2) # Create list1 with half elements (first 3 elements) list1 = NumList [0:n] # Create list2 with next half elements (next 3 elements) list2 = NumList [n:Number] # print list (s) print("list : ",NumList) print("list1: ",list1) print("list2: ",list2)

After executing the program, the output will be:

How many elements in list :- 6 Please enter the Value of 1 Element :- 9 Please enter the Value of 2 Element :- 8 Please enter the Value of 3 Element :- 7 Please enter the Value of 4 Element :- 6 Please enter the Value of 5 Element :- 5 Please enter the Value of 6 Element :- 4 list : [9, 8, 7, 6, 5, 4] list1: [9, 8, 7] list2: [6, 5, 4]

Video liên quan

Postingan terbaru

LIHAT SEMUA