π‘ Python: Converting Numbers to Human-Readable Words
Transforming numerical values into their word equivalents is crucial for various applications like financial reports, check writing, educational software, or enhancing accessibility. While complex to implement from scratch for all cases, Python's
Code explanation: This script uses the
#Python #TextProcessing #NumberToWords #num2words #DataManipulation
βββββββββββββββ
By: @DataScience4 β¨
Transforming numerical values into their word equivalents is crucial for various applications like financial reports, check writing, educational software, or enhancing accessibility. While complex to implement from scratch for all cases, Python's
num2words library provides a robust and easy solution. Install it with pip install num2words.from num2words import num2words
# Example 1: Basic integer
number1 = 123
words1 = num2words(number1)
print(f"'{number1}' in words: {words1}")
# Example 2: Larger integer
number2 = 543210
words2 = num2words(number2, lang='en') # Explicitly set language
print(f"'{number2}' in words: {words2}")
# Example 3: Decimal number
number3 = 100.75
words3 = num2words(number3)
print(f"'{number3}' in words: {words3}")
# Example 4: Negative number
number4 = -45
words4 = num2words(number4)
print(f"'{number4}' in words: {words4}")
# Example 5: Number for an ordinal form
number5 = 3
words5 = num2words(number5, to='ordinal')
print(f"Ordinal '{number5}' in words: {words5}")
Code explanation: This script uses the
num2words library to convert various integers, decimals, and negative numbers into their English word representations. It also demonstrates how to generate ordinal forms (third instead of three) and explicitly set the output language.#Python #TextProcessing #NumberToWords #num2words #DataManipulation
βββββββββββββββ
By: @DataScience4 β¨
π‘ Python Lists Cheatsheet: Essential Operations
This lesson provides a quick reference for common Python list operations. Lists are ordered, mutable collections of items, and mastering their use is fundamental for Python programming. This cheatsheet covers creation, access, modification, and utility methods.
Code explanation: This script demonstrates fundamental list operations in Python. It covers creating lists, accessing elements using indexing and slicing, modifying existing elements, adding new items with
#Python #Lists #DataStructures #Programming #Cheatsheet
βββββββββββββββ
By: @DataScience4β¨
This lesson provides a quick reference for common Python list operations. Lists are ordered, mutable collections of items, and mastering their use is fundamental for Python programming. This cheatsheet covers creation, access, modification, and utility methods.
# 1. List Creation
my_list = [1, "hello", 3.14, True]
empty_list = []
numbers = list(range(5)) # [0, 1, 2, 3, 4]
# 2. Accessing Elements (Indexing & Slicing)
first_element = my_list[0] # 1
last_element = my_list[-1] # True
sub_list = my_list[1:3] # ["hello", 3.14]
copy_all = my_list[:] # [1, "hello", 3.14, True]
# 3. Modifying Elements
my_list[1] = "world" # my_list is now [1, "world", 3.14, True]
# 4. Adding Elements
my_list.append(False) # [1, "world", 3.14, True, False]
my_list.insert(1, "new item") # [1, "new item", "world", 3.14, True, False]
another_list = [5, 6]
my_list.extend(another_list) # [1, "new item", "world", 3.14, True, False, 5, 6]
# 5. Removing Elements
removed_value = my_list.pop() # Removes and returns last item (6)
removed_at_index = my_list.pop(1) # Removes and returns "new item"
my_list.remove("world") # Removes the first occurrence of "world"
del my_list[0] # Deletes item at index 0 (1)
my_list.clear() # Removes all items, list becomes []
# Re-create for other examples
numbers = [3, 1, 4, 1, 5, 9, 2]
# 6. List Information
list_length = len(numbers) # 7
count_ones = numbers.count(1) # 2
index_of_five = numbers.index(5) # 4 (first occurrence)
is_present = 9 in numbers # True
is_not_present = 10 not in numbers # True
# 7. Sorting
numbers_sorted_asc = sorted(numbers) # Returns new list: [1, 1, 2, 3, 4, 5, 9]
numbers.sort(reverse=True) # Sorts in-place: [9, 5, 4, 3, 2, 1, 1]
# 8. Reversing
numbers.reverse() # Reverses in-place: [1, 1, 2, 3, 4, 5, 9]
# 9. Iteration
for item in numbers:
# print(item)
pass # Placeholder for loop body
# 10. List Comprehensions (Concise creation/transformation)
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
even_numbers = [x for x in numbers if x % 2 == 0] # [2, 4]
Code explanation: This script demonstrates fundamental list operations in Python. It covers creating lists, accessing elements using indexing and slicing, modifying existing elements, adding new items with
append(), insert(), and extend(), and removing items using pop(), remove(), del, and clear(). It also shows how to get list information like length (len()), item counts (count()), and indices (index()), check for item existence (in), sort (sort(), sorted()), reverse (reverse()), and iterate through lists. Finally, it illustrates list comprehensions for concise list generation and filtering.#Python #Lists #DataStructures #Programming #Cheatsheet
βββββββββββββββ
By: @DataScience4
Please open Telegram to view this post
VIEW IN TELEGRAM
β€2
β¨ activation function | AI Coding Glossary β¨
π A nonlinear mapping applied to neuron inputs that enables neural networks to learn complex relationships.
π·οΈ #Python
π A nonlinear mapping applied to neuron inputs that enables neural networks to learn complex relationships.
π·οΈ #Python
π₯1
β¨ recurrent neural network (RNN) | AI Coding Glossary β¨
π A neural network that processes sequences by applying the same computation at each step.
π·οΈ #Python
π A neural network that processes sequences by applying the same computation at each step.
π·οΈ #Python
π₯1
Forwarded from Machine Learning with Python
This channels is for Programmers, Coders, Software Engineers.
0οΈβ£ Python
1οΈβ£ Data Science
2οΈβ£ Machine Learning
3οΈβ£ Data Visualization
4οΈβ£ Artificial Intelligence
5οΈβ£ Data Analysis
6οΈβ£ Statistics
7οΈβ£ Deep Learning
8οΈβ£ programming Languages
β
https://t.me/addlist/8_rRW2scgfRhOTc0
β
https://t.me/Codeprogrammer
Please open Telegram to view this post
VIEW IN TELEGRAM
β¨ prompt injection | AI Coding Glossary β¨
π An attack where adversarial text is crafted to steer a model or model-integrated app into ignoring its original instructions and performing unintended actions.
π·οΈ #Python
π An attack where adversarial text is crafted to steer a model or model-integrated app into ignoring its original instructions and performing unintended actions.
π·οΈ #Python
β¨ retrieval-augmented generation (RAG) | AI Coding Glossary β¨
π A technique that improves a modelβs outputs by retrieving relevant external documents at query time and feeding them into the model.
π·οΈ #Python
π A technique that improves a modelβs outputs by retrieving relevant external documents at query time and feeding them into the model.
π·οΈ #Python
β¨ Logging in Python β¨
π If you use Python's print() function to get information about the flow of your programs, logging is the natural next step. Create your first logs and curate them to grow with your projects.
π·οΈ #intermediate #best-practices #tools
π If you use Python's print() function to get information about the flow of your programs, logging is the natural next step. Create your first logs and curate them to grow with your projects.
π·οΈ #intermediate #best-practices #tools
Forwarded from Kaggle Data Hub
Is Your Crypto Transfer Secure?
Score Your Transfer analyzes wallet activity, flags risky transactions in real time, and generates downloadable compliance reportsβno technical skills needed. Protect funds & stay compliant.
Sponsored By WaybienAds
Score Your Transfer analyzes wallet activity, flags risky transactions in real time, and generates downloadable compliance reportsβno technical skills needed. Protect funds & stay compliant.
Sponsored By WaybienAds
π‘ Python Tips Part 1
A collection of essential Python tricks to make your code more efficient, readable, and "Pythonic." This part covers list comprehensions, f-strings, tuple unpacking, and using
β’ List Comprehensions: A concise and often faster way to create lists. The syntax is
β’ F-Strings: The modern, readable way to format strings. Simply prefix the string with
β’ Extended Unpacking: Use the asterisk
β’ Using
#Python #Programming #CodeTips #PythonTricks
βββββββββββββββ
By: @DataScience4 β¨
A collection of essential Python tricks to make your code more efficient, readable, and "Pythonic." This part covers list comprehensions, f-strings, tuple unpacking, and using
enumerate.# Create a list of squares from 0 to 9
squares = [x**2 for x in range(10)]
print(squares)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
β’ List Comprehensions: A concise and often faster way to create lists. The syntax is
[expression for item in iterable].name = "Alex"
score = 95.5
# Using an f-string for easy formatting
message = f"Congratulations {name}, you scored {score:.1f}!"
print(message)
# Output: Congratulations Alex, you scored 95.5!
β’ F-Strings: The modern, readable way to format strings. Simply prefix the string with
f and place variables or expressions directly inside curly braces {}.numbers = (1, 2, 3, 4, 5)
# Unpack the first, last, and middle elements
first, *middle, last = numbers
print(f"First: {first}") # 1
print(f"Middle: {middle}") # [2, 3, 4]
print(f"Last: {last}") # 5
β’ Extended Unpacking: Use the asterisk
* operator to capture multiple items from an iterable into a list during assignment. It's perfect for separating the "head" and "tail" from the rest.items = ['keyboard', 'mouse', 'monitor']
for index, item in enumerate(items):
print(f"Item #{index}: {item}")
# Output:
# Item #0: keyboard
# Item #1: mouse
# Item #2: monitor
β’ Using
enumerate: The Pythonic way to get both the index and the value of an item when looping. It's much cleaner than using range(len(items)).#Python #Programming #CodeTips #PythonTricks
βββββββββββββββ
By: @DataScience4 β¨
β€3
π‘ Python Tips Part 2
More essential Python tricks to improve your code. This part covers dictionary comprehensions, the
β’ Dictionary Comprehensions: A concise way to create dictionaries, similar to list comprehensions. The syntax is
β’ Using
β’ Ternary Operator: A shorthand for a simple
β’ Using Underscore
#Python #Programming #CodeTips #PythonTricks
βββββββββββββββ
By: @DataScience4 β¨
More essential Python tricks to improve your code. This part covers dictionary comprehensions, the
zip function, ternary operators, and using underscores for unused variables.# Create a dictionary of numbers and their squares
squared_dict = {x: x**2 for x in range(1, 6)}
print(squared_dict)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
β’ Dictionary Comprehensions: A concise way to create dictionaries, similar to list comprehensions. The syntax is
{key_expr: value_expr for item in iterable}.students = ["Alice", "Bob", "Charlie"]
scores = [88, 92, 79]
for student, score in zip(students, scores):
print(f"{student}: {score}")
# Output:
# Alice: 88
# Bob: 92
# Charlie: 79
β’ Using
zip: The zip function combines multiple iterables (like lists or tuples) into a single iterator of tuples. It's perfect for looping over related lists in parallel.age = 20
# Assign a value based on a condition in one line
status = "Adult" if age >= 18 else "Minor"
print(status)
# Output: Adult
β’ Ternary Operator: A shorthand for a simple
if-else statement, useful for conditional assignments. The syntax is value_if_true if condition else value_if_false.# Looping 3 times without needing the loop variable
for _ in range(3):
print("Hello, Python!")
# Unpacking, but only needing the last value
_, _, last_item = (10, 20, 30)
print(last_item) # 30
β’ Using Underscore
_: By convention, the underscore _ is used as a variable name when you need a placeholder but don't intend to use its value. This signals to other developers that the variable is intentionally ignored.#Python #Programming #CodeTips #PythonTricks
βββββββββββββββ
By: @DataScience4 β¨
β€1
π‘ Python Tips Part 3
Advancing your Python skills with more powerful techniques. This part covers safe dictionary access with
β’ Dictionary
β’
β’ The
#Python #Programming #CodeTips #PythonTricks
βββββββββββββββ
By: @DataScience4 β¨
Advancing your Python skills with more powerful techniques. This part covers safe dictionary access with
.get(), flexible function arguments with *args and **kwargs, and context managers using the with statement.user_data = {"name": "Alice", "age": 30}
# Safely get a key that exists
name = user_data.get("name")
# Safely get a key that doesn't exist by providing a default
city = user_data.get("city", "Not Specified")
print(f"Name: {name}, City: {city}")
# Output: Name: Alice, City: Not Specifiedβ’ Dictionary
.get() Method: Access dictionary keys safely. .get(key, default) returns the value for a key if it exists, otherwise it returns the default value (which is None if not specified) without raising a KeyError.def dynamic_function(*args, **kwargs):
print("Positional args (tuple):", args)
print("Keyword args (dict):", kwargs)
dynamic_function(1, 'go', True, user="admin", status="active")
# Output:
# Positional args (tuple): (1, 'go', True)
# Keyword args (dict): {'user': 'admin', 'status': 'active'}
β’
*args and **kwargs: Use these in function definitions to accept a variable number of arguments. *args collects positional arguments into a tuple, and **kwargs collects keyword arguments into a dictionary.# The 'with' statement ensures the file is closed automatically
try:
with open("notes.txt", "w") as f:
f.write("Context managers are great!")
# No need to call f.close()
print("File written and closed.")
except Exception as e:
print(f"An error occurred: {e}")
β’ The
with Statement: The with statement creates a context manager, which is the standard way to handle resources like files or network connections. It guarantees that cleanup code is executed, even if errors occur inside the block.#Python #Programming #CodeTips #PythonTricks
βββββββββββββββ
By: @DataScience4 β¨
π‘ Python Tips Part 4
Level up your Python code with more advanced tips. This part covers chaining comparisons, using sets for uniqueness, and powerful tools from the
β’ Chaining Comparisons: Python allows you to chain comparison operators for more readable and concise range checks. This is equivalent to
β’ Sets for Uniqueness: Sets are unordered collections of unique elements. Converting a list to a set and back is the fastest and most Pythonic way to remove duplicates.
β’
β’
#Python #Programming #CodeTips #DataStructures
βββββββββββββββ
By: @DataScience4 β¨
Level up your Python code with more advanced tips. This part covers chaining comparisons, using sets for uniqueness, and powerful tools from the
collections module like Counter and defaultdict.x = 10
# Check if x is between 5 and 15 in a clean way
if 5 < x < 15:
print("x is in range.")
# Output: x is in range.
β’ Chaining Comparisons: Python allows you to chain comparison operators for more readable and concise range checks. This is equivalent to
(5 < x) and (x < 15).numbers = [1, 2, 2, 3, 4, 4, 4, 5]
# Use a set to quickly get unique elements
unique_numbers = list(set(numbers))
print(unique_numbers)
# Output: [1, 2, 3, 4, 5]
β’ Sets for Uniqueness: Sets are unordered collections of unique elements. Converting a list to a set and back is the fastest and most Pythonic way to remove duplicates.
from collections import Counter
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_counts = Counter(words)
print(word_counts)
# Output: Counter({'apple': 3, 'banana': 2, 'orange': 1})
print(word_counts.most_common(1))
# Output: [('apple', 3)]
β’
collections.Counter: A specialized dictionary subclass for counting hashable objects. It simplifies frequency counting tasks and provides useful methods like .most_common().from collections import defaultdict
data = [('fruit', 'apple'), ('fruit', 'banana'), ('veg', 'carrot')]
grouped_data = defaultdict(list)
for category, item in data:
grouped_data[category].append(item)
print(grouped_data)
# Output: defaultdict(<class 'list'>, {'fruit': ['apple', 'banana'], 'veg': ['carrot']})
β’
collections.defaultdict: A dictionary that provides a default value for a non-existent key, avoiding KeyError. It's perfect for grouping items into lists or dictionaries without extra checks.#Python #Programming #CodeTips #DataStructures
βββββββββββββββ
By: @DataScience4 β¨
β€1
π‘ Python
This guide covers Python's boolean values,
β’ Comparison Operators: Operators like
β’ Logical
β’ Logical
β’ Logical
β’ Truthiness: In a boolean context (like an
β’ Falsiness: Only a few specific values are
β’ Internally,
β’ This allows you to use them in mathematical calculations, a common feature in coding challenges.
#Python #Boolean #Programming #TrueFalse #CodingTips
βββββββββββββββ
By: @DataScience4 β¨
True & False: A Mini-GuideThis guide covers Python's boolean values,
True and False. We'll explore how they result from comparisons, are used with logical operators, and how other data types can be evaluated as "truthy" or "falsy".x = 10
y = 5
print(x > y)
print(x == 10)
print(y != 5)
# Output:
# True
# True
# False
β’ Comparison Operators: Operators like
>, ==, and != evaluate expressions and always return a boolean value: True or False.is_sunny = True
is_warm = False
print(is_sunny and is_warm)
print(is_sunny or is_warm)
print(not is_warm)
# Output:
# False
# True
# True
β’ Logical
and: Returns True only if both operands are true.β’ Logical
or: Returns True if at least one operand is true.β’ Logical
not: Inverts the boolean value (True becomes False, and vice-versa).# "Falsy" values evaluate to False
print(bool(0))
print(bool(""))
print(bool([]))
print(bool(None))
# "Truthy" values evaluate to True
print(bool(42))
print(bool("hello"))
# Output:
# False
# False
# False
# False
# True
# True
β’ Truthiness: In a boolean context (like an
if statement), many values are considered True ("truthy").β’ Falsiness: Only a few specific values are
False ("falsy"): 0, None, and any empty collection (e.g., "", [], {}).# Booleans can be treated as integers
sum_result = True + True + False
print(sum_result)
product = True * 15
print(product)
# Output:
# 2
# 15
β’ Internally,
True is equivalent to the integer 1 and False is equivalent to 0.β’ This allows you to use them in mathematical calculations, a common feature in coding challenges.
#Python #Boolean #Programming #TrueFalse #CodingTips
βββββββββββββββ
By: @DataScience4 β¨
β¨ tagging | AI Coding Glossary β¨
π The process of assigning one or more discrete labels to data items so that models and tools can learn from them.
π·οΈ #Python
π The process of assigning one or more discrete labels to data items so that models and tools can learn from them.
π·οΈ #Python
β¨ guardrails | AI Coding Glossary β¨
π Application-level policies and controls that constrain how a model or agent behaves.
π·οΈ #Python
π Application-level policies and controls that constrain how a model or agent behaves.
π·οΈ #Python
This media is not supported in your browser
VIEW IN TELEGRAM
Python: How to easily upload a file via SSH
Want to upload a file to a remote server via SSH directly from a Python script? It's easy to do with the paramiko library - it provides a clean and reliable implementation of the SSH protocol.
Just install paramiko (
Make sure the user has write permissions to the target directory on the server. Subscribe for more tips every day!
https://t.me/DataScience4
Want to upload a file to a remote server via SSH directly from a Python script? It's easy to do with the paramiko library - it provides a clean and reliable implementation of the SSH protocol.
Just install paramiko (
pip install paramiko), specify the connection details, and use an SFTP session to send the file.Make sure the user has write permissions to the target directory on the server. Subscribe for more tips every day!
import paramiko
Connection settings
hostname = "your-server.com"
port = 22
username = "your_username"
password = "your_password" # or use a key instead of a password
Local and remote paths
local_file = "local_file.txt"
remote_file = "/remote/path/local_file.txt"
Create SSH client
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname, port=port, username=username, password=password)
# Open SFTP session and upload the file
sftp = ssh.open_sftp()
sftp.put(local_file, remote_file)
sftp.close()
print("File uploaded successfully!")
except Exception as e:
print(f"Error: {e}")
finally:
()
https://t.me/DataScience4
β€2
π‘ Python Exam Cheatsheet
A quick review of core Python concepts frequently found in technical assessments and exams. This guide covers list comprehensions, dictionary methods,
β’ List Comprehension: A concise, one-line syntax for creating lists.
β’ The structure is
β’ The
β’ Dictionary
β’ The first argument is the key to look up.
β’ The optional second argument is the default value to return if the key does not exist.
β’ Using
β’ It returns a tuple
β’
β’
β’ This pattern allows a function to accept a variable number of arguments.
#Python #PythonExam #Programming #CodeCheatsheet #LearnPython
βββββββββββββββ
By: @DataScience4 β¨
A quick review of core Python concepts frequently found in technical assessments and exams. This guide covers list comprehensions, dictionary methods,
enumerate, and flexible function arguments.# Create a list of squares for even numbers from 0 to 9
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)
# Output:
# [0, 4, 16, 36, 64]
β’ List Comprehension: A concise, one-line syntax for creating lists.
β’ The structure is
[expression for item in iterable if condition].β’ The
if condition part is optional and acts as a filter.student_scores = {'Alice': 95, 'Bob': 87}
# Safely get a score, providing a default value if the key is missing
charlie_score = student_scores.get('Charlie', 'Not Found')
alice_score = student_scores.get('Alice', 'Not Found')
print(f"Alice: {alice_score}")
print(f"Charlie: {charlie_score}")
# Output:
# Alice: 95
# Charlie: Not Foundβ’ Dictionary
.get() Method: Safely access a dictionary key without causing a KeyError.β’ The first argument is the key to look up.
β’ The optional second argument is the default value to return if the key does not exist.
colors = ['red', 'green', 'blue']
for index, value in enumerate(colors):
print(f"Index: {index}, Value: {value}")
# Output:
# Index: 0, Value: red
# Index: 1, Value: green
# Index: 2, Value: blue
β’ Using
enumerate: The Pythonic way to loop over an iterable when you need both the index and the value.β’ It returns a tuple
(index, value) for each item in the sequence.def process_data(*args, **kwargs):
print(f"Positional args (tuple): {args}")
print(f"Keyword args (dict): {kwargs}")
process_data(1, 'hello', 3.14, user='admin', status='active')
# Output:
# Positional args (tuple): (1, 'hello', 3.14)
# Keyword args (dict): {'user': 'admin', 'status': 'active'}
β’
*args: Collects all extra positional arguments into a tuple.β’
**kwargs: Collects all extra keyword arguments into a dictionary.β’ This pattern allows a function to accept a variable number of arguments.
#Python #PythonExam #Programming #CodeCheatsheet #LearnPython
βββββββββββββββ
By: @DataScience4 β¨
Clean Code Tip:
The
Example:
βββββββββββββββ
By: @DataScience4 β¨
The
with statement simplifies resource management, like file handling. It ensures resources are automatically closed, even if errors occur. This prevents bugs and makes your code safer and cleaner than manual try...finally blocks. It's a must-know for any Python developer! πExample:
# The old, verbose way to ensure a file is closed
print("--- Old Way ---")
file = open('greeting.txt', 'w')
try:
file.write('Hello, world!')
finally:
# This block always runs to ensure the file is closed
print("File is being closed in 'finally' block.")
file.close()
# The clean, safe, and Pythonic way using 'with'
print("\n--- Clean Way ---")
with open('greeting.txt', 'w') as file:
file.write('Hello, Python!')
print("Inside 'with' block. File is still open here.")
# The file is now automatically and safely closed.
print("Outside 'with' block. File is guaranteed to be closed.")
βββββββββββββββ
By: @DataScience4 β¨
β€1
Clean Code Tip:
When you need both the index and the item while looping, avoid manual index counters. Use Python's built-in
Example:
βββββββββββββββ
By: @DataScience4 β¨
When you need both the index and the item while looping, avoid manual index counters. Use Python's built-in
enumerate() function for cleaner, more readable, and less error-prone code. It's the Pythonic way to count! π’Example:
# The old, manual way to track an index
print("--- Old Way ---")
fruits = ['apple', 'banana', 'cherry']
index = 0
for fruit in fruits:
print(f"Index: {index}, Fruit: {fruit}")
index += 1
# The clean and Pythonic way using enumerate()
print("\n--- Clean Way ---")
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
# You can even start counting from a different number!
print("\n--- Starting from 1 ---")
for position, fruit in enumerate(fruits, start=1):
print(f"Position: {position}, Fruit: {fruit}")
βββββββββββββββ
By: @DataScience4 β¨