Sunday, 20 August 2017

Python Basic Programs-1

1. Character Input:
name = input("Enter you name: ")
print("You name is: "+ name)

2. Divisors:
num = int(input("Enter the valid number: "))
divlst = []
for n in list(range(1,num+1)):
    if num % n == 0:
        divlst.append(n)
print(divlst)

3. Find even list
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
evenlst = []
for num in a:
    if num % 2 == 0:
        evenlst.append(num)

print("the new even list is", evenlst)
or
evenlst = [number for number in a if number % 2 == 0]
print("the new even list is", evenlst)

4. Fibonacci series
def fib(n):
    a = 0
    b = 1
    for i in range(1,n+1):
            c = a + b
            print (b,end=" ") ## to print in single line
            a = b
            b = c

print(fib(5))
 

5. Print list having numbers less than 10
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
numlst = []
for num in a:
    if num < 10:
        numlst.append(num)

print(numlst)

6. Find common elements between two lists
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# First convert the list to set
a = set([1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89])
print(type(a))
b = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
print(type(b))
res = a.intersection(b)
print("common elements: ", res)

7. Find max of three values
def max_3(a,b,c):
    if (a>b) and (a>c):
        return a
    if (b>a) and (b>c):
        return b
    if (c>a) and (c>b):
        return c
print("Max value is : ", max_3(7,3,9))

8. Find new list having 1st and last element
newlst = []
def test(lst):
    newlst.append(lst[0])
    newlst.append(lst[-1])
    print(newlst)
lst = [1,2,3,4,5,6,7]
test(lst)

9. Find odd or even number
num = int(input("Enter the number "))
if num %2 == 0:
    print(num, "is the even number")
else:
    print( num, "is the odd number")

10. Find if element is present in given list
def find(ordered_list, element_to_find):
    for element in ordered_list:
        if element == element_to_find:
            return True
    return False

l = [1,2,3,4,5]
print(find(l,10))

11. Find if given string is palindrome
name = input("Enter the string: ")
if name[::] == name[::-1]:
    print(name, "is a palindrome")
else:
    print(name, "is not a palindrome")

12. Find if number is prime or not
num = int(input("Enter a number: "))
if num %2 != 0 or num == 1:
    print(num , "is a prime number")
else:
    print(num, "is not a prime number")

11. Find the sum of two numbers
a = input ("Enter the value of a : ")
b = input ("Enter the value of b : ")
#Note :By defult input takes a string
res = int(a) + int(b)
print("Final ans = ", res)

12. Remove duplicate values from a list
lst = [1,1,2,3,4,5,4,2,10,15,5,6]
newlst = set(lst)
print(newlst)

13. Reverse the order
 def rev(str):
    str = input("Enter the sentence: ")
    new = str[::-1]
    print(new)
rev(str)

14. Square of all numbers
numlst = [1,2,3,4,5,6,7,8]
reslst=list(map(lambda x : x*x, numlst))
print(reslst)

15. Find missing number in list

def missing_no(lst):
    #print(range(lst[0],lst[-1]+1))
    return sum(range(lst[0],lst[-1]+1)) -sum(lst)
lst = [1,2,3,5,6]
print(missing_no(lst))

16. Find power of 2
def powerof2(num):
    ## bitwise calculation
    return ((num & (num - 1)) == 0) and (num != 0)
print(powerof2(8))

17.Print Calender for a given month and year.
import calendar
y = int(input("Input the year: "))
m = int(input("Input the month: "))
print(calendar.month(y,m))

18. Write a Python program to calculate the sum and average of n integer numbers(input from the user). Input 0 to finish.
print("Input some integers to calculate the sum and average. Input 0 for exit")
sum = 0
count = 0
lst = [1,3,4,5,9]
for n in lst:
    sum += n
    count += 1
if count == 0:
    print("Input some numbers")
else:
    print("Average and sum of numbers: ", sum/count, sum)

19. Write a Python program to create the multiplication table (from 1 to 10) of a number
n = int(input("input the number to create multiplication table: "))
for i in range(1,11):
    print(n, 'x', i, "=", n*i)

#Remember
n = 5      ## type is int
n = "5"  ## type is str


20.  Write a Python program to construct the following pattern, using a nested loop number
1
22
333
4444
55555
666666
7777777
88888888
999999999

for i in range(1,10):
    print(str(i)*i)

21. Write a Python script to concatenate following dictionaries to create a new one
dic = {}
dic1 = {1:10,2:20}
dic2 = {3:30,4:40}
dic3 = {5:50,6:60}
for d in (dic1, dic2, dic3):
    dic.update(d)
print(dic)

22. Write a Python program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and 2700 (both included)
lst = []
for n in range(1500,2701):
    if n%7 == 0 and n%5 == 0:
        lst.append(n)
print(lst)


23. Write a Python program to construct the following pattern, using a nested for loop.
* * 
* * * 
* * * * 
* * * * * 
* * * * 
* * * 
* * 
*

n = 5
for i in range(5):
    for j in range(i):
        print('* ', end='')
    print("")

for i in range(n,0,-1):
    for j in range(i):
        print("* ", end="")
    print('')


24. Write a Python program that accepts a word from the user and reverse it
word = input("Enter the word: ")
res = word[::-1]
print(res)

25. Write a Python program to count the number of even and odd numbers from a series of numbers
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
even_num = []
odd_num = []
for n in numbers:
    if n%2 == 0:
        even_num.append(n)
    else:
        odd_num.append(n)
print("Number of even numbers: ", len(even_num))
print("Number of odd numbers: ", len(odd_num))

#ALITER

numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
even_count = 0
odd_count = 0
for n in numbers:
    if n%2 == 0:
        even_count += 1
    else:
        odd_count += 1

print("Number of even numbers: ", even_count)
print("Number of odd numbers: ", odd_count)
#ALITER

even_num = len([n for n in numbers if n % 2 == 0])
odd_num = len([n for n in numbers if n % 2 != 0])

26. Write a Python program that prints each item and its corresponding type from the following list
datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {"class":'V', "section":'A'}]
print(datalist)
for item in datalist:
    print(item, type(item))
    
27.Write a Python program that prints all the numbers from 0 to 6 except 3 and 6
lst = []
for i in range(0,7):
    if i == 3 or i == 6:
        continue
    lst.append(i)
print(lst)

28. Write a Python program to print Fibonacci series b/t 0 to 50
x,y=0,1
while y<50: div="">
    print(y)
    x,y = y,x+y

#ALITER
    
def fib(num):
    a,b = 0,1
    for num in range(num):
        if a < num:
            yield a
            a,b =b,a+b
print(list(fib(50)))

29. Write a Python program which takes two digits m (row) and n (column) as input and generates a two-dimensional array. The element value in the i-th row and j-th column of the array should be i*j
row_num = int(input("Input number of rows: "))
col_num = int(input("Input number of columns: "))
multi_list = [[0 for col in range(col_num)] for row in range(row_num)]

for row in range(row_num):
    for col in range(col_num):
        multi_list[row][col]= row*col

print(multi_list)

#ALITER
        
row = 2
column = 3
a = [[i*j for j in range(column)] for i in range(row)]
print(a)

30. Write a Python program that accepts a string and calculate the number of digits and letters
data = "Python 3.2"
d=l=0
for i in data:
    if i.isdigit():
        d += 1
    elif i.isalpha():
        l += 1
    else:
        pass
print("letters: ", l)
print("digits: ", d)

31. Write a Python program to check whether an alphabet is a vowel or consonant
char = input("Input the letter of the alphabet: ")
if char in ('a','e','i','o','u'):
    print("%s is a vowel " % char)
else:
    print("%s is a consonant " % char)

32. Add key to dictionary
dict1 = {0:10, 1:20}
dict1[2] = "30"
print(dict1)

33.Write a Python script to check if a given key already exists in a dictionary
dict={1:"one",2:"two",3:"three"}
print(dict)
print(dict.keys())
print(dict.values())

key = input("Enter the value of key ")
for k in dict:
    if k == key:
        print("Entered key %s is already there", key)
    else:
        print("Entered key is not present")

34. Write a Python program to iterate over dictionaries using for loops
d = {"blue" : 1, "green" : 2, "yellow" : 3}
for key,value in d.items():
    print(key, value)

35. Write a Python program to map two lists into a dictionary
keys = ['1','2','3','4','5','6']
values = ['one','two','three','four','five','six']
d = dict(zip(keys, values))
print(d)

36. Write a Python function to find the Max of three numbers
def sum(n1,n2,n3):
    if n1>n2 and n1>n3:
        print("max number is", n1)
    elif n2>n1 and n2> n3:
        print("max number is", n2)
    else:
        print("max number is", n3)
sum(3,1,7)
        
37. Write a Python function to sum all the numbers in a list
def sum(lst):
    res = 0
    for i in lst:
        res += i
    return res
    
lst = [1,2,3,4,5,-1]
print(sum(lst))

38. Write a Python function to multiply all the numbers in a list
def mul(lst):
    res = 1
    for i in lst:
        res = res*i
    return res
lst = [8, 2, 3, -1, 7]
print(mul(lst))

39. Write a Python program to reverse a string
def rev(str):
    res = str[::-1]
    return res

str = "1234abcd"
print(rev(str))

40. Write a Python function to calculate the factorial of a number
def fac(n):
    if n <= 0:
        return 1
    else:
        res = n* fac(n-1)
        return res

print("factorial is :", fac(4))

41. Write a Python function to check whether a number is in a given range
def test_range(n):
    if n in range(3,9):
        print("%s is in range"%n)
    else:
        print("number is outside of range")
test_range(5)

42.Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters
def string_test(s):
    d={"UPPER_CASE":0, "LOWER_CASE":0}
    for c in s:
        if c.isupper():
            d["UPPER_CASE"] += 1
        elif c.islower():
            d["LOWER_CASE"] += 1
        else:
            pass
    print("No of upper case chars: ", d["UPPER_CASE"])
    print("NO of lower case chars:", d["LOWER_CASE"])

string_test('The quick Brown Fox')

43. Write a Python function that takes a list and returns a new list with unique elements of the first list
def unique_list(lst):
    x = []
    for a in lst:
        if a not in x:
            x.append(a)
    return x
   
lst = [1,2,3,3,4,4,5]
print(unique_list(lst))
    
44. Write a Python program to print the even numbers from a given list
def print_even(l):
    even_list = []
    for i in l:
        if i % 2 == 0:
            even_list.append(i)
    return even_list
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(print_even(l))

45. Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically
def input_str(s):
    lst = s.split('-')
    lst.sort()
    print('-'.join(lst))
    
input_str("green-red-yellow-black-white")

46. Write a Python function to create and print a list where the values are square of numbers between 1 and 30 (both included)
def sqr_num(n1,n2):
    res_list = []
    for i in range(n1,n2+1):
        res_list.append(i**2)
    return res_list

print(sqr_num(1,30))

47. Write a Python program to access a function inside a function
def test(a):
    def add(b):
        nonlocal a
        a += 1
        return a+b
    return add
func = test(4)
print(func(4))

48. Write a Python script to merge two Python dictionaries
d1 = {"a": "100", "b": "200"}
d2 = {"x": "4", "y": "500"}
d = d1.copy()
d.update(d2)
print(d)
print(d1.keys())
print(d1)
print(d1.values())

49. Write a Python program to get the maximum and minimum value in a dictionary.
my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))

print('Maximum Value: ',my_dict[key_max])
print('Minimum Value: ',my_dict[key_min])

#ALITER
values = my_dict.values()
print(values)
min = sorted(values)[0]
max = sorted(values)[-1]

print(min)
print(max)

50. Write a Python program to multiply all the items in a dictionary
#import math
d = {'n1': 5,'n2': 2,'n3': 3}
#print(mul.dict.vlaues())
res = 1
for key in d:
    res= res*d[key]

print(res)

#ALITER

d = {'n1': 5,'n2': 2,'n3': 3}
print(d.values())
res = 1
for i in d.values():
    res=res*i
print(res)
print(d.items())

51. Write a Python program to check that a string contains only a certain set of characters (in this case a-z, A-Z and 0-9).
import re
def match(str):
    charRe = re.compile(r'[^a-zA-Z0-9.]')
    str = charRe.search(str)
    return not bool(str)

print(match("ABCDEFabcdef123450"))
print(match("*&%@#!}{"))

52. Write a Python program that matches a string that has an a followed by zero or more b's 
import re
def text_match(text):
    patterns = 'ab*?'
    if re.search(patterns, text):
        return "match found"
    else:
        return "match not found"
print(text_match("ac"))
print(text_match("abc"))
print(text_match("abbc"))
print(text_match("bc"))
print(text_match("ababab"))


53. Write a Python program that matches a string that has an a followed by zero or one 'b'.
import re  
def text_match(text):  
        patterns = 'ab??'  
        if re.search(patterns,  text):  
                return 'Found a match!'  
        else:  
                return('Not matched!')    
print(text_match("ab"))  
print(text_match("abc"))  
print(text_match("abbc"))  
print(text_match("aabbc"))
print(text_match("a"))

54. Write a Python program that matches a string that has an a followed by three 'b' 
import re
def text_match(text):
        patterns = 'ab{3}?'
        if re.search(patterns,  text):
                return 'Found a match!'
        else:
                return('Not matched!')

print(text_match("abbb"))
print(text_match("aabbbbbc"))

55. Write a Python program that matches a string that has an a followed by two to three 'b' - 
import re  
def text_match(text):  
        patterns = 'ab{2,3}?'  
        if re.search(patterns,  text):  
                return 'Found a match!'  
        else:  
                return('Not matched!')  
  
print(text_match("ab"))  
print(text_match("aabbbbbc"))

56. Write a Python program to find sequences of lowercase letters joined with a underscore 
import re  
def text_match(text):  
        patterns = '^[a-z]+_[a-z]+$'  
        if re.search(patterns,  text):  
                return 'Found a match!'  
        else:  
                return('Not matched!')  
  
print(text_match("aab_cbbbc"))  
print(text_match("aab_Abbbc"))  
print(text_match("Aaab_abbbc"))

57. Write a Python program to find sequences of one upper case letter followed by lower case - 
import re  
def text_match(text):  
        patterns = '^[A-Z][a-z]+$'  
        if re.search(patterns,  text):  
                return 'Found a match!'  
        else:  
                return('Not matched!')  
  
print(text_match("bc"))  
print(text_match("Abbbc"))  
print(text_match("aabSBbbc"))

58. Write a Python program that matches a string that has an 'a' followed by anything, ending in 'b' 
import re
def text_match(text):
        patterns = 'a.*?b$'
        if re.search(patterns,  text):
                return 'Found a match!'
        else:
                return('Not matched!')

print(text_match("aabbbbd"))
print(text_match("aabAbbbc"))
print(text_match("accddbbjjjb"))

59. Write a Python program that matches a word at the beginning of a string
import re  
def text_match(text):  
        patterns = '^\w+'  
        if re.search(patterns,  text):  
                return 'Found a match!'  
        else:  
                return('Not matched!')  
  
print(text_match("The quick brown fox jumps over the lazy dog."))  
print(text_match(" The quick brown fox jumps over the lazy dog."))

60. Write a Python program that matches a word at end of string, with optional punctuation
import re  
def text_match(text):  
        patterns = '\w+\S*$'  
        if re.search(patterns,  text):  
                return 'Found a match!'  
        else:  
                return('Not matched!')  
  
print(text_match("The quick brown fox jumps over the lazy dog."))  
print(text_match("The quick brown fox jumps over the lazy dog. "))  
print(text_match("The quick brown fox jumps over the lazy dog "))

61. Write a Python program that matches a word containing 'z'
import re  
def text_match(text):  
        patterns = '\w*z.\w*'  
        if re.search(patterns,  text):  
                return 'Found a match!'  
        else:  
                return('Not matched!')  
  
print(text_match("The quick brown fox jumps over the lazy dog."))  
print(text_match("Python Exercises."))

61. Write a Python program that matches a word containing 'z', not start or end of the word. - 
patterns = '\Bz\B'

62. Write a Python program to match a string that contains only upper and lowercase letters, numbers, and underscores 
import re
def text_match(text):
        patterns = '^[a-zA-Z0-9_]*$'
        if re.search(patterns,  text):
                return 'Found a match!'
        else:
                return('Not matched!')

print(text_match("The quick brown fox jumps over the lazy dog."))
print(text_match("Python_Exercises_1"))

63. Write a Python program where a string will start with a specific number
import re
def match_num(string):
    text = re.compile(r"^5")
    if text.match(string):
        return True
    else:
        return False
print(match_num('5-2345861'))
print(match_num('6-2345861'))

2 comments:



  1. Very nice and informative blog. It really helped me add some useful points in my knowledge. Thanks for sharing!
    Also check out these amazing Cisco products if you want:

    C3850-NM-8-10G
    C3850-NM-2-10G
    C9200L-24P-4X-E

    ReplyDelete

Note: only a member of this blog may post a comment.