Python count word frequency dictionary – Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary

Program to Count the Frequency of Words Appearing in a String Using a Dictionary

Dictionaries in Python:

Python count word frequency dictionary: Dictionary is a mutable built-in Python Data Structure. It is conceptually related to List, Set, and Tuples. It is, however, indexed by keys rather than a sequence of numbers and can be thought of as associative arrays. On a high level, it consists of a key and its associated value. The Dictionary class in Python represents a hash-table implementation.

Examples:

Example1:

Input:

given string ="hello this is hello BTechGeeks BTechGeeks BTechGeeks this python programming python language"

Output:

{'hello': 2, 'this': 2, 'is': 1, 'BTechGeeks': 3, 'python': 2, 'programming': 1, 'language': 1}

Example2:

Input:

given string ="good morning this is good this python python BTechGeeks good good python online coding platform"

Output:

{'good': 4, 'morning': 1, 'this': 2, 'is': 1, 'python': 3, 'BTechGeeks': 1, 'online': 1, 'coding': 1, 'platform': 1}

Program to Count the Frequency of Words Appearing in a String Using a Dictionary

There are several ways to count the frequency of all words in the given string using dictionary some of them are:

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.

Method #1:Using count and zip function (Static Input)

Approach:

  • Give the string input as static and store it in a variable
  • Split the given string into words using split() function
  • Convert this into list using list() function.
  • Count the frequency of each term using count() function and save the results in a separate list using list Comprehension.
  • Merge the lists containing the terms and the word counts into a dictionary using the zip() function.
  • The resultant dictionary is printed
  • End of Program

Below is the implementation:

# given string
given_string = "hello this is hello BTechGeeks BTechGeeks BTechGeeks this python programming python language"
# Split the given string into words using split() function
# Convert this into list using list() function.
listString = given_string.split()
# Count the frequency of each term using count() function and
# save the results in a separate list using list Comprehension.
freqWords = [listString.count(k) for k in listString]
# Merge the lists containing the terms and the word counts
# into a dictionary using the zip() function.
resultdict = dict(zip(listString, freqWords))
# Print the resultant dictionary
print(resultdict)

Output:

{'hello': 2, 'this': 2, 'is': 1, 'BTechGeeks': 3, 'python': 2, 'programming': 1, 'language': 1}

Explanation:

  • A string must be entered by the user and saved in a variable.
  • The string is divided into words and saved in the list using a space as the reference.
  • Using list comprehension and the count() function, the frequency of each word in the list is counted.
  • The complete dictionary is printed after being created with the zip() method.

Method #2:Using count and zip function (User Input)

Approach:

  • Scan the string using input() function.
  • Split the given string into words using split() function
  • Convert this into list using list() function.
  • Count the frequency of each term using count() function and save the results in a separate list using list Comprehension.
  • Merge the lists containing the terms and the word counts into a dictionary using the zip() function.
  • The resultant dictionary is printed
  • End of Program

Below is the implementation:

# Scan the given string using input() function
given_string = input("Enter some random string separated by spaces = ")
# Split the given string into words using split() function
# Convert this into list using list() function.
listString = given_string.split()
# Count the frequency of each term using count() function and
# save the results in a separate list using list Comprehension.
freqWords = [listString.count(k) for k in listString]
# Merge the lists containing the terms and the word counts
# into a dictionary using the zip() function.
resultdict = dict(zip(listString, freqWords))
# Print the resultant dictionary
print(resultdict)

Output:

Enter some random string separated by spaces = good morning this is good this python python BTechGeeks good good python online coding platform
{'good': 4, 'morning': 1, 'this': 2, 'is': 1, 'python': 3, 'BTechGeeks': 1, 'online': 1, 'coding': 1, 'platform': 1}

Related Programs:

Remainder in python – Python Program to Read Two Numbers and Print Their Quotient and Remainder

Program to Read Two Numbers and Print Their Quotient and Remainder

Remainder in python: Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Given two numbers , the task is to print their quotient and Remainder in  Python.

Examples:

i)Floating Division

Example1:

Input:

first number =45
second number =17

Output:

The value of quotient after dividing 45 / 17 = 2.6470588235294117
The value of remainder after dividing 45 / 17 = 11

ii)Integer Division

Input:

first number =45
second number =17

Output:

The value of quotient after dividing 45 / 17 = 2
The value of remainder after dividing 45 / 17 = 11

Program to Read Two Numbers and Print Their Quotient and Remainder in  Python

Below are the ways to print the quotient and Remainder:

1)Using / and % modulus operator in Python (User Input separated by new line, Float Division)

Approach:

  • Scan the given two numbers using int(input()) and store them in two separate variables.
  • Calculate the quotient by using the syntax first number /second number and store it in a variable.
  • Calculate the remainder by using the syntax first number %second number and store it in a variable.
  • Print the above two variables which are the result of the program
  • Exit of Program.

Below is the implementation:

# scanning the given two numbers using int(input()) function
# first number
numb1 = int(input("Enter some random number = "))
# second number
numb2 = int(input("Enter some random number = "))
# Calculate the quotient by using the syntax first number /second number
# and store it in a variable.
quotie = numb1/numb2
# Calculate the remainder by using the syntax first number %second number
# and store it in a variable.
remain = numb1 % numb2
# Print the above two variables which are the result of the program
print("The value of quotient after dividing", numb1, "/", numb2, " = ", quotie)
print("The value of remainder after dividing",
      numb1, "/", numb2, " = ", remain)

Output:

Enter some random number = 86
Enter some random number = 12
The value of quotient after dividing 86 / 12 = 7.166666666666667
The value of remainder after dividing 86 / 12 = 2

2)Using / and % modulus operator in Python (User Input separated by spaces , Float Division)

Approach:

  • Scan the given two numbers using map and split() functions to store them in two separate variables.
  • Calculate the quotient by using the syntax first number /second number and store it in a variable.
  • Calculate the remainder by using the syntax first number %second number and store it in a variable.
  • Print the above two variables which are the result of the program
  • Exit of Program.

Below is the implementation:

# Scan the given two numbers using map and split() functions
# to store them in two separate variables.
numb1, numb2 = map(int, input("Enter two random numbers separated by spaces = ").split())
# Calculate the quotient by using the syntax first number /second number
# and store it in a variable.
quotie = numb1/numb2
# Calculate the remainder by using the syntax first number %second number
# and store it in a variable.
remain = numb1 % numb2
# Print the above two variables which are the result of the program
print("The value of quotient after dividing", numb1, "/", numb2, " = ", quotie)
print("The value of remainder after dividing",
      numb1, "/", numb2, " = ", remain)

Output:

Enter two random numbers separated by spaces = 45 17
The value of quotient after dividing 45 / 17 = 2.6470588235294117
The value of remainder after dividing 45 / 17 = 11

3)Using // and % modulus operator in Python (User Input separated by spaces , Integer Division)

Approach:

  • Scan the given two numbers using map and split() functions to store them in two separate variables.
  • Calculate the integer quotient by using the syntax first number //second number and store it in a variable.
  • Calculate the remainder by using the syntax first number %second number and store it in a variable.
  • Print the above two variables which are the result of the program
  • Exit of Program.

Below is the implementation:

# Scan the given two numbers using map and split() functions
# to store them in two separate variables.
numb1, numb2 = map(int, input("Enter two random numbers separated by spaces = ").split())
# Calculate the quotient by using the syntax first number /second number
# and store it in a variable.
quotie = numb1//numb2
# Calculate the remainder by using the syntax first number %second number
# and store it in a variable.
remain = numb1 % numb2
# Print the above two variables which are the result of the program
print("The value of quotient after dividing", numb1, "/", numb2, " = ", quotie)
print("The value of remainder after dividing",
      numb1, "/", numb2, " = ", remain)

Output:

Enter two random numbers separated by spaces = 45 17
The value of quotient after dividing 45 / 17 = 2
The value of remainder after dividing 45 / 17 = 11

Related Programs:

Python significant digits – Python Program to Form an Integer that has the Number of Digits at Ten’s Place and the Least Significant Digit of the Entered Integer at One’s Place

Program to Form an Integer that has the Number of Digits at Ten’s Place and the Least Significant Digit of the Entered Integer at One’s Place

Python significant digits: Given a number which is integer , the task is to create an integer with the number of digits at ten’s place and the least significant digit of the entered integer at one’s place.

Examples:

Example1:

Input:

given number = 37913749

Output:

The required number = 89

Example2:

Input:

 given number =78329942

Output:

The required number = 82

Create an integer with the number of digits at ten’s place and the least significant digit of the entered integer at one’s place in Python

There are several ways to create an integer with the number of digits at ten’s place and the least significant digit of the entered integer at one’s place some of them are:

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.

Method #1:Using while loop and String Conversion ( Static Input)

Approach:

  • Give a number as static input and store it in a variable.
  • Make a duplicate of the integer.
  • Take a variable which stores the count of digits and initialize it with 0
  • Using a while loop, calculate the number of digits in the given integer.
  • Convert the integer copy and the number of digits count to string.
  • Concatenate the integer’s last digit with the count.
  • The newly created integer should be printed.
  • Exit of program.

Below is the implementation:

# given number numb
numb = 37913749
# Taking a temporary variable which stores the given number
tempNum = numb
# Take a variable which stores the count of digits and initialize it with 0
countTotalDigits = 0
# looping till the given number is greater than 0
while(numb > 0):
    # increasing the count of digits by 1
    countTotalDigits = countTotalDigits+1
    # Dividing the number by 10
    numb = numb//10
# converting the temporary variable to string
strnum = str(tempNum)
# Extracting least significant digit
leastSigDigit = strnum[-1]
# converting the count Total Digits to string
countTotalDigits = str(countTotalDigits)
# calculating required number
resnum = countTotalDigits+leastSigDigit
print("The required number =", resnum)

Output:

The required number = 89

Explanation:

  • Give a number as static input and store it in a variable.
  • Because the original value of the variable would be modified for counting the number of digits, a copy of the variable is created.
  • The while loop is employed, and the modulus operator is utilized to get the last digit of the number.
  • The count value is incremented each time a digit is obtained.
  • The variable’s number of digits and the number are transformed to string for simplicity of concatenation.
  • The string’s final digit is then retrieved and concatenated to the count variable.
  • The newly generated number is then printed.

Method #2:Using while loop and String Conversion ( User Input)

Approach:

  • Scan the given number using int(input()) and store it in a variable.
  • Make a duplicate of the integer.
  • Take a variable which stores the count of digits and initialize it with 0
  • Using a while loop, calculate the number of digits in the given integer.
  • Convert the integer copy and the number of digits count to string.
  • Concatenate the integer’s last digit with the count .
  • The newly created integer should be printed.
  • Exit of program.

Below is the implementation:

# given number numb
numb = int(input("enter any number = "))
# Taking a temporary variable which stores the given number
tempNum = numb
# Take a variable which stores the count of digits and initialize it with 0
countTotalDigits = 0
# looping till the given number is greater than 0
while(numb > 0):
    # increasing the count of digits by 1
    countTotalDigits = countTotalDigits+1
    # Dividing the number by 10
    numb = numb//10
# converting the temporary variable to string
strnum = str(tempNum)
# Extracting least significant digit
leastSigDigit = strnum[-1]
# converting the count Total Digits to string
countTotalDigits = str(countTotalDigits)
# calculating required number
resnum = countTotalDigits+leastSigDigit
print("The required number =", resnum)

Output:

enter any number = 78329942
The required number = 82

Method #3: Using len() and indexing by converting number to string (Static Input)

Approach:

  • Give a number as static input and store it in a variable.
  • Using the str() method, convert the given number to a string.
  • Determine the number of digits in the given number by computing the length of the string with the len() function.
  • Concatenate the integer’s last digit with the count.
  • The newly created integer should be printed.
  • Exit of program.

Below is the implementation:

# given number numb
numb = 82179
# Using the str() method, convert the given number to a string.
strnum = str(numb)

# Determine the number of digits in the given number by computing
# the length of the string with the len() function.
countTotalDigits = len(strnum)

# Extracting least significant digit
leastSigDigit = strnum[-1]
# converting the count Total Digits to string
countTotalDigits = str(countTotalDigits)
# calculating required number
resnum = countTotalDigits+leastSigDigit
print("The required number =", resnum)

Output:

The required number = 59

Related Programs:

How to print a range of numbers in python – Python Program to Print Numbers in a Range (1,upper) Without Using any Loops or by Using Recursion

Program to Print Numbers in a Range (1,upper) Without Using any Loops or by Using Recursion

How to print a range of numbers in python: Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

If we examine closely at this problem, we can see that the concept of “loop” is to track some counter value, such as “i=0″ till I = higher”. So, if we aren’t permitted to use loops, how can we track something in Python?
One option is to use ‘recursion,’ however we must be careful with the terminating condition. Here’s a solution that uses recursion to output numbers.

Examples:

Example1:

Input:

Enter some upper limit range = 11

Output:

The numbers from 1 to 11 without using loops : 
1
2
3
4
5
6
7
8
9
10
11

Example2:

Input:

Enter some upper limit range = 28

Output:

The numbers from 1 to 28 without using loops : 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Program to Print Numbers in a Range (1,upper) Without Using any Loops/Recursive Approach

Below are the ways to print all the numbers in the range from 1 to upper without using any loops or by using recursive approach.

Method #1:Using Recursive function(Static Input)

Approach:

  • Give the upper limit range using static input.
  • Create a recursive function.
  • Create a basic case for that function in when the integer is greater than zero.
  • If the number is more than zero, call the function again with the input set to the number -1.
  • Print the number.
  • Exit of program.

Below is the implementation:

# function which prints numbers from 1 to gievn upper limit range
# without loop/by using recursion


def printNumbers(upper_limit):
  # checking if th upper limit value is greater than 0 using if statement
    if(upper_limit > 0):
      # If the number is more than zero, call the function again with
      # the input set to the number -1.
        printNumbers(upper_limit-1)
        # Print the upper limit
        print(upper_limit)


# giveen upper limt range
upper_limit = 28
print('The numbers from 1 to', upper_limit, 'without using loops : ')
# passing the given upper limit range to printNumbers
printNumbers(upper_limit)

Output:

The numbers from 1 to 28 without using loops : 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Method #2:Using Recursive function(User Input)

Approach:

  • Scan the upper limit range using int(input()).
  • Create a recursive function.
  • Create a basic case for that function in when the integer is greater than zero.
  • If the number is more than zero, call the function again with the input set to the number -1.
  • Print the number.
  • Exit of program.

Below is the implementation:

# function which prints numbers from 1 to gievn upper limit range
# without loop/by using recursion


def printNumbers(upper_limit):
  # checking if th upper limit value is greater than 0 using if statement
    if(upper_limit > 0):
      # If the number is more than zero, call the function again with
      # the input set to the number -1.
        printNumbers(upper_limit-1)
        # Print the upper limit
        print(upper_limit)


# giveen upper limt range
upper_limit = int(input('Enter some upper limit range = '))
print('The numbers from 1 to', upper_limit, 'without using loops : ')
# passing the given upper limit range to printNumbers
printNumbers(upper_limit)

Output:

Enter some upper limit range = 11
The numbers from 1 to 11 without using loops : 
1
2
3
4
5
6
7
8
9
10
11

Explanation:

  • The user must enter the range’s top limit.
  • This value is supplied to the recursive function as an argument.
  • The recursive function’s basic case is that number should always be bigger than zero.
  • If the number is greater than zero, the function is called again with the argument set to the number minus one.
  • The number has been printed.
  • The recursion will continue until the number is less than zero.

Cumulative sum python – Python Program to Find the Cumulative Sum of a List using Different Methods | How to Calculate Cumulative Sum in Python with Examples?

Program to Find the Cumulative Sum of a List

Cumulative sum python: The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Are you searching everywhere for a Program to Print the Cumulative Sum of Elements in a List? Then, this is the right place as it gives you a clear idea of what is meant by lists, the cumulative sum, different methods for finding the cumulative sum of numbers in a list, etc. Learn the simple codes for finding the cumulative sum of a list in python provided with enough examples and make the most out of them to write new codes on your own.

Lists in Python

Python cumulative sum: Python’s built-in container types are List and Tuple. Objects of both classes can store various additional objects that can be accessed via index. Lists and tuples, like strings, are sequence data types. Objects of different types can be stored in a list or a tuple.

A list is an ordered collection of objects (of the same or distinct types) separated by commas and surrounded by square brackets.

Cumulative Sum

The cumulative total denotes “how much thus far” The cumulative sum is defined as the sum of a given sequence that grows or increases with successive additions. The growing amount of water in a swing pool is a real-world illustration of a cumulative accumulation.

Given a list, the task is to find the cumulative sum of the given list in python

Cumulative Sum in Python Examples

Example 1:

Input:

given list = [34, 45, 12, 22, 33, 75, 10, 98, 222, 999, 1023, 32421]

Output:

The given list before calculating cumulative sum [34, 45, 12, 22, 33, 75, 10, 98, 222, 999, 1023, 32421] 
The given list before calculating cumulative sum [34, 79, 91, 113, 146, 221, 231, 329, 551, 1550, 2573, 34994]

Example 2:

Input:

given list =[78, 45, 26, 95, 1, 2, 45, 13, 29, 39, 49, 68, 57, 13, 1, 2, 3, 1000, 2000, 100000]

Output:

The given list before calculating cumulative sum [78, 45, 26, 95, 1, 2, 45, 13, 29, 39, 49, 68, 57, 13, 1, 2, 3, 1000,
 2000, 100000]
The given list before calculating cumulative sum [78, 123, 149, 244, 245, 247, 292, 305, 334, 373, 422, 490, 547,
560, 561, 563, 566, 1566, 3566, 103566]

How to find the Cumulative Sum of Numbers in a List?

There are several ways to find the Cumulative sum in python some of them are:

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.

Method #1:Using Count Variable and for loop (Static Input)

Approach:

  • Give the list input as static
  • Take a variable that stores the sum and initialize it with 0.
  • Take an empty list say cumulative list which stores the cumulative sum.
  • Using the for loop, repeat a loop length of the given list of times.
  • Calculate the sum till i th index using Count variable.
  • Append this count to the cumulative list using the append() function.
  • Print the cumulative list.

Write a Program to find the Cummulative Sum in a List?

# given list
given_list = [34, 45, 12, 22, 33, 75, 10, 98, 222, 999, 1023, 32421]
# Take a variable which stores the sum and initialize it with 0.
countsum = 0
# Take a empty list say cumulativelist which stores the cumulative sum.
cumulativelist = []
# calculating the length of given list
length = len(given_list)
# Using the for loop, repeat a loop length of the given list of times.
for i in range(length):
    # Calculate the sum till i th index using Count variable
    # increasing the count with the list element
    countsum = countsum+given_list[i]
    # Append this count to the cumulativelist  using append() function.
    cumulativelist.append(countsum)
# printing the given list  before calculating cumulative sum
print("The given list before calculating cumulative sum ", given_list)
# printing the list  after calculating cumulative su
print("The given list before calculating cumulative sum ", cumulativelist)

Python Program to Find the Cumulative Sum of a List using Count Variable and For Loop(Static Input)

Output:

The given list before calculating cumulative sum  [34, 45, 12, 22, 33, 75, 10, 98, 222, 999, 1023, 32421]
The given list before calculating cumulative sum  [34, 79, 91, 113, 146, 221, 231, 329, 551, 1550, 2573, 34994]

Method #2:Using Count Variable and for loop (User Input)

Approach:

  • Scan the given separated by spaces using a map, list, and split functions.
  • Take a variable that stores the sum and initialize it with 0.
  • Take an empty list say cumulative list which stores the cumulative sum.
  • Using the for loop, repeat a loop length of the given list of times.
  • Calculate the sum till i th index using Count variable.
  • Append this count to the cumulative list using the append() function.
  • Print the cumulative list.

Below is the implementation:

# Scan the given separated by spaces using map, list and split functions.
given_list = list(map(int, input(
    'enter some random numbers to the list separated by spaces = ').split()))
# Take a variable which stores the sum and initialize it with 0.
countsum = 0
# Take a empty list say cumulativelist which stores the cumulative sum.
cumulativelist = []
# calculating the length of given list
length = len(given_list)
# Using the for loop, repeat a loop length of the given list of times.
for i in range(length):
    # Calculate the sum till i th index using Count variable
    # increasing the count with the list element
    countsum = countsum+given_list[i]
    # Append this count to the cumulativelist  using append() function.
    cumulativelist.append(countsum)
# printing the given list  before calculating cumulative sum
print("The given list before calculating cumulative sum ", given_list)
# printing the list  after calculating cumulative su
print("The given list before calculating cumulative sum ", cumulativelist)

Python Program for finding the Cumulative Sum of a List using Loop Count Variable and for Loop(User Input)

Output:

enter some random numbers to the list separated by spaces = 78 45 26 95 1 2 45 13 29 39 49 68 57 13 1 2 3 1000 2000 100000
The given list before calculating cumulative sum [78, 45, 26, 95, 1, 2, 45, 13, 29, 39, 49, 68, 57, 13, 1, 2, 3, 1000,
2000, 100000]
The given list before calculating cumulative sum [78, 123, 149, 244, 245, 247, 292, 305, 334, 373, 422, 490, 547,
560, 561, 563, 566, 1566, 3566, 103566]

Method #3:Using Slicing (Static Input)

Approach:

  • Give the list input as static
  • Take an empty list say cumulative list which stores the cumulative sum.
  • Using the for loop, repeat a loop length of the given list of times.
  • Calculate the sum till ith index using slicing and sum function.
  • Append this count to the cumulative list using the append() function.
  • Print the cumulative list.

Below is the implementation:

# given list
given_list = [34, 45, 12, 22, 33, 75, 10, 98, 222, 999, 1023, 32421]
# Take a empty list say cumulativelist which stores the cumulative sum.
cumulativelist = []
# calculating the length of given list
length = len(given_list)
# Using the for loop, repeat a loop length of the given list of times.
for i in range(length):
    # Calculate the sum till i th index using slicing
    countsum = sum(given_list[:i+1])
    # Append this count to the cumulativelist  using append() function.
    cumulativelist.append(countsum)
# printing the given list  before calculating cumulative sum
print("The given list before calculating cumulative sum ", given_list)
# printing the list  after calculating cumulative su
print("The given list before calculating cumulative sum ", cumulativelist)

Python Program for finding the Cumulative Sum of a List Using Slicing(Static Input)

Output:

The given list before calculating cumulative sum  [34, 45, 12, 22, 33, 75, 10, 98, 222, 999, 1023, 32421]
The given list before calculating cumulative sum  [34, 79, 91, 113, 146, 221, 231, 329, 551, 1550, 2573, 34994]

Python get random item from list – Python Program to Get n Random Items from a List

Program to Get n Random Items from a List

Python get random item from list: In the previous article, we have discussed Python Program Divide all Elements of a List by a Number
Random Module in python :

As this Random module is one of Python’s predefined modules, its methods return random values.

It selects integers uniformly from a range. For sequences, it has a function to generate a random permutation of a list in-place, as well as a function to generate a random sampling without replacement. Let’s take a look at how to import the Random Module.

The random module in Python is made up of various built-in Methods.

choice():  choice() is used to select an item at random from a list, tuple, or other collection.

Because the choice() method returns a single element, we will be using it in looping statements.
sample(): To meet our needs, we’ll use sample() to select multiple values.

Examples:

Example1:

Input:

Given no of random numbers to be generated = 5
Given list =[1, 2, 3, 2, 2, 1, 4, 5, 6, 8, 9]

Output:

The given 5 Random numbers are :
2
3
8
6
9

Example 2:

Input:

Given no of random numbers to be generated = 3
Given list = [2, 1, 6, 1, 4, 5, 6, 8]

Output:

The given 3 Random numbers are :
6
5
1

Program to Get n Random Items from a List

Below are the ways to Get n Random Items from a Given List.

Method #1: Using random.choice() Method (Static input)

Approach:

  • Import random module using the import keyword.
  • Give the number as static input and store it in a variable.
  • Give the list as static input and store it in another variable.
  • Loop in the given list above given ‘n’ number of times using For loop.
  • Inside the loop, apply random.choice() method for the above-given list and store it in a variable.
  • Print the given number of random numbers to be generated.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number as static input and store it in a variable.
randm_numbrs = 3
# Give the list as static input and store it in another variable.
gvn_lst = [1, 2, 3, 2, 2, 1, 4, 5, 6, 8, 9]
print("The given", randm_numbrs, "Random numbers are :")
# Loop above given 'n' number of times using For loop.
for itr in range(randm_numbrs):
  # Inside the loop, apply random.choice() method for the above given list and
  # store it in a variable.
    reslt = random.choice(gvn_lst)
   # Print the given numbers of random numbers to be generated.
    print(reslt)

Output:

The given 3 Random numbers are :
5
3
4

Method #2: Using random.choice() Method (User input)

Approach:

  • Import random module using the import keyword.
  • Give the number as user input using int(input()) and store it in a variable.
  • Give the list as user input and using list(),map(), int(),input(),and split() functions store it in another variable
  • The loop above given ‘n’ number of times using For loop.
  • Inside the loop, apply random.choice() method for the above-given list and store it in a variable.
  • Print the given number of random numbers to be generated.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number as user input using int(input()) and store it in a variable.
randm_numbrs = int(input("Enter some random number = "))
#Give the list as user input and using list(),map(), int(),input(),and split() functions 
#store it in another variable
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
print("The given", randm_numbrs, "Random numbers are :")
# Loop above given 'n' number of times using For loop.
for itr in range(randm_numbrs):
 # Inside the loop, apply random.choice() method for the above given list and
 # store it in a variable.
    reslt = random.choice(gvn_lst)
 # Print the given numbers of random numbers to be generated.
    print(reslt)

Output:

Enter some random number = 4
Enter some random List Elements separated by spaces = 1 2 3 4 5 6 7 8 9 
The given 4 Random numbers are :
2
2
4
8

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.

 

Python tan function – Python Program to Get Tangent value Using math.tan()

Program to Get Tangent value Using math.tan()

Python tan function: In the previous article, we have discussed Python Program to Reverse each Word in a Sentence
Math Module :

Python’s math module is a built-in module. By importing this module, we can perform mathematical computations.

Numerous mathematical operations like ceil( ),floor( ),factorial( ),mod( ),value of pi ,…..etc .can be computed with the help of math module.

math.tan() Function in Python:

Using this function, we can quickly find the tangent value for a given angle.

Tan is a trigonometric function that represents the Tangent function.
Its value can be calculated by dividing the length of the opposite side by the length of the adjacent side of a right-angled triangle, as we learned in math.

By importing the math module that contains the definition, we will be able to use the tan() function in Python to obtain the tangent value for any given angle.

Examples:

Example1:

Input:

Given lower limit range =0
Given upper limit range =181
Given step size =30

Output:

The Tangent values in a given range are tan( 0 ) =  0.0
The Tangent values in a given range are tan( 30 ) =  0.5773502691896257
The Tangent values in a given range are tan( 60 ) =  1.7320508075688767
The Tangent values in a given range are tan( 90 ) =  1.633123935319537e+16
The Tangent values in a given range are tan( 120 ) =  -1.7320508075688783
The Tangent values in a given range are tan( 150 ) =  -0.5773502691896257
The Tangent values in a given range are tan( 180 ) =  -1.2246467991473532e-16

Example 2:

Input:

Given lower limit range = 40
Given upper limit range = 300
Given step size = 45

Output:

The Tangent values in a given range are tan( 40 ) =  0.8390996311772799
The Tangent values in a given range are tan( 85 ) =  11.430052302761348
The Tangent values in a given range are tan( 130 ) =  -1.19175359259421
The Tangent values in a given range are tan( 175 ) =  -0.08748866352592402
The Tangent values in a given range are tan( 220 ) =  0.8390996311772799
The Tangent values in a given range are tan( 265 ) =  11.430052302761332

Program to Get Tangent value using math.tan()

Below are the ways to Get Tangent value.

Method #1: Using math Module (Static input)

Approach:

  • Import math module using the import keyword.
  • Give the lower limit range as static input and store it in a variable.
  • Give the upper limit range as static input and store it in another variable.
  • Give the step size as static input and store it in another variable.
  • Loop from lower limit range to upper limit range using For loop.
  • Get the angle value in radians from the given range(converting from degree to radians ) and store it in a variable.
  • Calculate the Tangent value in a given range for the above-obtained radian values using math.tan() function and store it in another variable.
  • print the Tangent Values in the above-given range.
  • The Exit of the program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the lower limit range as static input and store it in a variable.
lwer_lmt = 0
# Give the upper limit range as static input and store it in another variable.
upp_lmt = 181
# Give the step size as static input and store it in another variable.
stp_sze = 30
# Loop from lower limit range to upper limit range using For loop.
for vale in range(lwer_lmt, upp_lmt, stp_sze):
  # Get the angle value in radians from the given range(converting from degree to radians )
  # and store it in a variable.
    radns = math.radians(vale)
    # Calculate the Tangent value in a given range of above obtained radian values using
    # tan()function and store it in another variable.
    tangt = math.tan(radns)
    # print the Tangent Values in the above given range.
    print("The Tangent values in a given range are tan(", vale, ') = ', tangt)

Output:

The Tangent values in a given range are tan( 0 ) =  0.0
The Tangent values in a given range are tan( 30 ) =  0.5773502691896257
The Tangent values in a given range are tan( 60 ) =  1.7320508075688767
The Tangent values in a given range are tan( 90 ) =  1.633123935319537e+16
The Tangent values in a given range are tan( 120 ) =  -1.7320508075688783
The Tangent values in a given range are tan( 150 ) =  -0.5773502691896257
The Tangent values in a given range are tan( 180 ) =  -1.2246467991473532e-16

Method #2: Using math Module (User input)

Approach:

  • Import math module using the import keyword.
  • Give the lower limit range as User input using the int(input(()) function and store it in a variable.
  • Give the upper limit range as User input using the int(input(()) function and store it in another variable.
  • Give the step size as User input and store it in another variable.
  • Loop from lower limit range to upper limit range using For loop.
  • Get the angle value in radians from the given range(converting from degree to radians ) and store it in a variable.
  • Calculate the Tangent value in a given range of the above-obtained radian values using the tan()function and store it in another variable.
  • print the Tangent Values in the above-given range.
  • The Exit of the program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the lower limit range as User input using the int(input(()) function and store it in a variable.
lwer_lmt = int(input('Enter some Random number ='))
# Give the upper limit range as User input using the int(input(()) function and store it in another variable.
upp_lmt = int(input('Enter some Random number ='))
# Give the step size as User input and store it in another variable.
stp_sze = int(input('Enter some Random number ='))
# Loop from lower limit range to upper limit range using For loop.
for vale in range(lwer_lmt, upp_lmt, stp_sze):
  # Get the angle value in radians from the given range(converting from degree to radians )
  # and store it in a variable.
    radns = math.radians(vale)
    # Calculate the Tangent value in a given range of above obtained radian values using
    # tan()function and store it in another variable.
    tangt = math.tan(radns)
    # print the Tangent Values in the above given range.
    print("The Tangent values in a given range are tan(", vale, ') = ', tangt)

Output:

Enter some Random number = 40
Enter some Random number = 300
Enter some Random number = 45
The Tangent values in a given range are tan( 40 ) = 0.8390996311772799
The Tangent values in a given range are tan( 85 ) = 11.430052302761348
The Tangent values in a given range are tan( 130 ) = -1.19175359259421
The Tangent values in a given range are tan( 175 ) = -0.08748866352592402
The Tangent values in a given range are tan( 220 ) = 0.8390996311772799
The Tangent values in a given range are tan( 265 ) = 11.430052302761332

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.

 

Python pick random element from list – Python Program to Select a Random Element from a Tuple

Program to Select a Random Element from a Tuple

Python pick random element from list: In the previous article, we have discussed Python Program to Get n Random Items from a List
Random Module in python :

Get random element from list python: As this Random module is one of Python’s predefined modules, its methods return random values.

It selects integers uniformly from a range. For sequences, it has a function to generate a random permutation of a list in-place, as well as a function to generate a random sampling without replacement. Let’s take a look at how to import the Random Module.

The random module in Python is made up of various built-in Methods.

choice():  choice() is used to select an item at random from a list, tuple, or other collection.

Because the choice() method returns a single element, we will be using  it in looping statements.
sample(): To meet our needs, we’ll use sample() to select multiple values.

Examples:

Example1:

Input:

Given no of random numbers to be generated = 3
Given tuple = ("btechgeeks", 321, "good morning", [7, 8, 5, 33], 35.8)

Output:

Example 2:

Input:

Given no of random numbers to be generated = 4
Given tuple = (255, "hello", "btechgeeks", 150,"good morning", [1, 2, 3, 4], 100, 98)

Output:

The given 4 Random numbers are :
[1, 2, 3, 4]
255
255
98

Program to Select a Random Element from a Tuple

Python select random element from list: Below are the ways to select a random element from a given Tuple.

Method #1: Using random.choice() Method (Only one element)

Approach:

  • Import random module using the import keyword.
  • Give the tuple as static input and store it in a variable.
  • Apply random. choice() method for the above-given tuple and store it in another variable.
  • Print the random element from the above-given tuple
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the tuple as static input and store it in a variable.
gvn_tupl = (255, "hello", "btechgeeks", 150,
            "good morning", [1, 2, 3, 4], 100, 98)
# Apply random.choice() method for the above given tuple and store it in another variable.
reslt = random.choice(gvn_tupl)
# Print the random element from the above given tuple
print("The random element from the above given tuple = ", reslt)

Output:

The random element from the above given tuple =  btechgeeks

Method #2: Using For Loop (N elements)

Approach:

  • Import random module using the import keyword.
  • Give the number as static input and store it in a variable.
  • Give the tuple as static input and store it in another variable.
  • Loop in the given tuple above given ‘n’ number of times using For loop.
  • Inside the loop, apply random.choice() method for the above-given tuple and store it in a variable.
  • Print the given number of random elements to be generated from the given tuple.
  • The Exit of the program.

Below is the implementation:

# Import random module using the import keyword.
import random
# Give the number as static input and store it in a variable.
randm_numbrs = 3
# Give the tuple as static input and store it in another variable.
gvn_tupl = ("btechgeeks", 321, "good morning", [7, 8, 5, 33], 35.8)
print("The given", randm_numbrs, "Random numbers are :")
# Loop in the given tuple above given 'n' number of times using For loop.
for itr in range(randm_numbrs):
  # Inside the loop, apply random.choice() method for the above given tuple and
  # store it in a variable.
    reslt = random.choice(gvn_tupl)
   # Print the given numbers of random elements to be generated.
    print(reslt)

Output:

The given 3 Random numbers are :
btechgeeks
[7, 8, 5, 33]
321

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.

 

Union of sets python – Python Program to Union of Set of Tuples

Python Program to Union of Set of Tuples

Union of sets python: In this tutorial, we will learn how to calculate the union of sets of tuples in Python. Let us begin by defining the union in set theory.
The set of every element in the collection of sets is the set of the union of sets. In the case of duplicate elements in different sets, the final union will only contain the specific element once. The letter ‘U’ represents the union.
This problem is centered on finding the union of sets of tuples, which indicates that the set is made up of tuple elements.

Examples:

Example1:

Input:

first = {('hello', 5), ('this', 100)}
second = {('this', 100), ('is', 200)}
third = {('hello', 5), ('btechgeeks', 461), ('python', 234)}

Output:

first Union Second =  {('is', 200), ('this', 100), ('hello', 5)}
Second Union third =  {('python', 234), ('is', 200), ('this', 100), ('hello', 5), ('btechgeeks', 461)}
first Union Second Union third =  {('python', 234), ('is', 200), ('this', 100), ('hello', 5), ('btechgeeks', 461)}

Program to Union of Set of Tuples in Python

Below are the ways to find the union of the set of tuples in Python.

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Method #1: Using  or( | ) operator

Approach:

  • Give the set of tuples as static input and store them in Separate Variables.
  • In Python, we may retrieve the union of a set of tuples by using the OR operator (|). In order to acquire the union of two variables, use the OR operator directly between them.
  • Calculate the union using | operator and store it in a variable.
  • Print the union.
  • The Exit of the Program.

Below is the implementation:

# Give the set of tuples as static input and store them in Separate Variables.
first = {('hello', 5), ('this', 100)}
second = {('this', 100), ('is', 200)}
third = {('hello', 5), ('btechgeeks', 461), ('python', 234)}

# In Python, we may retrieve the union of a set of tuples
# by using the OR operator (|). In order to acquire the union of two variables,
# use the OR operator directly between them.
# Calculate the union using | operator and store it in a variable.

reslt1 = second | third
reslt2 = first | second
reslt3 = first | second | third
# Print the union of first and second
print("first Union Second = ", reslt2)
# print the union of second and third
print("Second Union third = ", reslt1)
# print the union of first second and third.
print("first Union Second Union third = ", reslt3)

Output:

first Union Second =  {('this', 100), ('is', 200), ('hello', 5)}
Second Union third =  {('this', 100), ('hello', 5), ('btechgeeks', 461), ('python', 234), ('is', 200)}
first Union Second Union third =  {('this', 100), ('hello', 5), ('btechgeeks', 461), ('python', 234), ('is', 200)}

Method #2: Using union() method

Approach:

  • Give the set of tuples as static input and store them in Separate Variables.
  • The set union() method returns the union of the set variables supplied as parameters. The first set uses the dot operator (.) to call the union() method, and the other set variables are given as arguments.
  • Calculate the union using the union() method and store it in a variable.
  • Print the union.
  • The Exit of the Program.

Below is the implementation:

# Give the set of tuples as static input and store them in Separate Variables.
first = {('hello', 5), ('this', 100)}
second = {('this', 100), ('is', 200)}
third = {('hello', 5), ('btechgeeks', 461), ('python', 234)}

'''The set union() method returns the union of the set variables supplied as parameters.
The first set uses the dot operator (.) to call the union() method, and 
the other set variables are given as arguments.
Calculate the union using the union() method and store it in a variable.'''
reslt1 = second.union(third)
reslt2 = first.union(second)
reslt3 = first.union(second, third)
# Print the union of first and second
print("first Union Second = ", reslt2)
# print the union of second and third
print("Second Union third = ", reslt1)
# print the union of first second and third.
print("first Union Second Union third = ", reslt3)

Output:

first Union Second =  {('is', 200), ('this', 100), ('hello', 5)}
Second Union third =  {('python', 234), ('is', 200), ('this', 100), ('hello', 5), ('btechgeeks', 461)}
first Union Second Union third =  {('python', 234), ('is', 200), ('this', 100), ('hello', 5), ('btechgeeks', 461)}

Related Programs:

Python string to tuple – Python Program for Comma-separated String to Tuple

Program for Comma-separated String to Tuple

Python string to tuple: In the previous article, we have discussed Python Program to Shuffle Elements of a Tuple
Tuple in Python:

A tuple is an immutable list of objects. That means the elements of a tuple cannot be modified or changed while the program is running.

split() function:

Syntax: input string.split(seperator=None, maxsplit=-1)

Python split tuple: It delimits the string with the separator and returns a list of words from it. The maxsplit parameter specifies the maximum number of splits that can be performed. If it is -1 or not specified, all possible splits are performed.

Example:  Given string =  ‘hello btechgeeks goodmorning’.split()

Output : [‘hello’, ‘btechgeeks’, ‘goodmorning’ ]

Given a string and the task is to find a tuple with a comma-separated string.

Examples:

Example 1:

Input: 

Given String = 'good, morning, btechgeeks'     (static input)

Output:

Given input String =  good, morning, btechgeeks
A tuple with comma-separated string is :  ('good', ' morning', ' btechgeeks')

Example 2:

Input:

Given String = hello, btechgeeks, 123        (user input)

Output:

A tuple with comma-separated string is : ('hello', ' btechgeeks', ' 123')

Program for Comma-separated String to Tuple

Split a tuple python: Below are the ways to find a tuple with a comma-separated string.

Method #1: Using split() Method (Static input)

Approach:

  • Give the string as static input and store it in a variable.
  • Print the above-given input string.
  • Split the given input string separated by commas using the split() function and convert it into a tuple.
  • Store it in another variable.
  • Print the tuple with a comma-separated string.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'good, morning, btechgeeks'
# Print the above-given input string.
print("Given input String = ", gvn_str)
# Split the given input string separated by commas using the split() function
# and convert it into a tuple.
# Store it in another variable.
tupl = tuple(gvn_str.split(","))
# Print the tuple with a comma-separated string.
print("A tuple with comma-separated string is : ", tupl)

Output:

Given input String =  good, morning, btechgeeks
A tuple with comma-separated string is :  ('good', ' morning', ' btechgeeks')

Method #2: Using split() Method (User input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Print the above-given input string.
  • Split the given input string separated by commas using the split() function and convert it into a tuple.
  • Store it in another variable.
  • Print the tuple with a comma-separated string.
  • The Exit of the program.

Below is the implementation:

#Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Print the above-given input string.
print("Given input String = ", gvn_str)
# Split the given input string separated by commas using the split() function
# and convert it into a tuple.
# Store it in another variable.
tupl = tuple(gvn_str.split(","))
# Print the tuple with a comma-separated string.
print("A tuple with comma-separated string is : ", tupl)

Output:

Enter some random string = hello, btechgeeks, 123
Given input String = hello, btechgeeks, 123
A tuple with comma-separated string is : ('hello', ' btechgeeks', ' 123')

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.