0% found this document useful (0 votes)
8 views7 pages

Python Basics: 50 Code Examples

Uploaded by

flashman3009
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)
8 views7 pages

Python Basics: 50 Code Examples

Uploaded by

flashman3009
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

# 1.

Add two numbers


a, b = 5, 3
print("1. Sum:", a + b)

# 2. Subtract two numbers


print("2. Difference:", a - b)

# 3. Multiply two numbers


print("3. Product:", a * b)

# 4. Divide two numbers


print("4. Division:", a / b)

# 5. Find remainder
print("5. Remainder:", a % b)

# 6. Exponent
print("6. Power:", a ** b)

# 7. Floor division
print("7. Floor Division:", a // b)

# 8. Check even/odd
num = 7
print("8. Even/Odd:", "Even" if num % 2 == 0 else "Odd")

# 9. Swap numbers
x, y = 10, 20
x, y = y, x
print("9. After Swap:", x, y)

# 10. Compare numbers


print("10. Is a > b?", a > b)

# ------------------------------------
# Level 2: Logical & Membership
# ------------------------------------

# 11. Number between 10 and 50


n = 25
print("11. Between 10 and 50?", 10 < n < 50)
# 12. Number not in list
lst = [1, 2, 3, 4]
print("12. 10 not in list?", 10 not in lst)

# 13. OR operator
age, has_id = 15, True
print("13. OR operator:", age >= 18 or has_id)

# 14. String contains vowels


s = "hello"
print("14. Contains vowel?", any(v in s for v in "aeiou"))

# 15. Negate boolean


flag = True
print("15. Negation:", not flag)

# --------------------------
# Level 3: Lists
# --------------------------

# 16. Sum of list elements


nums = [1, 2, 3, 4, 5]
print("16. Sum:", sum(nums))

# 17. Maximum element


print("17. Max:", max(nums))

# 18. Reverse list (no slicing)


rev = []
for i in nums:
[Link](0, i)
print("18. Reverse:", rev)

# 19. Frequency of element


print("19. Count 3:", [Link](3))

# 20. Bubble sort


arr = [5, 1, 4, 2, 8]
for i in range(len(arr)):
for j in range(len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print("20. Bubble Sort:", arr)

# ----------------------------
# Level 4: Tuples & Sets
# ----------------------------

# 21. Tuple of student marks


marks = (90, 85, 78)
print("21. Marks Tuple:", marks)

# 22. Length of tuple


print("22. Length:", len(marks))

# 23. Check element in tuple


print("23. Is 85 present?", 85 in marks)

# 24. Union & Intersection


A, B = {1, 2, 3}, {3, 4, 5}
print("24. Union:", A | B)
print("24. Intersection:", A & B)

# 25. Remove duplicates


lst = [1, 2, 2, 3, 4, 4]
print("25. Unique:", list(set(lst)))

# -----------------------------
# Level 5: Dictionaries
# -----------------------------

# 26. Dictionary
students = {"A": 90, "B": 85}
print("26. Students:", students)

# 27. Update dictionary


students["A"] = 95
print("27. Updated:", students)

# 28. Char frequency


text = "banana"
freq = {}
for ch in text:
freq[ch] = [Link](ch, 0) + 1
print("28. Char Frequency:", freq)

# 29. Max value key


print("29. Top Student:", max(students, key=[Link]))

# 30. Merge dictionaries


d1 = {"x": 1, "y": 2}
d2 = {"y": 3, "z": 4}
merged = {**d1, **d2}
print("30. Merged:", merged)

# ----------------------------
# Level 6: Stack & Queue
# ----------------------------

# 31. Stack
stack = []
[Link](10)
[Link](20)
print("31. Stack Pop:", [Link]())

# 32. Queue
queue = []
[Link](10)
[Link](20)
print("32. Queue Pop:", [Link](0))

# 33. Balanced parentheses


expr = "(()())"
stack, balanced = [], True
for ch in expr:
if ch == "(":
[Link](ch)
elif ch == ")":
if not stack: balanced = False; break
[Link]()
print("33. Balanced?", balanced and not stack)

# 34. Reverse string using stack


s = "hello"
stack = list(s)
rev = ""
while stack:
rev += [Link]()
print("34. Reverse String:", rev)

# 35. Circular queue simulation


queue = [None]*5
front = rear = -1
rear = (rear+1)%5; queue[rear] = 10
rear = (rear+1)%5; queue[rear] = 20
front = (front+1)%5; print("35. Circular Queue Dequeue:", queue[front])

# --------------------------
# Level 7: String Operations
# --------------------------

# 36. Palindrome check


s = "madam"
print("36. Palindrome?", s == s[::-1])

# 37. Reverse words


sentence = "I love Python"
print("37. Reversed Words:", " ".join([Link]()[::-1]))

# 38. Count vowels & consonants


s = "python"
vowels = sum(1 for ch in s if ch in "aeiou")
consonants = len(s) - vowels
print("38. Vowels:", vowels, "Consonants:", consonants)

# 39. Longest word


sentence = "Python is powerful language"
words = [Link]()
print("39. Longest Word:", max(words, key=len))

# 40. Remove special characters


import re
s = "he@llo!! wo##rld"
print("40. Clean String:", [Link](r'[^a-zA-Z0-9 ]', '', s))

# ------------------------
# Level 8: Intermediate
# ------------------------
# 41. Fibonacci
n=7
a, b = 0, 1
print("41. Fibonacci:", end=" ")
for _ in range(n):
print(a, end=" ")
a, b = b, a+b
print()

# 42. Factorial recursion


def fact(n): return 1 if n==0 else n*fact(n-1)
print("42. Factorial(5):", fact(5))

# 43. Binary search


arr = [1, 3, 5, 7, 9]
target = 7
low, high = 0, len(arr)-1
found = False
while low <= high:
mid = (low+high)//2
if arr[mid] == target: found=True; break
elif arr[mid] < target: low = mid+1
else: high = mid-1
print("43. Binary Search:", "Found" if found else "Not Found")

# 44. Linear search


target = 9
print("44. Linear Search:", "Found" if target in arr else "Not Found")

# 45. Armstrong number


n = 153
print("45. Armstrong?", sum(int(d)**3 for d in str(n)) == n)

# -------------------------------
# Level 9: Advanced Structures
# -------------------------------

# 46. Priority queue


pq = []
[Link](4); [Link](1); [Link](3)
[Link](reverse=True)
print("46. Priority Queue Pop:", [Link](0))
# 47. Group words by length
words = ["cat", "dog", "apple", "hi"]
groups = {}
for w in words:
[Link](len(w), []).append(w)
print("47. Grouped:", groups)

# 48. Unique common elements


a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
print("48. Common Elements:", set(a) & set(b))

# 49. Matrix addition


A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
C = [[A[i][j]+B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
print("49. Matrix Sum:", C)

# 50. Graph adjacency list


graph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A", "D"],
"D": ["B", "C"]
}
print("50. Graph:", graph)

Common questions

Powered by AI

The bubble sort algorithm is demonstrated by iteratively comparing adjacent elements and swapping them if needed, until the entire list is sorted . On the other hand, binary search is shown as a more efficient searching method that works on a sorted list, repeatedly dividing the search interval in half to find a target value . Thus, bubble sort is a sorting algorithm, while binary search is a searching algorithm designed for sorted data.

The document illustrates that a stack uses a LIFO (Last In First Out) approach where elements are pushed onto the stack and popped from the top, as demonstrated by appending and popping operations . A queue, however, uses a FIFO (First In First Out) method where elements are appended at the rear and popped from the front, as shown in queue operations .

The document describes merging dictionaries by using syntax that combines the key-value pairs of two dictionaries, resolving key conflicts by choosing the value from the second dictionary . This approach implies that when keys overlap, the latter dictionary’s entries will overwrite the former’s, which can be useful for updating dictionaries but may result in data loss for overlapped keys.

The document uses a stack to check for balanced parentheses by pushing '(' onto the stack and popping it upon encountering ')'. If a closing parenthesis is encountered and the stack is empty, it indicates an imbalance . The algorithm ensures all opening parentheses are matched with closing ones and handles situations where extra closing parentheses or unclosed opening parentheses cause imbalances.

The document demonstrates using the modulus operation to determine if a number is even or odd by checking if it is divisible by 2 (i.e., num % 2 == 0 for even, else odd). This operation is fundamental because it provides a simple and efficient method for evaluating parity, which is useful for conditions and algorithms that depend on numeric properties.

The document uses a stack to reverse a string by pushing each character onto the stack and then popping them off in reverse order. This method takes advantage of the LIFO (Last In First Out) property of stacks, effectively reversing the order of the characters in the string .

The document performs matrix addition by iterating through each element of two matrices simultaneously and summing corresponding elements to form a new matrix . The approach efficiently handles matrix operations that require matching dimensions and correctly applies element-wise addition, which is critical in many mathematical computations involving matrices.

The document checks for an Armstrong number by summing the cubes of its digits and comparing the sum to the number itself. An example given in the document is the number 153, which is determined to be an Armstrong number because the sum of its digits raised to the power of three equals the number itself .

The document employs a dictionary to keep track of how often each character appears in a string. As each character is encountered, its count is incremented in the dictionary. This technique provides insights into character distribution within the text which could be vital for cryptographic analysis or text compression .

The document represents a graph using an adjacency list, where each vertex key maps to a list of adjacent vertices. For example, vertex 'A' maps to['B', 'C'], indicating an edge between A and both B and C . This representation is space-efficient, particularly for sparse graphs, because it only stores edges that are present and allows for efficient traversal of a node’s connections.

You might also like