Chapter 02 - Python Revision Tour - II

Chapter 02 - Python Revision Tour - II

1. Write a program that prompts for a phone number of 10 digits and two dashes, with dashes after the area code and the next three numbers. For example, 017-555-1212 is a legal input.

Display if the phone number entered is valid format or not(i.e., contains just the digits and dash at specific places).
phoneNo=input('Please enter a phone number e.g,017-555-1212: ')
if len(phoneNo)==12 and (phoneNo[3] and phoneNo[7])=='-':
 print('The entered phone number is valid')
else:
 print('The entered phone number is invalid')       
2.Write a program that should prompt the user to type some sentence(s) followed by "enter". It should then print the original sentence(s) and the following statistics relating to the sentence(s):
  • Number of words
  • Number of characters(including white-space and punctuation)
  • Percentage of character that are alpha numeric
Hints
  • Assume any consecutive sequence of non-blank characters is a word.
sentence=input("Enter: ")
print(sentence)
alist=sentence.split()
blist=''.join(alist)
print('Number of Words: ', len(alist))
print('Number of characters: ',len(sentence))
alp_char=len(blist)
non_alp_char=len(sentence)-alp_char
print('Number of alphanumeric characters: ',alp_char)
print('Number of non-alphanumeric characters: ',non_alp_char)
print('Percentage of alphanumeric character: ',(alp_char/len(sentence))*100,'%')      
3. Write a program that takes any two lists L and M of the same size and adds their elements together to form a new list N whose elements are sums of the corresponding elements in L and M. For instance, if L=[3, 1, 4] and M=[1, 5, 9] then N should equal [4, 6, 13].
L=[3,1,4]
M=[1,5,9]
N=[]
 
for x in range(len(L)):
 N.append(L[x]+M[x])

print('Elements of L = ', L)
print('Elements of M = ', M)
print('Adding elements of L and M together = ', N)         
4. Write a program that rotates the elements of a list so that the element at the first index moves to the second index, the element in the second index moves to the third index, etc., and the element in the last moves to the first index.
myList = [1, 2, 3, 4, 5]
print('List: ', myList)

myList=(myList[-1:] + myList[:-1])
print('After rotating: ', myList)     
5. Write a short Python code segment that prints the longest word in a list of words.
string_lengths_list = []
str_list = ['abcdeg', 'abacate', 'pera', 'goiaba', 'udfdfsva', 'abacaxi', 'laranja', 'maca'] 
print('Given list of strings: ',str_list)   

for x in str_list:
    string_lengths_list.append(len(x))

maximum_length_of_string = max(string_lengths_list)

for y in str_list:
 if len(y) == maximum_length_of_string:
  print('\nThe longest string of length ',maximum_length_of_string, ' is ',y)    
6. Write a program that creates a list of all the integers less that 100 that are multiples of 3 or 5.
integerList=[]
for i in range(0,100):
 if i%3==0 or i%5==0:
  integerList.append(i)

print(integerList)     
7. Define two variable first and second so that first ='Jimmy' and second='Johnny'. Write a short Python code segment that swaps the values assigned to these two variables and prints the results.
first='Jimmy'
second='Johnny'
print("Before Swap:")
print('first : ',first)
print('second: ',second)
third=first
first=second
second=third
print('\nAfter swapping:')
print('first : ',first)
print('second: ',second)
8. Write a Python program that creates a tuple storing first 9 terms of Fibonacci series.
fib=(0,)
n=int(input('Please enter a number '))
a,b=0,1
for i in range(n):
 a, b = b, a+b
 fib=fib+(a,)
print(fib)      
9. Create a dictionary whose keys are month names and whose values are the number of days in the corresponding months.

a. Ask the user to enter month name and use the dictionary to tell how many days are in the month.

b. Print out all the keys in alphabetical order.
c. Print out all of the months with 31 days
d. Print out the (key-value) pairs sorted by the number of days in each month.
Calendar2018 = {
'january' : 31,
'february' : 28,
'march' : 31,
'april' : 30,
'may' : 31,
'june' : 30,
'july' : 31,
'august' : 31,
'september' : 30,
'october' : 31,
'november' : 30,
'december' : 31
}

monthName=str(input("Please enter a month name: "))
monthName=monthName.lower()

if monthName in Calendar2018:
 print('\nThe month ',monthName,' has ',Calendar2018[monthName],'days\n')
else:
 print("the month doesnt exist")

sortedkeys = sorted(Calendar2018)
print('\nThe months in alphabetical order:\n')
for i in sortedkeys:
 print(i)

print("\nAll months with 31 days are as under: \n")
for month in Calendar2018:
 if Calendar2018[month]==31:
  print(month)

sortedByValues=sorted(Calendar2018.items(), key=lambda x: x[1])

print("\nThe (key-value) pairs sorted by the number of days in each month are as under.\n")

for i in range(len(sortedByValues)):
 print(sortedByValues[i])        
10.Write a function called addDict(dict1, dict2) which computes the union of two dictionaries. It should return a new dictionary; with all the items in both its arguments (assumed to be dictionaries). If the same key appears in both arguments, feel free to pick a value from either.

def addDict(dic1, dic2):
    dic3={}
    dic3.update(dic1)
    dic3.update(dic2)
    return dic3
dict1 = {'a': 10, 'b': 8,'e':1} 
dict2 = {'d': 6, 'c': 4,'e':2} 

print(addDict(dict1, dict2)) 
11. Write a program to sort a dictionary's keys using Bubble sort and produce the sorted keys as a list.
sample_dictionary={'name':'jack','salary':10000,'Age':24}
key_list=list(sample_dictionary.keys())
def bubbleSort(key_list):
    n = len(key_list)
    for i in range(n):
        for j in range(0, n-i-1):
            if key_list[j] > key_list[j+1] :
                key_list[j], key_list[j+1] = key_list[j+1], key_list[j]

bubbleSort(key_list)

print (key_list)     
12. Write a program to sort a dictionary's values using Bubble sort and produce the sorted values as a list.
sample_dictionary={'Height':170,'salary':10000,'Age':19}
value_list=list(sample_dictionary.values())
def bubbleSort(key_list):
    n = len(key_list)
    for i in range(n):
        for j in range(0, n-i-1):
            if key_list[j] > key_list[j+1] :
                key_list[j], key_list[j+1] = key_list[j+1], key_list[j]

bubbleSort(value_list)

print (value_list)      

Comments

Popular posts from this blog

Chapter 05 - File Handling

Dictionary (Python)

Tuple (Python)