1.Program to merge 2 string characters alternatively.
#E.g: a= abc b= def # Output: adbecf #E.g: a= abc b=stuvwx # Output: asbtcuvwx Solution:
a = input("Your first string.") b = input("Your second string.") i=0 j=0 newString = "" while i < len(a) and j<len(b): newString += a[i] newString += b[j] i+=1 j+=1 while i<len(a): newString += a[i] i+=1 while j<len(b): newString += b[j] j+=1 print(newString)
OutPut:
======
Your first string.abc
Your second string.def
adbecf
Aliter:
# Program to merge 2 string characters alternatively. #E.g: a= abc b= def # Output: adbecf #E.g: a= abc b=stuvwx # Output: asbtcuvwx a=input("enter 1st string : "); b=input("enter 2nd string : "); i=0 j=0 finalString="" while(i<len(a) and j<len(b)): finalString+=a[i]+b[j] i+=1 j+=1 if(i<len(a)): finalString+=a[i:] if(j<len(b)): finalString+=b[j:] print(finalString)
2. Program to remove
the repeated characters.
Solution:
======
str="manishmanishmanishmanishmanish"
result = []
for c in str:
if c not in result:
result.append(c)
result = ''.join(result)
print (result)
OutPut:
======
manish
3. Program for
find Factorial of a Number:
Solution1:
def fact(n): if n <=1: return 1 else: return n * fact(n-1) print(fact(6))
Solution2:
def fact(n): f = 1 for i in range(1, n+1): f = f * i return f print (fact(6))
4. Program to Fibonacci
series.
Solution1:
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(20))
Solution2:
def fibonacci(n): if(n <= 1): return n else: return(fibonacci(n-1) + fibonacci(n-2)) n = int(input("Enter number of terms:")) print("Fibonacci sequence:") for i in range(n): print (fibonacci(i)),
5 Create a Dictonary and print a key value pair, only key and only value. squares = {1:1, 2:4, 3:9, 4:16, 5:25} for key, value in squares.items(): print (key, value) for key in squares.keys(): print (key) for value in squares.values(): print (value)
6 .Convert the Doted Decimal subnet mast into CIDR Format
Solution1:netmask = "255.255.255.240"a=sum([bin(int(x)).count("1") for x in netmask.split(".")]) print(a)Solution2:CIDR=0 a = input("Enter the mask in doted decimal ") b=a.split('.') for x in b: y = int(x) binary=bin(y).count("1") CIDR+=binary print(CIDR)Solution3:CIDR=0 a = input("Enter the mask in doted decimal ") b=a.split('.') for x in b: y = int(x) while y>0: i=int(y % 2) if i==1: CIDR=CIDR+1 y=int(y/2) print(CIDR)
7.Program to reverse string.
#LOOPdef reverse1(s): final_string = "" for i in s: final_string=i+final_string return final_string print (reverse1("MANISH")) #Recursion def reverse2(s): if len(s) == 0: return s else: return reverse2(s[1:]) + s[0] print (reverse2("MANISH")) #slice def reverse3(s): if len(s) == 0: return s else: return s[::-1] print (reverse3("MANISH")) #Reverseddef reverse4(s): if len(s) == 0: return s else: return "".join(reversed(s)) print (reverse4("MANISH"))8.Program to find common elements in a two list. #Find Common Elements in 2 List a =[1,2,2,3,3,4,5,6,12,13,22,25,28,31] b =[2,3,4,5,6,7,8,9,7,11,12,13,14] c = set(a) d = set(b) e = c & d print(e)
9.Program to find max number of character occurances in a string
a"GiniiGinnnaaaaaaaaaaaaaaaaaaaaaaaaaProtiiiijayyyyyyyyyyyyyyyi"count = 0 maxcount = 0 lastCharacter = "" longestcharacter = "" for ch in a: if(ch== lastCharacter): count += 1 if(count> maxcount): maxcount = count longestcharacter = ch else: count = 1 lastCharacter = ch print(longestcharacter) print(maxcount)
10.Program to find number of occurrences in a listaList = [1,2,3,5,6,1,5,6,1]fDict = {} for i in set(aList): fDict[i] = aList.count(i) print (fDict)11.Program to find prime number and prime numbers in a given range#Program to find prime number. num = 29 if num > 1: for i in range(2, num): if (num% i) == 0: print(num, "isnot a prime number") break else: print(num,"is a prime number") else: print(num, "is not a prime number") # #Prime number between a range r = 30 for i in range(2, r+1): k=0 for j in range(2, int(i/2+1)): if(i%j==0): k=k+1 break if(k==0): print(i)12.Assert Exampledef get_age(age):assert age > 0, "Age cannot be negative" print(age) get_age(10) get_age(-1)13. Search number of elements which are repeated more than once:# Search number of elements which are repeated more than once # Ex: 1,2,3,2,1,4,5 # 1-->count(2), 2-->count(2), 3--->count(1),4-->count(1),5-->count(1) # So there are 2 elements whose count is more than 1 # Ex: 10,11,11,11,14 # 10-->count(1), 11-->count(3), 14--->count(1) # So there are 1 elements whose count is more than 1 def countDuplicate(numbers): count =0 result = dict((i,numbers.count(i))for i in numbers) for i in result.values(): if i>1: count=count+1 return count abc =18,1,3,1,4,5,6,3,2 print(countDuplicate(abc))14. Difference between dir() and help()#In Python, help() is a super useful built-in function that can be used to return the # Python documentation of a particular object, method, attributes, etc.my_list = [] #help(my_list.append) #Help on built-in function append: # append(...) method of builtins.list instance # L.append(object) -> None -- append object to end # In python, dir() shows a list of attributes for the object passed in as argument , # without an argument it returns the list of names in the current local namespace (similar to locals().keys() ) . my_list = [] print(dir(my_list)) #['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', # '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', ' # __le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__ # ', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', # 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] 15.Program to find longestcharacter in a string and its count.a = "GiniiGinnnaaaaaaaaaaaaaaaaaaaaaaaaaProtiiiijayyyyyyyyyyyyyyyi"count = 0 maxcount = 0 lastCharacter = "" longestcharacter = "" for ch in a: if(ch==lastCharacter): count += 1 if(count> maxcount): maxcount = count longestcharacter = ch else: count = 1 lastCharacter = ch print(longestcharacter) print(maxcount)16.Lambda Example:
#double =
lambda x: x * 2 #print(double(5)) def double(x): x=x*2 print(x) double(5)17.Remove Spaces from a string.sentence = ' helloapples Manish' print ("".join(sentence.split()))18.Remove _ from a string.strValue = "__a____de___r_manish______bidsar__10__"newString = "" for i in strValue: if len(strValue) == 1 and i == '_': newString += " " if i == "_": if len(newString) == 0 or newString[len(newString) - 1] != " ": newString += " " continue else: newString += i print (newString) #Result " a de r manish bidsar 10"19.Find the repeated word in string and count.def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print( word_count('the quick brown fox jumps over the lazy dog.'))20.Check if number is present in BST or not.If present return 1 else return 0.# defining Tree class class BSTNode: def __init__(self, nodeValue): self.value= nodeValue self.left=None self.right=None # Check if number is present in BST or not.If present return 1 else return 0 # Ex: 20 # 10 30 # 8 12 25 40 # Input : 30,10,12,15 # Outout: 1,1,1,0 # Explannation : 30,10,12 is present in binary tree so print 1, 15 not present in binary tree so print 0 def isPresent(root,val): if root is None: return 0 if root.value==val: return 1 if root.value<val: if isPresent(root.right,val)==1: return 1 else: if isPresent(root.left,val)==1: return 1 return 0 r = BSTNode(20) r.left=BSTNode(10) r.right=BSTNode(30) r.left.left=BSTNode(8) r.left.right=BSTNode(12) r.right.left=BSTNode(25) r.right.right=BSTNode(40) print(isPresent(r,50)) print(isPresent(r,10)) print(isPresent(r,12)) print(isPresent(r,15))21.Usage of tail -f command:
- tail fileName - This command will print the last ten
lines of fileName
- tail -nfileName - This command will print the last n lines
of fileName. Where as n is an integer
- tail -cfileName - This command will print the last c bytes
of fileName. Where as c is the size in bytes
MBIDSAR-M-R15H:GNS3
mbidsar$ tail -f projects/test/test.gns3
"x": -666,
"y": -111,
"z": 0
}
]
},
"type": "topology",
"version": "2.1.3",
"zoom": 100
}
^C
MBIDSAR-M-R15H:GNS3 mbidsar$
22.How to view hidden files in Linux.
23.How to create sub-interface in linux.
Create sub interfaces on CentOS and Redhat
Sub interfaces or virtual interfaces are used for a number of
reasons. Normally for VLANs, but also if you want your machine to have multiple
IP addresses.
This is relatively straight forward to do.
It can be done from the command line like this:
# ifconfig
eth0:1 192.168.111.1
The above command has just created a virtual / sub interface on
eth0 called eth0:1 and assigned it the IP 192.168.111.1
This however is not a permanent solution because when you
reboot, this interface will be lost. To make it permanent we need to create a
file in
/etc/sysconfig/network-scripts/ called ifcfg-eth0:1
DEVICE=eth0:1
BOOTPROTO=none
HWADDR=00:16:17:90:a5:15
ONPARENT=yes
IPADDR=192.168.111.1
NETMASK=255.255.255.0
TYPE=Ethernet
Very similar to ifcfg-eth0 but note there is no default gateway
set. Always remove the gateway line from the cfg file you will inevitably copy
to create this.
The MAC or Hardware address must also match the parent
interface.
If you need more than one virtual / sub interface, simply create
more config files.
To bring an interface up after creating the config file use:
# ifup eth0:1
24. Count the Number of Vowels Present in a String using Sets:
s=input("Enter string:")
count = 0
vowels =set("aeiou")
for letter in s:
if letter in vowels
count+= 1
print("Count of the vowels is:")
print(count)
Output:
======
1:
Enter string:Hello
world
Count of the vowels is:
3
2:
Enter string: manish
Count of the vowels is:
2
25. Program to Check Common Letters in Two Input Strings
s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)&set(s2))
print("The common letters are:")
for i in a:
print(i)
Output:
======
1:
Enter first string:
manish
Enter second string:
bidsar
The common letters are:
a
i
26. Program to check if number is a Palindrome.
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
27. Program to check if a string is a Palindrome.
For other functions to reverse a string check ,string reverse codes above.
#Palindrome
a = input("Enter a string to revsese: ")
def reverse(b):
return b[::-1]
print(reverse(a))
if reverse(a)==a:
print("Its a Palindrome ")
else:
print("Its not a Palindrome ")
28. Program to check if a two strings are anagrams.
#An anagram is a word or phrase formed by rearranging the letters in another word or phrase.
s1=input("Enter first string:")
s2=input("Enter second string:")
if(sorted(s1)==sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
Output:
======
Case 1:
Enter first string:anagram
Enter second string:nagaram
The strings are anagrams.
Case 2:
Enter first string:hello
Enter second string:world
The strings aren't anagrams.
29. Program to print directory tree structure in python.
#Here's a really simple example that walks a directory tree, printing out the #name of each directory and the files contained:
# Import the os module, for the os.walk function
import os
# Set the directory you want to start from
rootDir = '.'
for dirName, subdirList, fileList in os.walk(rootDir):
print('Found directory: %s' % dirName)
for fname in fileList:
print('\t%s' % fname)
Output:
=====
Found directory: .
countrepeatedelements.py
Palindrome.py
DivHelppython.py
reverse.py
_and__.py
CIDR.py
searchvalue in BST.py
__init__.py
assert_example.py
repeated_word_in_string_and_count.py
Find max number of character occurances in a string.py
count_number_of_vovels_in_string.py
temp.py
Factorial.py
Duplicate_Character.py
Remove_Underscore.py
common elements in a list.py
Restget.py
string alternate.py
Dict.py
lambdaexample.py
Remove_Spaces.py
network-automation.py
Prime_Numer.py
Fibonacci.py
Found directory: ./OOPS Programs
Encapsulation.py
Multiple_and_Multilevel_Inheritance.py
classarrtibute.py
Method_Overriding.py
__init__.py
Class and Instance Variables.py
Class.py
Polymorphism.py
Inheritance.py
Found directory: ./__pycache__
30. Program to find sub-string in a array.
# Function to check if small string is
# there in big string
def check(string, sub_str):
if (string.find(sub_str) == -1):
print("NO")
else:
print("YES")
string = "manish abc bcd asc"
sub_str = "manish"
check(string, sub_str)
31. Program to count the occurrence of a word in a Text File.
fname = input("Enter file name: ")
word=input("Enter word to be searched:")
k = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
k=k+1
print("Occurrences of the word:")
print(k)
Program Explanation
1. User must enter a file name and the word to be searched.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each line is split into a list of words using split().
5. Another for loop is used to traverse through the list and each word in the list is compared with the word provided by the user.
6. If both the words are equal, the word count is incremented.
7. The final count of occurrences of the word is printed.
OUTPUT:
=======
Case 1:
Contents of file:
hello world hello
hello
Output:
Enter file name: test.txt
Enter word to be searched:hello
Occurrences of the word:
3
Case 2:
Contents of file:
hello world
test
test test
Output:
Enter file name: test1.txt
Enter word to be searched:test
Occurrences of the word:
4