Saturday 26 August 2017

PPS 5

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

Practice Problems 5 Fall 17

1) CSE1701 Word histogram (Id-2103)
Histogram is a graphical representation drawn based on the frequency of occurrence of things. Histogram for a word is drawn based on the number of occurrences of each character in the word. An inverted dictionary is used to maintain the list of characters that has same frequency. Write an algorithm and the subsequent Python code to compute and print the frequency of occurrence of character as a dictionary (ch:count). Make the entire process to be case insensitive. For example, if the input word is ‘parrot’, then the dictionary with characters and frequency of occurrence is
{'a': 1, 'o': 1, 'p': 1, 'r': 2, 't': 1}
and the inverted dictionary is
{1: ['a', 'o', 'p', 't'], 2: ['r']}
Print dictionary in sorted order by key. Sort the values of each key in the inverted dictionary.
[Hint: use pprint function for printing dictionary in sorted order.
Syntax for pprint is
pprint(dictionary name)
Include the line “from pprint import pprint” in the top of your program
Check for boundary conditions and print 'Invalid input' if conditions are not met.
Input Format:
First line contains the input word
Output Format:
Dictionary of characters in the word as keys and count as values in sorted order by key.
Inverted dictionary in sorted order by key.
Boundary Conditions:
Given word should only contain alphabets
**********************************************************
CODE:(Verified👍)
word=input().rstrip().lower()
if(any(c.isnumeric() for c in word)==True):
    print('Invalid input')
    exit()
dic={}
for letter in word:
    if(letter not in dic):
        freq=word.count(letter)
        dic[letter]=freq

import pprint
#Finding the inverse dictionary:
inv_dic={}
for k,v in dic.items():
    inv_dic[v]=inv_dic.get(v,[])
    inv_dic[v].append(k)
    inv_dic[v]=sorted(inv_dic[v])

pprint.pprint(dic)
pprint.pprint(inv_dic)

2) CSE1701 Letter Identification (Id-2106)
Given three words, write an algorithm and the subsequent Python code to identify the following letters:
  1. Letters common to all the three words
  2. Letters in first two words but not in third word
  3. Letters in first word but not in second and third word
  4. Letters in all the three words
For example, if the words are apple, camel, element then letters in common to all the three words -  i, e
Letters in first two words but not in third word – a
Letters in first word but not in second and third word  - p
Letters in all the three words – a, p, p, l, e, c, m, n, t
Hint: Use sets in Python. While reading input, use rstrip() function to remove extra spaces 
Input Format
First line contains word1
Second line contains word2
Third line contains word3
Output Format
List of letters common to all the three words in lexicographical order
List of letters common to first two words but not in third word in lexicographical order
List of letters in first word but not in second or third word in lexicographical order
List of all letters in the three words in lexicographical order
**********************************************************
CODE:(Verified👍)
word1=input().rstrip().lower()
word2=input().rstrip().lower()
word3=input().rstrip().lower()
s1=set(word1)
s2=set(word2)
s3=set(word3)
L1=[]
L2=[]
L3=[]
L4=[]
for i in s1:
    if(i in s2 and i in s3):
        L1.append(i)
for i in s1:
    if(i in s2 and i not in s3):
        L2.append(i)
for i in s1:
    if(i not in s2 and i not in s3):
        L3.append(i)
s4=s1.union(s2).union(s3)
L4=list(s4)
print(sorted(L1))
print(sorted(L2))
print(sorted(L3))
print(sorted(L4))

3) CSE1701 Rook and a Queen (Id-2102)
Given the position of a Rook and a queen in a chess board (8X8 board),  write an algorithm and the subsequent Python code to determine the common positions where both rook and queen can be placed in the next move. Rook can move through any number of cells,  either horizontally or vertically. Queens can move through any number of cells,  either horizontally, vertically or diagonally.  Each cell in the chess board may be represented as a 2-tuple (row,col). For example, if the current position of the rook is (3,1) then the next possible position of the rook may be either in the same column {(2,1),(1,1),(4,1),(5,1),(6,1),(7,1),(8,1)} or in the same row {(3,2),(3,3),(3,4),(3,5),(3,6),(3,7),(3,8)}. If the queen is in the position (5,3) then it can be placed in the same row {(5,1),(5,2),(5,4),(5,5),(5,6),(5,7),(5,8)} or same column {(1,3),(2,3),(3,3),(4,3),(6,3),(7,3),(8,3)} or along the diagonal of the current position {(6,4),(7,5),(8,6),(4,2),(5,1),(6,2),(7,1),(4,4),(3,5),(2,6),(1,7)}. Then the common cells for next move are {(3,3), (5,1), (7,1)}.
The output is a set of common board positions where both queen and rook can be placed. The positions must be printed in sorted order, sort it by row. When rows are same,  sort it by column.

(Hint: Use built-in function to sort the values)
Input Format
Row position of rook
Column position of rook
Row position of queen
Column position of queen
Output Format
Common position1
Common position2
...
**********************************************************
#Reading the inputs
r_rook=int(input())
c_rook=int(input())
r_queen=int(input())
c_queen=int(input())

#Finding the next positions for Rook
positions_rook=[]
for i in range(1,9):
 positions_rook.append((r_rook,i)) #same row
 positions_rook.append((i,c_rook)) #same column
for rc in positions_rook:
 if(rc==(r_rook,c_rook) or rc==(r_queen,c_queen)):
  positions_rook.remove(rc)

#Finding the next positions for Queen
positions_queen=[]
for i in range(1,9):
 positions_queen.append((r_queen,i)) #same row
 positions_queen.append((i,c_queen)) #same column

#For diagonals_Queen
c=c_queen
r=r_queen
while(c!=1 and r!=8):
 positions_queen.append((r+1,c-1))
 r=r+1
 c=c-1
c=c_queen
r=r_queen
while(c!=1 and r!=1):
 positions_queen.append((r-1,c-1))
 r=r-1
 c=c-1
c=c_queen
r=r_queen
while(c!=8 and r!=8):
 positions_queen.append((r+1,c+1))
 r=r+1
 c=c+1
c=c_queen
r=r_queen
while(c!=8 and r!=1):
 positions_queen.append((r-1,c+1))
 r=r-1
 c=c+1

for rc in positions_queen:
 if(rc==(r_rook,c_rook) or rc==(r_queen,c_queen)):
  positions_queen.remove(rc)

final_list=[]
for i in positions_rook:
 if(i in positions_queen):
  final_list.append(i)

x=sorted(final_list)
for i in x:
print(i)

4) CSE1701 Minimum distance points (Id-2105)
Given 'n' points in an X-Y plane , write an algorithm and the subsequent Python code to determine the pair of points that are closer. Distance between two points (x1, y1) and (x2, y2) is determined using the formula.
Consider only two decimal places of distance for comparison. When there are multiple points with the same minimum distance print all points.
Input Format
Number of points
x coordinate of point1
y coordinate of point1
x coordinate of point2
y coordinate of point2
...
Output format
Point1 and Point2 that have minimum distance between them
CODE:(Verified👍)
import math
dist = lambda a,b,x,y : format(math.sqrt((a-b)**2+(x-y)**2), '.2f')
n = int(input())
x,y,mixx,l,sl=0,0,0,[],[]
for i in range(n):
    x = int(input())
    y = int(input())
    l.append((x,y))
for i in range(n-1):
    x,y = l[i][0],l[i][1]
    for j in range(i+1,n):
        a,b = l[j][0],l[j][1]
        d = float(dist(x,a,y,b))
        if i == 0 and j == 1:
            mixx = d
        if d < mixx:
            sl = []
            sl.append((x,y))
            sl.append((a,b))
            mixx = d
        elif d == mixx:
            sl.append((x,y))
            sl.append((a,b))
            mixx = d
for i in sl:
    print(i)

5) CSE1701 Count Words (Id-2104)
Write an algorithm and write the Python code to count the number of unique words in a given passage. The paragraph may contain words with special characters such as '!', '?', '.', ',' , ':' and ';' and digits are not permitted. Special character must occur only at the end of a word in a passage that is Hello World! is valid but Hello !World or Hello Wor!ld is invalid. No two special character occur together. Print 'Invalid input' for such cases. Count words without special characters. Counting must be case insensitive. Print words in lower case and in sorted order. For example, given a passage 'Programming is a skill in demand! Your programming skills are bankable assets.' The output should be
{'a': 1,
'are': 1,
'assets': 1,
'bankable': 1,
'demand': 1,
'in': 1,
'is': 1,
'programming': 2,
'skill': 1,
'skills': 1,
'your': 1}
[Hint: use pprint function for printing dictionary in sorted order.
Syntax for pprint is
pprint(dictionary name)
Include the line “from pprint import pprint” in the top of your program]
Input format:
enter a paragraph
Output format:
Dictionary of words in the passage and their count
Boundary conditions:
One paragraph is entered at a strech
CODE:(Verified👍)
from pprint import pprint
s = input()+' '
s = s.replace('! ',' ').replace('? ',' ').replace('. ',' ').replace(', ',' ').replace(': ',' ').replace('; ',' ').lower()
if '!' in s or '?' in s or '.' in s or ',' in s or ':' in s or ';' in s:
    print('Invalid input')
    exit()
l = s.split()
dic = {}
for i in l:
    if i not in dic:
        dic[i] = 1
    else:
        dic[i] += 1
pprint(dic)
************************************

7 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Minimum distance points question will show HIDDEN TEST CASE FAILED because there can be more than one points for the same distance. You need to first find the minimum distance and then check for all the points that have that distance between them, and print all of them.

    ReplyDelete
  3. The code 'count words' shows a different output. Please do the needful.

    ReplyDelete
    Replies
    1. The code is correct.
      U can better use tools like skillcopy. (Though I don't support)

      Delete
  4. What is the command for identifying the common elements of two lists.

    ReplyDelete
    Replies
    1. set(list1).intersection(list2)

      Example:
      >>> list1 = [1,2,3,4,5,6]
      >>> list2 = [3, 5, 7, 9]
      >>> list(set(list1).intersection(list2))
      [3, 5]

      Delete