Numpy arccos – Python NumPy arccos() Function

Python NumPy arccos() Function

NumPy arccos() Function:

Numpy arccos: The arc cosine i.e, inverse cosine of the array elements or a given value is calculated using this arccos() function of the NumPy module. The value returned will be in the range of 0 to 𝜋.

Syntax:

numpy.arccos(x, out=None)

Parameters

x: This is required. It is an array (array-like) having elements in the range [-1, 1] for which the arc cosine is calculated.

out: This is optional. It is the location where the result will be saved. It must have a shape that the inputs broadcast to if it is provided. If None or not given, a newly allocated array is returned.

Return Value: 

The arc cosine value of each element of x is returned.

NumPy arccos() Function in Python

Example1

Approach:

  • Import numpy module using the import keyword.
  • Pass some random list as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Convert the above-given array angles into radians using the pi/180 of numpy module.
  • Store it in the same variable.
  • Pass the above radian angles array to the cos() function of the numpy module to get the cosine values of the given array angles.
  • Store it in another variable.
  • Pass the above cosine values array to the arccos() function of the numpy module to get the arc cosine(inverse cosine) values of the given array.
  • Store it in another variable.
  • Print the given array’s angles cosine values.
  • Print the given array’s angles inverse cosine values in radians.
  • Print the given array’s angles inverse cosine values in degrees by passing the above inverse cosine values to the degrees() function.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([30, 45, 120, 180])
# Convert the above given array angles into radians using the pi/180 of 
# numpy module.
# Store it in the same variable.
gvn_arry = gvn_arry*np.pi/180
# Pass the above radian angles array to the cos() function of the 
# numpy module to get the cosine values of the given array angles
# Store it in another variable.
cosine_arry = np.cos(gvn_arry)
# Pass the above cosine values array to the arccos() function of the 
# numpy module to get the arc cosine values of the given array
inversecos_arry = np.arccos(cosine_arry)
# Print the given array's angles cosine values
print("The given array's angles cosine values:")
print(cosine_arry)
print()
# Print the given array's angles inverse cosine values in radians
print("The given array's angles inverse cosine values in radians:")
print(inversecos_arry)
print()
# Print the given array's angles inverse cosine values in degrees by 
# passing the above inverse cosine values to the degrees() function.
print("The given array's angles inverse cosine values in degrees:")
print(np.degrees(inversecos_arry))

Output:

The given array's angles cosine values:
[ 0.8660254 0.70710678 -0.5 -1. ]

The given array's angles inverse cosine values in radians:
[0.52359878 0.78539816 2.0943951 3.14159265]

The given array's angles inverse cosine values in degrees:
[ 30. 45. 120. 180.]

Example2

Approach:

  • Import numpy module using the import keyword.
  • Give the array as static input and store it in a variable.
  • Print the above-given array.
  • Pass the above given array as an argument to the arccos() function of the numpy module to get the arc cosine(inverse cosine) values of given array elements.
  • Store it in another variable.
  • Print the arc cosine(inverse cosine) values of given array elements.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Give the array as static input and store it in a variable
gvn_arry = [1, 0.5, -0.2]                   
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the above given array as an argument to the arccos() function of the 
# numpy module to get the arc cosine(inverse cosine) values of 
# given array elements
# Store it in another variable.
invcos_arry = np.arccos(gvn_arry)   
# Print the arc cosine(inverse cosine) values of given array elements
print("The inverse cosine values of given array elements:")
print(invcos_arry)

Output:

The above given array is:
[1, 0.5, -0.2]
The inverse cosine values of given array elements:
[0. 1.04719755 1.77215425]

Invalid shorthand property initializer – How to Solve Invalid shorthand property initializer Error in JavaScript

How to Solve Invalid shorthand property initializer Error in JavaScript

What is an Invalid shorthand property initializer Error?

Invalid shorthand property initializer: When we use an equal sign(=) instead of a colon(:) to separate the values in an object, we get the “Invalid shorthand property initializer” error. To correct the mistake, put colons between the keys and values of an object when declaring it.

For example:

const object =  { EmpId:2122, EmpName:'John' }
console.log(object);

Output:

{ EmpId: 2122, EmpName: 'John' }

When Does This Error Occur?

// Here we are giving equal sign(=) instead of a colon(:) 
// between the keys and values of an object
// Hence  Invalid shorthand property initializer error occurs
const object =  { EmpId = 2122, EmpName = 'John' }
console.log(object);

Output:

const object =  { EmpId = 2122, EmpName = 'John' }
^^^^^^^^^^^^

SyntaxError: Invalid shorthand property initializer
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here we are giving equal sign(=) instead of a colon(:) between the keys and values of an object 
Hence Invalid shorthand property initializer error occurs

Handling the Invalid shorthand property initializer Error

Uncaught syntaxerror invalid shorthand property initializer: To Handle this see the below code as explained in the above concept:

For example:

const object =  { EmpId:2122, EmpName:'John' }
console.log(object);

Output:

{ EmpId: 2122, EmpName: 'John' }

It’s worth noting that we used an equal sign(=) to separate the object’s key-value pairs.

A colon(:) should be used to separate key-value pairs when declaring an object.

Using equal sign(=) to Add a New Key-Value Pair

If you wish to add a new key-value pair to the object, however, you must use the equal sign(=).

Approach:

  • Give the object containing key-value pairs and store it in a variable
  • Add a new key-value pair to the above object using the equal sign(=)
  • Print the object after adding a key-value pair to the object on the console.
  • The Exit of the Program.

Below is the implementation:

// Give the object containing key-value pairs and store it in a variable 
const object = { EmpId:2122, EmpName:'John' }
// Add a new key-value pair to the above object using the 
// equal sign(=)
object.EmpSalary = 50000;
// Print the object after adding a key-value pair on the console
console.log(object);

Output:

{ EmpId: 2122, EmpName: 'John', EmpSalary: 50000 }

Using the Bracket Notation instead of Dot Notation

When adding a key-value pair to an object, use bracket notation rather than dot notation if the key contains spaces, begins with a number, or contains a special character.

Example:

Approach:

  • Give the object containing key-value pairs and store it in a variable
  • Add a new key-value pair to the above object using the bracket notation instead of dot notation(.)
  • Print the object after adding a key-value pair to the object on the console.
  • The Exit of the Program.

Below is the implementation:

// Give the object containing key-value pairs and store it in a variable
const object = { EmpId:2122, EmpName:'John' }
// Add a new key-value pair to the above object using the 
// bracket notation instead of dot notation(.)
object['Employee Address'] = 'Gachibowli, Hyderabad';
// Print the object after adding a key-value pair on the console
console.log(object);

Output:

{ EmpId: 2122,
EmpName: 'John',
'Employee Address': 'Gachibowli, Hyderabad' }

Conclusion:

To avoid the “Invalid shorthand property initializer” problem, use a colon instead of an equal sign between the key-value pairs of an object literal, such as

const object =  { EmpId:2122, EmpName:'John' }

nth prime number python – Python Program to Find nth Prime Number

Program to Find nth Prime Number

nth prime number python: In the previous article, we have discussed Python Program to Delete Random Item from a List
Prime Number :

A prime number is one that can only be divided by one and itself.

Given a number ‘n’, and the task to find the nth prime number.

Examples:

Example1:

Input:

Given number = 8

Output:

The above given nth Prime Number is =  19

Example2:

Input:

Given number = 3

Output:

The above given nth Prime Number is =  5

Program to Find nth Prime Number

Below are the ways to find the nth prime number.

Method #1: Using While, For Loop (Static Input)

Approach:

  • Give the number say ‘n’ as static input and store it in a variable.
  • Take a list say ‘prime_numbers’ and initialize it with 2, 3 values.
  • Take a variable and initialize it with 3 say ‘x’.
  • Check if the given number is between greater than 0 and less than 3 using the if conditional statement.
  • If the statement is true, then print the value of the list “prime_numbers[n-1] “.
  • Check if the given number is greater than 2 using the elif conditional statement.
  • Iterate the loop infinite times using the while loop i.e while(True).
  • Inside the loop increment the value of the above given ‘x’ variable by ‘1’.
  • Take a variable to say ‘y’ and initialize with ‘True’.
  • Loop from 2 to int((x/2)+1) using the for loop and int function().
  • Check if the value of variable ‘x’ modulus iterator value is equal to zero or not using the if conditional statement.
  • If the statement is true, assign “False” to the variable y, break the statement and come out of the loop.
  • Check if variable y is equal to True using the if conditional statement.
  • If the statement is true, then append the value of variable ‘x’ to the above list ‘prime_numbers’.
  • Check if the length of the above list ‘prime_numbers’ is equal to the given number.
  • If the statement is true, then give a break statement and come out of the while loop.
  • Print the value of the list “prime_numbers[n-1]” to get the nth prime number.
  • Else print “Invalid number. Please enter another number “.
  • The Exit of the Program.

Below is the implementation:

# Give the number say 'n' as static input and store it in a variable.
num = 5
# Take a list say 'prime_numbers' and initialize it with 2, 3 values.
prim_numbrs = [2, 3]
# Take a variable and initialize it with 3 say 'x'.
x = 3
# Check if the given number is between greater than 0 and less than 3 using the if
# conditional statement.
if(0 < num < 3):
 # If the statement is true, then print the value of the list "prime_numbers[n-1] ".
    print('The above given nth Prime Number is =', prim_numbrs[num-1])
# Check if the given number is greater than 2 using the elif conditional statement.
elif(num > 2):
  # Iterate the loop infinite times using the while loop i.e while(True).
    while (True):
     # Inside the loop increment the value of the above given 'x' variable by '1'.
        x += 1
 # Take a variable say 'y' and initialize with 'True'.
        y = True
  # Loop from 2 to int((x/2)+1) using the for loop and int function().
        for itr in range(2, int(x/2)+1):
          # Check if the value of variable 'x' modulus iterator value is equal to zero or not
          # using the if conditional statement.
            if(x % itr == 0):
                # If the statement is true, assign "False" to the variable y, break the statement and
                # come out of the loop.
                y = False
                break
 # Check if variable y is equal to True using the if conditional statement.
        if(y == True):
            # If the statement is true, then append the value of variable 'x' to the
            # above list 'prime_numbers'.
            prim_numbrs.append(x)
  # Check if the length of the above list 'prime_numbers' is equal to the given number.
        if(len(prim_numbrs) == num):
         # If the statement is true, then give a break statement and come out of the while loop.
            break
 # Print the value of the list "prime_numbers[n-1]" to get the nth prime number.
    print('The above given nth Prime Number is = ', prim_numbrs[num-1])
 # Else print "Invalid number. Please enter another number ".
else:
    print("Invalid number. Please enter another number ")

Output:

The above given nth Prime Number is =  11

Method #2: Using While, For Loop (User Input)

Approach:

  • Give the number say ‘n’ as user input using int(input()) and store it in a variable.
  • Take a list say ‘prime_numbers’ and initialize it with 2, 3 values.
  • Take a variable and initialize it with 3 say ‘x’.
  • Check if the given number is between greater than 0 and less than 3 using the if conditional statement.
  • If the statement is true, then print the value of the list “prime_numbers[n-1] “.
  • Check if the given number is greater than 2 using the elif conditional statement.
  • Iterate the loop infinite times using the while loop i.e while(True).
  • Inside the loop increment the value of the above given ‘x’ variable by ‘1’.
  • Take a variable to say ‘y’ and initialize with ‘True’.
  • Loop from 2 to int((x/2)+1) using the for loop and int function().
  • Check if the value of variable ‘x’ modulus iterator value is equal to zero or not using the if conditional statement.
  • If the statement is true, assign “False” to the variable y, break the statement and come out of the loop.
  • Check if variable y is equal to True using the if conditional statement.
  • If the statement is true, then append the value of variable ‘x’ to the above list ‘prime_numbers’.
  • Check if the length of the above list ‘prime_numbers’ is equal to the given number.
  • If the statement is true, then give a break statement and come out of the while loop.
  • Print the value of the list “prime_numbers[n-1]” to get the nth prime number.
  • Else print “Invalid number. Please enter another number “.
  • The Exit of the Program.

Below is the implementation:

# Give the number say 'n' as user input using int(input()) and store it in a variable.
num = int(input("Enter some random number = "))
# Take a list say 'prime_numbers' and initialize it with 2, 3 values.
prim_numbrs = [2, 3]
# Take a variable and initialize it with 3 say 'x'.
x = 3
# Check if the given number is between greater than 0 and less than 3 using the if
# conditional statement.
if(0 < num < 3):
 # If the statement is true, then print the value of the list "prime_numbers[n-1] ".
    print('The above given nth Prime Number is =', prim_numbrs[num-1])
# Check if the given number is greater than 2 using the elif conditional statement.
elif(num > 2):
  # Iterate the loop infinite times using the while loop i.e while(True).
    while (True):
     # Inside the loop increment the value of the above given 'x' variable by '1'.
        x += 1
 # Take a variable say 'y' and initialize with 'True'.
        y = True
  # Loop from 2 to int((x/2)+1) using the for loop and int function().
        for itr in range(2, int(x/2)+1):
          # Check if the value of variable 'x' modulus iterator value is equal to zero or not
          # using the if conditional statement.
            if(x % itr == 0):
                # If the statement is true, assign "False" to the variable y, break the statement and
                # come out of the loop.
                y = False
                break
 # Check if variable y is equal to True using the if conditional statement.
        if(y == True):
            # If the statement is true, then append the value of variable 'x' to the
            # above list 'prime_numbers'.
            prim_numbrs.append(x)
  # Check if the length of the above list 'prime_numbers' is equal to the given number.
        if(len(prim_numbrs) == num):
         # If the statement is true, then give a break statement and come out of the while loop.
            break
 # Print the value of the list "prime_numbers[n-1]" to get the nth prime number.
    print('The above given nth Prime Number is = ', prim_numbrs[num-1])
 # Else print "Invalid number. Please enter another number ".
else:
    print("Invalid number. Please enter another number ")

Output:

Enter some random number = 1
The above given nth Prime Number is = 2

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Collatz conjecture c++ – Program to Print Collatz Conjecture for a Given Number in C++ and Python

Program to Print Collatz Conjecture for a Given Number in C++ and Python

Collatz conjecture c++: In the previous article, we have discussed about Program to Read a Number n and Compute n+nn+nnn in C++ and Python. Let us learn Program to Print Collatz Conjecture for a Given Number in C++ Program.

Given a number , the task is to print Collatz Conjecture of the given number in C++ and Python.

Collatz Conjecture:

  • The Collatz Conjecture states that a specific sequence will always reach the value 1.
  • It is given as follows, beginning with some integer n:
  • If n is an even number, the following number in the sequence is n/2.
  • Otherwise, the following number is 3n+1 (if n is odd).

Examples:

Example1:

Input:

given number =5425

Output:

The Collatz Conjecture of the number :
5425 16276 8138 4069 12208 6104 3052 1526 763 2290 1145 3436 1718 859 2578 1289 3868 1934 967 2902 1451 4354 2177 6532 3266 1633 4900 2450 1225 3676 1838 919 2758 1379 4138 2069 6208 3104 1552 776 388 194 97 292 146 73 220 110 55 166 83 250 125 376 188 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2  1

Example2:

Input:

given number=847

Output:

The Collatz Conjecture of the number :
847 2542 1271 3814 1907 5722 2861 8584 4292 2146 1073 3220 1610 805 2416 1208 604 302 151 454 227 682 341 1024 512 256 128 64 32 16 8 4 2  1

Program to Print Collatz Conjecture for a Given Number in C++ and Python

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)Printing Collatz Conjecture sequence of the given number in Python

Approach:

  • Scan the given number or give number as static input.
  • Iterate till the given number is not equal to 1 using while loop.
  • Print the number numb.
  • If the number is even then set n to n/2.
  • If the number is odd then set  n to 3*n+1.
  • Print 1 after end of while loop.
  • The Exit of the Program.

Below is the implementation:

# function which prints collatz sequence of the given number
def printCollatz(numb):
  # Iterate till the given number is not equal to 1 using while loop.
    while numb > 1:
      # Print the number numb
        print(numb, end=' ')
        # If the number is even then set n to n/2.
        if (numb % 2 == 0):
            numb = numb//2
        # If the number is odd then set  n to 3*n+1.
        else:
            numb = 3*numb + 1
   # Print 1 after end of while loop.
    print(1, end='')


# given number
numb = 179
print('The Collatz Conjecture of the number :')
# passing the given numb to printCollatz function to
# print collatzConjecture sequence of the given number
printCollatz(numb)

Output:

The Collatz Conjecture of the number :
179 538 269 808 404 202 101 304 152 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

2)Printing Collatz Conjecture sequence of the given number in C++

Approach:

  • Scan the given number using cin or give number as static input
  • Iterate till the given number is not equal to 1 using while loop.
  • Print the number numb.
  • If the number is even then set n to n/2.
  • If the number is odd then set  n to 3*n+1.
  • Print 1 after end of while loop.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
// function which prints collatz sequence of the given
// number
void printCollatz(int numb)
{

    // Iterate till the given number is not equal to 1 using
    // while loop.
    while (numb > 1) {
        // Print the number numb
        cout << numb << " ";
        // the number is even then set n to n / 2.
        if (numb % 2 == 0) {
            numb = numb / 2;
        }
        // the number is odd then set  n to 3 * n + 1.
        else {
            numb = 3 * numb + 1;
        }
    }
    // Print 1 after end of while loop.
    cout << " 1";
}
int main()
{

    // given number
    int numb = 179;
    cout << "The Collatz Conjecture of the number :"
         << endl;
    // passing the given numb to printCollatz function to
    // print collatzConjecture sequence of the given number
    printCollatz(numb);
    return 0;
}

Output:

The Collatz Conjecture of the number :
179 538 269 808 404 202 101 304 152 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2  1

Related Programs:

Python file readable – Python File readable() Method with Examples

file-readable()-method-with-examples

Files In Python:

Python file readable: A file is a piece of data or information stored on a computer’s hard drive. You’re already familiar with a variety of file kinds, including music, video, and text files. Manipulation of these files is trivial with Python. Text files and binary files are the two types of files that are commonly used. Binary files contain binary data that can only be read by a computer, whereas text files include plain text.

For programmers and automation testers, Python file handling (also known as File I/O) is a crucial topic. Working with files is required in order to write to or read data from them.

In addition, if you didn’t know, I/O activities are the most expensive techniques via which software might fail. As a result, when implementing file processing for reporting or any other reason, you should proceed with caution. The construction of a high-performance application or a robust solution for automated software testing can benefit from optimizing a single file activity.

File readable() Method in Python:

The readable() method is a built-in function that produces a result True if the file is readable, False otherwise.

Syntax:

file.readable()

Parameters: This method doesn’t accept any arguments.

Return Value:

This method’s return type is <class ‘bool’>; it returns True if the file stream is readable and False if the file stream is not readable.

File readable() Method with Examples in Python

Example

Approach:

  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Open the file in write mode. In this case, we’re writing the contents into the file.
  • Apply readable() function to the given file to check if the file is readable or not and print the result.
  • Close the given file using the close() function.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Apply readable() function to the given file to check if the file is readable or not and print the result.
  • Close the given file using the close() function.
  • The Exit of the Program.

Below is the implementation:

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in write mode. In this case, we're writing the contents into the file.
gvn_file = open(givenFilename, 'w') 
# Apply readable() function to the given file to check if the file is readable or not
# and print the result.
print("In write-mode:", gvn_file.readable())
# Close the given file using the close() function
gvn_file.close()

# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
gvn_file = open(givenFilename, 'r') 
# Apply readable() function to the given file to check if the file is readable or not
# and print the result.
print("In read-mode:", gvn_file.readable())
# Close the given file using the close() function
gvn_file.close()

Output:

In write-mode: False
In read-mode: True

File Content:

Hello this is btechgeeks
Good morning btechgeeks 
welcome to python-coding platform

Google Colab Images:

Files and Code:

Read word by word python – Python Program to Read File Word by Word

Program to Read File Word by Word

Files In Python:

Read word by word python: A file is a piece of data or information stored on a computer’s hard drive. You’re already familiar with a variety of file kinds, including music, video, and text files. Manipulation of these files is trivial with Python. Text files and binary files are the two types of files that are commonly used. Binary files contain binary data that can only be read by a computer, whereas text files include plain text.

For programmers and automation testers, Python file handling (also known as File I/O) is a crucial topic. Working with files is required in order to write to or read data from them.

In addition, if you didn’t know, I/O activities are the most expensive techniques via which software might fail. As a result, when implementing file processing for reporting or any other reason, you should proceed with caution. The construction of a high-performance application or a robust solution for automated software testing can benefit from optimizing a single file activity.

Given a file, the task is to print all words in the given file using python.

Program to Read File Word by Word using Python

Approach:

  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Iterate through the lines of the file using the For loop.
  • Split the words of the line using the split() function and store them in a variable(it is of type list).
  • Loop in the above list using another Nested For loop and print all the contents of the list using the print() function.
  • The Exit of the Program.

Below is the implementation:

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
with open(givenFilename, 'r') as givenfilecontent:
    # Iterate through the lines of the file using the For loop.
    print('The words in the given file : ')
    for gvnfileline in givenfilecontent:
      # Split the words of the line using the split() function and store them in a variable(it is of type list).
        gvnfilewords = gvnfileline.split()
        # Loop in the above list using another Nested For loop
        # and print all the contents of the list using the print() function.
        for words in gvnfilewords:
            print(words)

Output:

The words in the given file : 
hello
this
is
btechgeeks
Good
morning
this
is
btechgeeks
By
now
you
might
be
aware
that
Python
is
a
Popular
Programming
Language
used
right
from
web
developers
to
data
scientists.
Wondering
what
exactly
Python
looks
like
and
how
it
works?
The
best
way
to
learn
the
language
is
by
practicing.
BTech
Geeks
have
listed
a
wide
collection
of
Python
Programming
Examples.

Explanation:

  • The file path is stored in the variable ‘file name.’ Change the value of this variable to the path of your own file.
  • Dragging and dropping a file onto the terminal will show its path. The code will not run unless you change the value of this variable.
  • The file will be opened in reading mode. Use the open() function to open a file. The path to the file is the method’s first parameter, and the mode to open the file is the method’s second parameter.
  • When we open the file, we use the character ‘r’ to signify read-mode.
  • The split() method separates all of the words in the given file, which we then print word by word.

samplefile.txt

hello this is btechgeeks
Good morning this is btechgeeks By now you might be aware that Python is a Popular Programming Language used right from web developers to data scientists.
Wondering what exactly Python looks like and how it works? The best way to learn the language is by practicing. 
BTech Geeks have listed a wide collection of Python Programming Examples.

Sample Implementation in google colab:

 

lt() python – Python Pandas Series lt() Function

Python Pandas Series lt() Function

Pandas Series lt() Function:

lt() python: The lt() function of the Pandas module compares series and other for less than and returns the outcome of the comparison. It’s the same as series<other, but with the ability to use a fill_value as one of the parameters to fill in missing data.

Syntax:

Series.lt(other, level=None, fill_value=None, axis=0)

Parameters

other: This is required. It indicates a Series or a scalar value.

level: This is optional. To broadcast over a level, specify an int or a name that matches the Index values on the passed MultiIndex level. The type of this may be int or name. None is the default value.

fill_value: This is optional. It indicates a value to fill in any current missing (NaN) values, as well as any new elements required for successful Series alignment. The result will be missing if data is missing in both corresponding Series locations. The type of this may be float or None. None is the default value.

axis:  This is optional. To apply the method by rows, use 0 or ‘index,’ and to apply it by columns, use 1 or ‘columns.’

Return Value:

The result of the comparison i.e, a boolean series is returned.

Pandas Series lt() Function in Python

Example1

Approach:

  • Import pandas module using the import keyword.
  • Pass some random list as an argument to the Series() function of the pandas module to create a series.
  • Store it in a variable.
  • Print the above-given series.
  • Apply lt() function on all the elements of the given series by passing some random number to it and print the result.
  • Here it compares if all the elements of the given series are < 40.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random list as an argument to the Series() function
# of the pandas module to create a series.
# Store it in a variable.
gvn_series = pd.Series([12, 25, 65, 45, 10])
# Print the above given series
print("The given series is:")
print(gvn_series)
print()
# Apply lt() function on all the elements of the given series
# by passing some random number to it and print the result.
# Here it compares if all the elements of the given series are < 40
print("Checking if all the elements of the given series are < 40:")
print(gvn_series.lt(40))

Output:

The given series is:
0    12
1    25
2    65
3    45
4    10
dtype: int64

Checking if all the elements of the given series are < 40:
0     True
1     True
2    False
3    False
4     True
dtype: bool

Example2

Here a series is compared to another series for less than of(<) condition element by element.

Approach:

  • Import pandas module using the import keyword.
  • Import numpy module using the import keyword.
  • Pass some random list, index values as the arguments to the Series() function of the pandas module to create a series.
  • Store it in a variable.
  • Similarly, Pass some random list, index values as the arguments to the Series() function of the pandas module to create another series.
  • Store it in another variable.
  • Print the above first given series
  • Print the above second given series
  • Pass the given second series and fill_value as some random number as the arguments to the lt() function and apply it to the first series and print the result.
  • Here, we compare gvn_series1 < gvn_series2 element-by-element by filling NaN values with the given fill_value.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Import numpy module using the import keyword.
import numpy as np
# Pass some random list, index values as the arguments to the 
# Series() function of the pandas module to create a series.
# Store it in a variable.
gvn_series1 = pd.Series([2, 15, 4, np.NaN], 
              index=['P', 'Q', 'R', 'S'])
# Similarly, Pass some random list, index values as the arguments to the 
# Series() function of the pandas module to create another series.
# Store it in another variable.
gvn_series2 = pd.Series([5, 3, np.NaN, 2], 
              index=['P', 'Q', 'R', 'S'])
# Print the above first given series
print("The given first series is:")
print(gvn_series1)
print()
# Print the above second given series
print("The given second series is:")
print(gvn_series2)
print()
# Pass the given second series and fill_value as some random number as the 
# arguments to the lt() function and apply it to the first series and  
# print the result.
# Here, we compare gvn_series1 < gvn_series2 element-by-element
# by filling NaN values with the given fill_value.
print("Comparing gvn_series1 < gvn_series2 element-by-element:")
print(gvn_series1.lt(gvn_series2, fill_value=10))

Output:

The given first series is:
P     2.0
Q    15.0
R     4.0
S     NaN
dtype: float64

The given second series is:
P    5.0
Q    3.0
R    NaN
S    2.0
dtype: float64

Comparing gvn_series1 < gvn_series2 element-by-element:
P     True
Q    False
R     True
S    False
dtype: bool

Example3

Approach:

  • Import pandas module using the import keyword.
  • Pass some random key-value pair(dictionary) as arguments to the DataFrame() function of the pandas module to create a dataframe.
  • Store it in a variable.
  • Print the given dataframe.
  • Compare both the columns gvn_list1 and gvn_list2 using the lt() function and store the result as a new column in the dataframe.
  • Here it checks if gvn_list1 < gvn_list2 element-wise.
  • Print the dataframe after adding a new column(gvn_list1 < gvn_list2).
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random key-value pair(dictionary) as arguments to the 
# DataFrame() function of the pandas module to create a dataframe
# Store it in a variable.
data_frme  = pd.DataFrame({
  "gvn_list1": [45, 24, 54, 90],
  "gvn_list2": [55, 7, 60, 44]
})
# Print the given dataframe
print("The given Dataframe:")
print(data_frme)
print()

# Compare both the columns gvn_list1 and gvn_list2 using the lt() function
# and store the result as a new column in the dataframe.
# Here it checks if gvn_list1 < gvn_list2 element-wise.
data_frme ['gvn_list1 < gvn_list2'] = data_frme ['gvn_list1'].lt(data_frme ['gvn_list2'])
# Print the dataframe after adding a new column(gvn_list1 < gvn_list2)
print("The dataframe after adding a new column(gvn_list1 < gvn_list2):")
print(data_frme )

Output:

The given Dataframe:
   gvn_list1  gvn_list2
0         45         55
1         24          7
2         54         60
3         90         44

The dataframe after adding a new column(gvn_list1 < gvn_list2):
   gvn_list1  gvn_list2  gvn_list1 < gvn_list2
0         45         55                   True
1         24          7                  False
2         54         60                   True
3         90         44                  False

 

Exports is not defined typescript – How to Fix ReferenceError: exports is not defined in TypeScript?

How to Fix ReferenceError exports is not defined in TypeScript

Exports is not defined typescript: To fix the "Uncaught ReferenceError: exports is not defined" error, add a script tag that declares/defines an exports variable, such as <script> var exports ={} ;</script>above your JS script tag if in the browser, or remove the type attribute if it is set to the module in your package.json file in Node.js.

Fixing ReferenceError: exports is not defined in TypeScript?

Browser – ReferenceError: exports is not defined

Exports is not defined: If you see the error when running code in the browser, try to define a global exports variable above the script tags that load your JavaScript files.

index.html

<script>var exports = {};</script>

<!-- Add the JavaScript script below -->
<script src="index.js"></script>

This will define the exports variable and set it to an empty object, preventing an error from occurring if properties are accessed on it.

Browsers do not support the CommonJS syntax of require and module.exports (without using a tool like webpack), which is creating an error.

If you’re testing your code in the browser, remove the module property from your tsconfig.json file and change the target to es6.

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",  // change the targe to es6
    // "module": "commonjs", // Remove this or comment it (if browser env)
  }
}

When you remove the module option and set the target to es6, the imports and exports of your ES6 modules will not be compiled to the older CommonJS syntax that browsers do not support.

Because modern browsers support all ES6 features, ES6 is a suitable choice.

If it doesn’t work, try to set the type attribute to module in your script tags.

index.html

<!-- Set the correct path according to the setup --> 
<script type="module" src="index.js"></script>

And use the ES6 Modules syntax to import and export.

index.ts

import {v4} from 'uuid'
// Create a function which does the product of two arguments provided
export function multiply(a, b) {
  return a * b;
}

Because browsers do not support the CommonJS syntax, setting the module to commonjs in your tsconfig.json instructs TypeScript to emit CommonJS files, which is a very likely cause of the issue.

If you see the error in a Node.js application, consider removing the type attribute from your package.json file if it is set to module.

{
  "type": "module", // remove this liine or comment it
}

When type is set to module, we can no longer use CommonJS’s exports and require syntax and must instead use ES Modules syntax for all imports and exports, which may be causing the error.

This occurs when your package.json file has type set to module but your tsconfig.json file has module set to commonjs.

Because type = module instructs Node.js to utilise ES Modules syntax, while module = commonjs encourages TypeScript to produce CommonJS files, these two options are incompatible.

Examine your tsconfig.json file and make sure it looks like this.

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "esModuleInterop": true,
    "moduleResolution": "node",
    // ... your other options
  }
}

Your target option should be es6 or higher, and your module should be CommonJS.

For imports and exports, make sure to utilize the ES6 modules syntax.

index.ts

import {myDefinedFunction} from './myFile'

export function multiply(a:number, b:number) {
  return a * b;
}

Because Node JS supports the CommonJS syntax, if you use the ES modules syntax and instruct TypeScript to produce CommonJS code by setting module to commonjs, the export above will be compiled to CommonJS and should work.

The only reason it wouldn’t work is that you’re emitting CommonJS files but instructing Node.js to read them using ES6 Module syntax.

 

Python random choice no repeat – Random Choice of Random Module in Python with no Repeat

Random Choice of Random Module in Python with no Repeat

Python random choice no repeat: Given the upper limit and lower limit, the task is to generate n natural numbers which are not repeating in Python.

Examples:

Example1:

Input:

Given N=13
Given lower limit range =19
Given upper limit range =45

Output:

The random numbers present in the range from 19 to 45 are :
28 40 24 25 20 44 38 29 21 31 43

Example2:

Input:

Given N=19
Given lower limit range =23
Given upper limit range =41

Output:

The random numbers present in the range from 23 to 41 are : 26 27 40 38 37 41 30 35 36 23 25

Random choice of Random module in Python with no Repeat

Below are the ways to generate n natural numbers which are not repeating in Python.

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

Method #1: Using For Loop and randint function (Static Input)

Approach:

  • Import the random module using the import keyword.
  • Give the number n as static input and store it in a variable.
  • Give the lower limit range and upper limit range as static input and store them in two separate variables.
  • Take an empty list (say rndmnumbs) and initialize it with an empty list using [] or list().
  • Loop till n times using For loop.
  • Generate a random number using randint(lowerlimitrange,upperlimitrange) and store it in a variable.
  • Check whether the above random number is present in the list or not using not in operator.
  • If it is not in the list then append the element to the rndmnumbs list using the append() function.
  • Print the rndmnumbs.
  • The Exit of the Program.

Below is the implementation:

# Import the random module using the import keyword.
import random
# Give the number n as static input and store it in a variable.
numbe = 13
# Give the lower limit range and upper limit range as static input
# and store them in two separate variables.
lowerlimitrange = 19
upperlimitrange = 45
# Take an empty list (say rndmnumbs) and initialize it with an empty list
# using [] or list().
rndmnumbs = []
# Loop till n times using For loop.
for m in range(numbe):
        # Generate a random number using randint(lowerlimitrange,upperlimitrange)
    # and store it in a variable.
    randomnumbe = random.randint(lowerlimitrange, upperlimitrange)
    # Check whether the above random number is present in the list or not
    # using not in operator.
    if randomnumbe not in rndmnumbs:
        # If it is not in the list then append the element
        # to the rndmnumbs list using the append() function.
        rndmnumbs.append(randomnumbe)

# Print the rndmnumbs
print('The random numbers present in the range from',
      lowerlimitrange, 'to', upperlimitrange, 'are :')
for q in rndmnumbs:
    print(q, end=' ')

Output:

The random numbers present in the range from 19 to 45 are :
28 40 24 25 20 44 38 29 21 31 43

Method #2: Using For Loop and randint function (User Input)

Approach:

  • Import the random module using the import keyword.
  • Give the number n as user input using int(input()) and store it in a variable.
  • Give the lower limit range and upper limit range as user input using map(),int(),split(),input() functions.
  • Store them in two separate variables.
  • Take an empty list (say rndmnumbs) and initialize it with an empty list using [] or list().
  • Loop till n times using For loop.
  • Generate a random number using randint(lowerlimitrange,upperlimitrange) and store it in a variable.
  • Check whether the above random number is present in the list or not using not in operator.
  • If it is not in the list then append the element to the rndmnumbs list using the append() function.
  • Print the rndmnumbs.
  • The Exit of the Program.

Below is the implementation:

# Import the random module using the import keyword.
import random
# Give the number n as user input using int(input()) and store it in a variable.
numbe = int(input('Enter some random number = '))
# Give the lower limit range and upper limit range as user input
# using map(),int(),split(),input() functions.
# Store them in two separate variables.
lowerlimitrange = int(input('Enter random lower limit range = '))
upperlimitrange = int(input('Enter random upper limit range = '))
# Take an empty list (say rndmnumbs) and initialize it with an empty list
# using [] or list().
rndmnumbs = []
# Loop till n times using For loop.
for m in range(numbe):
        # Generate a random number using randint(lowerlimitrange,upperlimitrange)
    # and store it in a variable.
    randomnumbe = random.randint(lowerlimitrange, upperlimitrange)
    # Check whether the above random number is present in the list or not
    # using not in operator.
    if randomnumbe not in rndmnumbs:
        # If it is not in the list then append the element
        # to the rndmnumbs list using the append() function.
        rndmnumbs.append(randomnumbe)

# Print the rndmnumbs
print('The random numbers present in the range from',
      lowerlimitrange, 'to', upperlimitrange, 'are :')
for q in rndmnumbs:
    print(q, end=' ')

Output:

Enter some random number = 19
Enter random lower limit range = 23
Enter random upper limit range = 41
The random numbers present in the range from 23 to 41 are :
26 27 40 38 37 41 30 35 36 23 25

Related Programs:

Loop through unordered_map – CPP Unordered_Map: Erase Elements While Iterating in a Loop | Remove Entries from an Unordered Map While Iterating it in C++

Unordered_Map Erase Elements While Iterating in a Loop

Loop through unordered_map: In the previous article, we have discussed CPP11 / CPP14 : ‘delete’ keyword and deleted functions with Use Case. Let us learn What exactly is Unordered_Map in C++, How to Erase Elements while Iterating in a Loop. We have followed a step-by-step approach to help you understand the CPP Program for Unordered Map Erasing Elements while Iterating in a Loop. Try to apply the related knowledge when you encounter any such CPP Programs in your learning process.

Unordered_Map

Iterate through unordered_map c++: An associative container containing key-value pairs with unique keys is known as an unordered map. The average constant-time complexity of element search, insertion, and removal is high.

Internally, the elements are organized into buckets rather than being sorted in any particular order. The hash of an element’s key determines which bucket it is placed in. Because the hash refers to the exact bucket the element is placed into after it is computed, this allows for quick access to individual elements.

Given a unordered_map, the task is to erase elements from it while iterating through it.

Examples:

Input:

 { "Hello", 50 }, { "This", 100 }, { "is", 150 }, { "BTech", 220 }, { "Geeks", 250 }

Output:

Unordered map before modifying elements:
Geeks = 250
BTech = 220
is = 150
This = 100
Hello = 50
Unordered map after removing values which are greater than 200 :
is = 150
This = 100
Hello = 50

How to Remove Elements from unordered_map while Iterating through it in C++?

C++ unordered_map erase: Assume we have an unordered map with key-value pairs of string and integers.

We now want to remove all elements with values greater than 200. So, in order to delete all of those elements, we must iterate over the map to find them. As a result, we want to remove all of those elements in a single iteration.

To delete an element with an iterator, we will use the unordered map erase() function, which accepts an iterator and deletes that element, i.e.

iterator erase ( const_iterator position );

However, if the element is deleted, the iterator’s “position” becomes invalid. So, how do we get to the next element in the loop?

To get around this issue, The erase() function returns an iterator to the last deleted element’s next element. We’ll make use of it.

itr = stringmap.erase(itr);

Below is the implementation:

C++ Program to Remove element from unordered_map while iterating through it

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // create and intialize unordered_map with strings as
    // keys and integer as values
    unordered_map<std::string, int> stringmap(
        { { "Hello", 50 },
          { "This", 100 },
          { "is", 150 },
          { "BTech", 220 },
          { "Geeks", 250 } });
    cout << "Unordered map before modifying elements:"
         << endl;
    for (auto element : stringmap)
        cout << element.first << " = " << element.second
             << endl;
    // Taking a iterator which points to first key of the
    // unordered map
    unordered_map<std::string, int>::iterator itr
        = stringmap.begin();
    // erasing all elements whose value is greater than 200
    while (itr != stringmap.end()) {
        // checking if the value is greater than 200
        if (itr->second >= 200) {
            // erasing the element using erase() function
            itr = stringmap.erase(itr);
        }
        else
            itr++;
    }
    // printing the unordered_map
    cout << "Unordered map after removing values which are "
            "greater than 200 :"
         << endl;
    for (auto element : stringmap)
        cout << element.first << " = " << element.second
             << endl;
    return 0;
}

Output:

Unordered map before modifying elements:
Geeks = 250
BTech = 220
is = 150
This = 100
Hello = 50
Unordered map after removing values which are greater than 200 :
is = 150
This = 100
Hello = 50

Related Programs: