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

Python Answers

The document contains various Python code snippets demonstrating different programming concepts such as string manipulation, regular expressions for mobile number validation, customer data retrieval, and matrix input handling. It includes functions for checking palindromes, calculating grades based on scores, and finding the greatest common divisor of strings. Additionally, it showcases examples of using loops, conditionals, and data structures like dictionaries and lists.

Uploaded by

hariikrishna5701
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 views23 pages

Python Answers

The document contains various Python code snippets demonstrating different programming concepts such as string manipulation, regular expressions for mobile number validation, customer data retrieval, and matrix input handling. It includes functions for checking palindromes, calculating grades based on scores, and finding the greatest common divisor of strings. Additionally, it showcases examples of using loops, conditionals, and data structures like dictionaries and lists.

Uploaded by

hariikrishna5701
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/ 23

2:39 00 O53%

Coding Python RUN MENU


Auto saved at 14:39:43

S ="abcd"
t ="cdab"
k = 2

for i
if
in range(k + 1):
s == t:
print(i)
break
s = s[-1]
+ s[:-1]
else:
print(-1)

Tab

&
2(c)ValidateMobileNumbers UsingRegular
Expressions

Python O Copy code

import re

def validate_mobile_numbers
(numbers):
pattern= re.compile(r'^9\d{9}$)
[YES"ifpattern.match
return (num) else"NO" fornum innumbers]

# Example usage
numbers = "9587456281", "1252478965 "
print("|n"join[validate_mobile
_numbers(numbers)))

Output:

O Copy code

YES
NO

Explanation:

•Avalidnumber startswith 9 and has exactl 10


digits.

•The program uses regularexpressions(re module) to


check validity.
6 5 4 3 2
Tab Auto

7:52

[
while
saved
import Coding

for at
signals=

,
True: time

07:51:52
Python

print

lights,

("Green"
time.sleep
(1ights)

20),

,
duration

(duration)
in
("Yellow"

5),
signals:

,
("Red"

]
92
20)

OO0.05

RUN
1l

O100%

MENU
8:18 9
Coding Python RUN MENU
Auto saved at 08:18:13

1 score=int(input('
Enter the Marks:'))
2 if score>=90:

3 grade='A'
4 elifscore>=80:
5 grade='B'
6 elifscore>=70:
7 grade='C'
8 elifscore>=60:
9
grade='D'
0 elifscore<60 and score>=0:
1
grade='F'
2 else:
3 print('
EnterMarks Correctly')
4 exit()
5

6 print(grade)
7

+ ! ()

%
4 2

3
da
Tab
hra Auto

=
= salary
8:06

= Coding

saved
0.9 at
0.3
if
ifint
print("Gross
08:06:12
Python

salary
(input
salary

Salary:",
>

>
("Enter
10000

20000

+
salary

else
else
salary:

0.8

0.25 "))
salary

* if

+ >
(hra
salary

)
da)

10000

else

0.2

OO100

RUN
1l

O99%

MENU
7:57 9M OO#lO 23%

Coding Python RUN MENU


Auto saved at 19:57:31

1 N1 = -5 # Assign a value to N1
2 N2 = 256 # Assign the same value to N2
3

4 ifid(N1) == id(N2):
5 print("n
"N1 and N2 point to
6 the same object."n")
7 else:
print("n
"N1 and N2 do not
point to the same object."*")

Tab

&
5 4 3 2

Tab
if Auto

8:02

=
Word Coding

saved
else: at

word

08:01:55
print Python

==
input

("Not

("Enter

Palind
word[::-1]:
print("Palindrome")
word:

rome")
")

AO

O.00

Y
RUN

l
O99%

MENU
8:59 O O OO lO19%

Coding Python RUN MENU


Auto saved at 20:59:13
1 def get_customer_by_name(customers, name):
2 for customer in customers
3 1f customer.get(name ) * name:
4
returncustomer
5 return None
6
7 # Listof dictionaries
8 customers [

9 {name: "ajay", age : 17, "purchase: ["Mac" ],"amount" : 198e00},


10
{'name" : "vijay",
"age":22, "purchase": ['MS, "mouse" ],"amount": 60
11 {"name: "sanjay , "age": 19, "purchase": [linux, pendrive.amou
12 J

13

14 # Example usage

15 d = get_customer_by_name (customers,ajay" )

16 print
(d)

+ ! ()

%
9:13 9O O3N lO17%

Coding Python RUN MENU


Auto saved at 21:12:52

n=int(input('Enter
Range:'))
{}
a

for
=

i
in range(1,n+1):
a[i] = i * i
print(a))

+ $ [ ()

%
9:28 9O Oal 15%

Coding Python RUN MENU


Auto saved at 21:28:17

D1 = {'c': 200, 'a':


100, 'b': 300}
2 D2 = {'b':200, 'a':
300, 'c':
400}
3 D3 = {}
4 for key in D1:
5
D3 [key] = D1[key] + D2[keyl)
5 print(D3)

Tab

&

and in

123 4 5 6 7 89
rt uio y p

a s d f g hi k

N X b n m <
?123 English
8:46 O 18l O51%

Coding Python RUN MENU


Auto saved at 20:46:33

def addStrings (num1 , num2):


a = b = 0

for i
r
in
= ord (num1
(num1 )):
range (len
[i])- 48 # Conv

a = a * 10 +r
for iin range(len(num2)):
s ord (num2
= [i])48 - # Conv
b =b * 10 + s

returnstr(a+ b) # Return the


s
#Correct function call
("20","60"))
print(addStrings # Outp

3b
(a,
Tab

&
8:55 O lO
50%

Coding Python RUN MENU


Auto saved at 20:55:45

N1=int(input
1 ())
2 N2=int(input())
3 if N1 isN2:
4 print("'
Pointssame object')
5 else:
6 print(" Doesn't point same object")

Tab

&
10:31 Oo OO #l O58%

Coding Python RUN MENU


Auto saved at 22:31:34

1 library-{
"Book 1":{
:
"author'""Name 1",
"year":2002,
}

"Book 2":{
"author":"Name2",
8 "year":2012,

10 "Book 3":{
11 "author":"Name3",
12 "year":1992,
13

14 }
(library[
15 print Book ' 3']['author
1)

+ ! $ ()

%
8:14 @ OO1e 13%

Coding Python RUN MENU

|
Auto saved at 08:13:31

def (s,t):
min_operations
for i
in range(len(s)
):
ifs == t:
return i
s = s[-1]+ s[:-1]# Move
return -1 # Ifnot possible

B# Example usage
s ="abcd"
Dt = cdab"

I
"

(s, t))
print(min_operations # 0utp

Tab

&
9:19 &lO46%
Coding Python RUN MENU
Auto saved at 21:19:19

1 import re
2

3n int(input()) Number of inputs


= #

4 results= [] # Listto store results


5

6 for - in range(n):
7 a = input() # Read input
8 if re.fullmatch((9\\d{9}',
a): # Reg
9 append ("YES")
results.
10 else:
11
results.
append("NO")
12

13 Printallresultsafterinput
# iscomple
14 print("\n".
join(results)
)

Tab

&
12:51 9 AO 4.90 lO85%

Coding Python RUN MENU


Auto saved at 12:50:57

a = [abc' 'xyz',
'aba','1221']
2 count = 0

3 for iin a:
4 iflen(i)
>= 2 and i[o]== i[-1]:
5 COunt += 1

6 print(count)

Tab
12:59 O OOF89lO84%
Coding Python RUN MENU
Auto saved at 12:59:23

1 def get_customer_by_name (customers,name):


2 for iin customers:
if
3
return
return No customers
i
i['name'] == name:

6 customers =[
7 , 'keyboard']},
{'name': 'ajay' 'age':17, 'purchase': ['laptop',
8 :
{'name' 'sanjay','age':37, 'purchase':['mouse',keyboard']},
9 'age':20, 'purchase':['laptop','
{'name':'vijay', tab']}
10 ]

11 print(get_customer_by_name (customers, 'ajay'))

$ %
10:12 OOP lO35%

Coding Python RUN MENU


Auto saved at 22:12:41

1 76,799,69,0,7]
a-[1,5,
2a .sort()
3 print("' a[o])
largestnumber:',
4 print('samllestnumber:',a[-1
)

Sa

+ ! $ ()

%
8:41 09 l12%

Coding Python RUN MENU


Auto saved at 20:41:27

1 from math import gcd


2 def (str1,
gcd0fStrings str2):
3 length = gcd(len(str1),len(str2))
return stri[:length]

6 str1 = "ABCABCABC";
str2 = "ABCABC"

8 (str1,
print(gcd0fStrings str2))

Tab 8
8:21 O

M
Coding Python RUN MENU
Nothing changed

def word_squares(words):
1
n= len(words [0])
def dfs ( square):

iflen(square)== n:
return [square]
# Build the prefix needed for the next word.
prefix =''.join (s[len (square)] for s in square)
result 0 =

for w inwords:
if w.startswith
(prefix):
result.
extend (dfs(square [w]))
+
return result

result = |
for w in words:
(dfs([w]
result.extend )
7
return result

9 # Example usage:
0 words = ["area", "lead","wall",
"lady", "ball"
]
1 print(word_squares(wo rds) )

Tab

&
4:49 9 OO93l 50%

Coding Python RUN MENU


Auto saved at 16:47:51

1 m = int(input("Enternumber of rows: "))


2 n = int (input("Enter
number of columns: "))

4 matrix =
0
5

6 print(f"
Enter (m} rows with (n) values each:")
7 for i in range (m) :
8 while True: # Keep asking untilthe correct input is given
row = list
(map (int,input(0.split()))
10 if len(row) == n: # Check ifthe row has exactly 'n nun
11
matrix.append(row)
12 break
13 else:
14 (f"XPlease enter exactly {n)
print numbers!")
15
16 # Printthe matrix
17 print("\nMatrixentered:")
18 for row inmatrix:
19 print(row)

Tab

&
12:06

Coding Python RUN MENU


Auto saved at 10:36:47

1 def is_isomorphic(s,t):
2
return 1len (set(s))== len(set(t)
) = (s,t)))
len(set(zip

4 # Example usage :

print(is_isomorphic("egg","add")) # Output: True


print(is_isomo rphic("foo", "bar")) # Output: False
print(is_isomorphic(" paper", "title"
)) Output: True

#
print(is_isomorphic(" ab", "aa" Output:
) ) False
#
8
l0C

+ ! $ ()

%
5:09 9 A O 0.05 l47%
Coding Python RUN MENU
Auto saved at 17:09:03

def isPrime (n):


if n<2:
return True
else:
for iin range(2,n)
if
n%i==0:
:

return False
break
return True

a-[22,3,
4, 55,67,87]
for i in a:
if isPrime (i) :

print(f'{i} is prime')
else:
print(f'{i}
is not prime')

Tab

&

You might also like