Advertisement
brandblox

Source of True Evil

May 5th, 2024 (edited)
1,320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 24.80 KB | None | 0 0
  1. #Reverse
  2. num = int(input("Enter a number: "))
  3. reversed_num = 0
  4. while num > 0:
  5.     digit = num % 10
  6.     reversed_num = (reversed_num * 10) + digit
  7.     num = num // 10
  8. print(f"The reversed number: {reversed_num}")
  9.  
  10. #fibonacchi
  11. num_terms = int(input("Enter the number of terms for the Fibonacci series: "))
  12. if num_terms <= 0:
  13.     print("Invalid input. Please enter a positive integer.")
  14. else:
  15.     fib_series = [0, 1]
  16.     while len(fib_series) < num_terms:
  17.         fib_series.append(fib_series[-1] + fib_series[-2])
  18.     sum_fib_series = sum(fib_series)
  19.     print(f"The sum of the first {num_terms} terms in the Fibonacci series is: {sum_fib_series}")
  20.  
  21. #armstrong
  22. num = int(input("Enter a number: "))
  23. original_num = num
  24. num_digits = len(str(num))
  25. sum_of_digits = 0
  26. while num > 0:
  27.     digit = num % 10
  28.     sum_of_digits += digit ** num_digits
  29.     num = num // 10
  30. if original_num == sum_of_digits:
  31.     print(f"{original_num} is an Armstrong number.")
  32. else:
  33.     print(f"{original_num} is not an Armstrong number.")
  34.  
  35.  
  36. #positive negative sum
  37. sum_positive = 0
  38. sum_negative = 0
  39. for i in range(10):
  40.     num = float(input(f"Enter number {i + 1}: "))
  41.  
  42.     if num > 0:
  43.         sum_positive += num
  44.     elif num < 0:
  45.         sum_negative += num
  46.  
  47. print(f"Sum of positive numbers: {sum_positive}")
  48. print(f"Sum of negative numbers: {sum_negative}")
  49.  
  50.  
  51. #palindrome
  52.  
  53. num = int(input("Enter a number: "))
  54. original_num = num
  55. reversed_num = 0
  56. while num > 0:
  57.     digit = num % 10
  58.     reversed_num = (reversed_num * 10) + digit
  59.     num = num // 10
  60. if original_num == reversed_num:
  61.     print(f"{original_num} is a palindrome.")
  62. else:
  63.     print(f"{original_num} is not a palindrome.")
  64.  
  65.  
  66. *
  67. * *
  68. * * *
  69. * * * *
  70. * * * * *
  71.  
  72. rows = 5
  73. for i in range(0, rows):    
  74.     for j in range(0, i + 1):        
  75.         print("*", end=' ')    
  76.     print()
  77.  
  78. 1
  79. 2 2
  80. 3 3 3
  81. 4 4 4 4
  82. 5 5 5 5 5
  83.  
  84. rows = 6
  85. for i in range(rows):    
  86.     for j in range(i):        
  87.         print(i, end=' ')    
  88.     print('')
  89.  
  90. 1
  91. 1 2
  92. 1 2 3
  93. 1 2 3 4
  94. 1 2 3 4 5
  95.  
  96. rows = 5
  97. for i in range(1, rows + 1):
  98.     for j in range(1, i + 1):
  99.         print(j, end=' ')
  100.     print('')
  101.  
  102. 1
  103. 2 3
  104. 4 5 6
  105. 7 8 9 10
  106. 11 12 13 14 15
  107.  
  108. rows = 5
  109. counter = 1
  110. for i in range(1, rows + 1):
  111.     for j in range(1, i + 1):
  112.         print(counter, end=' ')
  113.         counter += 1
  114.     print('')
  115.  
  116.         *  
  117.        *  *  
  118.       *  *  *  
  119.      *  *  *  *  
  120.     *  *  *  *  *  
  121.  
  122. size = 5
  123. m = (2 * size) - 2
  124. for i in range(0, size):
  125.     for j in range(0, m):
  126.         print(end=" ")    
  127.     m = m - 1
  128.     for j in range(0, i + 1):
  129.         print("* ", end=' ')
  130.     print(" ")
  131.  
  132. ''' OR
  133. n = 5
  134. for i in range(n):
  135.    print(' '*(n-i-1) + '* ' * (i))
  136. print()
  137. '''
  138.  
  139. *  *  *  *  *  
  140.  *  *  *  *  
  141.   *  *  *  
  142.    *  *  
  143.     *
  144.  
  145. size = 5
  146. m = 0
  147. for i in range(size, 0, -1):
  148.     for j in range(0, m):
  149.         print(end=" ")
  150.     m = m + 1
  151.     for j in range(0, i):
  152.         print("* ", end=' ')
  153.     print(" ")
  154.  
  155. ''' OR
  156. n = 5
  157. for i in range(n-1,-1,-1):
  158.    print(' ' * (n - i - 1) + '* ' * (i))
  159. '''
  160.  
  161.     *
  162.    * *
  163.   * * *
  164.  * * * *
  165.   * * *
  166.    * *
  167.     *
  168.  
  169. rows = 3
  170. k = 2 * rows - 2
  171. for i in range(0, rows):
  172.     for j in range(0, k):
  173.         print(end=" ")
  174.     k = k - 1
  175.     for j in range(0, i + 1):
  176.         print("* ", end="")
  177.     print("")
  178.    
  179. k = rows - 2
  180.  
  181. for i in range(rows, -1, -1):
  182.     for j in range(k, 0, -1):
  183.         print(end=" ")
  184.     k = k + 1
  185.     for j in range(0, i + 1):
  186.         print("* ", end="")
  187.     print("")
  188.    
  189.    
  190. '''OR    
  191.    
  192. n = 3
  193. for i  in range(n):
  194.    print(' '*(n-i-1) + '*' * (2*i+1))
  195. for i in range(n-2,-1,-1):
  196.    print(' ' * (n - i - 1) + '*' * (2 * i + 1))'''
  197.  
  198.  
  199. #calculator
  200.  
  201. def addition(num1, num2):
  202.     num1 += num2
  203.     return num1
  204.  
  205. def subtraction(num1, num2):
  206.     num1 -= num2
  207.     return num1
  208.  
  209. def mul(num1, num2):
  210.     num1 *= num2
  211.     return num1
  212.  
  213. def division(num1, num2):
  214.     if num2 != 0:
  215.         num1 /= num2
  216.         return num1
  217.     else:
  218.         return "Cannot divide by zero"
  219.  
  220. def module(num1, num2):
  221.     if num2 != 0:
  222.         num1 %= num2
  223.         return num1
  224.     else:
  225.         return "Cannot perform modulus with zero"
  226.  
  227. def default(num1, num2):
  228.     return "Incorrect day"
  229.  
  230. switcher = {
  231.     1: addition,
  232.     2: subtraction,
  233.     3: mul,
  234.     4: division,
  235.     5: module
  236. }
  237.  
  238. def switch(operation):
  239.     num1 = float(input("Enter the first number: "))
  240.     num2 = float(input("Enter the second number: "))
  241.     return switcher.get(operation, default)(num1, num2)
  242.  
  243. print('''You can perform the following operations:
  244.  
  245. 1. **Addition**
  246. 2. **Subtraction**
  247. 3. **Multiplication**
  248. 4. **Division**
  249. 5. **Modulus (Remainder)''')
  250.  
  251. # Take input from the user
  252. choice = int(input("Select an operation from 1 to 5: "))
  253. print(switch(choice))
  254.  
  255.  
  256.  
  257.  
  258. #Fibonacchi using recursion
  259. def fibonacci(n):
  260.     if n <= 0:
  261.         return "Please enter a positive integer"
  262.     elif n == 1:
  263.         return [0]
  264.     elif n == 2:
  265.         return [0, 1]
  266.     else:
  267.         fib_series = fibonacci(n - 1)
  268.         fib_series.append(fib_series[-1] + fib_series[-2])
  269.         return fib_series
  270.  
  271. n = int(input("Enter the value of 'n' to print Fibonacci series up to n: "))
  272.  
  273. result = fibonacci(n)
  274. print(f"Fibonacci series up to {n}: {result}")
  275.  
  276.  
  277.  
  278. #GCD using recurtion
  279. def gcd_recursive(a, b):
  280.     if b == 0:
  281.         return a
  282.     else:
  283.         return gcd_recursive(b, a % b)
  284.  
  285. # Take input from the user
  286. num1 = int(input("Enter the first number: "))
  287. num2 = int(input("Enter the second number: "))
  288.  
  289. result = gcd_recursive(num1, num2)
  290. print(f"The GCD of {num1} and {num2} is: {result}")
  291.  
  292.  
  293.  
  294. # Wap to print sum of list
  295. l1 = [12+13+14+15+56]
  296. sum = 0
  297.  
  298. for i  in l1:
  299.     sum += i
  300.  
  301. print(sum
  302.  
  303. #output
  304. 110
  305.  
  306. #Wap to print mal element
  307. ls=[]
  308. print("Enter Elements in array")
  309. for i in range(5):
  310.     el=int(input())
  311.     ls.append(el)
  312.    
  313. maxel=ls[0]
  314.  
  315. mi=0
  316. for i in range(1,len(ls)):
  317.     if ls[i]>maxel:
  318.         maxel=ls[i]
  319.         mi = i
  320.        
  321. print("Max element is: ",maxel)
  322.  
  323. #output
  324. Enter Elements in array
  325. 13
  326. 67
  327. 34
  328. 99
  329. 12
  330. Max element is:  99
  331.  
  332. #wap to print common elements
  333. def compare_lists(list1, list2):
  334.     common_elements = set(list1) & set(list2)
  335.     return list(common_elements)
  336.  
  337.  
  338. list1_input = input("Enter elements of the first list separated by spaces: ")
  339. list1 = list(map(str, list1_input.split()))
  340.  
  341.  
  342. list2_input = input("Enter elements of the second list separated by spaces: ")
  343. list2 = list(map(str, list2_input.split()))
  344.  
  345. common_elements = compare_lists(list1, list2)
  346.  
  347. if common_elements:
  348.     print("Common elements: ", common_elements)
  349. else:
  350.     print("No common elements found.")
  351.  
  352. #output
  353. Enter elements of the first list separated by spaces: 12 13 45 67 89
  354. Enter elements of the second list separated by spaces: 12 45 67 89
  355. Common elements:  ['12', '45', '67', '89']
  356.  
  357. #Wap to remove even numbers
  358. def remove_even_numbers(input_list):
  359.     return [num for num in input_list if int(num) % 2 != 0]
  360.  
  361. user_input = input("Enter a list of numbers separated by spaces: ")
  362. numbers_list = user_input.split()
  363.  
  364. filtered_list = remove_even_numbers(numbers_list)
  365.  
  366. print("List after removing even numbers:", filtered_list)
  367.  
  368.  
  369. #output
  370. Enter a list of numbers separated by spaces: 12 34 56 77 43 31
  371. List after removing even numbers: ['77', '43', '31']
  372.  
  373. #Wap to print number of occurance
  374. def count_occurrences(array, target_element):
  375.     return array.count(target_element)
  376.  
  377. user_input = input("Enter a list of numbers separated by spaces: ")
  378. numbers_list = user_input.split()
  379.  
  380.  
  381. target_element = input("Enter the element to count: ")
  382.  
  383. occurrences = count_occurrences(numbers_list, target_element)
  384.  
  385. print(f"The number of occurrences of {target_element} in the list is: {occurrences}")
  386.  
  387. #output
  388. Enter a list of numbers separated by spaces: 12 33 33 45 67 54
  389. Enter the element to count: 33
  390. The number of occurrences of 33 in the list is: 2
  391.  
  392.  
  393. #accept and print matrix
  394. matrix = []
  395.  
  396. for i in range(3):
  397.     row = []
  398.     for j in range(3):
  399.         row.append(int(input(f"Enter element at position ({i+1}, {j+1}): ")))
  400.     matrix.append(row)
  401.  
  402. print("Entered 3x3 matrix:")
  403. for row in matrix:
  404.     print(row)
  405.  
  406. output:
  407. Enter element at position (1, 1): 1
  408. Enter element at position (1, 2): 2
  409. Enter element at position (1, 3): 3
  410. Enter element at position (2, 1): 4
  411. Enter element at position (2, 2): 5
  412. Enter element at position (2, 3): 6
  413. Enter element at position (3, 1): 7
  414. Enter element at position (3, 2): 8
  415. Enter element at position (3, 3): 9
  416. Entered 3x3 matrix:
  417. [1, 2, 3]
  418. [4, 5, 6]
  419. [7, 8, 9]
  420.  
  421.  
  422. #accept matrix and element sum
  423. matrix = []
  424. a=0
  425. sum=0
  426.  
  427. for i in range(3):
  428.     row = []
  429.     for j in range(3):
  430.         a=int(input(f"Enter element at position ({i+1}, {j+1}): "))
  431.         row.append(a)
  432.         sum+=a
  433.     matrix.append(row)
  434.  
  435. print("Entered 3x3 matrix:")
  436. for row in matrix:
  437.     print(row)
  438.    
  439. print("Sum = ",sum)
  440.  
  441. Output:
  442. Enter element at position (1, 1): 1
  443. Enter element at position (1, 2): 2
  444. Enter element at position (1, 3): 3
  445. Enter element at position (2, 1): 4
  446. Enter element at position (2, 2): 5
  447. Enter element at position (2, 3): 6
  448. Enter element at position (3, 1): 7
  449. Enter element at position (3, 2): 8
  450. Enter element at position (3, 3): 9
  451. Entered 3x3 matrix:
  452. [1, 2, 3]
  453. [4, 5, 6]
  454. [7, 8, 9]
  455. Sum =  45
  456.  
  457.  
  458.  
  459. #Accept matrix and trace
  460. matrix = []
  461.  
  462. for i in range(3):
  463.     row = []
  464.     for j in range(3):
  465.         element = int(input(f"Enter element at position ({i+1}, {j+1}): "))
  466.         row.append(element)
  467.     matrix.append(row)
  468.  
  469. print("Entered 3x3 matrix:")
  470. for row in matrix:
  471.     print(row)
  472.  
  473. trace = 0
  474. for i in range(3):
  475.     trace += matrix[i][i]
  476.  
  477. print(f"Trace of the matrix: {trace}")
  478.  
  479. Output:
  480. Enter element at position (1, 1): 1
  481. Enter element at position (1, 2): 2
  482. Enter element at position (1, 3): 3
  483. Enter element at position (2, 1): 4
  484. Enter element at position (2, 2): 5
  485. Enter element at position (2, 3): 6
  486. Enter element at position (3, 1): 7
  487. Enter element at position (3, 2): 8
  488. Enter element at position (3, 3): 9
  489. Entered 3x3 matrix:
  490. [1, 2, 3]
  491. [4, 5, 6]
  492. [7, 8, 9]
  493. Trace of the matrix: 15
  494.  
  495.  
  496.  
  497. #Matrix multiplication
  498. import numpy as np
  499.  
  500. matrix1 = []
  501. for i in range(3):
  502.     row = []
  503.     for j in range(3):
  504.         element = int(input(f"Enter element for matrix1 at position ({i+1}, {j+1}): "))
  505.         row.append(element)
  506.     matrix1.append(row)
  507.  
  508. matrix2 = []
  509. for i in range(3):
  510.     row = []
  511.     for j in range(3):
  512.         element = int(input(f"Enter element for matrix2 at position ({i+1}, {j+1}): "))
  513.         row.append(element)
  514.     matrix2.append(row)
  515.  
  516. print("Entered 3x3 matrix 1:")
  517. for row in matrix1:
  518.     print(row)
  519.  
  520. print("\nEntered 3x3 matrix 2:")
  521. for row in matrix2:
  522.     print(row)
  523.  
  524. array1 = np.array(matrix1)
  525. array2 = np.array(matrix2)
  526.  
  527.  
  528. result_array = np.dot(array1, array2)
  529.  
  530. print("\nResult of matrix multiplication:")
  531. print(result_array)
  532.  
  533. Output:
  534. Enter element for matrix1 at position (1, 1): 1
  535. Enter element for matrix1 at position (1, 2): 2
  536. Enter element for matrix1 at position (1, 3): 3
  537. Enter element for matrix1 at position (2, 1): 4
  538. Enter element for matrix1 at position (2, 2): 5
  539. Enter element for matrix1 at position (2, 3): 6
  540. Enter element for matrix1 at position (3, 1): 7
  541. Enter element for matrix1 at position (3, 2): 8
  542. Enter element for matrix1 at position (3, 3): 9
  543. Enter element for matrix2 at position (1, 1): 1
  544. Enter element for matrix2 at position (1, 2): 10
  545. Enter element for matrix2 at position (1, 3): 11
  546. Enter element for matrix2 at position (2, 1): 12
  547. Enter element for matrix2 at position (2, 2): 13
  548. Enter element for matrix2 at position (2, 3): 14
  549. Enter element for matrix2 at position (3, 1): 15
  550. Enter element for matrix2 at position (3, 2): 16
  551. Enter element for matrix2 at position (3, 3): 17
  552. Entered 3x3 matrix 1:
  553. [1, 2, 3]
  554. [4, 5, 6]
  555. [7, 8, 9]
  556.  
  557. Entered 3x3 matrix 2:
  558. [1, 10, 11]
  559. [12, 13, 14]
  560. [15, 16, 17]
  561.  
  562. Result of matrix multiplication:
  563. [[ 70  84  90]
  564.  [154 201 216]
  565.  [238 318 342]]
  566.  
  567.  
  568.  
  569. #Count vowels, consonants and blanks
  570. def count_vowels_consonants_blanks(string):
  571.     vowels = 'aeiouAEIOU'
  572.     consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
  573.     blanks = ' '
  574.  
  575.     vowel_count = 0
  576.     consonant_count = 0
  577.     blank_count = 0
  578.  
  579.     for char in string:
  580.         if char in vowels:
  581.             vowel_count += 1
  582.         elif char not in consonants:
  583.             consonant_count += 1
  584.         elif char in blanks:
  585.             blank_count += 1
  586.  
  587.     return vowel_count, consonant_count, blank_count
  588.  
  589. input_string = input("Enter a string: ")
  590. vowels, consonants, blanks = count_vowels_consonants_blanks(input_string)
  591. print("Vowels:", vowels)
  592. print("Consonants:", consonants)
  593. print("Blanks:", blanks)
  594.  
  595. #Output:
  596. Enter a string: Arijit is my name
  597. Vowels: 6
  598. Consonants: 8
  599. Blanks: 3
  600.  
  601. #find substring in a string
  602. def find_substring(string, substring):    
  603.     index = string.find(substring)
  604.     if index != -1:
  605.         print(f"'{substring}' found at index {index} using find() method.")
  606.     else:
  607.         print(f"'{substring}' not found using find() method.")
  608.  
  609.  
  610. input_string = input("Enter the main string: ")
  611. input_substring = input("Enter the substring to find: ")
  612.  
  613. find_substring(input_string, input_substring)
  614.  
  615.  
  616. #Output:
  617. Enter the main string: i live in India
  618. Enter the substring to find: India
  619. 'India' found at index 10 using find() method.
  620.  
  621.  
  622. #print reverse and check palindrome
  623. def is_palindrome(string):
  624.     reversed_string = string[::-1]
  625.     if string == reversed_string:
  626.         return True, reversed_string
  627.     else:
  628.         return False, reversed_string
  629.  
  630. input_string = input("Enter a string: ")
  631. check, reversed_string = is_palindrome(input_string)
  632.  
  633. print("Original string:", input_string)
  634. print("Reversed string:", reversed_string)
  635.  
  636. if check:
  637.     print("The string is a palindrome.")
  638. else:
  639.     print("The string is not a palindrome.")
  640.  
  641.  
  642. #Output:
  643. Enter a string: malayalam
  644. Original string: malayalam
  645. Reversed string: malayalam
  646. The string is a palindrome.
  647.  
  648. #Print pattern
  649. word = "INDIA"
  650. for i in range(len(word), 0, -1):
  651.     print(word[:i])
  652.  
  653. #Ouput:
  654. INDIA
  655. INDI
  656. IND
  657. IN
  658. I
  659.  
  660.  
  661.  
  662.  
  663. def tuple_length(tup):
  664.     return len(tup)
  665. my_tuple = (1, 2, 3, 4, 5)
  666. print("Length of the tuple:", tuple_length(my_tuple))
  667.  
  668. Output:
  669. Length of the tuple: 5
  670.  
  671. def tuple_to_string(tup):
  672.     return ''.join(tup)
  673.  
  674. my_tuple = ('Hello', ' ', 'world', '!')
  675. result = tuple_to_string(my_tuple)
  676. print("Converted string:", result)
  677.  
  678. Output:
  679. Converted string: Hello world!
  680.  
  681. def common_elements(tup1, tup2):
  682.     common = tuple(x for x in tup1 if x in tup2)
  683.     return common
  684.  
  685. tuple1 = (1, 2, 3, 4, 5)
  686. tuple2 = (4, 5, 6, 7, 8)
  687. result = common_elements(tuple1, tuple2)
  688. print("Common elements:", result)
  689.  
  690. Output:
  691. Common elements: (4, 5)
  692.  
  693. def merge_tuples(tup1, tup2):
  694.     merged_list = list(tup1)
  695.     for item in tup2:
  696.         if item not in merged_list:
  697.             merged_list.append(item)
  698.     merged_tuple = tuple(merged_list)
  699.     return merged_tuple
  700.  
  701. tuple1 = (1, 2, 3, 4, 5)
  702. tuple2 = (4, 5, 6, 7, 8)
  703. result = merge_tuples(tuple1, tuple2)
  704. print("Merged tuple without duplicates:", result)
  705.  
  706. Output:
  707. Merged tuple without duplicates: (1, 2, 3, 4, 5, 6, 7, 8)
  708.  
  709. def even_odd_numbers(tup):
  710.     even_numbers = tuple(num for num in tup if num % 2 == 0)
  711.     odd_numbers = tuple(num for num in tup if num % 2 != 0)
  712.     return even_numbers, odd_numbers
  713.  
  714. my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
  715. even, odd = even_odd_numbers(my_tuple)
  716. print("Even numbers:", even)
  717. print("Odd numbers:", odd)
  718.  
  719. Output:
  720. Even numbers: (2, 4, 6, 8)
  721. Odd numbers: (1, 3, 5, 7, 9)
  722.  
  723. def tuple_product(tup):
  724.     product = 1
  725.     for num in tup:
  726.         product *= num
  727.     return product
  728.  
  729. my_tuple = (1, 2, 3, 4, 5)
  730. result = tuple_product(my_tuple)
  731. print("Product of all elements in the tuple:", result)
  732.  
  733. Output:
  734. Product of all elements in the tuple: 120
  735.  
  736.  
  737. emails = tuple()
  738. username = tuple()
  739. domainname = tuple()
  740. n = int(input("How many email ids you want to enter?: "))
  741. for i in range(0, n):
  742.     emid = input("> ")
  743.     emails = emails + (emid,)
  744.     spl = emid.split("@")
  745.     username = username + (spl[0],)
  746.     domainname = domainname + (spl[1],)
  747.  
  748. print("\nThe email ids in the tuple are:")
  749. print(emails)
  750.  
  751. print("\nThe username in the email ids are:")
  752. print(username)
  753.  
  754. print("\nThe domain name in the email ids are:")
  755. print(domainname)
  756.  
  757.  
  758. Output:
  759. How many email ids you want to enter?: 2
  760. > arijit@gmail.com
  761. > abir@outlook.com
  762.  
  763. The email ids in the tuple are:
  764. ('arijit@gmail.com', 'abir@outlook.com')
  765.  
  766. The username in the email ids are:
  767. ('arijit', 'abir')
  768.  
  769. The domain name in the email ids are:
  770. ('gmail.com', 'outlook.com')
  771.  
  772.  
  773.  
  774. #Q1. python program to check if a string starts with the and end with spain use regex
  775.  
  776.  
  777. import re
  778.  
  779. def check_string(input_string):
  780.     pattern = r'^the.*spain$'
  781.     if re.match(pattern, input_string, re.IGNORECASE):
  782.         return True
  783.     else:
  784.         return False
  785.  
  786. test_string1 = input("Enter string: ")
  787.  
  788. print(check_string(test_string1))
  789.  
  790. #output:
  791. Enter string: the spain
  792. True
  793. Enter string: the spain not
  794. False
  795.  
  796.  
  797. #Q. program to find all lowercase charcters aplhabetically between a and m, use regex
  798. import re
  799.  
  800. def find_lower_chars(input_string):
  801.     pattern = r'[a-m]'
  802.     result = re.findall(pattern, input_string)
  803.     return result
  804.  
  805. user_input = input("Enter a string: ")
  806. lowercase_chars = find_lower_chars(user_input)
  807. print("Lowercase characters between 'a' and 'm':", lowercase_chars)
  808.  
  809. #output:
  810. Enter a string: The quick brown fox jumps over the lazy dog
  811. Lowercase characters between 'a' and 'm': ['h', 'e', 'i', 'c', 'k', 'b', 'f', 'j', 'm', 'e', 'h', 'e', 'l', 'a', 'd', 'g']
  812.  
  813. #Q. program to search for the first white space character in the string
  814.  
  815.  
  816. import re
  817.  
  818. txt = "The rain in Spain"
  819. x = re.search("\s", txt)
  820.  
  821. print("The first white-space character is located in position:", x.start())
  822.  
  823. #Output:
  824. The first white-space character is located in position: 3
  825.  
  826. #Q. program to split at each whitespace character using regex
  827.  
  828. import re
  829.  
  830. def split_at_whitespace(input_string):
  831.     return re.split(r'\s+', input_string)
  832.  
  833. user_input = input("Enter a string: ")
  834. result = split_at_whitespace(user_input)
  835. print("Split at each whitespace character:", result)
  836.  
  837.  
  838. #Output:
  839. Enter a string: This is a demo input.
  840. Split at each whitespace character: ['This', 'is', 'a', 'demo', 'input.']
  841.  
  842.  
  843. #Q. replace every white space character with the number nine
  844.  
  845. import re
  846.  
  847. def replace_whitespace_with_nine(input_string):
  848.     return re.sub(r'\s', '9', input_string)
  849.  
  850. user_input = input("Enter a string: ")
  851. result = replace_whitespace_with_nine(user_input)
  852. print("String with every whitespace character replaced with '9':", result)
  853.  
  854.  
  855. #Output:
  856. Enter a string: This is a demo input
  857. String with every whitespace character replaced with '9': This9is9a9demo9inputp
  858.  
  859.  
  860. #Q: check if email valid or not:
  861. import re
  862.  
  863. def validate_email(email):
  864.     pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
  865.     regex = re.compile(pattern)
  866.     return bool(regex.match(email))
  867.  
  868. user_email = input("Enter your email address: ")
  869.  
  870. if validate_email(user_email):
  871.     print("Valid email address!")
  872. else:
  873.     print("Invalid email address. Please enter a valid email.")
  874.  
  875.  
  876. #Output:
  877. Enter your email address: arijit@gmail.com
  878. Valid email address!
  879.  
  880. Enter your email address: arijit@gmail
  881. Invalid email address. Please enter a valid email.
  882.  
  883.  
  884.  
  885. #Q1. python program to check if a string starts with the and end with spain use regex
  886.  
  887.  
  888. import re
  889.  
  890. def check_string(input_string):
  891.     pattern = r'^the.*spain$'
  892.     if re.match(pattern, input_string, re.IGNORECASE):
  893.         return True
  894.     else:
  895.         return False
  896.  
  897. test_string1 = input("Enter string: ")
  898.  
  899. print(check_string(test_string1))
  900.  
  901. #output:
  902. Enter string: the spain
  903. True
  904. Enter string: the spain not
  905. False
  906.  
  907.  
  908. #Q. program to find all lowercase charcters aplhabetically between a and m, use regex
  909. import re
  910.  
  911. def find_lower_chars(input_string):
  912.     pattern = r'[a-m]'
  913.     result = re.findall(pattern, input_string)
  914.     return result
  915.  
  916. user_input = input("Enter a string: ")
  917. lowercase_chars = find_lower_chars(user_input)
  918. print("Lowercase characters between 'a' and 'm':", lowercase_chars)
  919.  
  920. #output:
  921. Enter a string: The quick brown fox jumps over the lazy dog
  922. Lowercase characters between 'a' and 'm': ['h', 'e', 'i', 'c', 'k', 'b', 'f', 'j', 'm', 'e', 'h', 'e', 'l', 'a', 'd', 'g']
  923.  
  924. #Q. program to search for the first white space character in the string
  925.  
  926.  
  927. import re
  928.  
  929. txt = "The rain in Spain"
  930. x = re.search("\s", txt)
  931.  
  932. print("The first white-space character is located in position:", x.start())
  933.  
  934. #Output:
  935. The first white-space character is located in position: 3
  936.  
  937. #Q. program to split at each whitespace character using regex
  938.  
  939. import re
  940.  
  941. def split_at_whitespace(input_string):
  942.     return re.split(r'\s+', input_string)
  943.  
  944. user_input = input("Enter a string: ")
  945. result = split_at_whitespace(user_input)
  946. print("Split at each whitespace character:", result)
  947.  
  948.  
  949. #Output:
  950. Enter a string: This is a demo input.
  951. Split at each whitespace character: ['This', 'is', 'a', 'demo', 'input.']
  952.  
  953.  
  954. #Q. replace every white space character with the number nine
  955.  
  956. import re
  957.  
  958. def replace_whitespace_with_nine(input_string):
  959.     return re.sub(r'\s', '9', input_string)
  960.  
  961. user_input = input("Enter a string: ")
  962. result = replace_whitespace_with_nine(user_input)
  963. print("String with every whitespace character replaced with '9':", result)
  964.  
  965.  
  966. #Output:
  967. Enter a string: This is a demo input
  968. String with every whitespace character replaced with '9': This9is9a9demo9inputp
  969.  
  970.  
  971. #Q: check if email valid or not:
  972. import re
  973.  
  974. def validate_email(email):
  975.     pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
  976.     regex = re.compile(pattern)
  977.     return bool(regex.match(email))
  978.  
  979. user_email = input("Enter your email address: ")
  980.  
  981. if validate_email(user_email):
  982.     print("Valid email address!")
  983. else:
  984.     print("Invalid email address. Please enter a valid email.")
  985.  
  986.  
  987. #Output:
  988. Enter your email address: arijit@gmail.com
  989. Valid email address!
  990.  
  991. Enter your email address: arijit@gmail
  992. Invalid email address. Please enter a valid email.
  993.  
  994.  
  995.  
  996. #Bubble sort
  997. def bubble_sort(arr):
  998.     n = len(arr)
  999.     for i in range(n):
  1000.         for j in range(0, n-i-1):
  1001.             if arr[j] > arr[j+1]:
  1002.                 arr[j], arr[j+1] = arr[j+1], arr[j]
  1003.  
  1004. arr = []
  1005. size = int(input("Enter the size of the array: "))
  1006. print("Enter the elements of the array:")
  1007. for _ in range(size):
  1008.     element = int(input())
  1009.     arr.append(element)
  1010.  
  1011. bubble_sort(arr)
  1012. print("Sorted array is:", arr)
  1013.  
  1014.  
  1015.  
  1016.  
  1017. # Creating a dictionary with key-value pairs using dict() function taking user input
  1018.  
  1019. my_dict = {}
  1020. num_pairs = int(input("Enter the number of key-value pairs: "))
  1021.  
  1022. for i in range(num_pairs):
  1023.     key = input("Enter key {}: ".format(i+1))
  1024.     value = input("Enter value {}: ".format(i+1))
  1025.     my_dict[key] = value
  1026.  
  1027. print("Dictionary created:", my_dict)
  1028.  
  1029. #output
  1030. Enter the number of key-value pairs: 2
  1031. Enter key 1: hello
  1032. Enter value 1: 2
  1033. Enter key 2: word
  1034. Enter value 2: 2
  1035. Dictionary created: {'hello': '2', 'word': '2'}
  1036.  
  1037.  
  1038. #WAP in python to insert three elements and Pop 1 element from a Dictionary.
  1039.  
  1040. my_dict = {}
  1041.  
  1042. my_dict['apple'] = 10
  1043. my_dict['banana'] = 20
  1044. my_dict['orange'] = 30
  1045.  
  1046. print("Original dictionary:", my_dict)
  1047.  
  1048. popped_item = my_dict.popitem()
  1049.  
  1050. print("Popped item:", popped_item)
  1051. print("Dictionary after popping one element:", my_dict)
  1052.  
  1053. #output:
  1054. Original dictionary: {'apple': 10, 'banana': 20, 'orange': 30}
  1055. Popped item: ('orange', 30)
  1056. Dictionary after popping one element: {'apple': 10, 'banana': 20}
  1057.  
  1058.  
  1059. #WAP in python to find sum of all items in a Dictionary
  1060.  
  1061. my_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
  1062. total_sum = sum(my_dict.values())
  1063. print("Sum of all items in the dictionary:", total_sum)
  1064.  
  1065. #output:
  1066. Sum of all items in the dictionary: 100
  1067.  
  1068.  
  1069. # WAP in python update the value of a dictionary in Python if the particular key exists. If the key is not
  1070. #present in the dictionary, we will simply print that the key does not exist
  1071.  
  1072. my_dict = {'a': 10, 'b': 20, 'c': 30}
  1073.  
  1074. key_to_update = input("Enter the key to update: ")
  1075. new_value = input("Enter the new value: ")
  1076.  
  1077. if key_to_update in my_dict:
  1078.     my_dict[key_to_update] = new_value
  1079. else:
  1080.     print("The key does not exist")
  1081.  
  1082. print("Updated dictionary:", my_dict)
  1083.  
  1084. #output:
  1085. Enter the key to update: a
  1086. Enter the new value: 6
  1087. Updated dictionary: {'a': '6', 'b': 20, 'c': 30}
  1088.  
  1089.  
  1090. #Write a program to get the maximum and minimum value of dictionary
  1091.  
  1092. my_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 5}
  1093.  
  1094. max_value = max(my_dict.values())
  1095. min_value = min(my_dict.values())
  1096.  
  1097. print("Maximum value in the dictionary:", max_value)
  1098. print("Minimum value in the dictionary:", min_value)
  1099.  
  1100.  
  1101. #output
  1102. Maximum value in the dictionary: 30
  1103. Minimum value in the dictionary: 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement