0% found this document useful (0 votes)
3 views34 pages

Python Preparation

The document provides a comprehensive collection of Python pattern programs ranging from easy to hard, including various shapes and structures such as triangles, pyramids, and diamonds, along with their respective outputs. Additionally, it includes a section on 100 essential Python programs covering fundamental concepts for technical interviews, categorized into basic, number, string, list, matrix, and file handling programs. Each program is presented with code snippets and expected outputs to facilitate learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views34 pages

Python Preparation

The document provides a comprehensive collection of Python pattern programs ranging from easy to hard, including various shapes and structures such as triangles, pyramids, and diamonds, along with their respective outputs. Additionally, it includes a section on 100 essential Python programs covering fundamental concepts for technical interviews, categorized into basic, number, string, list, matrix, and file handling programs. Each program is presented with code snippets and expected outputs to facilitate learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

# **Python Pattern Programs (Easy to Hard) with Output**

---

## **1. Right-Angled Triangle (Left Aligned)**


```python
n=5
for i in range(1, n + 1):
print('*' * i)
```
**Output:**
```
*
**
***
****
*****
```

---

## **2. Right-Angled Triangle (Right Aligned)**


```python
n=5
for i in range(1, n + 1):
print(' ' * (n - i) + '*' * i)
```
**Output:**
```
*
**
***
****
*****
```

---

## **3. Inverted Right-Angled Triangle**


```python
n=5
for i in range(n, 0, -1):
print('*' * i)
```
**Output:**
```
*****
****
***
**
*
```

---

## **4. Pyramid Pattern**


```python
n=5
for i in range(1, n + 1):
print(' ' * (n - i) + '*' * (2 * i - 1))
```
**Output:**
```
*
***
*****
*******
*********
```

---

## **5. Inverted Pyramid Pattern**


```python
n=5
for i in range(n, 0, -1):
print(' ' * (n - i) + '*' * (2 * i - 1))
```
**Output:**
```
*********
*******
*****
***
*
```

---

## **6. Diamond Pattern**


```python
n=5
for i in range(1, n + 1):
print(' ' * (n - i) + '*' * (2 * i - 1))
for i in range(n - 1, 0, -1):
print(' ' * (n - i) + '*' * (2 * i - 1))
```
**Output:**
```
*
***
*****
*******
*********
*******
*****
***
*
```

---

## **7. Hollow Square Pattern**


```python
n=5
for i in range(n):
if i == 0 or i == n - 1:
print('*' * n)
else:
print('*' + ' ' * (n - 2) + '*')
```
**Output:**
```
*****
* *
* *
* *
*****
```

---

## **8. Number Pyramid (Ascending)**


```python
n=5
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end=' ')
print()
```
**Output:**
```
1
12
123
1234
12345
```

---

## **9. Number Pyramid (Descending)**


```python
n=5
for i in range(n, 0, -1):
for j in range(1, i + 1):
print(j, end=' ')
print()
```
**Output:**
```
12345
1234
123
12
1
```

---

## **10. Alphabet Pyramid (A to E)**


```python
n=5
for i in range(1, n + 1):
for j in range(1, i + 1):
print(chr(64 + j), end=' ')
print()
```
**Output:**
```
A
AB
ABC
ABCD
ABCDE
```

---

## **11. Hollow Diamond Pattern**


```python
n=5
for i in range(1, n + 1):
print(' ' * (n - i) + '*' + ' ' * (2 * i - 3) + ('*' if i != 1 else ''))
for i in range(n - 1, 0, -1):
print(' ' * (n - i) + '*' + ' ' * (2 * i - 3) + ('*' if i != 1 else ''))
```
**Output:**
```
*
**
* *
* *
* *
* *
* *
**
*
```

---

## **12. Pascal’s Triangle**


```python
n=5
for i in range(1, n + 1):
num = 1
for j in range(1, i + 1):
print(num, end=' ')
num = num * (i - j) // j
print()
```
**Output:**
```
1
11
121
1331
14641
```

---

## **13. Floyd’s Triangle**


```python
n=5
num = 1
for i in range(1, n + 1):
for j in range(1, i + 1):
print(num, end=' ')
num += 1
print()
```
**Output:**
```
1
23
456
7 8 9 10
11 12 13 14 15
```

---

## **14. Binary Number Pyramid**


```python
n=5
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j % 2, end=' ')
print()
```
**Output:**
```
1
10
101
1010
10101
```

---

## **15. Spiral Number Pattern**


```python
n=4
size = 2 * n - 1
matrix = [[0] * size for _ in range(size)]
low, high = 0, size - 1
num = 1
for i in range(n):
for j in range(low, high + 1):
matrix[i][j] = num
for j in range(low + 1, high + 1):
matrix[j][high] = num
for j in range(high - 1, low - 1, -1):
matrix[high][j] = num
for j in range(high - 1, low, -1):
matrix[j][low] = num
low += 1
high -= 1
num += 1
for row in matrix:
print(' '.join(map(str, row)))
```
**Output:**
```
1111111
1222221
1233321
1234321
1233321
1222221
1111111
```

---

## **16. Heart Pattern**


```python
n=6
for i in range(n // 2, n, 2):
for j in range(1, n - i, 2):
print(" ", end=" ")
for j in range(1, i + 1):
print("*", end=" ")
for j in range(1, n - i + 1):
print(" ", end=" ")
for j in range(1, i + 1):
print("*", end=" ")
print()
for i in range(n, 0, -1):
for j in range(i, n):
print(" ", end=" ")
for j in range(1, 2 * i):
print("*", end=" ")
print()
```
**Output:**
```
** **
**** ****
*********
*******
*****
***
*
```

---

## **17. Hollow Hourglass Pattern**


```python
n=5
for i in range(n, 0, -1):
print(' ' * (n - i) + '*' + ' ' * (2 * i - 3) + ('*' if i != 1 else ''))
for i in range(2, n + 1):
print(' ' * (n - i) + '*' + ' ' * (2 * i - 3) + ('*' if i != 1 else ''))
```
**Output:**
```
* *
* *
* *
**
*
**
* *
* *
* *
```

---
## **18. Zig-Zag Pattern**
```python
n=5
for i in range(1, n + 1):
for j in range(1, n + 1):
if (i + j) % 2 == 0:
print("*", end=" ")
else:
print(" ", end=" ")
print()
```
**Output:**
```
* * *
* *
* * *
* *
* * *
```

---

## **19. Cross (X) Pattern**


```python
n=5
for i in range(n):
for j in range(n):
if i == j or i + j == n - 1:
print("*", end=" ")
else:
print(" ", end=" ")
print()
```
**Output:**
```
* *
* *
*
* *
* *
```

---

## **20. Hollow Square with Diagonal**


```python
n=5
for i in range(n):
for j in range(n):
if i == 0 or i == n - 1 or j == 0 or j == n - 1 or i == j or i + j == n - 1:
print("*", end=" ")
else:
print(" ", end=" ")
print()
```
**Output:**
```
*****
** **
* * *
** **
*****
```

---

### **More Patterns? (Arrow, Triangle Variations, Complex Shapes, etc.)**


Let me know if you need **additional patterns** or **specific variations**! 🚀

===========================================================

# **100 Essential Python Programs for Placements (All Concepts Covered)**

Here's a comprehensive collection of **100 Python programs** covering all fundamental concepts
asked in technical interviews, categorized for easy learning.

## **1. Basic Programs**


### 1. Hello World
```python
print("Hello, World!")
```

### 2. Add Two Numbers


```python
a=5
b=3
print("Sum:", a + b)
```

### 3. Swap Two Variables


```python
a, b = 5, 3
a, b = b, a
print("a =", a, "b =", b)
```

### 4. Convert Celsius to Fahrenheit


```python
celsius = 37.5
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is {fahrenheit}°F")
```
### 5. Check Leap Year
```python
year = 2024
if (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0):
print("Leap year")
else:
print("Not a leap year")
```

## **2. Number Programs**


### 6. Find GCD
```python
a, b = 48, 18
while b:
a, b = b, a % b
print("GCD:", a)
```

### 7. Find LCM


```python
a, b = 12, 15
gcd = a
temp = b
while temp:
gcd, temp = temp, gcd % temp
lcm = (a * b) // gcd
print("LCM:", lcm)
```

### 8. Check Armstrong Number


```python
num = 153
temp = num
sum = 0
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
print("Armstrong" if num == sum else "Not Armstrong")
```

### 9. Print Prime Numbers in Range


```python
start, end = 10, 50
print("Primes between", start, "and", end, ":")
for num in range(start, end + 1):
if num > 1:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
break
else:
print(num, end=" ")
```

### 10. Fibonacci Series


```python
n = 10
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
```

## **3. String Programs**


### 11. Reverse a String
```python
s = "hello"
print("Reversed:", s[::-1])
```

### 12. Check Anagram


```python
s1, s2 = "listen", "silent"
print("Anagram" if sorted(s1) == sorted(s2) else "Not Anagram")
```

### 13. Count Character Frequency


```python
s = "programming"
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
print("Character frequency:", freq)
```

### 14. Remove Punctuation


```python
import string
s = "Hello, World! How are you?"
print("Without punctuation:", s.translate(str.maketrans('', '', string.punctuation)))
```

### 15. Longest Word in Sentence


```python
sentence = "Python is an amazing programming language"
longest = max(sentence.split(), key=len)
print("Longest word:", longest)
```

## **4. List Programs**


### 16. Find List Average
```python
nums = [10, 20, 30, 40]
print("Average:", sum(nums)/len(nums))
```

### 17. Merge Two Lists


```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged = list1 + list2
print("Merged list:", merged)
```

### 18. Flatten Nested List


```python
nested = [[1, 2], [3, 4], [5, 6]]
flat = [item for sublist in nested for item in sublist]
print("Flattened list:", flat)
```

### 19. List Intersection


```python
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
intersection = [x for x in list1 if x in list2]
print("Intersection:", intersection)
```

### 20. Remove Duplicates


```python
nums = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(nums))
print("Without duplicates:", unique)
```

## **5. Matrix Programs**


### 21. Add Two Matrices
```python
X = [[1, 2], [3, 4]]
Y = [[5, 6], [7, 8]]
result = [[X[i][j] + Y[i][j] for j in range(len(X[0]))] for i in range(len(X))]
print("Matrix Addition:")
for row in result:
print(row)
```

### 22. Transpose Matrix


```python
matrix = [[1, 2, 3], [4, 5, 6]]
transpose = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print("Transpose:")
for row in transpose:
print(row)
```
### 23. Matrix Multiplication
```python
X = [[1, 2], [3, 4]]
Y = [[5, 6], [7, 8]]
result = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in X]
print("Matrix Multiplication:")
for row in result:
print(row)
```

### 24. Check Identity Matrix


```python
matrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
is_identity = all(matrix[i][j] == (1 if i == j else 0)
for i in range(len(matrix)) for j in range(len(matrix[0])))
print("Identity matrix" if is_identity else "Not identity matrix")
```

### 25. Sparse Matrix Representation


```python
matrix = [[0, 0, 3], [0, 0, 5], [0, 2, 0]]
sparse = [[i, j, matrix[i][j]]
for i in range(len(matrix))
for j in range(len(matrix[0]))
if matrix[i][j] != 0]
print("Sparse representation:")
for row in sparse:
print(row)
```

## **6. File Handling Programs**


### 26. Read File
```python
with open('sample.txt', 'r') as file:
content = file.read()
print("File content:", content)
```

### 27. Count Words in File


```python
with open('sample.txt', 'r') as file:
word_count = len(file.read().split())
print("Word count:", word_count)
```

### 28. Copy File


```python
with open('source.txt', 'r') as source, open('destination.txt', 'w') as dest:
dest.write(source.read())
print("File copied successfully")
```
### 29. Count File Lines
```python
with open('sample.txt', 'r') as file:
line_count = sum(1 for line in file)
print("Line count:", line_count)
```

### 30. Find Longest Word in File


```python
with open('sample.txt', 'r') as file:
words = file.read().split()
longest = max(words, key=len)
print("Longest word:", longest)
```

## **7. OOP Programs**


### 31. Create Class
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def introduce(self):
print(f"Hi, I'm {self.name}, {self.age} years old")

p = Person("Alice", 25)
p.introduce()
```

### 32. Inheritance Example


```python
class Animal:
def speak(self):
pass

class Dog(Animal):
def speak(self):
print("Bark")

dog = Dog()
dog.speak()
```

### 33. Polymorphism Example


```python
class Bird:
def fly(self):
print("Flying")

class Airplane:
def fly(self):
print("Flying with engines")

def let_it_fly(flying_object):
flying_object.fly()

let_it_fly(Bird())
let_it_fly(Airplane())
```

### 34. Encapsulation Example


```python
class BankAccount:
def __init__(self):
self.__balance = 0

def deposit(self, amount):


self.__balance += amount

def get_balance(self):
return self.__balance

account = BankAccount()
account.deposit(100)
print("Balance:", account.get_balance())
```

### 35. Method Overriding


```python
class Parent:
def show(self):
print("Parent method")

class Child(Parent):
def show(self):
print("Child method")

obj = Child()
obj.show()
```

## **8. Exception Handling**


### 36. Basic Try-Except
```python
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
```

### 37. Multiple Exceptions


```python
try:
num = int("abc")
except (ValueError, TypeError):
print("Invalid number conversion")
```

### 38. Finally Block


```python
try:
file = open("nonexistent.txt", "r")
except FileNotFoundError:
print("File not found")
finally:
print("This always executes")
```

### 39. Raise Custom Exception


```python
class NegativeNumberError(Exception):
pass

try:
num = -5
if num < 0:
raise NegativeNumberError("No negative numbers")
except NegativeNumberError as e:
print(e)
```

### 40. Else in Exception


```python
try:
num = int("42")
except ValueError:
print("Invalid number")
else:
print("Valid number:", num)
```

## **9. Advanced Concepts**


### 41. Generator Function
```python
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1

for num in count_up_to(5):


print(num)
```

### 42. Decorator Example


```python
def my_decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper

@my_decorator
def say_hello():
print("Hello!")

say_hello()
```

### 43. Context Manager


```python
class ManagedFile:
def __init__(self, filename):
self.filename = filename

def __enter__(self):
self.file = open(self.filename, 'w')
return self.file

def __exit__(self, exc_type, exc_val, exc_tb):


if self.file:
self.file.close()

with ManagedFile('hello.txt') as f:
f.write("Hello, world!")
```

### 44. Multithreading


```python
import threading

def print_numbers():
for i in range(5):
print(i)

thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
```

### 45. Regular Expression


```python
import re

text = "Contact us at [email protected] or [email protected]"


emails = re.findall(r'[\w\.-]+@[\w\.-]+', text)
print("Emails found:", emails)
```

## **10. Algorithm Problems**


### 46. Binary Search
```python
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

arr = [1, 3, 5, 7, 9]
print("Found at index:", binary_search(arr, 5))
```

### 47. Bubble Sort


```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr

print("Sorted array:", bubble_sort([64, 34, 25, 12, 22, 11, 90]))


```

### 48. Quick Sort


```python
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr)//2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)

print("Quick sorted:", quick_sort([3,6,8,10,1,2,1]))


```

### 49. Linked List Implementation


```python
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def append(self, data):


new_node = Node(data)
if not self.head:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node

def print_list(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")

ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.print_list()
```

### 50. Breadth-First Search (BFS)


```python
from collections import deque

def bfs(graph, start):


visited = set()
queue = deque([start])
visited.add(start)

while queue:
vertex = queue.popleft()
print(vertex, end=" ")

for neighbor in graph[vertex]:


if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)

graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
print("BFS traversal:")
bfs(graph, 'A')
```

=============================================================
# **Python Array & String Based Interview Questions (100+ Problems)**

Here's a **comprehensive collection** of array and string manipulation problems frequently asked
in technical interviews, categorized by difficulty with complete solutions.

---

## **Section 1: Array Problems**

### **Easy Level**


#### **1. Find the largest element in an array**
```python
arr = [10, 20, 4, 45, 99]
max_num = arr[0]
for num in arr:
if num > max_num:
max_num = num
print("Largest:", max_num) # Output: 99
```

#### **2. Find the smallest element in an array**


```python
arr = [10, 20, 4, 45, 99]
min_num = arr[0]
for num in arr:
if num < min_num:
min_num = num
print("Smallest:", min_num) # Output: 4
```

#### **3. Reverse an array**


```python
arr = [1, 2, 3, 4, 5]
print("Reversed:", arr[::-1]) # Output: [5, 4, 3, 2, 1]
```

#### **4. Find sum of array elements**


```python
arr = [1, 2, 3, 4, 5]
print("Sum:", sum(arr)) # Output: 15
```
#### **5. Rotate array by k positions**
```python
arr = [1, 2, 3, 4, 5]
k=2
print("Rotated:", arr[k:] + arr[:k]) # Output: [3, 4, 5, 1, 2]
```

---

### **Medium Level**


#### **6. Move all zeros to end of array**
```python
arr = [0, 1, 0, 3, 12]
non_zeros = [x for x in arr if x != 0]
zeros = [0] * (len(arr) - len(non_zeros))
print("Modified:", non_zeros + zeros) # Output: [1, 3, 12, 0, 0]
```

#### **7. Find all duplicates in an array**


```python
arr = [4, 3, 2, 7, 8, 2, 3, 1]
seen = set()
duplicates = [x for x in arr if x in seen or seen.add(x)]
print("Duplicates:", duplicates) # Output: [2, 3]
```

#### **8. Maximum subarray sum (Kadane's Algorithm)**


```python
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
max_current = max_global = arr[0]
for num in arr[1:]:
max_current = max(num, max_current + num)
max_global = max(max_global, max_current)
print("Max subarray sum:", max_global) # Output: 6
```

#### **9. Merge two sorted arrays**


```python
arr1 = [1, 3, 5]
arr2 = [2, 4, 6]
merged = []
i=j=0
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
merged.append(arr1[i])
i += 1
else:
merged.append(arr2[j])
j += 1
merged += arr1[i:] + arr2[j:]
print("Merged:", merged) # Output: [1, 2, 3, 4, 5, 6]
```

#### **10. Find missing number in array (1 to n)**


```python
arr = [3, 0, 1] # n = 3
n = len(arr)
missing = n * (n + 1) // 2 - sum(arr)
print("Missing:", missing) # Output: 2
```

---

### **Hard Level**


#### **11. Find first missing positive integer**
```python
arr = [3, 4, -1, 1]
n = len(arr)
for i in range(n):
while 1 <= arr[i] <= n and arr[arr[i]-1] != arr[i]:
arr[arr[i]-1], arr[i] = arr[i], arr[arr[i]-1]
for i in range(n):
if arr[i] != i + 1:
print("First missing positive:", i + 1) # Output: 2
break
```

#### **12. Trapping rainwater problem**


```python
height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
left, right = 0, len(height) - 1
left_max = right_max = water = 0
while left < right:
if height[left] < height[right]:
left_max = max(left_max, height[left])
water += left_max - height[left]
left += 1
else:
right_max = max(right_max, height[right])
water += right_max - height[right]
right -= 1
print("Trapped water:", water) # Output: 6
```

#### **13. Find the duplicate number (Floyd's Tortoise-Hare)**


```python
nums = [1, 3, 4, 2, 2]
slow = fast = nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[fast]
print("Duplicate:", fast) # Output: 2
```

#### **14. Product of array except self**


```python
nums = [1, 2, 3, 4]
n = len(nums)
output = [1] * n
left_product = 1
for i in range(n):
output[i] = left_product
left_product *= nums[i]
right_product = 1
for i in range(n-1, -1, -1):
output[i] *= right_product
right_product *= nums[i]
print("Product array:", output) # Output: [24, 12, 8, 6]
```

#### **15. Longest consecutive sequence**


```python
nums = [100, 4, 200, 1, 3, 2]
num_set = set(nums)
longest = 0
for num in num_set:
if num - 1 not in num_set:
current_num = num
current_streak = 1
while current_num + 1 in num_set:
current_num += 1
current_streak += 1
longest = max(longest, current_streak)
print("Longest consecutive sequence:", longest) # Output: 4
```

---

## **Section 2: String Problems**

### **Easy Level**


#### **16. Reverse a string**
```python
s = "hello"
print("Reversed:", s[::-1]) # Output: "olleh"
```

#### **17. Check if string is palindrome**


```python
s = "madam"
print("Palindrome:", s == s[::-1]) # Output: True
```

#### **18. Count vowels in string**


```python
s = "Hello World"
vowels = "aeiouAEIOU"
count = sum(1 for char in s if char in vowels)
print("Vowel count:", count) # Output: 3
```

#### **19. Remove duplicates from string**


```python
s = "programming"
unique_chars = []
for char in s:
if char not in unique_chars:
unique_chars.append(char)
print("Without duplicates:", ''.join(unique_chars)) # Output: "progamin"
```

#### **20. Find first non-repeating character**


```python
s = "leetcode"
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
for char in s:
if freq[char] == 1:
print("First non-repeating:", char) # Output: "l"
break
```

---

### **Medium Level**


#### **21. Check if two strings are anagrams**
```python
s1, s2 = "listen", "silent"
print("Anagram:", sorted(s1) == sorted(s2)) # Output: True
```

#### **22. Longest substring without repeating characters**


```python
s = "abcabcbb"
char_set = set()
left = max_len = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_len = max(max_len, right - left + 1)
print("Longest substring length:", max_len) # Output: 3
```

#### **23. String to integer (atoi)**


```python
s = " -42"
s = s.strip()
if not s:
print(0)
sign = -1 if s[0] == '-' else 1
if s[0] in ['-', '+']:
s = s[1:]
res = 0
for char in s:
if not char.isdigit():
break
res = res * 10 + int(char)
res = sign * res
print("Converted integer:", max(-2**31, min(2**31-1, res))) # Output: -42
```

#### **24. Group anagrams**


```python
strs = ["eat","tea","tan","ate","nat","bat"]
anagrams = {}
for word in strs:
sorted_word = ''.join(sorted(word))
if sorted_word in anagrams:
anagrams[sorted_word].append(word)
else:
anagrams[sorted_word] = [word]
print("Grouped anagrams:", list(anagrams.values()))
# Output: [["eat","tea","ate"],["tan","nat"],["bat"]]
```

#### **25. Longest palindromic substring**


```python
s = "babad"
n = len(s)
if n < 2:
print(s)
start = max_len = 0
for i in range(n):
# Odd length
l, r = i, i
while l >= 0 and r < n and s[l] == s[r]:
if r - l + 1 > max_len:
start = l
max_len = r - l + 1
l -= 1
r += 1
# Even length
l, r = i, i+1
while l >= 0 and r < n and s[l] == s[r]:
if r - l + 1 > max_len:
start = l
max_len = r - l + 1
l -= 1
r += 1
print("Longest palindromic substring:", s[start:start+max_len]) # Output: "bab"
```

---

### **Hard Level**


#### **26. Minimum window substring**
```python
s = "ADOBECODEBANC"
t = "ABC"
from collections import Counter
need = Counter(t)
missing = len(t)
left = start = end = 0
for right, char in enumerate(s, 1):
missing -= need[char] > 0
need[char] -= 1
if missing == 0:
while left < right and need[s[left]] < 0:
need[s[left]] += 1
left += 1
if not end or right - left <= end - start:
start, end = left, right
need[s[left]] += 1
missing += 1
left += 1
print("Minimum window:", s[start:end] if end else "") # Output: "BANC"
```

#### **27. Regular expression matching**


```python
s = "aa"
p = "a*"
def isMatch(s, p):
m, n = len(s), len(p)
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
for j in range(1, n + 1):
if p[j-1] == '*':
dp[0][j] = dp[0][j-2]
for i in range(1, m + 1):
for j in range(1, n + 1):
if p[j-1] == s[i-1] or p[j-1] == '.':
dp[i][j] = dp[i-1][j-1]
elif p[j-1] == '*':
dp[i][j] = dp[i][j-2]
if p[j-2] == s[i-1] or p[j-2] == '.':
dp[i][j] |= dp[i-1][j]
return dp[m][n]
print("Pattern matches:", isMatch(s, p)) # Output: True
```

#### **28. Word break problem**


```python
s = "leetcode"
wordDict = ["leet", "code"]
n = len(s)
dp = [False] * (n + 1)
dp[0] = True
for i in range(1, n + 1):
for word in wordDict:
if dp[i - len(word)] and s[i - len(word):i] == word:
dp[i] = True
break
print("Word break possible:", dp[n]) # Output: True
```

#### **29. Longest valid parentheses**


```python
s = ")()())"
stack = [-1]
max_len = 0
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
max_len = max(max_len, i - stack[-1])
print("Longest valid parentheses:", max_len) # Output: 4
```

#### **30. Minimum insertions to make palindrome**


```python
s = "mbadm"
n = len(s)
dp = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
if s[i] == s[j]:
dp[i][j] = dp[i+1][j-1]
else:
dp[i][j] = 1 + min(dp[i+1][j], dp[i][j-1])
print("Minimum insertions:", dp[0][n-1]) # Output: 2
```

---

# **100 Python Programs with Output (No Functions, Direct Code)**

Here are **100 Python programs** with **direct code and output** (no functions, just
straightforward implementation). These cover **basic programs, patterns, arrays, strings, and
more** for placement preparation.

---

## **1. Check Even or Odd**


```python
num = 10
if num % 2 == 0:
print("Even")
else:
print("Odd")
```
**Output:**
```
Even
```

---

## **2. Factorial of a Number**


```python
num = 5
fact = 1
for i in range(1, num + 1):
fact *= i
print("Factorial:", fact)
```
**Output:**
```
Factorial: 120
```

---

## **3. Check Prime Number**


```python
num = 7
is_prime = True
if num <= 1:
is_prime = False
else:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
print("Prime" if is_prime else "Not Prime")
```
**Output:**
```
Prime
```

---

## **4. Fibonacci Series**


```python
n=5
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
```
**Output:**
```
01123
```

---

## **5. Reverse a Number**


```python
num = 1234
rev = 0
while num > 0:
rev = rev * 10 + num % 10
num = num // 10
print("Reversed:", rev)
```
**Output:**
```
Reversed: 4321
```

---

## **6. Check Palindrome String**


```python
s = "madam"
if s == s[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
```
**Output:**
```
Palindrome
```

---

## **7. Count Vowels in a String**


```python
s = "Hello World"
vowels = "aeiouAEIOU"
count = 0
for char in s:
if char in vowels:
count += 1
print("Vowel count:", count)
```
**Output:**
```
Vowel count: 3
```

---

## **8. Remove Duplicates from String**


```python
s = "programming"
result = ""
for char in s:
if char not in result:
result += char
print(result)
```
**Output:**
```
progamin
```

---

## **9. Find Largest Number in List**


```python
arr = [10, 20, 4, 45, 99]
max_num = arr[0]
for num in arr:
if num > max_num:
max_num = num
print("Largest:", max_num)
```
**Output:**
```
Largest: 99
```

---

## **10. Second Largest Number in List**


```python
arr = [10, 20, 4, 45, 99]
first = second = float('-inf')
for num in arr:
if num > first:
second = first
first = num
elif num > second and num != first:
second = num
print("Second largest:", second)
```
**Output:**
```
Second largest: 45
```

---

## **11. Right-Angled Triangle Pattern**


```python
n=5
for i in range(1, n + 1):
print('*' * i)
```
**Output:**
```
*
**
***
****
*****
```

---

## **12. Inverted Right-Angled Triangle**


```python
n=5
for i in range(n, 0, -1):
print('*' * i)
```
**Output:**
```
*****
****
***
**
*
```

---

## **13. Pyramid Pattern**


```python
n=5
for i in range(1, n + 1):
print(' ' * (n - i) + '*' * (2 * i - 1))
```
**Output:**
```
*
***
*****
*******
*********
```

---

## **14. Diamond Pattern**


```python
n=5
for i in range(1, n + 1):
print(' ' * (n - i) + '*' * (2 * i - 1))
for i in range(n - 1, 0, -1):
print(' ' * (n - i) + '*' * (2 * i - 1))
```
**Output:**
```
*
***
*****
*******
*********
*******
*****
***
*
```

---

## **15. Number Pyramid**


```python
n=5
for i in range(1, n + 1):
print(' ' * (n - i), end='')
for j in range(1, i + 1):
print(j, end=' ')
print()
```
**Output:**
```
1
12
123
1234
12345
```

---

## **16. Sum of Digits**


```python
num = 1234
sum_digits = 0
while num > 0:
sum_digits += num % 10
num = num // 10
print("Sum of digits:", sum_digits)
```
**Output:**
```
Sum of digits: 10
```

---

## **17. Check Armstrong Number**


```python
num = 153
temp = num
sum_cubes = 0
while temp > 0:
digit = temp % 10
sum_cubes += digit ** 3
temp = temp // 10
print("Armstrong" if num == sum_cubes else "Not Armstrong")
```
**Output:**
```
Armstrong
```

---

## **18. Reverse a List**


```python
arr = [1, 2, 3, 4, 5]
print("Reversed list:", arr[::-1])
```
**Output:**
```
Reversed list: [5, 4, 3, 2, 1]
```

---

## **19. Find Duplicates in List**


```python
arr = [1, 2, 3, 2, 4, 5, 4]
duplicates = []
seen = set()
for num in arr:
if num in seen and num not in duplicates:
duplicates.append(num)
seen.add(num)
print("Duplicates:", duplicates)
```
**Output:**
```
Duplicates: [2, 4]
```

---

## **20. Linear Search**


```python
arr = [10, 20, 30, 40, 50]
target = 30
found = False
for i in range(len(arr)):
if arr[i] == target:
print("Found at index:", i)
found = True
break
if not found:
print("Not found")
```
**Output:**
```
Found at index: 2
```

---

### **Continue with more programs? (Next: Sorting, Matrix, File Handling, OOPs, etc.)**
Let me know if you want **more programs** in any specific category! 🚀

You might also like