Saturday, June 10, 2017

Count of common factors

Given a set of numbers, the program must find the count of the common factors C excluding 1. 

Input Format: 

First line will contain the integer value N representing how many numbers are passed as input. Next N lines will have the numbers. 
Output Format: 
First line will contain the count of common factors C.

Sample Input/Output: 

Example 1: 
Input: 
100 
75 

Output: 

Explanation: The common factors excluding 1 are 5,25. Hence output is 2 

Example 2: 
Input: 
10 
20 
30 

Output: 
3

Explanation: The common factors excluding 1 are 2,5,10. Hence output is 3

Solution:

from fractions import gcd
from math import sqrt
import functools
n = []
for _ in range(int(input())):
    n.append(int(input()))

g = functools.reduce(gcd,n)
c = 0
for i in range(1,int(sqrt(g))+1):
    if g%i == 0:
        if g/i == i:
            c += 1
        else:
            c += 2
print(c-1)
Share:

Friday, June 9, 2017

Ways to repay loan

A poor man borrows a sum of N rupees from his neighbour. The neighbour is kind enough not to impose any interest on the loan. The poor man agrees to re-pay the loan by paying back either 1 rupee or 2 rupees to his neighbour. In how many distinct ways can he repay the loan? 

Input Format: 

The first line will contain the value of N which is the loan amount. 

Output Format: 

The first line will contain the number of distinct ways in which the loan can be repaid.  

Example Input/Output 1: 

Input: 

Output: 

Example Input/Output 3: 

Input: 

Output: 

Explanation: 
The loan can be re-paid as 
1,1,1,1,1 or 
1,1,1,2 or 
1,2,2 or 
1,1,2,1 or 
1,2,1,1 or 
2,2,1 or 
2,1,2 or 
2,1,1,1

Solution: 


n = int(input())
a = 0
b = 1
i = 0
while i<n:
    c = a+b
    a = b
    b = c
    i += 1
print(c)

Share:

Thursday, June 8, 2017

Number Odd and Even digit sum

A number N is passed as input to the program. If N has odd number of digits, the program must print "NotAccepted" and exit. If N has even number of digits, the program must print the sum of digits in odd position and also must print the sum of digits in the even position.

Input Format:

The first line contains the value of N

Output Format:

The first line contains the sum of digits in the odd positions or the value "NotAccepted"
The second line (if Accepted) contains the sum of digits in the even positions.

Example Input/Output 1:

Input:
1234

Output:
4
6

Example Input/Output 2:

 Input:
 156

 Output:
 NotAccepted

Solution:

n = input()
o = 0
e = 0
if len(n)%2 != 0:
    print("NotAccepted")
else:
    for i in range(len(n)):
        if i % 2 == 0:
            o += int(n[i])
        else:
            e += int(n[i])
    print(o)
    print(e)


Share:

String - Characters count

A string S containing N unique characters is passed as input to the program. The program must print the character and it's occurrence count in N lines of output. The characters with their count in the output are in the same order of occurrence as in the string S. Note: All the characters will be alphabets and in lower case. 

Input Format: 

The first line contains the value of S 

Output Format: 

N lines containing the character and it's count. 

Example Input/Output 1:

Input: 
programming 

Output: 
p1 
r2 
o1 
g2 
a1 
m2 
i1 
n1 

Example Input/Output 2: 

Input: 
engineering 

Output: 
e3 
n3 
g2 
i2 
r1

Solution: 

s = input()
c = [0]*26
a = []*len(s)
for i in range(len(s)):
    c[ord(s[i])-ord('a')] += 1
    if c[ord(s[i])-ord('a')] == 1:
        a.append(s[i])
for i in range(len(a)):
    print(a[i]+str(c[ord(a[i])-ord('a')]))


Share:

Anagrams

Write a program to find whether the 2 given strings are anagrams or not. Anagrams are words or phrases made by mixing up the letters of other words or phrases, 

Input and Output Format: 


Input consists of 2 string. Assume that all characters in the string are lowercase letters or spaces and the maximum length of the string is 100. Refer sample input and output for formatting specifications. All text in bold corresponds to input and the rest corresponds to output. 

Sample Input and Output 1:


Enter the first string
anitha
Enter the second string
amphisoft 
anitha and amphisoft are not anagrams 

Sample Input and Output 2:


Enter the first string
the eyes 
Enter the second string
they see 
the eyes and they see are anagrams

Solution:

Method – 1:

print('Enter the first string')
str1=input()
print('Enter the second string')
str2=input()
from collections import Counter
if Counter(str1)== Counter(str2):
    print(str1+' and '+str2+' are anagrams')
else:
    print(str1+' and '+str2+' are not anagrams') 

Method – 2:

def anagram(s1,s2):
 if len(s1) is len(s2):
  count1=[0]*25
  count2=[0]*25
  for i in range(len(s1)):
     count1[ord(s1[i])-ord('a')]+=1
     count2[ord(s2[i])-ord('a')]+=1
  for i in range(25):
     if count1[i] is not count2[i]:
         return 0
  return 1
 else:
  return 0

print('Enter the first string')
str1=input()
print('Enter the second string')
str2=input()
if anagram(str1,str2):
  print(str1+' and '+str2+' are anagrams')
else:
    print(str1 + ' and ' + str2 + ' are not anagrams')


Share:

Strong password check

Recently a security committee decided to enforce the following rules when an employee creates/changes his/her password. 

- The password must contain atleast one special character among # ! _ $ @ 
- The password must contain atleast two numbers
- The password must contain atleast one upper case alphabet and one lower case alphabet. 
- The password must have a minimum length of 8. 
- The password must have a maximum length of 25. 

The program must accept a given password string P as input and check for these rules and output VALID or INVALID. Boundary Conditions: Length of P is from 2 to 50. 

Input Format: 

First line will contain the string value of the password P 

Output Format: 

VALID or INVALID based on the check performed by the program by applying the rules. 

Example Input/Output:

Example 2: 
Input: 
kiC_3b0x3r 

Output: 
VALID 

Example 2: 
Input: 
m@d31nindia 

Output: 
INVALID 

Explanation: No alphabet in uppercase. 

Solution:

s = input().strip()
if 8 <= len(s) <= 25:
    n,sp = 0,0
    for i in s:
        if i in '0123456789': n += 1
        elif i in '#!_$@': sp += 1
    if n >= 2 and sp >= 1 and (any(x.islower() for x in s)) and (any(x.isupper() for x in s)):
        print('VALID')
    else:
        print('INVALID')
else:

    print('INVALID')
Share:

Tuesday, June 6, 2017

Kaprekar number

A Kaprekar number is a number whose square when divided into two parts and such that sum of parts is equal to the original number and none of the parts has value 0. 
Given a number, the task is to check if it is Kaprekar number or not.

Input : n = 13
Output : No
Explanation : 13^2 = 169. Neither 16 + 9 nor 1 + 69 is equal to 13

Input  : n = 297 
Output : Yes
Explanation:  297^2 = 88209 and 88 + 209 is 297

Input  : n = 10
Output : No
Explanation:  10^2 = 100. It is not a Kaprekar number even if sum of 100 + 0 is 100. This is because of the condition that none of the parts should have value 0.

Solution:

n = int(input())
sq = n*n
r = 0
i = 0
while sq:
      r = (sq%10)*(10**i) + r
      sq = int(sq/10)
      i += 1
      if r + sq == n:
           break
s = "Yes" if sq + r == n and r != 0 else "No"
print(s)


Share:

Rotate Matrix 90 Degree Anti-Clockwise

A MxN matrix is passed as the input. The program must rotate the matrix by 90 degrees in anti-clock wise direction and print the rotated matrix as the output.

Input Format: 

First line will contain the value of M. Second line will contain the value of N. Next M lines will contain the N values with each value separated by one or more space.

 Output Format:

 N lines will contain the M values with each value separated by one or more space.

Boundary Conditions: 

2 <= M <= 15 2 <= N <= 15

Example Input/Output 1: 

Input:
2
3
4 5 9
1 3 5

Output:
9 5
5 3
4 1

Solution:

row = int(input())
col = int(input())
mat = [0]*row

for i in range(row):
    mat[i] = [int(x) for x in input().strip().split()]

for i in range(col-1,-1,-1):
    for j in range(row):
        print(mat[j][i]," ", end = '')
    print('\r')
Share:

Monday, June 5, 2017

Chars To Remove For Same String Value

N string values S1, S2, S3, SN are passed as input to the program. Values of S1, S2, S3, SN are such that if one character is removed from each of these string values, then the resulting string values are equal (same). The characters to be removed from the string values named C1, C2, C3, CN will be different for each string.

Input Format: 

The first line will contain the value of N. The next N lines will contain the values of strings S1 to SN.

Boundary Conditions: 

2 <= N <= 10 Length of string SN is from 2 to 200

Output Format: 

The first line will contain the characters C1, C2, C3, .. CN to be removed from each of these string without any space between them.

Example Input/Output : 

Input:
2
bmanabgerb
manasgsesr

Output:
bs

Explanation:
If the character b is removed from the first string, it becomes manager. If the character s is removed from the second string, it becomes manager. Hence bs is printed as output.

Solution:

n = int(input())
nstring = [] 

for i in range(n):
    nstring += set(list(input().strip()))   

count = [0]*26

for char in nstring:
    count[ord(char)-ord('a')]+=1   

for char in nstring:
    if count[ord(char)-ord('a')]==1:
         print(char,end='')
Share:

Sunday, June 4, 2017

Reverse Pattern Printing - Numbers

Numbers Based on the input value of N, the program must print the pattern described below.

Input Format: 

First line will contain the value of N.

Output Format:

 N lines will contain the number pattern as described below with each value separated by a single space.

Boundary Conditions: 

1 <= N <= 50

 Example Input/Output : 

Input:
5

Output:
15 10 6 3 1
14 9 5 2
13 8 4
12 7
11

Solution:

n = int(input())

# calculate the total no of elements in upper diagonal
d = int((n * n) - (n * (n - 1)) / 2)  

for i in range(n):
    s = d - i
    for j in range(n, i, -1):
        print(s, end=" ")
        s -= j
    print('\r')

Share:

Saturday, June 3, 2017

Flipping the Matrix

Sean invented a game involving a  matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times, and the goal of the game is to maximize the sum of the elements in the  submatrix located in the upper-left corner of the  matrix (i.e., its upper-left quadrant).
Given the initial configurations for  matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal. For each matrix, print the maximized sum on a new line.
Input Format
The first line contains an integer, , denoting the number of queries. The subsequent lines describe each of the  queries in the following format:
  1. The first line of each query contains an integer, .
  2. Each line  the  subsequent lines contains  space-separated integers describing the respective values of row  in the matrix.
Output Format
You must print  lines of output. For each query (i.e., matrix), print the maximum possible sum of the elements in the matrix's upper-left quadrant.
Sample Input
1
2
112 42 83 119
56 125 56 49
15 78 101 43
62 98 114 108
Sample Output
414
Explanation
We start out with the following  matrix:
We can perform the following operations to maximize the sum of the  submatrix in the upper-left corner:
  1. Reverse column  (), resulting in the matrix: 
  2. Reverse row  (), resulting in the matrix: 
When we sum the values in the  submatrix in the upper-left quadrant, we get . Thus, we print  on a new line.
Solution:

for _ in range(int(input())):
    n = int(input()) 
    n2 = 2 * n
    maxSum = 0
    
    matrix = [0] * n2
    
    for i in range(n2):
        matrix[i] = [int(x) for x in input().strip().split()]
    for i in range(n):
        for j in range(n):
            maxSum += max([matrix[i][j],matrix[i][n2-1-j], matrix[n2-1-i][j],matrix[n2-1-i][n2-1-j]])
                   
    print (maxSum)
Share: