Simple Programming Questions and Solutions

1. Print "Hello World"

In [1]:
print("Hello World")
Hello World

2. Ask Name and Greet with that name

In [2]:
name = input('What is your name? ')
print("Hello ", name)
What is your name? Oindrila
Hello  Oindrila

3. Modify above code such that the users Sam and Bob are only greeted with their names

In [3]:
name = input('What is your name?')
if name.lower() in ['sam','bob']:
    print("Hello " +name)
What is your name?Sam
Hello Sam

4. Ask the user for a number n and prints the sum of the numbers 1 to n

In [4]:
n = int(input("Enter a number: "))
print("You have entered: ", n)

result = 0
for i in range(n+1):
    #print(i)
    result = result + i
print("The sum of numbers from 1..", n," is: " ,result)
Enter a number: 5
You have entered:  5
The sum of numbers from 1.. 5  is:  15

5. Modify the previous program such that only multiples of three or five are considered in the sum,

In [5]:
n = int(input("Enter a number: "))
print("You have entered:", n)

result = 0
for i in range(n+1):
    if (i%3 == 0) or (i%5==0):
         #print(i)
         result = result + i
print("Your answer is:" ,result)
Enter a number: 8
You have entered: 8
Your answer is: 14

6. Print odd or even

In [6]:
n = input("Enter a Number: ")
n = int(n)
if (n%2 == 0):
    print("You have entered an Even Number")
else:
    print("You have entered an Odd Number")
Enter a Number: 87
You have entered an Odd Number

7. Print a multiplication table for a given number

In [7]:
n = input("Enter a number: ")
n = int(n)
print("***Multiplation table***")
for i in range(1,11):
    print(n, 'x', i, '=', n*i)
Enter a number: 9
***Multiplation table***
9 x 1 = 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90

8. Find kth smallest element

In [8]:
def find_kth_smallest_element(arr, k):
    arr = sorted(arr)
    print("Sorted Array: ", arr)
    return(arr[k-1])
    
In [9]:
arr = [3,5,78,2,89,5,101,0,87]
find_kth_smallest_element(arr,8)
Sorted Array:  [0, 2, 3, 5, 5, 78, 87, 89, 101]
Out[9]:
89

9. Check If a Number is Prime

In [10]:
# taking input from user
number = int(input("Enter any number: "))

# prime number is always greater than 1
if number > 1:
    for i in range(2, number):
        if (number % i) == 0:
            print(number, "is not a prime number")
            break
    else:
        print(number, "is a prime number")

# if the entered number is less than or equal to 1
# then it is not prime number
else:
    print(number, "is not a prime number")
Enter any number: 67
67 is a prime number

10. Take a number and returns a list of its digits.

In [11]:
# taking input from user
number = input("Enter any number: ")
res = [int(x) for x in number] 
print(res)
Enter any number: 6789345689
[6, 7, 8, 9, 3, 4, 5, 6, 8, 9]

11. Write a program that asks the user for a number n and gives them the possibility to choose between computing the sum and computing the product of 1,…,n.

In [12]:
n = int(input("Enter a Number: "))
choice = input("Do you want to get a Sum or Product of 1..n?")
choice = choice.lower()
sum_value = 0
prod_value = 1
if choice == "sum":
    for i in range(1, n+1):
        sum_value = sum_value + i
    print("Your answer is:" ,sum_value)
elif choice == "product":
    for i in range(1,n+1):
        #print(i)
        prod_value = (prod_value * i)
    print("Your answer is:" , prod_value)
else:
    print("Please enter your choice correctly")
Enter a Number: 6
Do you want to get a Sum or Product of 1..n?product
Your answer is: 720

12. Check if a string is palindrome or not

In [13]:
def isPalindrome(s): 
    return s == s[::-1] 

a = str(input("Enter a string: "))
result = isPalindrome(a)
if result:
    print("You have entered a palindrome")
else:
    print("Your entered string is not a palindrome")
Enter a string: madam
You have entered a palindrome

13. Count the occurrence of a given character in a String

In [14]:
a = str(input("Enter a string: "))
b = input("Which character you need a count for? ")
count = 0

for i in a:
    if i.lower() == b.lower():
        count = count + 1
print("The Count is:" , count)
Enter a string: What a beautiful day!
Which character you need a count for? a
The Count is: 4

14. Write a Function such that given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.

In [15]:
def FindMissingNum(A):
    try:
        B = [x for x in A if x > 0]
        B = sorted(B)
        for i in range(len(B)):
            if (B[i+1] - B[i] > 1):
                return(B[i] + 1)
            elif (B[i+1] - B[i] == 0) or (B[i+1] - B[i] == 1):
                pass
            else:
                return(B[-1] + 1)
    except  e:
        print(e)
        
In [16]:
A = [1, 3, 6, 4, 1, 2]
FindMissingNum(A)
Out[16]:
5

15. Guess the Number Game

In [17]:
import random
print("*** Number Guessing Game***")
num = random.randint(1,99)
guess = int(input("Guess the number between 1 and 100: "))
chance = 0
while chance < 5:
    if guess == num:
        print("Congrats! You have guessed the number correct")
        break
    elif guess > num:
        print("Your guess is too high. Try again!")
        guess = int(input("Guess the number between 1 and 100 and something less than before: "))
        #chance = chance + 1
    else:
        print("Your guess is too less.Try again")
        guess = int(input("Guess the number between 1 and 100 and something more than before: "))
    
    chance = chance + 1
    
if not chance < 5: 
    print("Sorry! YOU LOSE!!! The number is", num) 
*** Number Guessing Game***
Guess the number between 1 and 100: 50
Your guess is too high. Try again!
Guess the number between 1 and 100 and something less than before: 40
Your guess is too high. Try again!
Guess the number between 1 and 100 and something less than before: 30
Your guess is too less.Try again
Guess the number between 1 and 100 and something more than before: 34
Your guess is too less.Try again
Guess the number between 1 and 100 and something more than before: 37
Your guess is too less.Try again
Guess the number between 1 and 100 and something more than before: 39
Sorry! YOU LOSE!!! The number is 38

16. Linear Search Algorithm

In [18]:
def linear_search(arr,x):
    '''check if num is present in given array arr '''
    print("The input array is: ", arr)
    print("The target number is: ", x )
    for i in range(len(arr)):
        if arr[i] == x:
            print("The target number is present in the array at: ",i)
            return(i)
        
    print("The target number is Not present in the array")
    return(-1)
In [19]:
index = linear_search([6,12,4,56,78,85,1,2,89,100],3)
The input array is:  [6, 12, 4, 56, 78, 85, 1, 2, 89, 100]
The target number is:  3
The target number is Not present in the array

17. Binray Search Algorithm

In [20]:
def binary_search(arr, x):
    '''check if num is present in given array arr '''
    print("The input array is: ", arr)
    print("The target number is: ",x )
    arr = sorted(arr)
    print("The sorted array is: ", arr)
    low = 0
    high = len(arr) - 1
    mid = 0
  
    while low <= high:  
        mid = (high + low) // 2
  
        # Check if x is present at mid 
        if arr[mid] < x: 
            low = mid + 1  
        # If x is greater, ignore left half 
        elif arr[mid] > x: 
            high = mid - 1
        # If x is smaller, ignore right half 
        else: 
            print("The targer element is present in the given array")
            return mid 
    # If we reach here, then the element was not present 
    print("The targer element is NOT present in the given array")
    return -1
  
In [21]:
index = binary_search([6,12,4,56,78,85,1,2,89,100],89)
The input array is:  [6, 12, 4, 56, 78, 85, 1, 2, 89, 100]
The target number is:  89
The sorted array is:  [1, 2, 4, 6, 12, 56, 78, 85, 89, 100]
The targer element is present in the given array

18.a. Check if a Number exist in a Matrix - Method 1

In [22]:
def matrix_search(mat,x):
    '''check if num is present in given matrix mat '''
    print("The input matrix is: ", mat)
    print("The target number is: ", x )
    rows = len(mat)
    cols = len(mat[1])
    print("Rows: ",rows , "Columns: ",cols)
    for i in range(rows):
        for j in range(cols):
            if mat[i][j] == x:
                print("The target number is present in the matrix at: ",(i,j))
                return(i,j)
                
    print("The target number is NOT present in the matrix. ")
    return(-1)
In [23]:
mat = [[4, 5, 6,7], 
       [10, 2, 13, 0], 
       [1, 11, 18, 45]
      ] 
matrix_search(mat,18)
The input matrix is:  [[4, 5, 6, 7], [10, 2, 13, 0], [1, 11, 18, 45]]
The target number is:  18
Rows:  3 Columns:  4
The target number is present in the matrix at:  (2, 2)
Out[23]:
(2, 2)

18.b. Check if a Number exist in a Matrix - Method 2

In [24]:
def matrix_search_any(mat,x):
    # using any() + list comprehension 
    result = any(x in sub for sub in mat)
    return(result)
In [25]:
mat = [[4, 5, 6,7], 
       [10, 2, 13, 0], 
       [1, 11, 18, 45]
      ] 
matrix_search_any(mat, 5)
Out[25]:
True

19. Find the Largest Number in a Matrix

In [26]:
def find_largest_num(mat):
    rows = len(mat)
    cols = len(mat[0])
    n = mat[0][0]
    
    for i in range(rows):
        for j in range(cols):
            if n < mat[i][j]:
                n = mat[i][j]
    return(n)
            
In [27]:
mat = [[4, 5, 6,7], 
       [87, 2, 13, 0], 
       [1, 11, 18, 45]
      ] 
find_largest_num(mat)
Out[27]:
87

20. Given a full name, Init capitalize the name

In [28]:
def capitalize_input(s):
    a = s.split()
    result = ''
    for i in range(len(a)):
        result = result + " " +a[i].capitalize()
    return(result)    
In [29]:
capitalize_input('oindrila sen')
Out[29]:
' Oindrila Sen'
In [ ]: