Advertisement
fsoc131y

npc

Jan 11th, 2024
881
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.16 KB | Source Code | 0 0
  1. 1. String Functions
  2. def my_concatenation(str1, str2):
  3.     result = ""
  4.     for char in str1:
  5.         result += char
  6.     for char in str2:
  7.         result += char
  8.     return result
  9.  
  10. def my_reverse(string):
  11.     result = ""
  12.     for i in range(len(string) - 1, -1, -1):
  13.         result += string[i]
  14.     return result
  15.  
  16. def my_replication(string, n):
  17.     result = ""
  18.     for _ in range(n):
  19.         result = my_concatenation(result, string)
  20.     return result
  21.  
  22. def my_slicing(string, start, end):
  23.     result = ""
  24.     for i in range(start, end):
  25.         result += string[i]
  26.     return result
  27.  
  28. def my_equals(str1, str2):
  29.     if len(str1) != len(str2):
  30.         return False
  31.     for i in range(len(str1)):
  32.         if str1[i] != str2[i]:
  33.             return False
  34.     return True
  35.  
  36. def my_iterate_string(string):
  37.     for char in string:
  38.         print(char, end=" ")
  39.  
  40. def my_substring(string, start, length):
  41.     result = ""
  42.     for i in range(start, start + length):
  43.         result += string[i]
  44.     return result
  45.  
  46. # Example usage
  47. string1 = "Hello"
  48. string2 = "World"
  49. concatenated_str = my_concatenation(string1, string2)
  50. reversed_str = my_reverse(string1)
  51. replicated_str = my_replication(string1, 3)
  52. sliced_str = my_slicing(string1, 1, 4)
  53. equal_check = my_equals(string1, string2)
  54. print("Concatenated String:", concatenated_str)
  55. print("Reversed String:", reversed_str)
  56. print("Replicated String:", replicated_str)
  57. print("Sliced String:", sliced_str)
  58. print("Equals Check:", equal_check)
  59.  
  60. print("\nIterating over the string:")
  61. my_iterate_string(string1)
  62.  
  63. substring_str = my_substring(string1, 1, 3)
  64. print("\nSubstring:", substring_str)
  65.  
  66. --------------------------------------------------------------------------------------------
  67.  
  68. 2. Basic Regular Expression
  69. import re
  70.  
  71. print("Matching a pattern")
  72. pattern = r"apple"
  73. text = "I like apples and oranges."
  74.  
  75. print("Using re.search() to find the first occurrence of the pattern")
  76. match = re.search(pattern, text)
  77. if match:
  78.     print(f"Pattern '{pattern}' found at index {match.start()} in the text.")
  79. else:
  80.     print(f"Pattern '{pattern}' not found in the text.")
  81.  
  82. print("\nExtracting matches using groups")
  83. pattern_with_groups = r"(\w+) (\w+)"
  84. name_text = "John Doe, Jane Smith"
  85.  
  86. print("Using re.findall() to find all occurrences of the pattern with groups")
  87. matches = re.findall(pattern_with_groups, name_text)
  88. for match in matches:
  89.     first_name, last_name = match
  90.     print(f"First Name: {first_name}, Last Name: {last_name}")
  91.  
  92. print("\nReplacing matches")
  93. pattern_to_replace = r"apple|orange"
  94. replacement_text = "fruit"
  95.  
  96. print("Using re.sub() to replace all occurrences of the pattern")
  97. updated_text = re.sub(pattern_to_replace, replacement_text, text)
  98. print(f"Original Text: {text}")
  99. print(f"Updated Text: {updated_text}")
  100.  
  101. -----
  102. import re
  103.  
  104. # Function to demonstrate basic regular expressions
  105. def demonstrate_regex(text):
  106.     # 1. Matching a specific pattern
  107.     pattern1 = re.compile(r'apple')
  108.     match1 = pattern1.search(text)
  109.     print("1. Matching 'apple':", match1.group() if match1 else "Not Found")
  110.  
  111.     # 2. Matching any digit
  112.     pattern2 = re.compile(r'\d')
  113.     match2 = pattern2.search(text)
  114.     print("2. Matching any digit:", match2.group() if match2 else "Not Found")
  115.  
  116.     # 3. Matching any word character
  117.     pattern3 = re.compile(r'\w+')
  118.     match3 = pattern3.findall(text)
  119.     print("3. Matching any word character:", match3)
  120.  
  121.     # 4. Matching any non-word character
  122.     pattern4 = re.compile(r'\W+')
  123.     match4 = pattern4.findall(text)
  124.     print("4. Matching any non-word character:", match4)
  125.  
  126.     # 5. Matching a specific number of occurrences
  127.     pattern5 = re.compile(r'o{2}')
  128.     match5 = pattern5.search(text)
  129.     print("5. Matching 'oo':", match5.group() if match5 else "Not Found")
  130.  
  131.     # 6. Matching the start of a string
  132.     pattern6 = re.compile(r'^Hello')
  133.     match6 = pattern6.search(text)
  134.     print("6. Matching 'Hello' at the start:", match6.group() if match6 else "Not Found")
  135.  
  136.     # 7. Matching the end of a string
  137.     pattern7 = re.compile(r'World$')
  138.     match7 = pattern7.search(text)
  139.     print("7. Matching 'World' at the end:", match7.group() if match7 else "Not Found")
  140.  
  141.     # 8. Matching any character (except for a newline)
  142.     pattern8 = re.compile(r'.')
  143.     match8 = pattern8.findall(text)
  144.     print("8. Matching any character:", match8)
  145.  
  146. # Example usage
  147. sample_text = "Hello apple! 123 World."
  148. demonstrate_regex(sample_text)
  149.  
  150. ----------------------------------------------------------------------------------------------------------------
  151. doubtful
  152.  
  153. 3. Advanced Regular Expressions using Tkinter
  154. import re
  155. import tkinter as tk
  156. from tkinter import ttk
  157.  
  158. def validate_input():
  159.     name = name_entry.get()
  160.     email = email_entry.get()
  161.     phone = phone_entry.get()
  162.  
  163.     # Regular expressions for validation
  164.     name_pattern = re.compile(r'^[A-Za-z\s]+$')
  165.     email_pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
  166.     phone_pattern = re.compile(r'^\d{10}$')
  167.  
  168.     # Validate name
  169.     if not name_pattern.match(name):
  170.         result_label.config(text="Invalid name format", fg="red")
  171.         return
  172.  
  173.     # Validate email
  174.     if not email_pattern.match(email):
  175.         result_label.config(text="Invalid email format", fg="red")
  176.         return
  177.  
  178.     # Validate phone number
  179.     if not phone_pattern.match(phone):
  180.         result_label.config(text="Invalid phone number format", fg="red")
  181.         return
  182.  
  183.     result_label.config(text="Input is valid", fg="green")
  184.  
  185. # Create the main application window
  186. app = tk.Tk()
  187. app.title("Data Validation")
  188. app.geometry("300x200")
  189.  
  190. # Create and set up the form
  191. frame = ttk.Frame(app, padding="10")
  192. frame.grid(column=0, row=0, sticky=(tk.W, tk.E, tk.N, tk.S))
  193.  
  194. name_label = ttk.Label(frame, text="Name:")
  195. name_label.grid(column=0, row=0, sticky=tk.W, pady=5)
  196. name_entry = ttk.Entry(frame, width=30)
  197. name_entry.grid(column=1, row=0, sticky=tk.W, pady=5)
  198.  
  199. email_label = ttk.Label(frame, text="Email:")
  200. email_label.grid(column=0, row=1, sticky=tk.W, pady=5)
  201. email_entry = ttk.Entry(frame, width=30)
  202. email_entry.grid(column=1, row=1, sticky=tk.W, pady=5)
  203.  
  204. phone_label = ttk.Label(frame, text="Phone:")
  205. phone_label.grid(column=0, row=2, sticky=tk.W, pady=5)
  206. phone_entry = ttk.Entry(frame, width=15)
  207. phone_entry.grid(column=1, row=2, sticky=tk.W, pady=5)
  208.  
  209. validate_button = ttk.Button(frame, text="Validate", command=validate_input)
  210. validate_button.grid(column=0, row=3, columnspan=2, pady=10)
  211.  
  212. result_label = ttk.Label(frame, text="")
  213. result_label.grid(column=0, row=4, columnspan=2)
  214.  
  215. # Run the Tkinter event loop
  216. app.mainloop()
  217.  
  218. --------------------------------------------------------------------------------------------------------------
  219. 4. Calculator using Tkinter
  220. import tkinter as tk
  221. from tkinter import ttk
  222.  
  223. def on_click(button_text):
  224.     current_text = entry_var.get()
  225.    
  226.     if button_text == "C":
  227.         entry_var.set("")
  228.     elif button_text == "=":
  229.         try:
  230.             result = eval(current_text)
  231.             entry_var.set(str(result))
  232.         except Exception as e:
  233.             entry_var.set("Error")
  234.     else:
  235.         entry_var.set(current_text + button_text)
  236.  
  237. # Create the main application window
  238. calculator = tk.Tk()
  239. calculator.title("Calculator")
  240.  
  241. # Entry widget for displaying the input and result
  242. entry_var = tk.StringVar()
  243. entry = ttk.Entry(calculator, textvariable=entry_var, font=('Arial', 14), justify="right")
  244. entry.grid(row=0, column=0, columnspan=4, sticky="nsew", pady=10)
  245. calculator.columnconfigure((0, 1, 2, 3), weight=1)
  246.  
  247. # Button layout
  248. buttons = [
  249.     '7', '8', '9', '/',
  250.     '4', '5', '6', '*',
  251.     '1', '2', '3', '-',
  252.     '0', '.', 'C', '+',
  253.     '='
  254. ]
  255.  
  256. # Add buttons to the grid
  257. row_val = 1
  258. col_val = 0
  259.  
  260. for button_text in buttons:
  261.     ttk.Button(calculator, text=button_text, command=lambda text=button_text: on_click(text)).grid(row=row_val, column=col_val, sticky="nsew", padx=5, pady=5)
  262.     col_val += 1
  263.     if col_val > 3:
  264.         col_val = 0
  265.         row_val += 1
  266.  
  267. # Configure row and column weights
  268. for i in range(1, 6):
  269.     calculator.rowconfigure(i, weight=1)
  270.  
  271. # Run the Tkinter event loop
  272. calculator.mainloop()
  273.  
  274.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement