Posts

Showing posts from April, 2023

Python String isascii() Method

The isascii() method is a string method that returns True if all the characters in the string are ASCII characters (a-z). ASCII stands for American Standard Code for Information Interchange. It is a character encoding standard that uses numbers from 0 to 127 to represent English characters and some symbols. For example: name = "Alice" print(name.isascii()) # prints True The method returns False if the string contains any non-ASCII characters, such as accented letters, emojis, etc. For example: name = "Alïce" print(name.isascii()) # prints False If you have any questions about this code, you can drop a line in comment .  

Python filter() Built in Function

The filter() function in Python is used to filter out elements from an iterable (such as a list, tuple, or string) that satisfy a given condition. The filter() function takes two arguments: a function that returns True or False for each element, and an iterable to apply the function to. The filter() function returns a new iterable with only the elements that return True for the function. Here are some examples of using filter() in Python: Filter a list of numbers to only include even numbers: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) Output: [2, 4, 6, 8, 10] In this example, we use filter() to create a new list called even_numbers that only includes the even numbers from the original list numbers. The lambda function inside the filter() function takes a single argument x and returns True if x is even (x % 2 == 0), and False otherwise. The list() function is used to convert the resulting filter object...

Python Flight Price Prediction

Flight price prediction is a challenging task that involves analyzing various factors that affect the ticket prices, such as date, time, destination, airline, seasonality, demand and supply. You can use Python to build a machine learning model that predicts the flight prices based on historical data and features. Here are some examples of flight price prediction using Python: Using Kaggle dataset of flight booking data obtained from “Ease My Trip” website to perform exploratory data analysis and build a regression model using scikit-learn library. # Import libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression # Read the dataset data = pd.read_csv("flight_price_prediction.csv") # Explore the dataset data.head() # Plot a boxplot of price vs airline sns.boxplot(x="Airline", y="Price", data=data) plt.xticks(rotation=90) plt.show() # Train a linear regression m...

Python String isalnum() Method

The isalnum() method is a string method that returns True if all the characters in the string are alphanumeric, meaning letters (a-z) and numbers (0-9). For example: name = "Alice123" print(name.isalnum()) # prints True The method returns False if the string contains any non-alphanumeric characters, such as spaces, punctuation marks, symbols, etc. For example: name = "Alice 123" print(name.isalnum()) # prints False If you have any questions about this code, you can drop a line in comment .

Python String index() Method

The index() method is a list method that returns the position of the first occurrence of a given element in the list. For example: fruits = ["apple", "banana", "cherry", "orange"] print(fruits.index("cherry")) # prints 2 You can also specify a start and end index to limit the search range. For example: numbers = [1, 2, 3, 4, 5, 6, 7, 8] print(numbers.index(5, 3)) # prints 4 print(numbers.index(5, 3, 6)) # prints 4 If the element is not found in the list, a ValueError exception is raised. For example: animals = ["cat", "dog", "bird", "fish"] print(animals.index("lion")) # raises ValueError: 'lion' is not in list If you have any questions about this code, you can drop a line in comment .

Python String format_map() Method

The format_map() method is a string method that allows you to insert variables from a dictionary into a string with placeholders. For example: person = {"name": "Alice", "age": 25} print("My name is {name} and I am {age} years old.".format_map(person)) # prints My name is Alice and I am 25 years old. You can also use a subclass of dictionary that provides a default value for missing keys. For example: class Default(dict):     def __missing__(self, key):         return key person = Default(name="Bob") print("Hello, {name}. You are {age} years old.".format_map(person)) # prints Hello, Bob. You are age years old. If you have any questions about this code, you can drop a line in comment .

Python String format() Method

The format() method is a string method that allows you to insert variables into a string with placeholders. For example: name = "Alice" age = 25 print("My name is {0} and I am {1} years old.".format(name, age)) # prints My name is Alice and I am 25 years old. You can also use named arguments instead of positional arguments. For example: name = "Bob" age = 30 print("My name is {name} and I am {age} years old.".format(name=name, age=age)) # prints My name is Bob and I am 30 years old. If you have any questions about this code, you can drop a line in comment .

Python String find() Method

The find() method is a string method that returns the lowest index of a substring within a string if it is found. If not, it returns -1. For example: s = "Hello world" print(s.find("world")) # prints 6 print(s.find("Python")) # prints -1 You can also specify the start and end positions to search within a slice of the string. For example: s = "Hello world" print(s.find("o", 5)) # prints 7 print(s.find("o", 5, 8)) # prints -1 If you have any questions about this code, you can drop a line in comment .  

Python String expandtabs() Method

The Python expandtabs() method is a string method that returns a string with all tab characters \t replaced with one or more spaces, depending on the number of characters before \t and the specified tab size. The default tab size is 8. The method does not modify the original string, but returns a new string. Here are some examples of using the expandtabs() method in Python: To replace tab characters with 8 spaces by default: txt = "Hello\tWorld" x = txt.expandtabs() print(x) Output: Hello   World To replace tab characters with 2 spaces by specifying the tab size: txt = "H\tello\tWorld" x = txt.expandtabs(2) print(x) Output: H ello World To replace tab characters with different numbers of spaces depending on the cursor position: str = 'xyz\t12345\tabc' result = str.expandtabs(4) print(result) Output: xyz 12345   abc To replace multiple tab characters with spaces:  str = 'x\ty\tz' result = str.expandtabs(10) print(result) Output: x     ...

Python String endswith() Method

The Python endswith() method is a string method that returns True if the string ends with the specified suffix, otherwise False. The method can also take optional parameters to specify the start and end positions of the range to check within the string. Here are some examples of using the endswith() method in Python: To check if a string ends with a punctuation mark: txt = "Hello, welcome to my world." x = txt.endswith(".") print(x) Output: True To check if a string ends with a certain word: str = "Hello!Welcome to Tutorialspoint." suffix = "oint" x = str.endswith(suffix) print(x) Output: True To check if a string ends with a substring within a specified range: text = "Python is easy to learn." result = text.endswith('is', 0, 8) print(result) Output: True To check if a string ends with any of multiple suffixes: text = "geeks for geeks." suffixes = (".", "?", "!") result = text.endswi...

Python String encode() Method

The Python encode() method is a string method that returns an encoded version of the given string using a specified encoding. Encoding is the process of converting a string into a sequence of bytes that can be stored or transmitted. If no encoding is specified, UTF-8 will be used by default. Here are some examples of using the encode() method in Python: To encode a string using UTF-8 encoding: title = "Python Programming" x = title.encode() print(x) Output: b'Python Programming' To encode a string using ASCII encoding and ignore any errors:  str = "Hello World!" x = str.encode("ascii", "ignore") print(x) Output: b'Hello World!' To encode a string using base64 encoding: str = "Hello World!" x = str.encode("base64") print(x) Output: b'SGVsbG8gV29ybGQh\n' To encode a string containing non-ASCII characters using ISO 8859-1 encoding: str = "HËLLO" encode = str.encode("iso8859_1") pri...

Python String count() Method

In Python, count() is a method that can be used with both strings and lists. The string.count() function counts the number of occurrences of a substring within a string. The list.count() function counts the number of times an element appears in a list. Here are some examples of using the count() method in Python: To count the number of times a character appears in a string:   str = "Hello World" x = str.count("o") print(x) Output: 2 To count the number of times a substring appears in a string within a specified range: str = "Hello World" x = str.count("l", 3, 10) print(x) Output: 2 To count the number of times an element appears in a tuple: my_tuple = ("apple", "banana", "cherry", "banana") count = my_tuple.count("banana") print(count) Output: 2 To count the number of times an item appears in a list: my_list = ["a", "b", "a", "c", "a"] count...

Python pow() Built in Function

The pow() function is used to calculate the power of a number by raising the first argument to the second argument. The syntax of the pow() function is: pow(x, y, z) The x and y parameters are required and represent the base and the exponent respectively. The z parameter is optional and represents the modulus. If z is present, it returns x to the power of y, modulus z. Otherwise, it returns x to the power of y. Here are some examples of using the pow() function in Python: To calculate 4 to the power of 3 (same as 4 * 4 * 4): print(pow(4, 3)) # prints 64 To calculate 2 to the power of 10 (same as 2 * 2 * … * 2): print(pow(2, 10)) # prints 1024 To calculate 5 to the power of 2, modulus 7 (same as (5 * 5) % 7): print(pow(5, 2, 7)) # prints 4  If you have any questions about this code, you can drop a line in comment .

Python dict() Built in Function

The dict() function in Python is used to create a dictionary object. A dictionary is an unordered collection of key-value pairs, where each key is unique and associated with a value. The syntax of the dict() function is: dict(**kwarg) dict(mapping, **kwarg) dict(iterable, **kwarg) Here are a few examples of using the dict() function in Python: Create a dictionary from keyword arguments # create a dictionary from keyword arguments d = dict(name="Alice", age=25, city="New York") # print the dictionary print(d) The dict() function in Python is used to create a dictionary object. A dictionary is an unordered collection of key-value pairs, where each key is unique and associated with a value. The syntax of the dict() function is: dict(**kwarg) dict(mapping, **kwarg) dict(iterable, **kwarg) Here are a few examples of using the dict() function in Python: Example 1: Create a dictionary from keyword arguments # create a dictionary from keyword arguments d = dict(name=...

Python delattr() Built in Function

The delattr() function in Python is used to delete an attribute from an object. The syntax of the delattr() function is: delattr(object, attribute_name) Here are a few examples of using the delattr() function in Python: Example 1: Delete an attribute from an object class Person:     def __init__(self, name, age):         self.name = name         self.age = age # create a Person object person = Person("Alice", 25) # delete the 'age' attribute from the Person object delattr(person, "age") # print the object's attributes print(person.__dict__) In this example, a Person class is defined with two attributes, name and age. An object of this class is created with the name "Alice" and age 25. The delattr() function is then used to delete the age attribute from the person object. The __dict__ attribute of the person object is then printed to show that the age attribute has been deleted. The output will be:...

Python complex() Built in Function

The complex() function in Python is used to create a complex number object. A complex number is a number that has two parts, a real part and an imaginary part, and is represented as a+bi, where a and b are real numbers and i is the imaginary unit. Here is an example of using the complex() function in Python: # create a complex number object z = complex(3, 4) # print the complex number object print(z) In this example, the complex() function is used to create a complex number object with a real part of 3 and an imaginary part of 4. The resulting complex number object is assigned to the variable z. The print() function is then used to display the complex number object, which will output: (3+4j) This output indicates that the complex number object has a real part of 3 and an imaginary part of 4i. The j character represents the imaginary unit. If you have any questions about this code, you can drop a line in comment .

Python compile() Built in Function

The Python compile() function is a built-in function that returns a code object from a source string or an AST object. A code object is an internal representation of Python code that can be executed by the exec() or eval() functions. The compile() function takes three mandatory parameters: source, filename and mode. The source can be a string or an AST object containing Python code. The filename can be any string indicating where the code came from. The mode can be either ‘exec’, ‘eval’ or ‘single’ depending on what kind of code you want to compile. Here are some examples of using the compile() function: # Example 1: Compile and execute a simple statement x = compile('print(55)', 'test', 'exec') exec(x) # 55 # Example 2: Compile and execute multiple statements y = compile('a = 8\nb = 7\nsum = a + b\nprint("sum =", sum)', 'test', 'exec') exec(y) # sum = 15 # Example 3: Compile and evaluate an expression z = compile('3 ...

Python classmethod() Built in Function

The Python classmethod() function is a built-in function that returns a class method for a given function. A class method is a method that is bound to a class rather than an instance of the class. It can access and modify class variables and can be called by both instances and classes. One use case of class methods is to create factory methods that can create objects of different subclasses based on some parameters. Another use case is to access or modify class variables without creating an instance. Here are some examples of using the classmethod() function: # Example 1: Define a class method using @classmethod decorator class Person:     age = 25     @classmethod     def printAge(cls):         print('The age is:', cls.age) Person.printAge() # The age is: 25 # Example 2: Define a factory method using @classmethod decorator class Animal:     def __init__(self, name):    ...

Python chr() Built in Function

The Python chr() function is used to get a string representing a character that corresponds to a Unicode code integer. For example, chr(97) returns the string 'a'. This function takes an integer argument and throws an error if it exceeds the range of 0 to 1,114,111. Here are some examples of using the chr() function in Python: # Get the character for ASCII code 65 print(chr(65)) # Output: A # Get the character for Unicode code point 1200 print(chr(1200)) # Output: Ұ # Get the characters for a list of integers codes = [71, 101, 101, 107, 115] chars = [chr(code) for code in codes] print(''.join(chars)) # Output: Geeks To print ‘Hello World’ using chr() , you can write: print(chr(72) + chr(101) + chr(108) + chr(108) + chr(111) + chr(32) + chr(87) + chr(111) + chr(114) + chr(108) + chr(100)) To print a list of all uppercase letters using chr() , you can write: letters = [] for i in range(65, 91):     letters.append(chr(i)) print(letters) To print a smiley face emoji...

Python callable() Built in Function

The Python callable() function returns True if the specified object is callable, otherwise it returns False. A callable object is an object that can be invoked using the () operator, such as functions, methods, classes, etc. The callable() function checks if the object has a call() method. Here are some examples of using callable() function: # Example 1: Check if a function is callable def add(x, y):     return x + y print(callable(add)) # Output: True # Example 2: Check if a class is callable class Person:     def __init__(self, name):         self.name = name print(callable(Person)) # Output: True # Example 3: Check if an instance of a class is callable p = Person("Alice") print(callable(p)) # Output: False # Example 4: Check if a lambda expression is callable square = lambda x: x * x print(callable(square)) # Output: True # Example 5: Check if a built-in function is callable print(callable(print)) # Output: True...

Python bytes() Built in Function

The Python bytes() function returns a bytes object that is an immutable sequence of bytes. The bytes object can be created from various sources, such as strings, integers, iterables, buffers, etc. The bytes object supports methods and operations similar to bytearray objects. Here are some examples of using bytes() function: # Example 1: Create a bytes object from a string with encoding string = "Python is fun" # string with encoding 'utf-8' arr = bytes(string, 'utf-8') print(arr) # Output: b'Python is fun' # Example 2: Create a bytes object of given size and initialize with null bytes size = 10 arr = bytes(size) print(arr) # Output: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' # Example 3: Create a bytes object from an iterable of integers lst = [65, 66, 67] arr = bytes(lst) print(arr) # Output: b'ABC' # Example 4: Access a byte in a bytes object using index print(arr[0]) # Output: 65 # Example 5: Concatenate two bytes objects usin...

Python bytearray() Built in Function

The Python bytearray() function returns a bytearray object that is a mutable sequence of bytes. The bytearray object can be created from various sources, such as strings, integers, iterables, buffers, etc. The bytearray object supports methods and operations similar to list objects. Here are some examples of using bytearray() function: # Example 1: Create a bytearray object from a string with encoding string = "Python is fun" # string with encoding 'utf-8' arr = bytearray(string, 'utf-8') print(arr) # Output: bytearray(b'Python is fun') # Example 2: Create a bytearray object of given size and initialize with null bytes size = 10 arr = bytearray(size) print(arr) # Output: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') # Example 3: Create a bytearray object from an iterable of integers lst = [65, 66, 67] arr = bytearray(lst) print(arr) # Output: bytearray(b'ABC') # Example 4: Modify a byte in a bytearray object using index...

Python bool() Built in Function

The Python bool() function returns a Boolean value (True or False) for a given object. The object can be any data type, such as numbers, strings, lists, tuples, sets, dictionaries, etc. The bool() function follows some rules to evaluate the truth value of an object: Any numeric value that is not zero is True. Zero (0) is False. Any non-empty string is True. Empty string (‘’) is False. Any non-empty collection (list, tuple, set, dictionary) is True. Empty collection ([], (), {}, set()) is False. None is always False. True and False are keywords that represent the Boolean values. Here are some examples of using bool() function: # Example 1: Convert different data types to Boolean with bool() function num = 10 print(bool(num)) # Output: True str = "Hello" print(bool(str)) # Output: True lst = [] print(bool(lst)) # Output: False none = None print(bool(none)) # Output: False # Example 2: Use bool() function in conditional statements name = input("Enter your name: ...

Python bin() Built in Function

The Python bin() function converts an integer number to a binary string prefixed with 0b. For example, the binary equivalent of 2 is 0b10. The result is a valid Python expression. Here are some examples of using bin() function: # Example 1: Convert integer to binary with bin() method num = 10 print(bin(num)) # Output: 0b1010 # Example 2: Convert negative integer to binary with bin() method num = -5 print(bin(num)) # Output: -0b101 # Example 3: Convert float to binary with bin() method (raises TypeError) num = 3.14 print(bin(num)) # Output: TypeError: 'float' object cannot be interpreted as an integer # Example 4: Convert string to binary with bin() method (raises ValueError) num = "Hello" print(bin(num)) # Output: ValueError: invalid literal for int() with base 10: 'Hello' If you have any questions about this code, you can drop a line in comment .

Python ascii() Built in Function

The ascii() function in Python returns a readable version of any object (Strings, Tuples, Lists, etc). The ascii() function will replace any non-ascii characters with escape characters. ASCII stands for American Standard Code for Information Interchange. It is a character encoding standard that uses numbers from 0 to 127 to represent English characters. For example, ASCII code for the character A is 65, and 90 is for Z. Similarly, ASCII code 97 is for a, and 122 is for z. Here are some examples of Python code using ascii(): # Print ascii representation of a string normal_text = 'Python is interesting' print(ascii(normal_text)) # prints 'Python is interesting' # Print ascii representation of a string with non-ascii characters other_text = 'Pythön is interesting' print(ascii(other_text)) # prints 'Pyth\\xf6n is interesting' # Print ascii representation of a list my_list = ['a', 'b', 'c', '√'] print(ascii(my_list)) # ...

Python any() Built in Function

The any() function in Python returns True if any item in an iterable is true, otherwise it returns False. An iterable is an object that can be looped over, such as a list, a tuple, a set, a string or a dictionary. If the iterable is empty, the any() function also returns False. The any() function can be used to check if any element of an iterable satisfies a certain condition or if an iterable contains any true values. Here are some examples of Python code using any() :   # Check if any item in a list is negative my_list = [1, 2, 3, -4] print(any(x < 0 for x in my_list)) # prints True # Check if any item in a tuple is odd my_tuple = (2, 4, 6) print(any(x % 2 != 0 for x in my_tuple)) # prints False # Check if any item in a set is non-empty string my_set = {"hello", "world", ""} print(any(my_set)) # prints True # Check if any character in a string is digit my_string = "Python3" print(any(my_string.isdigit())) # prints True # Check if any ...

Python all() Built in Function

The all() function in Python returns True if all items in an iterable are true, otherwise it returns False. An iterable is an object that can be looped over, such as a list, a tuple, a set, a string or a dictionary. If the iterable is empty, the all() function also returns True. The all() function can be used to check if all elements of an iterable satisfy a certain condition or if an iterable contains any false values. Here are some examples of Python code using all() : # Check if all items in a list are positive my_list = [1, 2, 3, 4] print(all(x > 0 for x in my_list)) # prints True # Check if all items in a tuple are even my_tuple = (2, 4, 6) print(all(x % 2 == 0 for x in my_tuple)) # prints True # Check if all items in a set are non-empty strings my_set = {"hello", "world", ""} print(all(my_set)) # prints False # Check if all characters in a string are alphabets my_string = "Python" print(all(my_string.isalpha())) # prints True # Ch...

Python abs() Built in Function

The abs() function in Python returns the absolute value of a number. The absolute value of a number is its distance from zero on the number line. For example, the absolute value of -5 is 5 and the absolute value of 5 is also 5. The abs() function can take any numeric type as an argument, such as integers, floats or complex numbers. If the argument is a complex number, abs() returns its magnitude, which is the square root of the sum of squares of its real and imaginary parts. Here are some examples of Python code using abs() : # Absolute value of an integer print(abs(-10)) # prints 10 # Absolute value of a float print(abs(-3.14)) # prints 3.14 # Absolute value of a complex number print(abs(2+3j)) # prints 3.605551275463989 If you have any questions about this code, you can drop a line in comment .

Python Tuple Data

A tuple is a collection of data that is ordered and unchangeable. In Python, tuples are written with round brackets. For example, my_tuple = (1, 2, 3) is a tuple with three elements. You can access the elements of a tuple by using indexing or slicing. For example, my_tuple[0] returns 1 and my_tuple[1:3] returns (2, 3). You can also use some methods on tuples such as count() and index(). For example, my_tuple.count(2) returns how many times 2 appears in the tuple and my_tuple.index(3) returns the position of 3 in the tuple. Tuples are useful for storing data that does not change and for packing and unpacking values. Here are some examples of Python code using tuples: # Creating a tuple fruits = ("apple", "banana", "cherry") # Accessing a tuple element print(fruits[1]) # prints banana   # Slicing a tuple print(fruits[-2:]) # prints ("banana", "cherry")   # Looping through a tuple for fruit in fruits:     print(fruit)   # Checking if an el...

Stock Market Predictions with LSTM in Python

Stock Market Predictions with LSTM in Python is a tutorial that shows how to create a three-layer LSTM model using TensorFlow and Keras. Here is a snippet of how to define the model: # Define the LSTM model model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1))) model.add(LSTM(units=50)) model.add(Dense(1))   # Compile and fit the model model.compile(loss='mean_squared_error', optimizer='adam') model.fit(x_train, y_train, epochs=25, batch_size=32) Stock Market Analysis + Prediction using LSTM is a notebook that shows how to load stock market data from Yahoo finance using yfinance module, how to explore and visualize time-series data using pandas, matplotlib, and seaborn, how to measure the correlation between stocks, how to measure the risk of investing in a particular stock, and how to use LSTM (Long Short-Term Memory) model for predicting future stock prices. Here is a snippet of how to create and train an LSTM model f...