0% found this document useful (0 votes)
108 views15 pages

ITA 6017 - Python Programming Challenging Cyclesheet Name - Anjali Sharma Reg. No. - 19MCA0210

Here is a password generator program that meets the requirements: import random import string def generate_password(): chars = string.ascii_letters + string.digits + string.punctuation password = "".join(random.choice(chars) for i in range(12)) return password def main(): while True: print("Here is a randomly generated password:") print(generate_password()) if input("Would you like another password? (y/n) ").lower() != "y": break if __name__ == "__main__": main() This program imports the random and string modules. It defines a generate_password() function that concatenates 12 random

Uploaded by

anjali sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views15 pages

ITA 6017 - Python Programming Challenging Cyclesheet Name - Anjali Sharma Reg. No. - 19MCA0210

Here is a password generator program that meets the requirements: import random import string def generate_password(): chars = string.ascii_letters + string.digits + string.punctuation password = "".join(random.choice(chars) for i in range(12)) return password def main(): while True: print("Here is a randomly generated password:") print(generate_password()) if input("Would you like another password? (y/n) ").lower() != "y": break if __name__ == "__main__": main() This program imports the random and string modules. It defines a generate_password() function that concatenates 12 random

Uploaded by

anjali sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

ITA 6017 – Python Programming

Challenging Cyclesheet
Name – Anjali Sharma
Reg. No. – 19MCA0210

1. Given an English word, write an algorithm and the subsequent Python code to check if the
given word can be typed using just a single row of the keyboard. (e.g. POTTER, EQUITY). Print
‘Yes’ if the letters of the word are from a single row and print ‘No’ otherwise.
Algorithm –
Step 1 – Take a string as an input.
Step 2 – Create a flag variable and set its value to True.
Step 3 – Check if the given word can be typed using just a single row of the keyboard.
Step 4 – End.

Code –
row1 = "qwertyuiop"
row2 = "asdfghjkl"
row3 = "zxcvbnm"
s = input("Enter your string")
s = s.lower()
flag = True
if s[0] in row1:
for i in s:
if i not in row1:
flag = False
elif s[0] in row2:
for i in s:
if i not in row2:
flag = False
elif s[0] in row3:
for i in s:
if i not in row3:
flag = False
if flag == True:
print("Yes")
else:
print("No")

Output –

1
2. Pangrams are words or sentences containing every letter of the English alphabet at the least
once. Write an algorithm and a subsequent Python code to check whether a string is a pangram
or not. Write a function to check if a given string is a pangram.

Algorithm –
Step1 - define the function Pangram with one parameter s
Step 2 - remove all the whitespace characters in the string and join the words.
Step 3 -convert all the letters to lowercase to make the string case insensitive
Step 4 -check if length of the string s is equal to all the unique letters in the string s if yes
then display the string is a Pangram else display not Pangram
Step 5 - get the string s
Step 6 -call the function Pangram with s as the actual parameter to check whether its a
Pangram or not
Step 7 -End

Code –
def Pangram(a):
a = ''.join(a.split())
a = a.lower()
if len(set(a))>=26:
print('Pangram')
else:
print('Not pangram')
a = input().rstrip()
Pangram(a)

Output –

2
3. Write appropriate functions for changing GMT to IST.Check boundary conditions and print
‘Invalid input’ for wrong input.

Code –
days=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunda
y"]
day=input().rstrip()
hours_min=int(input())*60
minutes=int(input())
total=hours_min+minutes+330
if hours_min>0 and hours_min<24*60 and minutes>0 and minutes<60 and day in days:
if total>=1440:
for i in range(len(days)-1):
if day==days[i]:
print(days[i+1])
break
print(total//60-24)
print(total%60)
else:
print(day)
print(total//60)
print(total%60)
else:
print("Invalid input")

Output –

3
4. Given a number, write Python code to check whether the given number is deficient or not.

Code –
import math
def divsum(n) :
sum = 0
i=1
while i<= math.sqrt(n) :
if (n % i == 0) :

if (n / i == i) :
sum = sum + i
else :
sum = sum + i;
sum = sum + (n / i)
i=i+1
return sum
def isDef(n) :

return (divsum(n) < (2 * n))

n = int(input("Enter the number"))


if ( isDef(n) ):
print("The number is deficient.")
else :
print("The number is not deficient.")

Output –

4
5. Write a Python program to identify the pair of computers from the same locality.

Code –
def localPC(ip_list):
for i in range(len(ip_list)-1):
ip_1 = ip_list[i].split(".")
for j in range(i+1, len(ip_list)):
ip_2 = ip_list[j].split(".")
if int(ip_1[0]) == int(ip_2[0]) and int(ip_1[1]) == int(ip_2[1]):
print("Machines {} and {} are on the same local network".format(i+1,j+1))

def main():
try:
ip_list = []
for i in range(int(input("Number of computers :"))):
ip_list += [input("IP address of the computer {} :".format(i+1)).strip()]
localPC(ip_list)
except:
pass

main()
Output –

6. Write a Python program to read a noun and print their plurals on the basis of the following
rules:
a. If noun ends in “y”, remove the “y” and add“ies”.

b. If noun ends in “s”, “ch”, or “sh”, add“es”.

c. In all other cases, just add“s”.

Code –

5
def _singular_to_plural(noun):
if noun.endswith('y'):
return noun[:len(noun)-1] + 'ies'
if noun.endswith('s') or noun.endswith('ch') or noun.endswith('sh'):
return noun[:] + 'es'
return noun[:] + 's'

def main():
try:
noun = input("Enter a noun :").strip()
print("Plural of the noun is :", _singular_to_plural(noun))
except:
print('Error')
main()
Output –

7. Consider a nxn board game with four types of coins red, green, blue and yellow. Given the
state of the board with coins in all cells, develop an algorithm and write a python program to
check if the same coins are placed in ‘L’ shape on the board. The number of cells in the vertical
and horizontal line of ‘L’ shape should be same and should be greater than 1. Red coins are
represented by ‘r’, blue coins are represented by ‘b’, green coins are represented by ‘g’ and
yellow coins are represented by ‘y’.
Algorithm –
Step 1 – declare a global variable

6
Step 2 – Take a 2x2 matrix and check for L shape pattern. Match the diaagonal element.
Step 3 – If L shape pattern exist then return True else return False.
Step 4 – Now take input in list and convert the list into numpy array. Use global variable so that
array can be used by other functions and the size of the array provided must be greater than 1
and it should be square matrix.
Step 5 – Exit the loop once found the L sahpe pattern.
Step 6 – End.
Code –
import numpy as np
List = []
def findPattern(i , j):
return (List[i][j-1] == List[i][j]== List[i+1][j]) or (List[i+1][j] == List[i+1][j-1]== List[i][j])

def main():
try:
global List
row = 4

List = np.array([list(map(str, input("Enter row :").strip().split())) for _ in range(row)])

for i in range(row - 1):


for j in range(1,row - 1):
if findPattern(i,j):
raise Exception('Pattern Exist')
else:
print("Doesn't exist")
except Exception as e:
print(e)
main()
Output –

7
8. Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input),
compare them, print out a message of congratulations to the winner, and ask if the players
want to start a new game)
Remember the rules:

Rock beats scissors


Scissors beats paper
Paper beats rock

Algorithm –

Step 1 – define a function that starts a game of Rock,Paper and Scissor.


Step 2 – define two variables as player_1 and player_2.
Step 3 – define conditions using if else and nesting of loops.
Step 4 – Also specify whether the user want to play again or not.
Step 5 – End.
Code –
def playGame():

print("R for Rock")


print("P for Paper")
print("S for scissors")

while True:
player_1 = input("Enter your choice(1) :").strip()
player_2 = input("Enter your choice(2) :").strip()

if player_1 != player_2:
if player_1 == "R":
if player_2 == "P":
print("Player 2 wins")

else:
print("Player 1 wins")
elif player_1 == "P":

8
if player_2 == "S":
print("Player 2 wins")
else:
print("Player 1 wins")
else:
if player_2 == "R":
print("Player 2 wins")
else:
print("Player 1 wins")
else:
print("Draw")

if input("Do you want to play again [Y/N]:").strip() not in ['Y','y','yes','YES']:


break
print('Bye')

def main():
try:
playGame()
except:
pass
main()

Output –

9. Write a password generator in Python. Be creative with how you generate passwords - strong
passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The
passwords should be random, generating a new password every time the user asks for a new
password. Include your run-time code in a main method.

9
Code –
import string
import random

def generatePassword(size = 8, resource = string.ascii_letters + string.punctuation):

return "".join(random.choice(resource) for _ in range(size))

def main():
try:
if input("Do you want a strong password [y/n]:").strip() in ['y','Y','yes','Yes']:
password = generatePassword()

else:
password = generatePassword(size = 5, resource = string.ascii_lowercase)
print("Your password is '{}'".format(password))
except:
pass
main()
Output –

10. For this exercise, we will keep track of when our friend’s birthdays are, and be able to find
that information based on their name. Create a dictionary (in your file) of names and birthdays.
When you run your program it should ask the user to enter a name, and return the birthday of
that person back to them. The interaction should look something like this:

>>> Welcome to the birthday dictionary. We know the birthdays of: Albert Einstein
Benjamin Franklin Ada Lovelace
>>> Who's birthday do you want to look up? Benjamin Franklin
>>> Benjamin Franklin's birthday is 01/17/1706.

Code –
def main():

10
try:

name_dict = {

'Anjali Sharma':'26/11/1998',

'Akansha':'10/06/1998',

'Nidhi Sharma':'10/12/1996'

print('Welcome to the birthday dictionary. We know the birthdays of :')

print(*name_dict.keys(), sep="\n")

name = input("Who's birthday do you want to look up ? ").strip()

if name in name_dict:

print("{}'s birthday is {}".format(name, name_dict[name]))

else:

print("Sorry! No Match")

except Exception as e:

print(e)

main()

Output –

11. Write the Python code to store the members of the two teams as dictionaries, print the new
(concatenated) dictionary with the names in an increasing order of experience, to check whether
a given name is present in the new dictionary or not and to print the name of the chairperson of
the new team.

11
Code –
def userInput():
team_1 = {}
team_2 = {}
count_dict = { 0 : 'First',
1 : 'Second',
2 : 'Third'
}
print("Enter the details of first team")
for i in range(1):
str1 = "Name of the {} member :".format(count_dict[i])
str2 = "Experience (in years) of the {} member :".format(count_dict[i])
key = input(str1).strip()
team_1[key] = int(input(str2).strip())

print()
print("Enter the details of second team")

for i in range(1):
str1 = "Name of the {} member :".format(count_dict[i])
str2 = "Experience (in years) of the {} member :".format(count_dict[i])
key = input(str1).strip()
team_2[key] = int(input(str2).strip())
team_1.update(team_2)

temp_storage = sorted(list(team_1.items()), key = lambda e:e[1],reverse = True)


del temp_storage[len(temp_storage)-1]

new_team = dict(temp_storage)
if input("Enter the name to be checked in the new team : ") in new_team:
print("Exists")
else:
print("Not Exists")
print(new_team)
print("Chairperson of the new team is {}".format(list(new_team.keys())[0]))

def main():
try:
userInput()
except Exception as e:
print(e)
main()

12
Output –

12. At the end of the survey the scores of the individual metrics are added up to get the total
score and the institutes are ranked based on the total score. The institute that scores the highest
score is ranked 1st. Next highest score is given the rank 2 and so on. Write a program to read the
scores of the three metrics for each institute, store the scores in a list. Make a list of individual
score list for 10 institutes. Print only the Total score in the sorted (Descending) order. Use
insertion sort for arranging the data in descending order.

Code –
def insertion_sort(List):
for i in range(1, len(List)):
if List[i]>List[i-1]:
key = List[i]
j = i-1
while j >= 0 and key > List[j]:
List[j+1]=List[j]
j -= 1
List[j+1] = key
return List

def rankUniversity(rankMatrix):
return insertion_sort(list(map(sum, rankMatrix)))

def main():
try:
scoreMatrix = [list(map(int , input("Enter value :").strip().split())) for _ in range(3)]
rankList = rankUniversity(scoreMatrix)
print("Individual score of each University")

13
print(*scoreMatrix, sep="\n")
print("Ranking Matrix")
print(rankList)
except Exception as e:
print(e)
main()

Output –

14
15

You might also like