0% found this document useful (0 votes)
2 views50 pages

Python / C language notes and questions

The document provides a comprehensive guide to Python programming covering various topics across three levels. It includes fundamental concepts such as input handling, control structures (if, for, while), data types (lists, sets, tuples, dictionaries), and functions for mathematical operations. Each section contains code examples and explanations to illustrate the usage of different Python features.

Uploaded by

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

Python / C language notes and questions

The document provides a comprehensive guide to Python programming covering various topics across three levels. It includes fundamental concepts such as input handling, control structures (if, for, while), data types (lists, sets, tuples, dictionaries), and functions for mathematical operations. Each section contains code examples and explanations to illustrate the usage of different Python features.

Uploaded by

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

PYTHON

LEVEL - 1
Topics : If , elif

1.​Getting Input

a=int(input); #Integer
b=input(); #String

2.​Leap year

year = int(input("Enter a year: "))


if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("leap")
else:
print("not")
else:
print("leap")
else:
print(" not")

3.​Rounding

a=int(input())
print(round(a))
// Input : 133.78698
//Output: 134
4.​Rounding with precision

Round()
a=65.7689
b=round(a,2)

Output : 65.77

5.​Format() (To print 0 after decimal point)

A=50 or A=65.6777
B="{:.2f}".format(A)

Output: 50.00 or 65.68

6.​To print same number with 2 precision

a=65.6777 //Output: 65.77


b=int(a*100)/100

7.​Swap (Another version)

a=33
b=89
print(int((a*b)/a))
print(int((a*b)/b))

8.​Input : 16
Output : 4 #(2^4)

import math
number = int(input())
power = int(math.log2(number))
print(power)

9.​Use of end

print("HEY",end=' ')
print("HELLO") // HEY HELLO
LEVEL - 2
Topics : For loop , while loop

1.​Prime or Composite

n=int(input())
if n<=1:
print("com")
exit()
f=1
for i in range(2,int(n/2)+1):
if n%i==0:
f=0
break
if (f==1):
print("Prime")
else:
print("Com")

2.​Armstrong Number or Narcissistic Number

a=int(input())
c=0
temp=a
while(temp!=0):
temp//=10;
c+=1
sum=0
org=a
while(a!=0):
rem=a%10
sum+=rem**c
a//=10
print(sum)
if(sum==org):
print("ARM")
else:
print(“NOT”)

3.​Abundant Number

a=int(input())
sum=0
for i in range(1,a):
if(a%i==0):
sum+=i
if(sum>a):
print("ABUNDANT")
else:
print("NOT")

4.​Replace all 0 with 1 using arithmetic operators

a=int(input())
rev,revv=0,0
re,rem=0,0
while(a!=0):
rem=a%10
if(rem==0):
rem=rem+1
rev=rev*10+rem
a//=10
while(rev!=0):
re=rev%10
revv=revv*10+re
rev//=10
print(revv)
5.​Find the factorials of each digit in the input and sum it up

a=int(input())
rev,rem=0,0
sum=0
while(a!=0):
rem=a%10
for i in range(1,rem//2+1):
if rem%i==0:
sum+=i
rev=rev*10+rem
a//=10
print(sum)

6.​*
**
***
****
*****

r=int(input())
for i in range(1,r+1):
print('*' * i)

7.​To reverse the given number

a=int(input())
rem,rev=0,0
while(a!=0):
rem=a%10
rev=rev*10+rem
a//=10
print(rev)
8.​To count the number of digits in input including negative

a=int(input())
c=0
rem,rev=0,0
a=abs(a)
while(a!=0):
rem=a%10
rev=rev*10+rem
c+=1
a//=10
print(c)

9.​To reverse the input including negative numbers (Wrong for


some inputs)

a=int(input())
c=0
rem,rev=0,0
sign = -1 if a < 0 else 1
a=abs(a)
while(a!=0):
rem=a%10
rev=rev*10+rem
c+=1
a//=10
rev*=sign
print(rev)
print(c)

10.​ Find even , odd , prime numbers in the given input

n=int(input())
l=[]
while(n!=0):
rem=n%10
l.append(rem)
n//=10
lst=sorted(l)
print("EVEN")
for i in lst:
if i%2==0:
print(i)
print("ODD")
for i in lst:
if i%2!=0:
print(i)
print("PRIME")
f=1
for i in lst:
if i%2!=0:
for j in range(2,int(i/2)+1):
if i%j==0:
f=0
break
if(f==1):
print(i)

11.​ Prime numbers between range

l=int(input())
u=int(input())
for i in range(l,u+1):
f=1
if i==1:
continue
for j in range(2,int(i/2)+1):
if i%j==0:
f=0
break
if(f==1):
print(i)

12.​ Leap year between range

l=int(input())
u=int(input())
for i in range(l,u+1):
if (i%4==0 and i%100!=0) or (i%400==0):
print(i)
13.​ Multiply each digit if even or sum up the each digit in the
given input

n=int(input())
mul,add=1,0
while(n!=0):
rem=n%10
if(rem%2==0):
mul*=rem
else:
add+=rem
n//=10
print(mul)
print(add)

14.​ Factorial of a number

n=int(input())
mul=1
for i in range(1,n+1):
mul*=i
print(mul)

15.​ Fibonacci series

n=int(input())
n1=0
n2=1
for i in range(0,n):
print(n1,end=' ')
no=n1+n2
n1=n2
n2=no

16.​ Armstrong number between range

l=int(input())
u=int(input())
sum=0
for i in range(l,u+1):
c=0
sum=0
org=i
num=i
while(i!=0):
rem=i%10
c+=1
i//=10
while(org!=0):
re=org%10
sum+=re**c
org//=10
if sum==num:
print(sum)

17.​ Find sum of natural numbers

n=int(input())
sum=0
for i in range(1,n+1):
sum+=n
n-=1
print(sum)

18.​ Find Hcf or Gcd

a=int(input())
b=int(input())
if a<b:
sm=a
else:
sm=b
for i in range(1,sm+1):
if a%i==0 and b%i==0:
hcf=i
print(hcf)
19.​ Find Lcm
a=int(input())
b=int(input())
if a<b:
g=b
else:
g=a
while(True):
if g%a==0 and g%b==0:
lcm=g
break
g+=1
print(lcm)

—--------------------------------------------**********************----------------------------------------------
LEVEL - 3
Topics : Lists , Sets , Tuples , Dictionaries , Array , String method

LISTS :

●​ list1 * 2
It puts the same list into 2 times eg:[1,2] the answer will be [1,2,1,2]
●​ list1 + list2
It concatenate two lists eg:[1,2] [3,4] output will be [1,2,3,4]
●​ (check_value in list) //Prints true if the value is in list or prints false

1.​To declare Lists ( 3 methods )

Marks = [10, 23, 41, 75]


Fruits = [“Apple”, “Orange”, “Mango”, “Banana”]
MyList = [ ]

2.​To find length

>>> MySubject = [“Tamil”, “English”, “Comp. Science”, “Maths”]


>>> len(MySubject)
4 // Output

3.​To update/change single value


MyList = [2, 4, 5, 8, 10]
MyList[2] = 6
[2 4 6 8 10] // Output

4.​To update/change range of values

MyList = [1, 3, 5, 7, 9]
MyList[0:5] = 2,4,6,8,10
[ 2 4 6 8 10] // Output

5.​To add a single element

>>> Mylist=[34, 45, 48]


>>> Mylist.append(90)
>>> print(Mylist)
[34, 45, 48, 90] // Output

6.​To add more than one element

>>> Mylist.extend([71, 32, 29])


>>> print(Mylist)
[34, 45, 48, 90, 71, 32, 29] // Output

7.​To insert an element in particular position

MyList=[34,98,47,'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan' ] // Input


>>> MyList.insert(3, 'Ramakrishnan')
>>> print(MyList)
[34, 98, 47, 'Ramakrishnan', 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan'] // Output

8.​ Deleting elements from a list


Syntax:
del List [index of an element] # to delete a particular element
del List [index from : index to] # to delete multiple elements
del List # to delete entire list (after using this , if you try to print the list
it will show error )

MySubjects = ['Tamil', 'Hindi', 'Telugu', 'Maths'] // Input

>>> del MySubjects[1]


>>> print (MySubjects)
['Tamil', 'Telugu', 'Maths'] // Output

>>> del MySubjects[1:3]


>>> print(MySubjects)
['Tamil'] // Output

9.​Deleting

>>> MyList=[12,89,34,'Kannan', 'Gowrisankar', 'Lenin']


>>> MyList.remove(89)
>>> print(MyList)
[12, 34, 'Kannan', 'Gowrisankar', 'Lenin'] //Output

>>> MyList.pop(1)
34
>>> print(MyList)
[12, 'Kannan', 'Gowrisankar', 'Lenin'] // Output

>>> MyList.clear( )
>>> print(MyList)
[ ] // Output
10.​ Creating a list with series of values

>>> Even_List = list(range(2,11,2))


>>> print(Even_List)
[2, 4, 6, 8, 10] // Output

11.​ Generating squares of first 10 natural numbers using the


concept of List comprehension

>>> squares = [ x ** 2 for x in range(1,11) ]


>>> print (squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] //Output

Lists Functions

copy ( ) : Returns a copy of the list


List.copy( )

MyList=[12, 12, 36]


x = MyList.copy()
print(x)
Output: [12, 12, 36]

count ( ) : Returns number of similar elements present in


the last.
List.count(value)

MyList=[36 ,12 ,12]


x = MyList.count(12)
print(x)
Output: 2
index ( ) : Returns index value of the first recurring element
List.index(element)

MyList=[36 ,12 ,12]


x = MyList.index(12)
print(x)
Output: 1

reverse ( ) : Reverses the order of the element in the list.


List.reverse( )

MyList=[36 ,23 ,12]


MyList.reverse()
print(MyList)
Output: [12 ,23 ,36]

sort ( ) : Sorts element in list. sort( ) will affect the original


list.
list.sort() //ASCENDING
list.sort(reverse=True) //DESCENDING

max( ) : Returns the maximum value in a list.


max(list)

MyList=[21,76,98,23]
print(max(MyList))
Output: 98

min( ) : Returns the minimum value in a list


min(list)

MyList=[21,76,98,23]
print(min(MyList))
Output: 21

sum( ) : Returns the sum of values in a list.


sum(list)

MyList=[21,76,98,23]
print(sum(MyList))
Output: 218

****************************************************************************************************

TUPLES :

1.​Creating Tuples

Syntax:

# Empty tuple Tuple_Name = ( )


# Tuple with n number elements Tuple_Name = (E1, E2, E2 ……. En)
# Elements of a tuple without parentheses Tuple_Name = E1, E2, E3….. En

2.​ Accessing values in a Tuple

>>> Tup1 = (12, 78, 91, “Tamil”, “Telugu”, 3.14, 69.48) //Input

# to access all the elements of a tuple


>>> print(Tup1)
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)

#accessing selected elements using indices


>>> print(Tup1[2:5])
(91, 'Tamil', 'Telugu')

#accessing from the first element up to the specified index value


>>> print(Tup1[:5])
(12, 78, 91, 'Tamil', 'Telugu')
# accessing from the specified element up to the last element.
>>> print(Tup1[4:])
('Telugu', 3.14, 69.48)

# accessing from the first element to the last element


>>> print(Tup1[:])
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)

3.​To join two tuples


Input: tup1=(1,2) tup2=(3,4) Output: tup3=(1,2,3,4)

tup3=tup1+tup2

4.​ To delete an entire tuple

The del command can be used.


Syntax:
del tuple_name

5.​ Tuple Assignment

>>> (a, b, c) = (34, 90, 76)


>>> print(a,b,c)
34 90 76 //Output

6.​In and Not in operator

tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")

# In operator

print('Tuple' in tuple_) //True

print('Items' in tuple_) //False


# Not in operator

print('Immutable' not in tuple_) //False

print('Items' not in tuple_) //True

7.​count ( ) : Returns number of similar elements present


in the last.
List.count(value)

MyList=[36 ,12 ,12]


x = MyList.count(12)
print(x)
Output: 2

index ( ) : Returns index value of the first recurring element


List.index(element)

MyList=[36 ,12 ,12]


x = MyList.index(12)
print(x)
Output: 1

****************************************************************************************************

SETS :

●​ Sets only contain unique elements.


●​ set.discard(value) OR set.remove(value)
This deletes the particular element from the set.
discard() will not give error even if the value does not exists in the set but
remove() will give error
●​ set.add(value)
This is used to add an additional element.
●​ set.update([value1,value2,etc...])

This is also used to add additional elements but to add more than one element.
●​ In sets, the values will be unsorted so while printing we cannot predict the order.
1.​ Creating set

Set_Variable = {E1, E2, E3 …….. En}

2.​ Set Operations

Union :
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
U_set=set_A|set_B OR set_U=set_A.union(set_B)
print(U_set)
{2, 4, 6, 8, 'A', 'D', 'C', 'B'} //Output

Intersection:

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B) OR print(set_A.intersection(set_B))
Output: {'A', 'D'}
Difference :

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B) OR print(set_A.difference(set_B))
Output: {2, 4}

Symmetric difference :

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B) OR print(set_A.symmetric_difference(set_B))
Output: {2, 4, 'B', 'C'}

****************************************************************************************************
INBUILT-FUNCTIONS IN LIST:
Strings
Inbuilt-functions :
●​ To reverse : str[::-1]
●​ To check of a character or word is in another string : in
●​ To check if a character or word is not in another string : not in
●​ To find length of a string : len
●​ To convert a string to uppercase : str.upper()
●​ To convert a string to lowercase : str.lower()
●​ To change one character or word to another in a string :
str.replace(val1,val2)
●​

Program

1.​Count the number of duplicates


Input: 9
1,2,2,3,4,4,4,5,5
Output: 3

lst=[]
n=int(input())
for i in range(0,n):
j=int(input())
lst.append(j)
ones=set()
for i in range(0,n):
if lst.count(lst[i])>1:
ones.add(lst[i])
print(len(ones))

2.​To remove a particular character in string

str1=input()
lst=list(str1)
le=len(lst)
ch=input()
str2=""
for i in range(0,le):
if lst[i]==ch:
pass
else:
str2+=lst[i]
print(str2)

3.​To remove particular character at beginning and end of a


string

Input: pinep Output: ine


Input: apple Output: apple

str1 = input()
str2 = str1.strip('p')
print(str2)

4.​To replace particular substring with another substring

Input: manusan san zxy


Output: manuzxy

str1 = input()
str2 = input()
str3=input()
print(str1.replace(str2,str3))

5.​To count occurrences of particular substring in a string

Input: manithnianni ni
Output : 3
str1 = input()
str2 = input()
print(str1.count(str2))

6.​String to list

str1 = input()
print(str1.split())
print(list(str1))

Input : hey hi hello


Output :
['hey', 'hi', 'hello']
['h', 'e', 'y', ' ', 'h', 'i', ' ', 'h', 'e', 'l', 'l', 'o']

7.​To reverse a string

string = "Hello, World!"


reversed_string = string[::-1]
print(reversed_string)

8.​To count the number of vowels

string = "OpenAI"
vowels = 'aeiouAEIOU'
count = 0
for char in string:
if char in vowels:
count += 1
print(f"Number of vowels in '{string}':", count)

9.​To find length of a string

string = "Python"
length = len(string)
print(f"Length of '{string}':", length)
10.​ To convert to uppercase or lowercase

string = "hello"
uppercase_string = string.upper()
lowercase_string=string.lower()
print(uppercase_string,lowercase_string)

11.​ To replace a character or word with another

string = "Python is fun"


no_spaces_string = string.replace(" ", "")
str1=”is”
str2=”will be”
new_string=string.replace(str1,str2)
print(no_spaces_string,new_string)

12.​ Capitalize the First Letter of Each Word

sentence = "hello world"


capitalized_sentence = sentence.title()
print(capitalized_sentence)
# Output: Hello World

13.​ Find the First Occurrence of a Substring

string = "Hello, World!"


index = string.find("World")
print(index)
# Output: 7

14.​ Remove Whitespace from Both Ends of a String

string = " Hello, World! "


trimmed_string = string.strip()
print(trimmed_string)
# Output: Hello, World!

15.​ Repeat a String Multiple Times

string = "Hello"
repeated_string = string * 3
print(repeated_string)
# Output: HelloHelloHello

16.​ Split a String into a List of Words

sentence = "Python is great"


words_list = sentence.split()
print(words_list)
# Output: ['Python', 'is', 'great']

17.​ Check if a String is Numeric and alphabetic

string1 = "12345"
string2=”hello”
is_numeric = string1.isdigit()
is_alpha=string2.isalpha()
print(is_alpha)
print(is_numeric)
# Output: True
True

18.​ Find the Last Occurrence of a Substring

string = "Hello, World! Hello again!"


last_occurrence = string.rfind("Hello")
print(last_occurrence)
# Output: 14
19.​ Check if All Characters in a String are Uppercase and
lowercase

string1 = "HELLO"
string2=”hello”
is_upper = string1.isupper()
is_lower=string2.islower()
print(is_upper)
print(is_lower)
# Output: True
True

—--------------------------------------------**********************----------------------------------------------
LEVEL - 4

Topics : Functions

1.​Circular prime number ( The number when rotated will also be


prime number)

def func(n):
for i in n:
s=str(i)
f=1
for j in range(len(s)):
rot=int(s[j:]+s[:j])
if rot<2:
f=0
break
for k in range(2,int(rot**0.5)+1):
if rot%k==0:
f=0
break
if f==0:
print("NOT")
else:
print("YES")
n=input().split()
func(n)
2.​ATM Machine ( input : 3 10 2 9 4 3 2 output : 10110
Explanation: If withdrawal possible put 1 if not put 0 )

def func(n,nums):
amt=int(n[1])
lst=[]
ans=""
for i in nums:
lst.append(int(i))
for i in lst:
if amt>=i:
amt-=i
ans+="1"
else:
ans+="0"
print(ans)

n=input().split()
nums=input().split()
func(n,nums)

3.​Get a single input from the user, convert it to a list, pass it


to a function, multiply all the values inside list [including float
and int] and return the value. ( if input contains even 1 float
number then output should be in float)
Sample input : 2,3,4,5 sample output : 120
Sample input : 1.5,2,3.5,4 sample output : 42.0

def func(n):
lst=[]
c=0
s=str(n)
if '.' in s:
c=1
for i in n:
lst.append(float(i))
ans=1
for i in lst:
ans*=i
if c==1:
print(float(ans))
else:
print(int(ans))

n=input().split(",")
func(n)

4.​Buy Two Chocolates

def func(n,m):
lst=[]
for i in n:
lst.append(int(i))
lst.sort()
if lst[0]+lst[1]<=m:
m-=lst[0]
m-=lst[1]
print(m)

n=input().split()
m=int(input())
func(n,m)

5.​Maximum Product of Three Numbers

def func(n):
lst=[]
for i in n:
lst.append(int(i))
lst.sort()
m1=lst[-1]*lst[-2]*lst[-3]
m2=lst[0]*lst[1]*lst[-1]
ans=max(m1,m2)
print(ans)

n=input().split(",")
func(n)

6.​Count of palindromic substrings from a given string

def sub(s):
c=0
for i in range(len(s)):
for j in range(i+1,len(s)+1):
substr=s[i:j]
if substr==substr[::-1]:
c+=1
return c
s=input()
ans=(sub(s))
print(ans)

7.​Combinations: nCr = n! / (r! * (n – r)!)

import math
def func(n,r):
print(math.comb(n,r))
n=int(input())
r=int(input())
func(n,r)
8.​Prime Number in the given range note: Two Inputs to be given

def func(n1,n2):
for i in range(n1,n2):
f=1
for j in range(2,i):
if i%j==0:
f=0
break
if f==1 and i>1:
print(i,end=" ")
n1=int(input())
n2=int(input())
func(n1,n2)

9.​Maximum digit sum of two combinations :


Input: 3 (no.of.inputs) 867
Output : 12
Explanation: (8,6) (8,7) (6,7) => 8*6=48, 8*7= 56, 6*7 = 42
Digit sum the answers : 4+8 =12, 5+6 = 11, 4+2=6; max =
12

def func(nums):
m=0
lst=[]
for i in nums:
lst.append(int(i))
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
p=lst[i]*lst[j]
csum=sum(int(k) for k in str(p))
m=max(m,csum)
print(m)
n = int(input())
nums=input().split()
func(nums)

10.​ Time Conversion to 24 hour format


def func(s):
hr=int(s[:2])
ms=s[2:8]
ap=s[-2:]
if ap=='AM':
if hr==12:
hr=0
else:
if hr!=12:
hr+=12
print("{:02d}{}".format(hr,ms))
s = input()
func(s)

11.​ To count number of upper and lowercase letters in a string

def func(s):
u=0
l=0
for i in s:
if i.isupper():
u+=1
if i.islower():
l+=1
print("UPPER:",u,"LOWER:",l)
s=input()
func(s)
12.​ Keyboard Row - LeetCode

def func(s):
one=['q','w','e','r','t','y','u','i','o','p']
two=['a','s','d','f','g','h','j','k','l']
three=['z','x','c','v','b','n','m']
st=[]
ans=[]
lower=''
o,t,th,l=0,0,0,0
for i in s:
lower=i.lower()
o,t,th=0,0,0
l=len(lower)
for j in lower:
if j in one:
o+=1
elif j in two:
t+=1
elif j in three:
th+=1
if o==l or t==l or th==l:
ans.append(i)
print(ans)
n=int(input())
s=[]
for i in range(0,n):
s.append(input())
func(s)

13.​ Maximum product of word length


def func(s,n):
maxp=0
for i in range(0,n):
l1=len(s[i])
for j in range(i+1,n):
l2=len(s[j])
if not set(s[i]) & set(s[j]):
p=l1*l2
maxp=max(maxp,p)
print(maxp)
n=int(input())
s=[]
for i in range(0,n):
s.append(input())
func(s,n)

14.​ Integer to English Words

def func(num):
if num == 0:
print("Zero")
return

below_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",
"Eighteen", "Nineteen"]

tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]

thousands = ["", "Thousand", "Million", "Billion"]


result = ""
i=0
while num > 0:
if num % 1000 != 0:
c = num % 1000
cword= ""
if c >= 100:
cword+= below_20[c// 100] + " Hundred "
c%= 100
if c>= 20:
cword+= tens[c// 10] + " "
c%= 10
if c> 0:
cword+= below_20[c] + " "
result = cword+ thousands[i] + " " + result
num //= 1000
i += 1
result.strip()
result +=”.”
print(result)

num= int(input())
func(num)

15.​ Decimal to Binary with 7 precision

def func(n,p):
ipart=int(n)
fpart=n-ipart
ibin=bin(ipart)[2:]
fbin="."
for i in range(p):
fpart*=2
bit=int(fpart)
fbin+=str(bit)
fpart-=bit
print(ibin+fbin)

n=float(input())
func(n,7)
16.​ Two out of three ( Resultant array needs to be sorted
ascending)

def func(n1,n2,n3):
num1,num2,num3=[],[],[]
for i in n1:
num1.append(int(i))
for i in n2:
num2.append(int(i))
for i in n3:
num3.append(int(i))
s1,s2,s3=set(num1), set(num2), set(num3)
ans=(s1 & s2) | (s1 & s3) | (s2 & s3)
lst=list(ans)
lst.sort()
print(lst)

n1=input().split(",")
n2=input().split(",")
n3=input().split(",")
func(n1,n2,n3)

17.​ Print the longest word


Input =programming python
Output = programming

def func(s):
w=s.split()
ans=max(w,key=len)
print(ans)
s=input()
func(s)
18.​ Last Stone Weight

def func(n):
lst=[int(i) for i in n]
while(len(lst)>=2):
lst.sort(reverse=True)
x=lst.pop(0)
y=lst.pop(0)
if x!=y:
lst.append(x-y)
print(lst[0] if lst else 0)

n=input().split(",")
func(n)

19.​ Consecutive Characters

def func(s):
maxp=1
cp=1
#print(len(s))
for i in range(len(s)-1):
if s[i]==s[i+1]:
cp+=1
else:
cp=1
maxp=max(maxp,cp)
print(maxp)

s=input()
func(s)
20.​ House Robber - LeetCode ( 198 )

def func(n):
lst=[]
for i in n:
lst.append(int(i))
sum=0
#print(len(lst))
for i in range(0,len(lst),2):
sum+=lst[i]
print(sum)
n=input().split()
func(n)

21.​ Prime factors ( Explanation : if number is 18 checks


factors 18/2=9 and checks factors for 9 so 9/3=3 the checks
factors for 3 so 3/3=0 so output is 2,3,3 )

def func(n):
pf = []
for i in range(2, n + 1):
while n % i == 0:
pf.append(i)
n //= i
pf.sort()
print(pf)

n = int(input())
func(n)

22.​ Intersection of Two Arrays - LeetCode


def func(n1, n2):
lst1 = list(n1)
lst2 = list(n2)
lst=[]
ans = list(set(lst1) & set(lst2))
for i in ans:
lst.append(int(i))
print(lst)

n1 = input()
n2 = input()
func(n1, n2)

23.​ https://leetcode.com/problems/min-cost-climbing-stairs/de
scription/

def func(n):
lst=[int(i) for i in n]
n=len(lst)
if n==0:
print(“0”)
if n==1:
print(lst[0])
dp0,dp1=0, 0
for i in range(2, n + 1):
cost=min(dp1+lst[i - 1], dp0 + lst[i - 2])
dp0,dp1=dp1,cost
print(dp1)

n=input().split()
func(n)

24.​ Maximum binary number


def func(n,nums):
op=int(n[1])
ans=0
lst=[int(i) for i in nums]
for i in range(0,op):
if lst[0]==0:
lst[0]=1
elif lst[0]==1:
lst.append(0)
for i in lst:
ans=ans*10+i
print(ans)

n=input().split()
nums=input()
func(n,nums)

25.​ Permutations in String

from itertools import permutations


def func(s):
l=permutations(s)
lst=[' '.join(i) for i in l]
print(lst)
print(len(lst))

s=input()
func(s)

26.​ Middle Number Identification

def func(n):
lst=[]
for i in n:
lst.append(int(i))
l=len(lst)
ans=l//2
if l%2==1:
print(lst[ans])
else:
print((lst[ans]-1+lst[ans])/2)

n=input().split()
func(n)

27.​ Matrix Multiplication

def input_matrix():
r=int(input())
c=int(input())
m=[]
for i in range(r):
row=[int(input()) for i in range(c)]
m.append(row)
return m

def multiply_matrix(m1,m2):
r1,c1=len(m1),len(m1[0])
r2,c2=len(m2),len(m2[0])

ans=[[sum(m1[i][k] * m2[k][j] for k in range(c1)) for j in range(c2)] for i in range(r1)]


for row in ans:
print(row)

m1 = input_matrix()
m2 = input_matrix()
ans = multiply_matrix(m1,m2)
28.​ Minimum Amount of Time to Fill Cups - LeetCode

def func(amt):
lst=[int(i) for i in amt]
lst.sort(reverse=True)
print(max(lst[0], (sum(lst) + 1) // 2))+

amt=input().split()
func(amt)

29.​ Interleaving
(https://leetcode.com/problems/interleaving-string/description/ )

def is_interleave(s1, s2, s3, i=0, j=0, memo={}):


if (i, j) in memo:
return memo[(i, j)]

if i == len(s1) and j == len(s2):


return True

k=i+j
if k >= len(s3):
return False

if i < len(s1) and s1[i] == s3[k] and is_interleave(s1, s2, s3, i+1, j, memo):
memo[(i, j)] = True
return True
if j < len(s2) and s2[j] == s3[k] and is_interleave(s1, s2, s3, i, j+1, memo):
memo[(i, j)] = True
return True

memo[(i, j)] = False


return False

s1 = input().strip()
s2 = input().strip()
s3 = input().strip()

if len(s1) + len(s2) != len(s3):


print("false")
else:
print("true" if is_interleave(s1, s2, s3) else "false")

30.​ Poison Attacking


https://leetcode.com/problems/teemo-attacking/description/

def func(nums,s):
num=[int(i) for i in nums]
if not num or s==0:
print("0")
tot= 0
for i in range(len(num)-1):
tot+=min(s,num[i+1]-num[i])
print(tot+s)

nums=input().split()
s=int(input())
func(nums,s)

31.​ Quadratic Equation Solving


import math
def func(a,b,c):
if a==0:
print("NO")
return
dis=b**2 - 4*a*c
if dis>0:
r1=(-b + math.sqrt(dis))/2*a
r2=(-b - math.sqrt(dis))/2*a
print("Two real and distinct roots : {:.2f} , {:.2f}".format(r1,r2))
elif dis==0:
r=-b/2*a
print("One real and repeated roots : {:.2f}".format(r))
else:
r=-b/2*a
i=math.sqrt(abs(dis))/2*a
print("Two complex roots {:.2f} +- {:.2f}i".format(r,i))

a=int(input())
b=int(input())
c=int(input())
func(a,b,c)

You might also like