Python Part-1-1
Python Part-1-1
Python Part-1-1
• Python is known for its simplicity, readability, and versatility, making it one of the most
popular programming languages in the world
Jupyter Notebooks
Jupyter notebooks are a powerful tool for interactive programming and data analysis. They
provide a convenient way to work with code, text, and visualizations all in one place. Here are
some essential keyboard shortcuts.
• Ctrl+Enter: Execute the current cell and stay on the same cell.
• Alt+Enter: Execute the current cell and move to the next cell.
• Shift+Enter: Execute the current cell and move to the next cell.
a=10
print('Namaste World')
print('This is Ismail')
print(type(a))
10
Namaste World
This is Ismail
<class 'int'>
10
Variables
In Python, variables are used to store data values. They act as containers to hold different types
of information, such as numbers, strings, lists, dictionaries, and more
variable_name = value
# Integer variable
age = 30
# String variable
name = "Ismail"
# List variable
fruits = ['apple', 'banana', 'orange']
# Dictionary variable
person = {'name': 'Ismail', 'age': 21, 'occupation': 'Engineer'}
30
10 20
ac_c1= 10
#this is a comment
print(ac_c1)
10
a = 10
print(a) # Output: 10
a = 20
print(a) # Output: 20
10
20
Hi, this is ismail
a=10
a=10
print(a,type(a))
10 <class 'int'>
a1 = 23
a2= 3.4
a3= 4+5j
print(a1,type(a1))
print(a2,type(a2))
print(a3,type(a3))
23 <class 'int'>
3.4 <class 'float'>
(4+5j) <class 'complex'>
• Each time we assign a new value to the variable a, it creates a new object and, hence, a
new memory address. As a result, the id() function will return different unique identifiers
for each value assigned to a.
a=4
print(id(a))
a=6
print(id(a))
140731876893576
140731876893608
140731876893640
a=10
b=10
print(id(a))
print(id(b))
# points to same value
# this optimmization only for -5 to 256
140732494111816
140732494111816
a=1000
b=1000
print(id(a))
print(id(b))
# for java/c++ some fixed memory for integer ex:4 bytes
# For python its different
Arithmetic Operations
The basic arithmetic operations are:
• Addition (+)
• Subtraction (-)
• Multiplication (*)
• Division (/)
• Integer Division (//)
• Exponentiation (**)
• Modulus (%)
a=9
b=4
print(a+b)
print(a-b)
print(a*b)
print(a/b) # returns float
print(a//b) #integer division
print(a**b) #exponentiation
print(a%b) #remaindeer
13
5
36
2.25
2
6561
1
2*3/4
1.5
2*(3//4)
(2*3)//4
1
## Simple Intrest
p=100
t=5
r=5
print((p*t*r)//100)
25
# fareheit to celcius
f=100
c=(f-32)*5/9
c
37.77777777777778
Input
a=input() #always takes as string
print(type(a),a)
<class 'str'> 5
c=a+b
print(c)
i = int(5.5)
print(i,type(i))
12
79
<class 'int'>
91.0
5 <class 'int'>
Boolean
a=True
b=False # capital
c="World"
type(b)
bool
Relational Operator
a=10
b=20
print(a>b)
print(a>=b)
print(a<=b)
print(a==b)
print(a!=b)
False
False
True
False
True
Logical Operators
a = 5>10
b = 4<5
c = False
r1 = a and b
r2 = a or b
r3 = not c
print(r1,r2,r3)
Conditional Operators
if a>b:
print("False")
else:
print("True")
True
# even or odd
n= int(input())
if n%2==0:
print("Even")
else:
print("Odd")
5456
Even
454561
Odd
a = int(input())
b = int(input())
12
45
True
a= int(input())
b= int(input())
c= int(input())
max: 45
n= int(input())
if n> 10:
print("Red")
elif n>=5:
print("Green")
elif n>0:
print("Yellow")
45
Red
n= int(input())
if n>0:
print("Positive")
elif n<0:
print( "Negative")
else:
print( "Zero")
45
Positive
Nested Conditionals
n= int(input())
if n%2==0:
print("Even")
if n==0:
print("zero")
else:
print("Odd")
789
Odd
Loops
#first n natural numbers
n = int(input())
i=1
while i<=n:
print(i)
i+=1
1
2
3
4
5
n = int(input())
sum=0
i=1
while i<=n:
sum+=i
i+=1
print(sum)
456
104196
#prime or not
import math
n = int(input())
i=2
istrue= True
11
Prime
Nested While
# print all prime numbers between range 2,n
n = int(input())
i = 2
while i<=n:
istrue= True
j=2
while j <= math.sqrt(i):
if i%j ==0:
istrue= False
j+=1
if istrue:
print(i,"Prime")
i+=1
11
2 Prime
3 Prime
5 Prime
7 Prime
11 Prime
while s<=e:
print( (5*(s-32)) / 9)
s+=w
0
200
30
-17.77777777777778
-1.1111111111111112
15.555555555555555
32.22222222222222
48.888888888888886
65.55555555555556
82.22222222222223
n= int (input())
if n== 1:
a= int (input())
b= int (input())
print(a+b)
elif n == 2:
a= int (input())
b= int (input())
print(a-b)
elif n == 3:
a= int (input())
b= int (input())
print(a*b)
elif n == 4:
a= int (input())
b= int (input())
print(a//b)
elif n==5:
a= int (input())
b= int (input())
print(a%b)
else:
print ("Invalid Operation")
3
12
12
144
# reverse a number
n=int(input())
result=0
while n!=0:
l=n%10
result=result*10 + l
n=n//10
print(result)
449854896565
565698458944
# palindrome
123321
Palindrome
n = int(input())
e = 0
odd = 0
while n != 0:
l = n % 10
if l % 2 == 0:
e += l
else:
odd += l
n = n // 10
print("even", e)
print("odd", odd)
123456
even 12
odd 9
n= int(input())
print(fib(n))
12
144
Patterns
# Steps to approach a pattern
# 1.No of rows
# 2.No of columns to print at generic ith row => can be a function of
n,i,j =>f(n,i,j)
# 3.What to print
# SQUARE PATTERN
n=int(input())
i=1
while(i<=n):
j=1
while j<=n:
print("*",end="") # print command go to next line
automatically
j+=1
print()
i+=1
*****
*****
*****
*****
*****
n=int(input())
i=1
while(i<=n):
j=1
while j<=n:
print(i,end="")
j+=1
print()
i+=1
1111
2222
3333
4444
n=int(input())
i=1
while(i<=n):
j=1
while j<=n:
print(j,end="")
j+=1
print()
i+=1
1234
1234
1234
1234
n=int(input())
i=1
while(i<=n):
j=n
while j>=1:
print(j,end="")
j-=1
print()
i+=1
4321
4321
4321
4321
1
12
123
1234
12345
1
23
345
4567
56789
n=int(input())
i=1
k=1
while(i<=n):
j=1
while j<=i:
print(k,end=" ")
k+=1
j+=1
print()
i+=1
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Character Patterns
• In Python, adding a string and an integer together is invalid: str + int =
invalid.
• To get the ASCII value of a character, use the ord() function, but remember it works
for single characters only: ord('A').
• To get the character from its ASCII value, use the chr() function: chr(65) returns
'A'.
# A B C D E
n=int(input())
i=1
while(i<=n):
j=1
while j<=n:
print(chr(ord('A') + j - 1),end=" ")
j+=1
print()
i+=1
A B C D E
A B C D E
A B C D E
A B C D E
A B C D E
n=int(input())
i=1
while(i<=n):
j=1
while j<=n:
print(chr(ord('A')+(i+j-1)-1),end=" ")
j+=1
print()
i+=1
A B C D E
B C D E F
C D E F G
D E F G H
E F G H I
n=int(input())
i=1
while(i<=n):
j=1
k=n-i+1
while j<=i:
print(chr(ord('A')+ k -1),end=" ")
k+=1
j+=1
print()
i+=1
F
E F
D E F
C D E F
B C D E F
A B C D E F
INVERTED PATTERNS
n=int(input())
i=1
while(i<=n):
j=1
while j<=(n-i+1):
print("*",end=" ")
j+=1
print()
i+=1
* * * * *
* * * *
* * *
* *
*
# n-i+1
n=int(input())
i=1
while(i<=n):
j=1
while j<=(n-i+1):
print(j,end=" ")
j+=1
print()
i+=1
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Reversed Pattern or Mirror Pattern
n=int(input())
i=1
while(i<=n):
s=1
while s<=(n-i):
print(" ",end="")
s+=1
j=1
while j<=(i):
print("*",end="")
j+=1
print()
i+=1
*
**
***
****
*****
Isoceles Pattern
n=int(input())
i=1
while(i<=n):
# Spaces
s=1
while s<=(n-i):
print(" ",end="")
s+=1
# increasing sequence
j=1
while j<=i:
print(j,end="")
j+=1
k=1
j=j-1
# decreasing sequence
while k<=i-1:
j=j-1
print(j,end="")
k+=1
print()
i+=1
4
1
121
12321
1234321
n=int(input())
i=1
while(i<=n):
# Spaces
s=1
while s<=(n-i):
print(" ",end="")
s+=1
# increasing sequence
j=1
while j<=i:
print(j+i-1,end="")
j+=1
k=1
j=j-1
j=j+i-1
# decreasing sequence
while k<=i-1:
j=j-1
print(j,end="")
k+=1
print()
i+=1
1
232
34543
4567654
567898765
67891011109876
n=int(input())
i=1
while(i<=n):
# Spaces
s=1
while s<=(n-i):
print(" ",end="")
s+=1
# increasing sequence
j=1
while j<=i:
print("*",end="")
j+=1
k=1
j=j-1
# decreasing sequence
while k<=i-1:
j=j-1
print("*",end="")
k+=1
print()
i+=1
*
***
*****
*******
n=int(input())
n1=(n+1)//2
n2=n1-1
i=1
while(i<=n1):
a=1
while(a<=n1-i):
print(" ",end="")
a=a+1
b=1
while(b<=2*i-1):
print('*',end="")
b=b+1
print()
i=i+1
i=n2
while(i>=1):
a=1
while(a<=n2 - i +1):
print(" ",end='')
a = a+1
j=1
while(j<=2*i-1):
print('*',end="")
j=j+1
print()
i = i-1
10
*
***
*****
*******
*********
*******
*****
***
*
for i in sequence:
# code block to execute for each element in the sequence
where start is the starting value (inclusive), stop is the ending value (exclusive),
and step is the increment between values (equences for looping purposes.
n= int(input())
for i in range(1,n+1,1):
print(i)
1
2
3
4
5
#single argument then it takes as end
n= int(input())
for i in range(n+1):
print(i)
0
1
2
3
4
5
print(n)
for i in range(1,n+1):
print(i)
5
1
2
3
4
5
4
3
2
1
0
a=int(input())
b=int(input())
for i in range(a,b+1):
if i%3==0:
print(i)
1
12
3
6
9
12
for i in range(s,b+1,3):
print(i)
4
23
6
9
12
15
18
21
Wrong Syntax
for i in range(0.1, 0.4,0.1): range accepts only integer values
5461
Not Prime
for i in range(1,n+1):
# spaces
for j in range(1, n-i+1):
print(" ", end="")
1
232
34543
4567654
567898765
Keywords in Python
1. break:
• Used to exit from a loop prematurely.
• Stops the current loop iteration and continues with the next statement after the loop.
2. continue:
• Skips the remaining code within the current loop iteration and starts the next iteration.
• Useful for excluding specific items from a loop.
3. pass:
• Acts as a null operation or a no-operation statement.
• Used as a placeholder when a statement is syntactically required but doesn't need to do
anything.
2 7
3 7
4 7
5 7
6 7
Else statement
2 7
3 7
4 7
5 7
6 7
Else statement
1
2
3
4
6
7
8
9
# in c, c++,
# we can do this
# if(a>b){
# }
while i<=3:
pass
i+=1
for i in range(1,4):
pass
# Tems of Ap
# print first x terms of the series 3*N+2 which are not multiples of 4
x= int(input())
i=0
k=1
while i<=x:
if (3*k+2)% 4 != 0:
print(3*k+2)
i+=1
k+=1
5
5
11
14
17
23
26
# sum of numbers 1 to n
n= int(input())
sum=0
for i in range(1, n+1):
sum+=i
# product of numbers 1 to n
product =1
for i in range(1, n+1):
product*=i
print("Product",product)
print("Sum",sum)
Product 120
Sum 15
Strings
A string is a collection of characters, and it can be represented using either single quotes (' ') or
double quotes (" "). For example, a string can be "Namaste, World!" or 'Python Programming'.
Lists
A list is a collection of elements, and it can contain any combination of data types, including
other lists. Lists are enclosed in square brackets [ ] and can be accessed by their index. For
instance, a list could be [1, 2.2, 3, "apple", "banana"].
a="This is a string"
a='This is also a string'
a
str
a[0]
'T'
type(a[0])
str
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[121], line 3
1 # Strings are immutable
2 a="This is"
----> 3 a[3]='a' # can't be changed
5 # string is immutable, variable is not
6 a="Other string"
# To use "" in string use '' and for '' use ""
# we can use escape character \'
a='it\'s a googly'
a
"it's a googly"
# looping a string
a='it\'s a google product'
for i in a:
print(i,end="")
print()
for i in range(0,len(a)):
print(a[i],end="")
it's a google product
it's a google product
c= a+b
a= a+b
print(a)
print(c)
# string comparing
# Capital A to Z (65 to 90)
# Small a to z (97 to 122)
# 'Z' < 'a'
a='Z'
b='a'
print(a<b)
True
print(a.split("world"))
# lower
a= a.lower()
print(a)
# islower
print(a.islower())
True
# isupper
print(a.isupper())
False
# startswith
print(a.startswith("th"))
print(a.endswith("th"))
True
False
'is '
a[:4]
'this'
a[:]
a[2:13:2]
'i sanw'
# ---->end<-----
# end-1 end+1
a[18:2:-1] # up to 3 reverse
'nirts wen a si s'
if p!=-1:
ans= s[:index]+b+s[index+1:]
ans
expressxerox
'eypressxerox'
ans=input()
a='x'
b='y'
for i in range(0,len(ans)):
if ans[i]==a:
ans = ans[:i]+b+ans[i+1:]
ans
codex
'codey'
'eypressyeroy'
# replace :not changed the orginal string , returns the new string
print(a)
This is big string with is random words
Thare are big string with are random words
This is big string with is random words
"abc"[:2]
'ab'
str1="hello"
str1[-1] #same
str1[-1:] #same
'o'
s="abcdefghi"
s[-3:-1]
'gh'
Lists in Python:
• Collection of elements, no need to predefine size or data type.
• Dynamic in size: can grow or shrink as needed.
• Stores various data types.
• Efficiently allocates space and resizes when necessary.
• internally list allocates some space, if we ask more , it will copy the elements to new list
with additional storage and returns it
List Methods
Python provides several built-in methods to perform operations on lists. Some commonly used
list methods include:
[1, 2, 3]
[3, 4, 6]
[] #empty list
[]
a=[1,2,"abc",5+3j]
a
[[1, 2, 3], 5]
b= [ 0 for i in range(0,10)]
print(b)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
b= [ i for i in range(0,10)]
print(b)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b= [ i for i in "ismail"]
print(b)
# length of string
a=[1,2,4,5,6]
print(len(a))
b=[6,7,8]
a=a+b
print(a)
[1, 2, 4, 5, 6, 6, 7, 8]
a=[1,3,5]
b=[6,7,8]
c=a+b
print(c)
[1, 3, 5, 6, 7, 8]
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[184], line 1
----> 1 c+3 #not possible
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[185], line 1
----> 1 a*b
a*3 #possible
# copies 3 times and gives new
[1, 3, 5, 1, 3, 5, 1, 3, 5]
# add to end
a.append(4)
print(a)
[1, 3, 5, 4]
[10, 1, 3, 5, 4]
# add b to a
a.extend(b) # a=a+b
print(a)
[10, 1, 3, 5, 4, 6, 7, 8]
# remove "data"
a.remove(7)
a
[10, 1, 3, 5, 4, 6, 8]
# remove from particular index, removes and returns the popped value
a.pop(0)
print(a)
[1, 3, 5, 4, 6, 8]
del a[1]
a
[1, 5, 4, 8]
Sort
The list.sort() method is a built-in method available for lists in Python. It sorts the elements of
the list in place, which means it modifies the original list directly without creating a new one.
max,min
• min() and max() are built-in functions used to find the minimum and maximum
elements, from an iterable or a set of arguments.
• Both functions work on various data structures like lists, tuples, strings, and other
iterables.
a=[10, 1, 3, 5, 4, 6, 7, 8]
a.sort() #orginal list sorted
print(a)
[1, 3, 4, 5, 6, 7, 8, 10]
b=[1,3,5,7,9,8,5,4,2,1]
print(max(b))
The in operator is a built-in operator in Python used to check for membership in a sequence or
container
100 in a
False
10
n=int(input())
a=[]
for i in range(n):
s= int(input())
a.append(s)
a
5
1
4
5
5
8
[1, 4, 5, 5, 8]
## 5
# 1 2 3 4 5
n=int(input())
a=input().split(" ")
s=[]
for i in a:
s.append(int(i))
s
5
1 2 3 4 5
[1, 2, 3, 4, 5]
s=[int(i) for i in a]
s
5
1 2 2 4 5
[1, 2, 2, 4, 5]
5
1 2 3 4 5
[1, 2, 3, 4, 5]
## 5 1 2 3 4 5
even=0
odd=0
for i in l:
if i%2 == 0:
even+=i
else:
odd+=i
print(even-odd)
12 3 4 5
8
length= len(l)
for i in range(0,length,2):
if i< length-1:
l[i],l[i+1]= l[i+1],l[i]
for i in l:
print(i,end="")
1 2 3 4 5 678
21436785
List in Python
List slicing in Python allows you to extract a portion of a list by specifying start, stop, and step
parameters. The syntax for list slicing is as follows:
new_list = list_name[start:stop:step]
Where:
• start: The index where the slice begins (inclusive). If omitted, the slicing starts from the
beginning of the list (index 0).
• stop: The index where the slice ends (exclusive). If omitted, the slicing goes until the end
of the list.
• step: The step size or increment. If omitted, the default value is 1, which means
consecutive elements will be included in thd = 4 print(my_list[start:end]) # Output: [2, 3,
4] ```
Keep in mind that list slicing does not modify the origina
l list; it creates a new list containing the sliced elements. Also, if the start index is greater than
the stop index, or the step is negative, the slice will return an empty list.
# Basic slicing
print(my_list[2:6]) # Output: [3, 4, 5, 6]
print(my_list[:5]) # Output: [1, 2, 3, 4, 5]
print(my_list[5:]) # Output: [6, 7, 8, 9, 10]
print(my_list[:]) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] (a
copy of the entire list)
# Slicing with step
print(my_list[::2]) # Output: [1, 3, 5, 7, 9] (every second
element)
print(my_list[1::3]) # Output: [2, 5, 8] (every third element
starting from index 1)
print(my_list[::-1]) # Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
(reversed list)
# Negative indexing
print(my_list[-3:]) # Output: [8, 9, 10] (last three elements)
print(my_list[:-3]) # Output: [1, 2, 3, 4, 5, 6, 7] (all elements
except the last three)
[3, 4, 5, 6]
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 3, 5, 7, 9]
[2, 5, 8]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[8, 9, 10]
[1, 2, 3, 4, 5, 6, 7]
[2, 3, 4]
print(my_list)
my_list.reverse()
my_list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Multidimensional Lists
In Python, there is nothing specifically called a "multidimensional list." However, we can
represent multidimensional structures using lists of lists. One common example is a 2D list (m x
n), which is essentially a list of lists where each sub-list represents a row or a 1D array.
two_dimensional_list = [
[element_00, element_01, element_02, ..., element_0n],
[element_10, element_11, element_12, ..., element_1n],
...
[element_m0, element_m1, element_m2, ..., element_mn]
]
Here:
While working with more dimensions, the concept remains the same, and you can nest
additional lists to create 3D or higher-dimensional arrays. However, as the dimensionality
increases, it becomes more complex, and using specialized libraries like NumPy for handling
multidimensional arrays becomes more efficient and convenient.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
6
3
3
Method 1:
This method takes input in a specific format where the first line contains two space-separated
integers m and n, followed by m * n space-separated integers representing the elements of the
2D lis oose any of them based on your preference and the input format you want to use.
m, n = map(int, input().split())
l = []
for i in range(m):
next_row = [int(i) for i in input().split()]
l.append(next_row)
print(l)
# Input:
# 2 3
# 1 2 3
# 4 5 6
# Output:
# l = [[1, 2, 3], [4, 5, 6]]
2 3
1 2 3
4 5 6
Method 2:
This method is similar to Method 1, but it uses nested loops to take input for each element of the
2D list.
m, n = map(int, input().split())
l = []
for i in range(m):
next_row = []
for j in range(n):
next_row.append(int(input()))
l.append(next_row)
print(l)
# Input:
# 2 3
# 1
# 2
# 3
# 4
# 5
# 6
# Output:
# l = [[1, 2, 3], [4, 5, 6]]
2 3
1
2
3
4
5
6
[[1, 2, 3], [4, 5, 6]]
Method 3:
This method takes input in the same format as Method 1 but uses list slicing to construct the 2D
list.
m, n = map(int, input().split())
l = [int(i) for i in input().split()]
ol = []
for i in range(m):
start_index = n * i
end_index = n * (i + 1) # excludes kabbati
next_row = l[start_index:end_index]
ol.append(next_row)
print(ol)
# Input:
# 2 3
# 1 2 3 4 5 6
# Output:
# ol = [[1, 2, 3], [4, 5, 6]]
2 3
1 2 3 4 5 6
# diagnol of 2d matrix
a=[[1,2,3],[4,5,6],[7,8,9]]
[1, 5, 9]
Keep in mind that slicing creates new lists containing the sliced elements and doesn't modify the
original list.
List comprehension
List comprehension is a concise way to create lists in Python. It provides a compact and readable
syntax for generating new lists from existing ones, applying transformations, and filtering
elements based on specific conditions. List comprehension is a powerful feature in Python that
allows you to write elegant and efficient code.
Where:
List comprehensions are concise and often more readable than writing equivalent code using
traditional loops. They are widely used in Python and are considered one of the "Pythonic" ways
to create and manipulate lists. However, it's essential to use them judiciously to maintain code
clarity and readability.
# Slicing rows
row_slice = matrix[1:3] # Rows 2 and 3
print(row_slice)
# Output: [[4, 5, 6], [7, 8, 9]]
numbers = [1, 2, 3, 4, 5]
number_squares = [(x, x**2) for x in numbers]
print("number squares:",number_squares)
# Output: [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
[[0, 0], [1, 2], [2, 4], [3, 6], [4, 8]]
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28],
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42],
[0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56]]
0
10
20
30
40
0
10
20
30
40
a=[1,2,3,4,[56]]
b=list(a)
a[0] = 5
a[4][0]=3
print(b)
# They only create a copy on the 0th level . Thats called shallow
copy. The elements of a nested
# elements are copied by reference
[1, 2, 3, 4, [3]]
Palindrome
print("".join(reversed("Hello World")))
dlroW olleH
<class 'reversed'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
a= "Albr"
for i in range(len(a)):
s=""
for j in range(i,len(a)):
s+=a[j]
print(s)
A
Al
Alb
Albr
l
lb
lbr
b
br
r
array = [1, 4, 9, 3, 2]
found_equilibrium = False
for i in range(len(array)):
left_sum = sum(array[0:i])
right_sum = sum(array[i+1:])
if left_sum == right_sum:
print(i)
found_equilibrium = True
break
if not found_equilibrium:
print(-1)
[[0, 0, 0, 0, 0],
[0, 1, 2, 3, 4],
[0, 2, 4, 6, 8],
[0, 3, 6, 9, 12],
[0, 4, 8, 12, 16]]
# Wave print: print first column top to bottom and 2nd column bottom
to top , repeat this
isdown= True
for i in range(5):
if isdown:
for j in range(0,5):
print(a[j][i],end=" ")
print()
isdown=False
else:
for j in range(4,-1,-1):
print(a[j][i],end=" ")
print()
0 0 0 0 0
4 3 2 1 0
8 6 4 2 0
12 9 6 3 0
16 12 8 4 0
Functions
Functions are blocks of reusable code that perform specific tasks. Functions help in organizing
code, making it modular, and improving code readability. They allow you to break down complex
problems into smaller, manageable parts, making the code easier to maintain and understand.
In Python, functions are blocks of reusable code that perform specific tasks. Functions help in
organizing code, making it modular, and improving code readability. They allow you to break
down complex problems into smaller, manageable parts, making the code easier to maintain
and understand.
To define a function in Python, you use the def keyword, followed by the function name, a list of
parameters (if any), and a colon (:). The function body is indented, and it contains the code that
will be executed when the function is called.
In Python, functions are first-class citizens, which means you can pass functions as arguments to
other functions, return functions from functions, and store functions in variables or data
structures. This capability is essential for functional programming and enables powerful
programming paradigms.) `
# nCr =n!/(n-r)!*r!
# def name(arguments/inputs)
def factorial(a):
fact=1
for i in range(1,a+1):
fact= fact*i
return fact
n= int(input())
r= int(input())
10
2
The nCr is 45
def greet(name="Telangana"):
return f"Hello, {name}!"
print(greet())
Hello, Telangana!
2.Readable
import math
# prime function
def isPrime(a):
for i in range(2,int(math.sqrt(a))+1):
if a%i==0:
break
else:
return True
return False
isPrime(100)
False
import math
PrintPrimes2ToN(20)
2
3
5
7
11
13
17
19
def ncr(n,r):
return factorial(n)//(factorial(n-r) * factorial(r))
ncr(5,4)
# D
# C
# B
# A
def A():
print('A starts')
print('A ends')
def B():
print('B starts')
A()
print('b ends')
def C():
B()
print('C starts ')
print('C ends ')
C()
B starts
A starts
A ends
b ends
C starts
C ends
def increment(i):
i= i+1
print("in function,",i)
k=10
increment(k)
print("outside function",k)
in function, 11
outside function 10
# using list
# changes effects the orginal
# pointer stores reference
a=[2,3,4]
increment(a)
print("outside function",a)
in function, [3, 3, 4]
outside function [3, 3, 4]
# change list
# pointer stores reference, completly changing to other list
def increment(l):
l=[0,8]
print("in function,",l)
a=[2,3,4]
increment(a)
print("outside function",a)
in function, [0, 8]
outside function [2, 3, 4]
increment(a)
print("outside function:",a)
def create_n_array(n):
l=[ i for i in range(n,0,-1)]
return l
print(create_n_array(5))
[5, 4, 3, 2, 1]
n=int(input())
l=[ i for i in range(n)]
for i in range(0,length,2):
l[i],l[i+1]=l[i+1], l[i]
10
[1, 0, 3, 2, 5, 4, 7, 6, 9, 8]
# other approach
n=int(input())
l=[ i for i in range(n,0,-1)]
i=0
while i+1 < len(l):
l[i],l[i+1]=l[i+1], l[i]
i= i+2
l
10
[9, 10, 7, 8, 5, 6, 3, 4, 1, 2]
Variable Scope in Python
In Python, variables can have different scopes, which determine where the variable is accessible
and how long it exists. There are two main types of variable scope:
1. Local Variables: These variables are defined inside a function and are only
accessible within that function. They are created when the function is called and
exist as long as the function is executing.
2. Global Variables: These variables are defined outside any function and are
accessible throughout the entire program. They are created when the program
starts and exist until the program he function will result in an error.
def f1():
b1 =12 #local variable
print(a1) #global variable is acessible here
print(b1)
print(a1)
f1()
print(b1) #cannot print a local variable outside a function
10
10
12
----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Cell In[50], line 10
8 print(a1)
9 f1()
---> 10 print(b1) #cannot print a local variable outside a function
def f1():
b1 =12 #local variable
print(a1) #a1 can be called, even a1 is defined after function but
it should be defined before the function call
print(b1)
# print(c3) #cant accessible, c2 is defined after function call
a4 = 13
def f4():
a4=12 #acess is fine but when you try to change, python assumes
you want to create a variable
print(a4)
print(a4) #13
f4()
print(a4)
13
12
13
a4 = 13
def f4():
global a4 #this is syntax, dont assign in this statement
a4 =12 #if you want use global, we explicitly specify global
print(a4)
print(a4) #13
f4()
print(a4)
13
12
12
# Default Parameters
# ex: print("abc")
# ex: print("abc",end="")
# arguments order:
# non default, default
15
sum_of_numbers(b=8,a=5,d=56)
69
# must pass default arguments by specifying or normal passing
sum_of_numbers(3,4,d=7)
14
# Farenheit to celcius
# s,e.w
def f_to_c(f):
return (f-32)*5//9
s=int(input())
e=int(input())
w=int(input())
for i in range(s,e+1,w):
print(i," ",f_to_c(i))
50
300
20
50 10
70 21
90 32
110 43
130 54
150 65
170 76
190 87
210 98
230 110
250 121
270 132
290 143
def check_fibanocci(n):
if n==1:
return True
past=1
curr=1
i=1
while i<n:
future = past+curr
past =curr
curr=future
i=future
if i== n:
return True
else:
return False
# if returns not works then else works
check_fibanocci(3)
True
Tuples
• Tuples are similar to list but not same
• Tuples are enclosed in parentheses ( ).
• Tuples are immutable, while lists are mutable.
• Elements in a tuple can be accessed using indexing.
• Tuples can be unpacked into multiple variables.
• Commonly used for returning multiple values from functions.
• Tuples can be used as keys in dictionaries due to their immutability.
• To create a single-element tuple, use a trailing comma after the element: (42,).
• Useful for representing fixed collections of elements.
a=[1,2] #list
b=(1,2) #tuple
print(c,d)
e=1,2 #when you keep multiple things into a single thing, python makes
it a tuple
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
1 2
<class 'list'>
<class 'tuple'>
<class 'int'>
<class 'int'>
<class 'tuple'>
# the indexing and slicing works same way for strings, tuples and
lists
# Tuples are also ordered
a=(1,2,4,7,8,9)
a[0]
a[1:3]
a[1:]
(2, 4, 7, 8, 9)
a=(1,2,4,7,8,9)
a[0]=1
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[69], line 2
1 a=(1,2,4,7,8,9)
----> 2 a[0]=1
a=(1,2,4,7,8,9)
a=(4,5) #this is possible
a=(1,2,4,7,8,9,1,3,5)
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[71], line 1
----> 1 del a[3] #not possible
Functions in tuples
Python provides several built-in functions that you can use with tuples. Here are some of the
most commonly used built-in functions on tuples:
5. sum(tuple): Returns the sum of all elements in the tuple (works only with
numeri,atleast comparablesc elements).
6. tuple.count(element): Returns the number of occurrences of a specific element
in the tuple.
my_tuple = (1, 2, 3, 4, 5, 2)
6
5
1
17
2
2
1 in a #membership checking
True
(1, 2, 3, 4, 5, 6)
# tuple of tuples
d =(a,c)
d
(1, 2, 3, 1, 2, 3)
a=("ab","bc","de")
min(a)
'ab'
# list to tuple
l=[1,2,3]
t=tuple(l)
t
(1, 2, 3)
def sum2(a,b,*more):
print(type(more))
ans=a+b
for i in more:
ans+=i
return ans
print("Sum is ",sum2(10,4,6,10,20))
<class 'tuple'>
Sum is 50
(9, -1)
15
5
Dictionary
• In Python, a dictionary is a data structure that stores a collection of key-value pairs.
• It is also known as an associative array or a hash map in other programming languages.
• Dictionaries are unordered, mutable, and indexed by unique keys.
my_dict = {
key1: value1,
key2: value2,
...
}
• key1, key2, ...: Unique keys used to access the corresponding values.
• value1, value2, ...: Values associated wi related data.
Some of the most commonly used inbuilt methods for dictionaries in Python include:
1. dict.get(key, default): Returns the value associated with the specified key. If
the key is not found, it returns the specified default value (if provided) or None.
4. dict.items(): Returns a view of all the key-value pairs in the dictionary as tuples.
6. dict.pop(key, default): Removes the key and its associated value from the
dictionary. If the key is not found, it returns the specified default value (if provided)
or raises a KeyError.
7. dict.popitem(): Removes and returns the last key-value pair (in Python 3.7+).
8. dict.clear(): Removes all key-value pairs from the dictionary, making it empty.
9. len(dict): Returns the number of making it easy to manipulate and access data in
the dictionary.
my_dict = {
'name': 'Ismail abi',
'age': 30,
'city': 'New York'
}
my_dict.update({'country': 'USA'})
print(my_dict) # Output: {'name': 'John', 'age': 30,
'city': 'New York', 'country': 'USA'}
my_dict.pop('age',0)
print(my_dict) # Output: {'name': 'John', 'city': 'New
York', 'country': 'USA'}
my_dict.clear()
print(my_dict) # Output: {}
Ismail abi
dict_keys(['name', 'age', 'city'])
dict_values(['Ismail abi', 30, 'New York'])
dict_items([('name', 'Ismail abi'), ('age', 30), ('city', 'New
York')])
{'name': 'Ismail abi', 'age': 30, 'city': 'New York', 'country':
'USA'}
{'name': 'Ismail abi', 'city': 'New York', 'country': 'USA'}
{}
a={
"the":2,
"a":5
}
print(type(a))
b= {
100:"the",
}
print(b)
<class 'dict'>
{100: 'the'}
# for lists, 10000 index means you need to have atleast 1000
# but for dictionary it is not, it is still 1
len(b)
b=a.copy()
print(b)
{'the': 2, 'a': 5}
c=dict([("the",3),
("and",6)]
)
print(c)
{'the': 3, 'and': 6}
d = dict.fromkeys(["abc",32,5], 10) #if you dont provide, then None
d
a={
1:2,
3:4,
"list":[1,23],
"dict":{
1:1,
2:3,
4:5}
}
print(a)
# acessing
a["list"]
[1, 23]
None
a.values()
for i in a:
print(i) #keys
1
3
list
dict
for i in a:
print(i,":",a[i]) #keys
1 : 2
3 : 4
list : [1, 23]
dict : {1: 1, 2: 3, 4: 5}
for i in a.values():
print(i)
2
4
[1, 23]
{1: 1, 2: 3, 4: 5}
True
"li" in a
False
{1: 2,
3: 4,
'list': [1, 23],
'dict': {1: 1, 2: 3, 4: 5},
'78': '345',
'abc': 'def'}
# updating
a["abc"] ="hik"
a
{1: 2,
3: 4,
'list': [1, 23],
'dict': {1: 1, 2: 3, 4: 5},
'78': '345',
'abc': 'hik'}
# update
b={1:100,"aas":"fd"}
a.update(b) #what ever the values of b not available in a, will be
added
# what ever keys available in both a and b, value will be according to
b
{1: 100,
3: 4,
'list': [1, 23],
'dict': {1: 1, 2: 3, 4: 5},
'78': '345',
'abc': 'hik',
'aas': 'fd'}
# remove
a.pop('as',0) #key required, if not found gives error, give default
value to avoid
del a[1]
a.clear()
{}
def Print_allWordWithFrequencyk(s,k):
l= s.split()
d={}
for i in l:
d[i] = d.get(i,0)+1
for i in d:
if d[i]==k:
print(i)
Print_allWordWithFrequencyk(s,1)
This
good
Sets in Python
• A set is a collection of unique elements, where each element is unique and unordered.
• Sets are useful for eliminating duplicates from a collection and performing set
operations like union, intersection, and difference.
my_set = {element1, element2, ...}
• Sets are defined using curly braces {}, but be cautious because using empty curly
braces will create an empty dictionary, not an empty set.
type(a)
set
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[69], line 1
----> 1 a[0] #not valid
'abc' in a
False
23 in a
True
for i in a:
print(i)
banana
apple
23
len(a)
Functions in sets
1. set(): Creates an empty set.
5. remove(element): Removes the specified element from the set. Raises a KeyError
if the element is not found.
6. discard(element): Removes the specified element from the set (if it exists). Does
not raise an error if the element is not found.
7. pop(): Removes and returns an arbitrary element from the set. Raises a KeyError
if the set is empty.
10. union(other_set), |: Returns a new set containing all elements from both sets
(elements are unique).
11. intersection(other_set), &: Returns a new set containing common elements
between both sets.
12. difference(other_set), -: Returns a new set containing elements that are in the
first set but not in the second set.
14. issubset(other_set): Returns True if the set is a subset of the specified set,
otherwise False.
15. issuperset(other_set): Returns True if the set is a superset of the specified set,
otherwise False.
Additional functions
Here are additional functions and methods on sets, including a.intersection_update(b),
a.difference_update(b), a.symmetric_difference_update(b), and
a.isdisjoint(b):
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Adding elements
set1.add(5) # After adding 5 to set1: {1, 2, 3, 4, 5}
set1.update([6, 7]) # After updating set1 with [6, 7]: {1, 2, 3, 4, 5,
6, 7}
# Removing elements
set1.remove(2) # After removing 2 from set1: {1, 3, 4, 5, 6, 7}
set1.discard(10) # No error even if 10 is not in set1: {1, 3, 4, 5,
6, 7}
# Set operations
union_set = set1.union(set2) # Union of set1 and set2:
{1, 3, 4, 5, 6, 7}
intersection_set = set1.intersection(set2) # Intersection of set1 and
set2: {3, 4}
difference_set = set1.difference(set2) # Set difference (set1 -
set2): {1, 6, 7}
symmetric_difference_set = set1.symmetric_difference(set2) #
Symmetric difference of set1 and set2: {1, 5, 6, 7} # A Δ B = (A ∪ B)
- (A ∩ B)
{1, 3, 4, 5, 6, 7}
{1, 3, 4, 5, 6, 7}
{3, 4, 5, 6}
{1, 7}
{1, 7}
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Intersection update
# Updates set1 with the intersection of set1 and set2,
# keeping only the elements that are common to both sets.
set1.intersection_update(set2)
print(set1) # Output: {3, 4}
# Difference update
# Updates set2 by removing the elements present in set1 from set2.
set1 = {1, 2, 3, 4}
set2.difference_update(set1)
print(set2) # Output: {5, 6}
# Is disjoint
# Checks if set1 and set2 have no elements in common.
set1 = {1, 2, 3, 4}
set2 = {5, 6, 7}
is_disjoint = set1.isdisjoint(set2)
print(is_disjoint) # Output: True (set1 and set2 have no elements in
common)
{3, 4}
{5, 6}
{1, 2, 3, 4, 5, 6}
True
a={"Apples","Bananas","Oranges"}
b={"Bananas","Oranges","Pine Apples","Dragon Fruits"}
print("Before:")
print(a)
print(b)
b.update(a)
print("After:")
print(a)
print(b)
Before:
{'Bananas', 'Oranges', 'Apples'}
{'Bananas', 'Oranges', 'Pine Apples', 'Dragon Fruits'}
After:
{'Bananas', 'Oranges', 'Apples'}
{'Oranges', 'Apples', 'Pine Apples', 'Bananas', 'Dragon Fruits'}
'Bananas'
a={1,2,3,4}
b={3,4}
b.issubset(a)
True
a.issuperset(b)
True
print(a)
print(b)
a.isdisjoint(b)
{1, 2, 3, 4}
{3, 4}
False
## Problems
s=set()
for i in l:
s.add(i)
sum_of_uniques=0
for i in s:
sum_of_uniques+=i
print(sum_of_uniques)
25
# using sets
l=[1,2,3,4,5,1,2,3,4]
s= set()
elements=0
for i in l:
if i in s:
elements+=1
else:
s.add(i)
print(elements)
elements=0
for i in l:
if d.get(i,0)!=0:
elements+=1
else:
d[i]= d.get(i,0)+1
print(elements)
# printing result
print ("Most frequent number is : " + str(res)) #if two same freq,
first value return
# using dictionary
test_list = [9, 4, 5, 4, 4, 5, 9, 5, 4,9,9]
test_list = test_list[::-1]
dict ={}
for i in test_list:
dict[i]=dict.get(i,0)+1
max_freq=0
for i in dict:
if dict[i]>max_freq:
max_freq= dict[i]
max_freq #if two same freq, last stating value return
arr = [1, 3, 1, 4, 5, 6, 4, 8]
max_distance=0
for i in range(0,len(arr)):
val =arr[i]
for j in range(i+1,len(arr)):
if arr[j]==val:
dist=j-i
if max_distance<dist:
max_distance= dist
print(max_distance)
str="abc def"
'd' in str[5:]
False
# Different Names
# print repeating names in a str
if repeat_exist == False:
print(-1)
harshit 2
Ayush 3
Iti 2
arr=[2, 3, 4, 4, 4, 4, 5, 3, 5]
dic={}
for i in arr:
dic[i]=dic.get(i,0)+1
for i in dic:
if dic[i]%2==0:
print(i)
break
else:
print(-1)
#***********
# Unique triangles
# A triangle is said to be unique if there is no other triangle with
same set of sides.
# sample input
# 5
# 7 6 5
# 5 7 6
# 8 2 9
# 2 3 4
# 2 4 3
n = int(input())
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [7, 8, 9], [1, 2, 3]]
#*****************
# Pairs with difference K
l=[5,1,9,8,12]
k=4
pairs_nums=0
for i in range(0,len(l)-1):
for j in range(i+1,len(l)):
if abs(l[i]-l[j]) ==k:
print(l[i]," ",l[j])
pairs_nums+=1
print(pairs_nums)
5 1
5 9
8 12
3