Basics of Python
Libraries are important:
import json
import csv
import ast
import sys
import time
import os
from collections import defaultdict
from datetime import dateti
import subprocess
import signal
import shutil
import bz2
import re
import urllib.parse
import requests
Dictionay methods:
d = dict() # It creates dictionary
d['name']='Anjaneya' # Assigns value to dictionary
print(d) # prints dictionary
d.update({'age':30}) # update dictionary
print(d)
d2={'city':'haveri'} # create new dictionary
d.update(d2) #append dictionary
print(d)
dv = d.pop('age') # removes keys values and returns value
print("dv",dv)
print(d)
print(d.get('name','None')) # retrievs values
del d['name'] #delete keys, does not return values
print(dv)
d['name']='anjaneya'
print(d)
dv = d.popitem() # removes last inserted key values and returns key, value ex;('name':'Anjaneya')
print(dv)
d[(1,2)] = 'kk' # tuple as key, it not allowed list&ditionary as key
print(d)
d[2]='rr'
print(d)
d[3]={'a':10,'b':25}
print(d)
d.setdefault('name','Anji') #It returns values if key exits #else it add key to dictionay with default values.
for k,v in d.items(): # iterate dictioanry and checks nest #dictionary
if isinstance(v,dict):
print(v)or methods Retrieve and use methods
******** Programs********
s = "the sky is blue" # Output: "blue is sky the" ss = s.split(" ") x = [ss[-i] for i in range(1,len(ss)+1)] print(x) def flatten(lst): result = [] for item in lst: if isinstance(item, list): result.extend(flatten(item)) else: result.append(item) return result ip = [[[1, 2, 3], [4, 5]], 6] op = flatten(ip) print(op) # Output: [1, 2, 3, 4, 5, 6] def interleave(word1, word2): result = "" len1, len2 = len(word1), len(word2) max_len = max(len1, len2) for i in range(max_len): if i < len1: result += word1[i] if i < len2: result += word2[i] return result # Example usage: word1 = "abc" word2 = "pqr" output = interleave(word1, word2) print(output) # Output: "apbqcr" def findLeastNumOfUniqueInts(arr, k): frequency = {} # Count the frequency of each element for num in arr: frequency[num] = frequency.get(num, 0) + 1 # Sort elements based on frequency sorted_nums = sorted(frequency.items(), key=lambda x: x[1]) # Remove elements to meet the k requirement count = len(sorted_nums) for num, freq in sorted_nums: if k >= freq: k -= freq count -= 1 else: break return count # Example usage: arr = [4,3,1,1,3,3,2] k = 3 print(findLeastNumOfUniqueInts(arr, k)) # Output: 2 pairs={"}":"{","]":"[",")":"("} stack = [] def check(str): for char in str: if char in pairs.values(): stack.append(char) elif char in pairs.keys(): if pairs[char] == stack[-1]: stack.pop() else: return "Unbalanced" else: continue if len(stack)==0: return "Balanced" print(check("[{()}]")) class Node: def __init__(self,data): self.data = data self.next = None class Linked_List: def __init__(self): self.head = None def append(self,data): new_node = Node(data) if self.head == None: self.head = new_node return last_node = self.head while last_node.next: last_node = last_node.next last_node.next = new_node def disp(self): current_node = self.head while current_node: print(current_node.data,end="->") current_node = current_node.next print() def prepend(self,data): new_node = Node(data) new_node.next = self.head self.head = new_node ll = Linked_List() ll.append(5) ll.append(6) ll.append(7) ll.prepend(4) ll.disp() # print longest word from given string str = "Anjaneya Basappanava python developer" words = str.split() print(words) for i in range(len(words)-1): for j in range(i+1,len(words)): if len(words[i])<len(words[j]): t = words[i] words[i]=words[j] words[j]=t print(words[1]) def count_characters(string): # Initialize counts digit_count = 0 alphabet_count = 0 symbol_count = 0 # Iterate through each character in the string for char in string: # Check if the character is a digit if char.isdigit(): digit_count += 1 # Check if the character is an alphabet elif char.isalpha(): alphabet_count += 1 # If not a digit or alphabet, consider it as a symbol else: symbol_count += 1 return digit_count, alphabet_count, symbol_count # Test the function input_string = input("Enter a string: ") digit_count, alphabet_count, symbol_count = count_characters(input_string) print("Digits:", digit_count) print("Alphabets:", alphabet_count) print("Symbols:", symbol_count) n = 154 rn=0 while n>0: digit = n%10 rn = rn*10+digit n //=10 print(rn) def square_generator(input_list): for num in input_list: yield num ** 2 # Example usage: my_list = [1, 2, 3, 4, 5] result_generator = square_generator(my_list) # Access squares one by one for square in result_generator: print(square) class ParentClass: def __init__(self, name): self.name = name def say_hello(self): print(f"Hello from {self.name}") class SubClass(ParentClass): def __init__(self, name, age): # Call the constructor of the parent class super().__init__(name) self.age = age def greet(self): # Call the method of the parent class super().say_hello() print(f"{self.name} is {self.age} years old") # Create an instance of the subclass obj = SubClass("Alice", 25) # Call the method of the subclass obj.greet() # Online Python - IDE, Editor, Compiler, Interpreternext class Node: def __init__(self,data): self.data = data self.next = None class L_list: def __init__(self): self.head = None def create(self,data): node = Node(data) if not self.head: self.head = node return current = self.head while current.next: current = current.next current.next=node def disp(self): elements = [] current = self.head while current: elements.append(current.data) current = current.next print("-->".join(map(str,elements))) linked = L_list() linked.create(1) linked.create(2) linked.create(3) linked.disp() A = ["Anjaneya","sanjane"] output = {} for n in A: d={} for c in n: d[c]=n.count(c) output[n] = d for k,v in output.items(): print(k,v) find prime number list using class concept class prime_class: def __init__(self,start,end): self.s = start self.e = end def find_prime(self): l=[] for i in range(self.s,self.e): for j in range(2,i): if i%j == 0: break else: l.append(i) return l if __name__ == "__main__": obj = prime_class(2,100) r = obj.find_prime() print(r) def O_list(A): l1=[] for n in A: d={} for l in n: d[l]=n.count(l) # print(n,":",d) l1.append(d) return l1 if __name__ == "__main__": A = ["Anjaneya","sanjane",] r = O_list(A) for i in r: print(i) ip = [63,23,41,21] # op = [9,5,5,3] op=[] for i in ip: si = str(i) s = int(si[0])+int(si[1]) op.append(s) print(op) or ip = [63,23,41,21] # op = [9,5,5,3] t = [] for n in ip: sum=0 while n>0: sum += n%10 n//= 10 t.append(sum) #find sum of dictionary values d={'a':2,'b':5} val=d.values() s=sum(val) print(s) #or d={'a':2,'b':5} val=d.values() s=0 for i in val: s+=i print(s) # Python code to illustrate # reduce() with lambda() # to get sum of a list from functools import reduce li = [5, 8, 10, 20, 50, 100] sum = reduce((lambda x, y: x + y), li) print (sum) # or l1=list([i for i in range(10,21)]) print(l1) from functools import reduce sum = reduce((lambda x,y : x+y),l1) print(sum) # dictionary cities = {'San Francisco': 'US', 'London': 'UK', 'Manchester': 'UK', 'Paris': 'France', 'Los Angeles': 'US', 'Seoul': 'Korea'} a = {} for key, value in cities.items(): a.setdefault(value,[]).append(key) print(a) ########OR##### o={} for k, v in cities.items(): if v in o: o[v]=[o[v],k] else: o[v]=k print(o) =>o/p {'US':['San Francisco', 'Los Angeles'], 'UK':[,], ...} #access element from dictionary d={1:'a',2:'b',3:'c'} d2={1:'d',2:'e'} a=list(d.values())[0] b=list(d2.values())[-1] print(a,b) d={1:'a',2:'b',3:'c'} d2={1:'d',2:'e'} c=[] l=len(d2) print(l) for i in range(len(d)): if i < 1: #print(d[1]) c.append(d[1]) for j in range(0,len(d2)): if len(d2): print(j) print(d2[1]) c.append(d2[1]) print(c) #convert dict to list l1=[1,5,6,8] l2=[4,2,9,3] l3=dict({l1[i]:l2[i] for i in range(len(l1))}) print(l3) l4=list(l3.items()) print(l4) #access elements from dictionary a=list({1:'a',2:'b'}.values())[0] b=list({1:'c',2:'d'}.values())[-1] c=a,b l1=[] l1.append(c) print(l1) ##sort given list using bobble sort a=[4,8,1,3,9] b=[7,5,2,10] a.extend(b) l=len(a) for i in range(l-1): for j in range(i+1,l): if a[i]>a[j]: t=a[i] a[i]=a[j] a[j]=t print(a) time complexity of bubble sort is O(n). #binary search def bin_search(arr,low,high,x): if high>low: mid=int((low+high)/2) if arr[mid]==x: return mid elif arr[mid]>x: return bin_search(arr,low,mid-1,x) else: return bin_search(arr,mid+1,high,x) else: return -1 arr=[1,20,60,70,80,10] arr.sort() x=80 result=bin_search(arr,0,len(arr),x) if result==-1: print("element is not found") else: print("the given element found at:",str(result)) #program to find minimum values from pair of given list # o/p: mimimum diff is :1 and pair is: (9,10) def findMin(l): diff=10**20 n=len(l) for i in range(n-1): for j in range(i+1,n): if abs(l[i]-l[j])<=diff: # abs() it converts negative value to positiver ex: -54 as 54 diff=abs(l[i]-l[j]) + a=(l[i],l[j]) # pair values return diff,a l=[4,8,1,9,3,10] res=findMin(l) print("Minimum difference is:",res[0],"and pair is:",res[1]) # program for make capital of first letter of each words str="my name is shruti" #o/p My Name Is Shruti st=str.split() s="" for i in st: #print(i.capitalize(),end=" ") for j in range(len(i)): if j==0: s=s+i[j].upper() else: s=s+i[j] s=s+" " print(s) #or using ASCII str="my name is Anjaneya" st=str.split() s="" for i in st: #print(i.capitalize(),end=" ") for j in range(len(i)): if j==0: a=ord(i[j]) # get ASCII value p=a-32 #p=chr() # print character for ASCII value s=s+(chr(p)) else: s=s+i[j] s=s+" " print(s) #program for string "8a7b2c917d90" and o/p: 8a:7b:2c:91:7d:90 st="8a7b2c917d90" ss=str(st) result="" for s in range(0,len(ss)): if s%2!=0: if s==len(ss)-1: result=result+ss[s] else: result=result+ss[s]+":" else: result=result+ss[s] print(result) #s="Apple Mango Java Mango Python Apple Django Mango Html" s="Apple Mango Java Mango Python Apple Django Mango Html" from collections import Counter str=s.split() d={} d=(dict(Counter(str))) max_key=max(d,key=d.get) print(max_key) # try except which exception will execute first def AdivB(a , b): try: c = ((a+b) // (a-b)) except Exception as e: #- (1) print(e) except ZeroDivisionError: # - (2) print ("a/b result in 0") AdivB(1,1) #o/p : interger division list = ["apple", "banana", "cherry", "kiwi", "mango"] newlist=[i for i in list if "a" in i ] print(newlist) #find the sum of cubes of given number a=int(input("enter the number:")) s=0 for i in range(1,a+1): q=i**3 s+=q print(q,i) print(s) # find the ultiplication table using lambda x= lambda x,y : x*y n=10 for i in range(1,n+1): for j in range(2,4): r=x(i,j) print(j,'*',i,'=',r,end=' ') print() #swap the list revese list def swap(n): l=len(n) s=n[0] n[0]=n[l-1] n[l-1]=s print(n) n=[1,2,3,4] swap(n) #o/p:[4, 2, 3, 1] #remove the enterd numbers from list def repeat(inp): #n=[1,2,3,2,4] for i in range(len(n)): if n[i] == inp: c = i n.pop(c) print(n) n=[1,2,3,2,4] inp=int(input("Enter the number:")) repeat(inp) # copying list l1=l2, if changes to l2 it appects to l1 both stores in same id def Clonning(l1): l2=l1 l2.append(6) l2.pop(3) print("After Clonning \n",l2) print(l1) print(id(l1)) print(id(l2)) # driver code l1=[4,8,10,3,18] Clonning(l1) # zip The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together a=[1,2,3,4,1] s=['q','w','e','r','f'] x=zip(a,s) z=[i for i in sorted(x)] print(z) # o/p : [(1, 'f'), (1, 'q'), (2, 'w'), (3, 'e'), (4, 'r')] # remove duplicates from list p=[6,2,3,1,2,4,5,6] l1=[] for i in p: if i not in l1: l1.append(i) # sort the list z=sorted(l1) print(z[-3]) # 3rd greatest number print(z) #find minimum and maximum usning min and max function q=[1,2,5,8,6] d=min(q) mx=max(q) s=max(q)-1 print("min:",d) print("max:",mx) print("second large:",s) #print first and last charaters are same in a list def number(n): c=0 for n in n: if n[0]==n[-1]: c=c+1 print(n,c) n=['1231','asda','1234','fdcf'] number(n) """ o/p : 1231 1 asda 2 fdcf 3 """ #print last element from list def last(n): return n[-1] print(last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)])) #o/p : (2, 1) # sort the list def sort_list(tuple): return sorted(tuple) print(sort_list([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]) # return words from list with length is > 4 l=['asd','qwe','aswqq','wqer','ddddsdd'] n=4 for i in l: if len(i)>4: print(i) #o/p: aswqq ,ddddsdd l=["anjaneya","sanjay","shivappa"] x=filter(lambda x: int(len(x)<8), l) print(list(x)) #Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. #This enumerated object can then be used directly for loops or converted into a list of tuples using the list() method. # changing index and printing separately l1 = ["eat", "sleep", "repeat"] for count, ele in enumerate(l1, 100): # starting index print (count, ele) #Shuffle a list (reorganize the order of the list items): import random l=[2,3,4,5,6,7,8,9] random.shuffle(l) print(l) #******* Armstrong number #Input : 153 #Output : Yes #153 is an Armstrong number. #1*1*1 + 5*5*5 + 3*3*3 = 153 n=int(input("Enter the number:")) a=str(n) b=len(a) c=0 for i in a: j=int(i) c=c+j**b if c==n: print("Number is armstrong") else: print("not armstrong") #prime or not n=int(input("Enter the number:")) if n>1: #iterate 2, to n/2 for i in range(2,int(n/2)+1): if n%i==0: print("num is npt prime") break else: print("num is prime",n) else: print("not prime") # 1-100 prime for i in range(2,100): for j in range(2,int(i/2)+1): if i%j==0: break #print(i, end=",") else: print(i,end=" ") #factorial n=5 s=1 for i in range(1,n): s+=s*i print(s) # factorial using recursive def fact(n): if n==0: result=1 else: result=n*(fact(n-1)) return result print(fact(5)) #lambda to lower case x=lambda x: x.lower() print(x("ANJANEYA")) #type error tuple insertion a=(10,50,1) a[0]=1 print(a) # print duplicate number=[1,10,23,7,10,3,3,90] dp=[] for i in number: if i not in dp: dp.append(i) else: print(i, end=",") #find the count of the words in a list n=['varsa','shruti','varsa'] output=[] for i in n: p= i,n.count(i) if p not in output: output.append(p) print(output) #count the upper case and lower case in a string s="My Name Is Anjaneya" v=s.replace(" ",'') c=0 k=0 print(v) for i in v: if i.isupper(): c+=1 else: k+= 1 print("upper letters:",c) print("Lower letters:",k) #max_difference input_data=[1,4,7,19,20,4] max=max(input_data) min=min(input_data) d=max-min print("The max_difference is (max-min)=",d) #searching mobile number import re input="mobile:8867224452" d=re.search('\d{10}',input) d=d.group(0) print(d) #count the consecutive number from a string a="1s23fgh789gh76" c=0 for i in range(len(a)+1): if i < len(a)-1: if a[i].isdigit() and a[i+1].isdigit(): print(a[i],a[i+1],"---") c=c+1 print("total count:",c) #count the consecutive number from a string import re s='1sd34dd23uh43' z=re.findall('\d{2}',s) print(z) #adding list a=['bana','app','oran'] b=['na','le','ge'] c=[] for x,y in zip(a,b): completed=x+y c.append(completed) print(c) # o/p: ['banana', 'apple', 'orange'] # remove duplicate words from list a="hello world and practice make perfect and hello world again" s=a.split(" ") print("s= ",s) d=set(s) print("d= ",d) l=" ".join(sorted(d)) print("l=",l) list1=[10,5,2,-1,100,0] print(sorted(list1)) #string is palidrome or not def isPalidrome(s): for i in range(0,int(len(s)/2)): if s[i]!=s[len(s)-i-1]: return False return True s="malayalam" ans=isPalidrome(s) if ans==1: print("is palidrom") else: print("Not palidrom") ### other method s="malayalam" rs=s[::-1] if s==rs: print("yes, it is palidrome") else: print("No, its not a palidrome" ) ## Generating dictionary with alphabets as keys and prime numbers as values num=int(input("Enter last number:")) listt=[] for i in range(2,num): for n in range(2,i): if i%n==0: break else: listt.append(i) print(listt) d={chr(x):" " for x in range(ord('a'), ord('z')+1)} print(d) #factorial of given number num=int(input("Enter The Number:")) factorial= 1 if num<0: print("No factorial for given number") elif num==0: print("factorial of 0 is 1") else: for i in range(1, num+1): factorial=factorial*i print("factorial of", num,"is ", factorial) #fibbonacci number nterm=int(input("Enter the input:")) n1=0 n2=1 count=0 if nterm<=0: print("Enter positive number") else: print("fibbonacci of",nterm,"is :") while count<nterm: print(n1,end=" ") nth=n1+n2 n1=n2 n2=nth count=count+1 # Extracting_string_from_nested_list test_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]] print("the original list:" + str(test_list)) res=[ele for sub in test_list for ele in sub if isinstance(ele,str)] #The isinstance() function returns True if the specified object is of the specified type, otherwise False. print("The string instances:" + str(res)) #Filter fuction l=[0,10,15,20,25,30] l1=list(filter(lambda x:x%2==0,l)) print(l1) ##Map fundtion # l=[0,1,2,3,4] # l1=list(map(lambda x:x*x,l)) # print(l1) ##Reduce function # import functools # l=[10,20,30,40] # l1=functools.reduce(lambda x,y:x*y,l) # print(l1) l=[2,4,3,7,3,8,5,4] from collections import Counter x=Counter(l) print("x=",x) l1=[] # The items() method returns a view object. #The view object contains the key-value pairs of the dictionary, as tuples in a list. for i in x.items(): if i[1]==1: l1.append(i[0]) print("after removing duplicates:",l1) ##get odd numbers using list comprehension l=[1,2,3,4,5,6,7,8,9] print([i for i in l if i%2!=0]) #create class and object class A: def __str__(self): return("Anjaneya") a=A() print(a) ##Anagram using Sorted def check(s1,s2): if(sorted(s1)==sorted(s2)): print("strings are Anagram") else: print("strings are not Anagram") s1="listen" s2="silent" check(s1,s2) # program to count Input = [3,4,3,5,3,6] from collections import Counter #Output{3:3,4:1,5:1,6:1} d={} d=dict(Counter(Input)) print(d) # Anagram using Counter counter method from collections import Counter def checker(s1,s2): if (Counter(s1)==Counter(s2)): print("Strngs are Anagram") else: print("Strings are not Anagram") s1="silent" s2="listen" checker(s1,s2) #Print name 10 times without iterator def display(n): if n==0: return " " else: print("Anjaneya") return display(n-1) display(10) # Or s="anjaneya" print(s*10) #age calculator def ageCalulator(y,m,d): import datetime today=datetime.datetime.now().date() dob=datetime.date(y,m,d) age=int((today-dob).days/365) print(age) ageCalulator(1991,7,31) #Input:[1,2,3,4,5] Output:[1,4,3,16,5] l1=[1,2,3,4,5] l2=[i*i if i%2==0 else i for i in l1] print(l2) #Number of occurance a="hello" b="l" c=0 for i in range(len(a)): if a[i]==b: c=a.count(a[i]) print(c) ##Alternate Lowrcase string to Uppercase #i/p: Anjaneya, O/p: AnJaNeYa str="Anjaneya" s="" for i in range(len(str)): if i%2==0: s=s+str[i].upper() else: s=s+str[i].lower() print(s) #Count Vowels in string and print in dictionary format str="shruti sattigeri" d={} v=['a','e','i','o','u'] count=0 for s in str: if s in v: count+=1 d[s]=d.get(s,0)+1 #The get() method returns the value of the item with the specified key. #print(s) print("count:",count) print("d=",d) #Generate prime numbers from 10 to 50 first=10 last=50 for i in range(first, last+1): for j in range(2,i): #print(i,j) if i%j==0: break else: print(i) print(list(filter(lambda i:i%2==0, range(1,20)))) #convert Roman number to integers dict={'i':1,'v':5,'l':50,'c':100,'x':10} input='xxi' o=dict['x']+dict['x']+dict['i'] print(o) #other methoddict={'i':1,'v':5,'x':10,'l':50,'c':100} input='xxi' s=0 for i in input: for j in dict.items(): if j[0]==i: s=s+j[1] print(s) ##Print first non repeating character str="abigmango" d={} count=0 for i in str: d[i]=d.get(i,0)+1 print(d) for key,value in d.items(): if value==1: print(key,end=" ") break #print 1-50 prime number for i in range(2,50): for j in range(2,int(i/2)+1): if i%j == 0: break else: print(i, end=",") # if user enters name it disaplay corresponding age arr = [ {'id': 1, 'name': "test1", 'age':22} # {id: 2, name: "test2", age:23}, # {id: 3, name: "test3", age:24}, # {id: 4, name: "test4", age:25}, # {id: 5, name: "test5", age:26} ] input=input("enter the name:") for i in arr: # print(i['name']) if input==i['name']: print(i['age']) #find the pair of numbers pair sum=16 arr=[2,4,8,10,7,9,5,6] sum=16 for i in range(len(arr)-1): for j in range(i+1,len(arr)): if arr[i]+arr[j]==sum: print(arr[i],arr[j]) ############ inter 18/9/22 #Input: Hello World GFG Welcomes You #Output:You semocleW GFG dlroW Hello input=input("enter string").split() print(input) revers_input=input[::-1] print(revers_input) rs="" for i in range(len(revers_input)): rs+=" " if (i==0) or (i==int(len(revers_input)-1)): rs+=revers_input[i] else: a=revers_input[i] rr=a[::-1] rs+=rr print(rs) cities = {'San Francisco': 'US', 'London':'UK', 'Manchester':'UK', 'Paris':'France', 'Los Angeles':'US', 'Seoul':'Korea'} output = {} for key,val in cities.items(): print(val) if val in output: output[val] = [output[val],key] else: output[val] = key print(output)
def flatten(lst): result = [] for item in lst: if isinstance(item, list): result.extend(flatten(item)) else: result.append(item) return result ip = [[[1, 2, 3], [4, 5]], 6] op = flatten(ip) print(op) # Output: [1, 2, 3, 4, 5, 6]