AI Forever
3 subscribers
1 link
๐ŸŒฑ Beginner โ†’ ๏ฟฝ Intermediate โ†’ ๐Ÿš€ Advanced โ†’ ๐Ÿ† Mastery
Download Telegram
๐Ÿ Python Problem 0ne

Problem: Square every digit of a number and concatenate them.
Example:
- 9119 โ†’ 811181 (since 9ยฒ=81, 1ยฒ=1, 1ยฒ=1, 9ยฒ=81 โ†’ "81"+"1"+"1"+"81")
- 765 โ†’ 493625 (49-36-25)

---

My Solution:
def square_every_digit(num):
num_str = str(num)
result = ""
for digit in num_str:
squared = int(digit) ** 2
result += str(squared)
return int(result)


AI's Solution (via ChatGPT):
def square_every_digit(num):
squared_digits = ''.join(str(int(digit) ** 2) for digit in str(num))
return int(squared_digits)


---

๐Ÿ’ก Key Takeaway:
The AI uses join() with a generator expression to simplify the loop, making the code shorter and more "Pythonic". Both methods work, but join() is cleaner for string concatenation!

๐Ÿ”— Sources: Codewars, ChatGPT

๐Ÿ‘‰ Try it yourself!
How would YOU approach this problem?

#Python #Codewars #Coding #LearnPython
๐Ÿš€ Problem 2

Problem: Determine if a string is an isogram (no repeating letters, case-insensitive).
Examples:
- "Dermatoglyphics" โ†’ True
- "moOse" โ†’ False (duplicate 'o' when lowercased)
- Empty string โ†’ True

๐Ÿง‘๐Ÿ’ป My Approach:
def is_isogram(string):
string = string.lower()
for i in string:
if string.count(i) > 1:
return False
return True

โœ… Works butโ€ฆ
- Checks each character's count, leading to O(nยฒ) time complexity.
- Early exit if duplicates found, but inefficient for large strings.

๐Ÿค– AI's Optimized Approach:
def is_isogram(string):
lowered = string.lower()
return len(set(lowered)) == len(lowered)

๐Ÿ”ฅ Why Better?
1. O(n) Time: Converts string to a set (auto-removes duplicates).
2. Concise: One-liner using Python's built-in functions.
3. Readable: Leverages set properties for uniqueness check.

๐Ÿ’ก Key Takeaways:
- Use Sets for Uniqueness: Perfect for checking duplicates.
- Case Handling: Always lowercase the string first.
- Edge Cases: Empty string is handled gracefully.

๐Ÿ” Compare Efficiency:
| Method | Time Complexity | Lines of Code |
|--------------|-----------------|---------------|
| Loop & Count | O(nยฒ) | 5 |
| Set & Length | O(n) | 1 |

*Credits: Codewars problem + ChatGPT optimization.*

Try both methods and share your thoughts! ๐Ÿ‘‡

#Python #CodingTips #Algorithms #Programming
๐Ÿ”ท Problem 3: A Square of Squares ๐Ÿ”ท

๐Ÿ‘ท You love building blocksโ€”especially square ones! But can you tell if the total number of blocks you have can form a perfect square?

๐ŸŽฏ Task:
Given an integer n, determine whether it's a *perfect square* (i.e., the square of an integer).

๐Ÿง  Examples:
-1 => False  
0 => True
3 => False
4 => True
25 => True
26 => False


---

๐Ÿงช My Initial Solution (Not Efficient for Large Numbers)

def is_square(n): 
def find_factors(n):
factors = []
for i in range(1, n + 1):
if n % i == 0:
factors.append(i)
return factors
factors = find_factors(n)

for i in factors:
if i * i == n:
return True
if n == 0:
return True
return False


โš ๏ธ *Why this fails on Codewars:*
While logically correct, itโ€™s too slow for large values of n, because it checks all factors up to n.

---

โšก๏ธ AI/Optimal Solution (Codewars Accepted โœ…)

import math

def is_square(n):
if n < 0:
return False
sqrt_n = math.isqrt(n) # Efficient integer square root
return sqrt_n * sqrt_n == n


๐Ÿ“Œ Key Notes:
- math.isqrt(n) returns the integer square root efficiently (no floating point issues).
- Checking sqrt_n * sqrt_n == n is both fast and accurate.
- Negative numbers can't be perfect squares, so return False early.

โœ… Best Practice: Use mathematical functions when available. They are optimized and make your code cleaner and faster.

---

๐Ÿ’ก *Follow for more real-world coding challenges and clean solutions!*

#Python #Codewars #Math #PerfectSquare #LearnToCode #ProgrammingTips
๐Ÿ“˜ Day 3: Basic Arithmetic & Input/Output in Python
Letโ€™s build the foundation of your programming skills with math operations and user input handling!

---

๐Ÿ”ข Basic Arithmetic Operations

print(5 + 3)    # Addition โ†’ 8
print(10 - 4) # Subtraction โ†’ 6
print(7 * 2) # Multiplication โ†’ 14
print(15 / 3) # Division โ†’ 5.0
print(15 // 2) # Floor Division โ†’ 7
print(15 % 4) # Modulus โ†’ 3
print(2 ** 3) # Exponentiation โ†’ 8


---

๐Ÿงฎ Order of Operations (PEMDAS)

print(2 + 3 * 4)      # Output: 14
print((2 + 3) * 4) # Output: 20


---

๐Ÿ—ฃ User Input and Output

name = input("What is your name? ")
print("Hello, " + name + "!")


---

### ๐Ÿ” Convert Input to Numbers

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Sum:", num1 + num2)


---

โœ… Practice Problems

1๏ธโƒฃ Area of a Rectangle
length = float(input("Enter length: "))
width = float(input("Enter width: "))
area = length * width
print("Area:", area)


2๏ธโƒฃ Square of a Number
num = int(input("Enter a number: "))
print("Square:", num ** 2)


3๏ธโƒฃ Basic Arithmetic Calculator
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

print("Addition:", num1 + num2)
print("Subtraction:", num1 - num2)
print("Multiplication:", num1 * num2)
print("Division:", num1 / num2)


---

๐ŸŽฏ Goal for Day 3
โœ… Use Pythonโ€™s arithmetic operators confidently
โœ… Understand input/output with input() and print()
โœ… Practice writing small interactive programs

โ€”

๐Ÿ‘จโ€๐Ÿ’ป Keep coding! Day 4 coming soon...
#Python #Day3 #LearnToCode #ProgrammingBasics #BeginnerFriendly
๐Ÿšถโ€โ™‚๏ธ Problem 4: Cartesia City Walk

You live in the city of Cartesia, where roads form a perfect grid.
Your walk app gives you directions like ['n', 's', 'w', 'e'], each taking 1 minute and 1 block.

๐Ÿ•™ Youโ€™ve got 10 minutes and must return exactly to where you started.
โœ… Return True if the walk takes 10 minutes and ends at the starting point.
โŒ Otherwise, return False.

---

๐Ÿง  Your Idea (Step-by-Step Position Tracking)

def is_valid_walk(walk):
if len(walk) != 10:
return False
x, y = 0, 0
for drn in walk:
if drn == 'n':
y += 1
elif drn == 's':
y -= 1
elif drn == 'e':
x += 1
elif drn == 'w':
x -= 1
return x == 0 and y == 0


๐Ÿ”Ž Why it works:
You simulate the entire walk and check if youโ€™ve come back to the original (0,0) point.

---

โšก๏ธ AIโ€™s Optimized Version (Count Matching)

def is_valid_walk(walk):
if len(walk) != 10:
return False
return walk.count('n') == walk.count('s') and walk.count('e') == walk.count('w')


โš ๏ธ Key Note:
This version does not simulate movement. It cleverly checks balance:
- 'n' must equal 's'
- 'e' must equal 'w'
If thatโ€™s true and the walk is 10 steps long โ†’ โœ… you're back on time and at the start.

---

๐Ÿงช Example Tests

print(is_valid_walk(['n','s','n','s','n','s','n','s','n','s']))  # โœ… True
print(is_valid_walk(['w','e','w','e','w','e','w','e','w','e'])) # โœ… True
print(is_valid_walk(['n','n','n','s','s','s','e','w','e','w'])) # โœ… True
print(is_valid_walk(['n','n','n','s'])) # โŒ False


---

โœ… Key Learning:
- Use coordinate tracking for clarity and understanding
- Use frequency counting for efficiency and elegance
- Always validate input length before logic

โ€”

๐Ÿ‘จโ€๐Ÿ’ป Keep walking (and coding)!
#Python #Codewars #GridWalk #LearnToCode #DailyChallenge