-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPython_Playground.py
More file actions
305 lines (254 loc) · 10.1 KB
/
Python_Playground.py
File metadata and controls
305 lines (254 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""
Python Playground - Simple and Famous Programs
@author: Santosh Goteti
This module contains various Python programs covering different skills
and concepts. Includes basic programs, mathematical operations, string
manipulation, and interactive programs.
"""
# ============================================================================
# 1. FIBONACCI SERIES
# ============================================================================
def fibonacci_series(n):
"""Generate Fibonacci series up to n terms"""
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
return fib
n = 10
print("1. Fibonacci series:")
print(fibonacci_series(n))
# ============================================================================
# 2. FACTORIAL
# ============================================================================
def factorial(num):
"""Calculate factorial of a number recursively"""
if num == 0 or num == 1:
return 1
else:
return num * factorial(num - 1)
print("\n2. Factorial of 5:", factorial(5))
# ============================================================================
# 3. PRIME NUMBER CHECK
# ============================================================================
def is_prime(num):
"""Check if a number is prime"""
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
print("\n3. Prime numbers between 1 and 20:")
primes = [x for x in range(1, 21) if is_prime(x)]
print(primes)
# ============================================================================
# 4. PALINDROME CHECK
# ============================================================================
def is_palindrome(s):
"""Check if a string is a palindrome"""
s = s.replace(" ", "").lower()
return s == s[::-1]
print("\n4. Palindrome Check:")
print("'racecar' is palindrome:", is_palindrome("racecar"))
print("'hello' is palindrome:", is_palindrome("hello"))
# ============================================================================
# 5. ARMSTRONG NUMBER
# ============================================================================
def is_armstrong(num):
"""Check if a number is an Armstrong number"""
digits = len(str(num))
sum_of_powers = sum(int(digit)**digits for digit in str(num))
return sum_of_powers == num
print("\n5. Armstrong Numbers between 1 and 1000:")
armstrong_nums = [x for x in range(1, 1001) if is_armstrong(x)]
print(armstrong_nums)
# ============================================================================
# 6. REVERSE A STRING
# ============================================================================
def reverse_string(s):
"""Reverse a string"""
return s[::-1]
print("\n6. Reverse String:")
print("'Python' reversed:", reverse_string("Python"))
# ============================================================================
# 7. SUM OF DIGITS
# ============================================================================
def sum_of_digits(num):
"""Calculate sum of all digits in a number"""
return sum(int(digit) for digit in str(abs(num)))
print("\n7. Sum of digits in 12345:", sum_of_digits(12345))
# ============================================================================
# 8. GREATEST COMMON DIVISOR (GCD)
# ============================================================================
def gcd(a, b):
"""Find GCD using Euclidean algorithm"""
while b:
a, b = b, a % b
return a
print("\n8. GCD of 48 and 18:", gcd(48, 18))
# ============================================================================
# 9. LEAST COMMON MULTIPLE (LCM)
# ============================================================================
def lcm(a, b):
"""Calculate LCM of two numbers"""
return (a * b) // gcd(a, b)
print("\n9. LCM of 12 and 18:", lcm(12, 18))
# ============================================================================
# 10. BUBBLE SORT
# ============================================================================
def bubble_sort(arr):
"""Sort array using bubble sort algorithm"""
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("\n10. Bubble Sort:")
print(bubble_sort([64, 34, 25, 12, 22, 11, 90]))
# ============================================================================
# 11. BINARY SEARCH
# ============================================================================
def binary_search(arr, target):
"""Find target in sorted array using binary search"""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
print("\n11. Binary Search (find 25 in [11, 12, 22, 25, 34, 64, 90]):")
print("Index:", binary_search([11, 12, 22, 25, 34, 64, 90], 25))
# ============================================================================
# 12. INTERACTIVE: CALCULATOR
# ============================================================================
def interactive_calculator():
"""Simple interactive calculator"""
print("\n12. INTERACTIVE CALCULATOR")
print("Operations: +, -, *, /, %")
try:
num1 = float(input("Enter first number: "))
op = input("Enter operation: ")
num2 = float(input("Enter second number: "))
if op == '+':
print(f"Result: {num1 + num2}")
elif op == '-':
print(f"Result: {num1 - num2}")
elif op == '*':
print(f"Result: {num1 * num2}")
elif op == '/':
print(f"Result: {num1 / num2}" if num2 != 0 else "Error: Division by zero")
elif op == '%':
print(f"Result: {num1 % num2}" if num2 != 0 else "Error: Modulo by zero")
else:
print("Invalid operation")
except ValueError:
print("Invalid input")
# Uncomment to run interactive calculator
# interactive_calculator()
# ============================================================================
# 13. INTERACTIVE: NUMBER GUESSING GAME
# ============================================================================
def guessing_game():
"""Interactive number guessing game"""
import random
print("\n13. INTERACTIVE NUMBER GUESSING GAME")
secret = random.randint(1, 100)
attempts = 0
while True:
try:
guess = int(input("Guess a number between 1 and 100: "))
attempts += 1
if guess < secret:
print("Too low, try again!")
elif guess > secret:
print("Too high, try again!")
else:
print(f"Correct! You guessed in {attempts} attempts.")
break
except ValueError:
print("Please enter a valid number")
# Uncomment to run guessing game
# guessing_game()
# ============================================================================
# 14. FACTORIAL USING ITERATION
# ============================================================================
def factorial_iterative(num):
"""Calculate factorial using iteration"""
result = 1
for i in range(2, num + 1):
result *= i
return result
print("\n14. Factorial of 6 (iterative):", factorial_iterative(6))
# ============================================================================
# 15. POWER FUNCTION
# ============================================================================
def power(base, exp):
"""Calculate base raised to exponent"""
if exp == 0:
return 1
result = 1
for _ in range(exp):
result *= base
return result
print("\n15. 2 raised to power 8:", power(2, 8))
# ============================================================================
# 16. MULTIPLICATION TABLE
# ============================================================================
def multiplication_table(num):
"""Generate multiplication table for a number"""
table = [f"{num} x {i} = {num * i}" for i in range(1, 11)]
return table
print("\n16. Multiplication table of 5:")
for line in multiplication_table(5):
print(line)
# ============================================================================
# 17. VOWEL COUNTER
# ============================================================================
def count_vowels(s):
"""Count vowels in a string"""
vowels = "aeiouAEIOU"
return sum(1 for char in s if char in vowels)
print("\n17. Vowels in 'Python Programming':", count_vowels("Python Programming"))
# ============================================================================
# 18. DUPLICATE REMOVER
# ============================================================================
def remove_duplicates(lst):
"""Remove duplicates from list maintaining order"""
seen = set()
result = []
for item in lst:
if item not in seen:
seen.add(item)
result.append(item)
return result
print("\n18. Remove duplicates from [1,2,2,3,3,4,5,5]:")
print(remove_duplicates([1, 2, 2, 3, 3, 4, 5, 5]))
# ============================================================================
# 19. LIST FLATTENER
# ============================================================================
def flatten_list(lst):
"""Flatten a nested list"""
result = []
for item in lst:
if isinstance(item, list):
result.extend(flatten_list(item))
else:
result.append(item)
return result
print("\n19. Flatten [[1,2],[3,[4,5]],6]:")
print(flatten_list([[1, 2], [3, [4, 5]], 6]))
# ============================================================================
# 20. ANAGRAM CHECK
# ============================================================================
def is_anagram(s1, s2):
"""Check if two strings are anagrams"""
s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()
return sorted(s1) == sorted(s2)
print("\n20. Anagram Check:")
print("'listen' and 'silent' are anagrams:", is_anagram("listen", "silent"))