Thursday, 13 February 2020

*********** PYTHON ASSIGNMENTS ********************


1-
Define a Python function remdup(l) that takes a nonempty list of integers l and removes all duplicates in l, keeping only the first occurrence of each number. For instance:

Solution

def remdup(duplicate):
  finalist=[];
  for num in duplicate:
    if num not in finalist:
        finalist.append(num);

  return finalist;

testcases:

>>> remdup([3,1,3,5,5,5]) [3, 1, 5] >>> remdup([7,3,-1,-5,-3]) [7, 3, -1, -5] >>> remdup([5,7,5,3,7,10]) [3, 5, 7, 10]



2-
Write a Python function sumsquare(l) that takes a nonempty list of integers and returns a list [odd,even], where odd is the sum of squares all the odd numbers in l and even is the sum of squares of all the even numbers in l.

Solution:

def sumsquare(list):
  flist=[];
  odd=0;
  even=0;
  for num in list:
    if num%2==0:
        even=even + num*num;
    else: 
        odd=odd+num*num;
  flist.append(odd);
  flist.append(even);
  return flist;

testcases:
>>> sumsquare([1,3,5])
[35, 0]

>>> sumsquare([2,4,6])
[0, 56]

>>> sumsquare([-1,-2,3,7])
[59, 4]

***************************************************************************************


3-
We represent scores of batsmen across a sequence of matches in a two level dictionary as follows:
{'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}
Each match is identified by a string, as is each player. The scores are all integers. 
Define a Python function orangeecap(d) that reads a dictionary d of this form and identifies the player with the highest total score. Your function should return a pair (playername,topscore) where playername is a string, the name of the player with the highest score, and topscore is an integer, the total score of playername.
The input will be such that there are never any ties for highest total score.

Solution:
def orangeecap(d): total={} for match,player in d.items(): for n in list(player.keys()): total[n]=0 for match in d.keys(): if n in d[match].keys(): total[n]=total[n]+d[match][n] o=[] o=o+sorted(total.items(), key = lambda kv:(kv[1], kv[0])) return(o[-1]);

**************************************************************************************

4-
Accept two strings as input and form a new string by removing all chars from the second string which are present in the first string. 
Print this new string as output.  Assume  all input strings are in lower case.

SOLUTION
=========
str1=input()
str2=input()
str3=''
L1=[]
L2=[]
L3=[]
for i in str1:
 L1.append(i)
for i in str2:
 L2.append(i)
for i in L1:
 for j in range(0,len(L2)):
  if i in L2:
    L2.remove(i)
str3=''.join(L2)
print(str3)

Sample in/op
testcase:1
an
adnan

d
 
testcase:2
aeiou
this is a python program
ths s  pythn prgrm
********************************************************************************

5-
Accept a positive integer n as input and print the sum of all prime numbers in the range [1, n], endpoints inclusive.

SOLUTION:
n=int(input())
L=[]

for i in range(2,n+1):
  flag=True
  for j in range(2,i+1):
   if(i%j)==0 and j<i:
     flag=False
  if flag:
   L.append(i)
#print(L)
sum=0
for i in L:
  sum=sum+i
print(sum)

testcase:1
10
17
testcase:2
100
1060

*******************************************************************

6-
The input should be four integers in four lines. The output should be a single line with all the integers separated by  single space in ascending order.


SOLUTION:
L=[]
n1=int(input())
L.append(n1)
n2=int(input())
L.append(n2)
n3=int(input())
L.append(n3)
n4=int(input())
L.append(n4)
L.sort()
for i in L:
  print(i,end=' ')
print() 

*********************************************************************

7-
Take as input 4 input lines. First and third line =names of persons . While second and fourth lines refer to  date of births of  the persons. Output should be the name of the younger person .

SOLUTION:
==========
from datetime import datetime, timedelta
n1=input()
d1=input()
n2=input()
d2=input()
L1=[]
L1=d1.split('-')
L2=[]
L2=d2.split('-')
dob1=datetime(int(L1[2]),int(L1[1]),int(L1[0]))
dob2=datetime(int(L2[2]),int(L2[1]),int(L2[0]))
ct=datetime.today()
age1=ct-dob1
age2=ct-dob2
if (age1>age2):
  print(n2)
if (age2>age1):
  print(n1)
if(age1==age2):
  if(n1>n2):
    print(n2)
  else:
    print(n1)

*******************************************************************


8-
Program to find the median of the given sample list: marks

SOLUTION:

marks=[23,25,43,12,2,1]
final=[]
while(len(marks)>0):
 least=marks[0]
#sorting the list marks
 for i in range(len(marks)):
  if marks[i]<least:
   least=marks[i]
 final.append(least)
 marks.remove(least)
print(final)  #sorted list
#median calculation
if(len(final)%2!=0):
  value=((len(final)+1)//2)
  #print(value)
  median=final[value-1]
  print(median)
else:
  value1=(len(final)//2)-1
  value2=((len(final)//2)+1)-1
  median=(final[value1]+final[value2])/2
  print(median)

************************************************************

9- 
Reading of Matrix from input. Use ',' in split if comma is given as separator and we can also use ' ' in split if the space is given as separator in the question .

dim=int(input())
A=[]
for i in range(dim):
 l=[int(eleme) for eleme in input().split(",")]
 A.append(l)
B=[]
for i in range(dim):
 l=[int(eleme) for eleme in input().split(",")]
 B.append(l)
 print(A)
 print(B)

********************************************************************

10-
Print identity matrix in the comma separated format

SOLUTION:

n=int(input())
for i in range(n):
  for j in range(n):
    if(i!=j) and j<n-1: # this has been put to avoid comma at the end #                               #of every row
      print('0',end=",")
    if(i!=j) and j==n-1:
      print('0',end="")
    if(i==j) and j<n-1:
      print('1',end=",")
    if(i==j) and j==n-1:
      print('1',end="")
  print()   # this print is to change line after every row

Input:
2
Output:
1,0
0,1

************************************************************************

11-
 Accept a positive integer as input and print the digits present in it from left to right. Each digit should be printed as a lower case word on a separate line.

d={1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',0:'zero'}
#print(d)
n=int(input())
lst=[]
while(n>0):
  num=n%10
  lst.append(d[num])
  n=n//10
 # method to reverse the list
l=[]
for i in lst:
    # reversing the list
    l.insert(0, i)
for i in range(len(l)):
 print(l[i])


InputExpected Output
123
one
two
three
************************************************************************

12
Write a function named value_to_keys that accepts a dictionary d and a variable named val as arguments. It should return the list of all keys in the dictionary that have value equal to val. If the value is not present in the dictionary, the function should return the empty list.

def value_to_keys(d, val):
  l=[]
  for x in d:
  if(d[x]==val):
    l.append(x)
  return(l)

*************************************************************************

13-
Accept a ten-digit number as input. Find the number of places where the numbers 0 and 1 have been replaced by letters(o and l respectively). If there are no such replacements, print the string No mistakes. If not, print the number of mistakes   and in the next line, print the correct phone number.

n=input()
l=[]
for i in range(len(n)):
  l.append(n[i])
count=0
for i in l:
  if(i=='l') or (i=='o'):
    count=count+1
for  x in range(len(l)):
  if(l[x]=='l'):
      l[x]='1'
  if(l[x]=='o'):
      l[x]='0'

if(count!=0):
  print(count ,"mistakes")
  st=''.join(l)
  print(st)
else:
  print("No mistakes")
===============================================

Test  1

InputExpected Output 
987o35l7o4
3 mistakes
9870351704
 
 

Test  2

InputExpected Output 
9874618291
No mistakes
 
===============================================

******************************************************************

14-

Write a recursive function named counter that accepts the following arguments:

  • L: list of words.
  • word: a word, could be any string.

This function should return the number of occurrences of word in L.


def counter(L,word):

  c=0

  n=len(L)

  if n==0:

   return 0

  if L[0]==word:

     return 1+count(L[1:n],word)

  else:

    return count(L[1:n],word)


L=['a','sd','adnan','tom','tom','harry']

print(count(L,'tom'))

OUTPUT:

2




No comments:

Post a Comment