Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Question

The document contains multiple Python functions addressing various programming challenges, including finding the maximum sum of contiguous subarrays, merging overlapping intervals, and calculating the minimum number of street lights needed to cover a road. It also includes problems related to job scheduling for maximum profit, repackaging data packets, and determining the longest odd-length word from a list. Each problem is accompanied by input and output formats, constraints, and sample inputs and outputs.

Uploaded by

dbda.iacsdakurdi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Question

The document contains multiple Python functions addressing various programming challenges, including finding the maximum sum of contiguous subarrays, merging overlapping intervals, and calculating the minimum number of street lights needed to cover a road. It also includes problems related to job scheduling for maximum profit, repackaging data packets, and determining the longest odd-length word from a list. Each problem is accompanied by input and output formats, constraints, and sample inputs and outputs.

Uploaded by

dbda.iacsdakurdi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Write a Python function called max_subarray_sum that takes an array of integers as input and

returns the maximum sum of any contiguous subarray within the array.

Input Format: The input will be a list of integers.

Constraints

 The length of the array will be at least 1.


 The array may contain both positive and negative integers.

Output Format: The output will be a single integer representing the maximum sum of a
subarray.

Sample Input: [1, 2, 3, -2, 5]

Sample Output: 9

def max_subarray_sum(arr):
max_sum = arr[0]
current_sum = arr[0]
for i in range(1, len(arr)):
current_sum = max(arr[i], current_sum + arr[i])
max_sum = max(max_sum, current_sum)
return max_sum

Write a Python function called merge_intervals that takes a list of intervals as input and returns a
new list of intervals where overlapping intervals are merged.

Input Format: The input will be a list of intervals, where each interval is represented by a list
with two elements: the start and end points of the interval.

Constraints

 The list of intervals will be non-empty.


 The start and end points of each interval will be integers.

Output Format: The output will be a list of merged intervals, where each interval is represented
by a list with two elements: the start and end points of the merged interval.

Sample Input: [[1, 3], [2, 6], [8, 10], [15, 18]]

Sample Output: [[1, 6], [8, 10], [15, 18]]

def merge_intervals(intervals):
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
else:
merged[-1][1] = max(merged[-1][1], interval[1])
return merged

Street Lights are installed at every position along a 1-D road of length n. Locations[] (an array)
represents the coverage limit of these lights. The ith light has a coverage limit of locations[i] that
can range from the position max((i – locations[i]), 1) to min((i + locations[i]), n ) (Closed
intervals). Initially all the lights are switched off. Find the minimum number of fountains that
must be switched on to cover the road.

Example

n=3

locations[] = {0, 2, 13}then

For position 1: locations[1] = 0, max((1 – 0),

1) to mini (1+0), 3) gives range = 1 to 1

For position 2: locations[2] = 2, max((2-2),

1) to min( (2+2), 3) gives range = 1 to 3

For position 3: locations[3] = 1, max( (3-1),

1) to min( (3+1), 3) gives range = 2 to 3

For the entire length of this road to be covered, only the light at position 2 needs to be activated.

Returns:

int : the minimum number of street lights that must be activated

Constraints :

 1<_n<_ 10^5
 O<_locations[i] <_ mini (n,100) (where 1 <_1<_10^5)

Sample Input For Custom Testing :

3 ->locations[] size n = 3

1 ->locations[] [1, 1, 1]
1 ->Sample Output

Sample Output :

def Sort_Tuple(tup):

# getting length of list of tuples


lst = len(tup)
for i in range(0, lst):
for j in range(0, lst-i-1):
if (tup[j][1] > tup[j + 1][1]):
temp = tup[j]
tup[j]= tup[j + 1]
tup[j + 1]= temp
return tup

def solve(l,n):
rang=[[0,0]for i in range(n)]
#print(rang)
for i in range(n):
id=i+1
rang[i][0]=max(1,id-l[i])
rang[i][1]=min(n,id+l[i])

Sort_Tuple((rang))

i=0
ans=0
while ip[1]:
break
i+=1

return ans
n=int(input())
l=[]
for i in range(n):
l.append(int(input()))
print(solve(l,n))
A company has a list of jobs to perform. Each job has a start time, end time and profit value. The
manager has asked his employee Anirudh to pick jobs of his choice. Anirudh being greedy wants
to select jobs for him in such a way that would maximize his earnings.

Given a list of jobs how many jobs and total earning are left for other employees once Anirudh

Picks jobs of his choice.

Note: Anirudh can perform only one job at a time.

Input format:

Each Job has 3 pieces of info – Start Time,End Time and Profit

The first line contains the number of Jobs for the day. Say ‘n’. So there will be ‘3n lines
following as each job has 3 lines.

Each of the next ‘3n’ lines contains jobs in the following format:


o start_time
o end-time
o Profit

start-time and end-time are in HHMM 24HRS format i.e. 9am is 0900 and 9PM is 2100

Constraints

 The number of jobs in the day is less than 10000 i.e. 0<_n<_10000
 Start-time is always less than end time.

Output format :-

Program should return an array of 2 integers where 1st one is number of jobs left and earnings of
other employees.

Sample Input 1 :
3

0900

1030

100

1000

1200

500

53

1100

1200

300

Sample Output 1:

400

Sample Explanation 1

Anirudh chooses 1000-1200 jobs. His earnings is 500. The 1st and 3rd jobs i.e. 0900-1030 and
1100-1200 respectively overlap with the 2nd jobs. But profit earned from them will be 400 only.
Hence Anirudh chooses 2nd one. Remaining 2 Jobs & 400 cash for other employees.

Sample Input 2:

0805

0830

100
0835

0900

100

0905

0930

100

0935

1000

100

1005

1030

100

Sample output 2:

Sample Explanation 2:

Anirudh can work on all appointments as there are none overlapping. Hence 0 appointments and
0 earnings for other employees.
A stream of n data packets arrives at a server. This server can only process packets that are
exactly 2^n units long for some non-negative integer value of n (0<=n).

All packets are repackaged in order to the 1 largest possible value of 2^n units. The remaining
portion of the packet is added to the next arriving packet before it is repackaged. Find the size of
the largest repackaged packet in the given stream.

Example :

 arriving Packets = [12, 25, 10, 7, 8]


 The first packet has 12 units. The maximum value of 2^n that can be made has 2^n = 2^3
= 8 units because the next size up is 2^n = 2^4 = 16 (16 is greater than 12).
 12 – 8 = 4 units are added to the next packet. There are 4 + 25 = 29 units to repackage,
2^n = 2^4 = 16 is the new size leaving 9 units (29-16 = 9)
Next packet is 9 + 10 = 29 unists & the maximum units(in 2^n) is 16 leaving 3 units.
 3 + 7 = 10 , the max units is 8 Leaving 2 units, and so on.
 The maximum repackaged size is 16 units.

Returns:

 Long : the size of the largest packet that is streamed

Constraints :

 1<=n<=10^5
 1<=arriving Packets[i] size<=10^9

Sample case :

Sample input :
5 → number of packets=5
12 → size of packets=[13,25,12,2,8]
25
10
2
8
Sample output :
16

def largeRepackagedPacket(arr):
twoP=[int(2**i) for i in range(31)]
x=0
ans=0
for i in arr:
i=i+x
for j in range(31):
if i<twoP[j]:
break
x=i-twoP[j-1]
if ans<=twoP[j-1]:
ans=twoP[j-1]
return ans
Packets=[]
for i in range(int(input())):
Packets.append(int(input()))
print(largeRepackagedPacket(Packets))

Anirudh is attending an astronomy lecture. His professor who is very strict asks students to write
a program to print the trapezium pattern using stars and dots as shown below . Since Anirudh is
not good in astronomy can you help him?

Sample Input:

N=3

Output:

**.**

*…*

…..

*…*

**.**

n=int(input())
for i in range(n):
print(“*”*(n-1-i)+“.”*(2*i+1)+“*”*(n-1-i))
for i in range(n-1):
print(“*”*(i+1)+“.”*(2*(n-2-i)+1)+“*”*(i+1))

Kochouseph Chittilappilly went to Dhruv Zplanet , a gaming space, with his friends and played a
game called “Guess the Word”.
Rules of games are –

 Computer displays some strings on the screen and the player should pick one string /
word if this word matches with the random word that the computer picks then the player
is declared as Winner.
 Kochouseph Chittilappilly’s friends played the game and no one won the game. This is
Kochouseph Chittilappilly’s turn to play and he decided to must win the game.
 What he observed from his friend’s game is that the computer is picking up the string
whose length is odd and also that should be maximum. Due to system failure computers
sometimes cannot generate odd length words. In such cases you will lose the game
anyways and it displays “better luck next time”. He needs your help. Check below cases
for better understand

Sample input :
5 → number of strings
Hello Good morning Welcome you
Sample output :
morning

Explanation:

 Hello → 5
 Good → 4
 Morning → 7
 Welcome → 7
 You → 3

First word that is picked by computer is morning

Sample input 2 :
3
Go to hell

Sample output 2:
Better luck next time

Explanation:
Here no word with odd length so computer confuses and gives better luck next time

n=int(input())
sentence=input().split()
length=[]
for i in sentence:
L=len(i)
if L%2==1:
length.append(len(i))
else:
length.append(0)
if max(length)==0:
print("Better Luck next Time")
else:
print(sentence[length.index(max(length))])
Raman was playing a game, in starting he has x coins at some point of the game he has to pay some
coins to get into the next level of the game, during each game he can collect some coins. If at anypoint
of the game numbers of coins of Raman is less than one he will lose the game. Find the minimum value
of x such that Raman wins.
n=int(input())
arr=[]
for i in range(n):
arr.append(int(input()))
s,a=0,0
for i in arr:
s=s+i
if(s<1):
a=a+(-1*s)+1
s=1
print(a)

There are some groups of devils and they splitted into people to kill them. Devils make People to
them left as their group and at last the group with maximum length will be killed. Two types of
devils are there namely “@” and “$”
People is represented as a string “P”

Input Format:
First line with the string for input

Output Format:
Number of groups that can be formed.

Constraints:
2<=Length of string<=10^9

Input string
PPPPPP@PPP@PP$PP

Output
7

Explanation
4 groups can be formed

 PPPPPP@
 PPP@
 PP$
 PP

Most people in the group lie in group 1 with 7 members.

s=input()
s=s.replace("@"," ").replace("$"," ")
s=s.split()
ans=[]
for i in s:
ans.append(len(i)+1)
ans[-1]-=1
print(max(ans))

Stephan is a vampire. And he is fighting with his brother Damon. Vampires get energy from
human bloods, so they need to feed on human blood, killing the human beings. Stephan is also
less inhuman, so he will like to take less life in his hand. Now all the people’s blood has some
power, which increases the powers of the Vampire. Stephan just needs to be more powerful than
Damon, killing the least human possible. Tell the total power Steohan will have after drinking
the bloods before the battle.

 Note that: Damon is a beast, so no human being will be left after Damon drinks
everyone’s blood. But Stephan always comes early in the town.

Input Format:

First line with the number of people in the town, n.

Second line with a string with n characters, denoting the one digit power in every blood.

Output Format:

Total minimum power Stephan will gather before the battle.

Constraints:

 n<=10^4

Sample input :

093212

Sample output :

Explanation:

Stephan riches the town, drinks the blood with power 9. Now Damon cannot reach 9 by drinking
all the other bloods.
n=int(input())
ar=input()
sorted(ar,reverse=True)
br=[]
s=0
aa=[]
for i in ar:
aa.append(int(i))

su=sum(aa)
while(s<=su):
s+=(aa[0])
su=su-(aa[0])
br.append(aa.pop(0))
print(sum(br))

Rahul copies in the exam from his adjacent students. But he doesn’t want to be caught, so he
changes words keeping the letter constant. That means he interchanges the positions of letters in
words. You are the examiner and you have to find if he has copied a certain word from the one
adjacent student who is giving the same exam, and give Rahul the markings he deserves.

Note that: Uppercase and lowercase are the same.

Input Format:

 First line with the adjacent student’s word


 Second line with Rahul’s word

Output Format:

 0 if not copied
 1 if copied

Constraints:

 1<=Length of string<=10^6

Sample Input:

CAR

Acr

Sample Output:

s=input()
s1=input()
s=s.lower()
s=sorted(s)
s1=s1.lower()
s1=sorted(s1)
if s1==s:
print(1)
else:
print(0)

You might also like