Python

Python: Add a Column to an Existing CSV File

Methods to add a column to an existing CSV File

In this article, we will discuss how to add a column to an existing CSV file using csv.reader and csv.DictWriter  classes. Apart from appending the columns, we will also discuss how to insert columns in between other columns of the existing CSV file.

Original CSV file content

total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
  • Method 1-Add a column with the same values to an existing CSV file

In this, we see how we make one column and add it to our CSV file but all the values in this column are the same.

Steps will be to append a column in CSV file are,

  1. Open ‘input.csv’ file in read mode and create csv.reader object for this CSV file
  2. Open ‘output.csv’ file in write mode and create csv.writer object for this CSV file
  3. Using reader object, read the ‘input.csv’ file line by line
  4. For each row (read like a list ), append default text in the list.
  5. Write this updated list / row in the ‘output.csv’ using csv.writer object for this file.
  6. Close both input.csv and output.csv file.

Let see this with the help of an example

from csv import writer
from csv import reader
default_text = 'New column'
# Open the input_file in read mode and output_file in write mode
with open('example1.csv', 'r') as read_obj, \
        open('output_1.csv', 'w', newline='') as write_obj:
    # Create a csv.reader object from the input file object
    csv_reader = reader(read_obj)
    # Create a csv.writer object from the output file object
    csv_writer = writer(write_obj)
    # Read each row of the input csv file as list
    for row in csv_reader:
        # Append the default text in the row / list
        row.append(default_text)
        # Add the updated row / list to the output file
        csv_writer.writerow(row)
output_data=pd.read_csv('output_1.csv')
output_data.head()

Output

total_bill tip sex smoker day time size New column
0 16.99 1.01 Female No Sun Dinner 2 New column
1 10.34 1.66 Male No Sun Dinner 3 New column
2 21.01 3.50 Male No Sun Dinner 3 New column
3 23.68 3.31 Male No Sun Dinner 2 New column
4 24.59 3.61 Female No Sun Dinner 4 New column

Here we see that new column is added but all value in this column is same.

Now we see how we can add different values in the column.

  •  Method 2-Add a column to an existing CSV file, based on values from other columns

In this method how we can make a new column but in this column the value we add will be a combination of two or more columns. As we know there is no direct function to achieve so we have to write our own function to achieve this task. Let see the code for this.

from csv import writer
from csv import reader
def add_column_in_csv(input_file, output_file, transform_row):
    """ Append a column in existing csv using csv.reader / csv.writer classes"""
    # Open the input_file in read mode and output_file in write mode
    with open(input_file, 'r') as read_obj, \
            open(output_file, 'w', newline='') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        # Read each row of the input csv file as list
        for row in csv_reader:
            # Pass the list / row in the transform function to add column text for this row
            transform_row(row, csv_reader.line_num)
            # Write the updated row / list to the output file
            csv_writer.writerow(row)
add_column_in_csv('example1.csv', 'output_2.csv', lambda row, line_num: row.append(row[0] + '__' + row[1]))
output_data=pd.read_csv('output_2.csv')
output_data.head()

Output

total_bill tip sex smoker day time size total_bill__tip
0 16.99 1.01 Female No Sun Dinner 2 16.99__1.01
1 10.34 1.66 Male No Sun Dinner 3 10.34__1.66
2 21.01 3.50 Male No Sun Dinner 3 21.01__3.5
3 23.68 3.31 Male No Sun Dinner 2 23.68__3.31
4 24.59 3.61 Female No Sun Dinner 4 24.59__3.61

Here we see the new column is formed as the combination of the values of the 1st and 2nd column.

Explanation:

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is a merger of the first and second value of the list. It appended the column in the contents of example1.csv by merging values of the first and second columns and then saved the changes as output_2.csv files.

  • Method 3-Add a list as a column to an existing csv file

In this method, we will add our own value in the column by making a list of our values and pass this into the function that we will make. Let see the code for this.

from csv import writer
from csv import reader
def add_column_in_csv(input_file, output_file, transform_row):
    """ Append a column in existing csv using csv.reader / csv.writer classes"""
    # Open the input_file in read mode and output_file in write mode
    with open(input_file, 'r') as read_obj, \
            open(output_file, 'w', newline='') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        # Read each row of the input csv file as list
        for row in csv_reader:
            # Pass the list / row in the transform function to add column text for this row
            transform_row(row, csv_reader.line_num)
            # Write the updated row / list to the output file
            csv_writer.writerow(row)
l=[]
l.append("New Column")
rows = len(data.axes[0])
for i in range(rows):
    val=i+1
    l.append(val)
add_column_in_csv('example1.csv', 'output_3.csv', lambda row, line_num: row.append(l[line_num - 1]))
output_data=pd.read_csv('output_3.csv')
output_data.head()

Output

total_bill tip sex smoker day time size New Column
0 16.99 1.01 Female No Sun Dinner 2 1
1 10.34 1.66 Male No Sun Dinner 3 2
2 21.01 3.50 Male No Sun Dinner 3 3
3 23.68 3.31 Male No Sun Dinner 2 4
4 24.59 3.61 Female No Sun Dinner 4 5

Explanation

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is an entry from our list l at index  line_num – 1.Thus all the entries in the list l are added as a column in the CSV.

So these are some of the methods to add new column in csv.

Python: How to create a zip archive from multiple files or Directory

Method to create zip archive from multiple files or directory in python

In this article, we discuss how we can create a zip archive of multiple files or directories in python. To understand this let us understand about ZipFile class.

ZipFile class

To execute this program we have to import ZipFile class of zipfile module.ZipFile is a class of zipfile modules for reading and writing zip files.

syntax: zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True)

Create a zip archives of multiples file

    • Method 1:Without using with statement

Let us first write the program and then see how code works.

from zipfile import ZipFile
# create a ZipFile object
zipObj = ZipFile('sample.zip', 'w')
# Add multiple files to the zip
zipObj.write('file1.txt')
zipObj.write('file2.txt')
# close the Zip File
zipObj.close()

Output

Directory structure before the execution of the program

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:06 216 zip.py

Directory structure after the execution of the program

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:09 239 sample.zip
-a---- 10-06-2021 19:09 216 zip.py

Here we clearly see that a zip file is created.

Let see how the program works. First, we create a ZipFile object bypassing the new file name and mode as ‘w’ (write mode). It will create a new zip file and open it within the ZipFile object. Then we use Call write() function on ZipFile object to add the files in it and then call close() on ZipFile object to Close the zip file.

  • Method 2:Using with statement

The difference between this and the previous method is that when we didn’t use with the statement then we have to close the zip file when the ZipFile object goes out of scope but when we use with statement the zip file automatically close when the ZipFile object goes out of scope. Let see the code for this.

from zipfile import ZipFile
# Create a ZipFile Object
with ZipFile('sample2.zip', 'w') as zipObj:
   # Add multiple files to the zip
   zipObj.write('file1.txt')
   zipObj.write('file2.txt')

Output

Directory structure before the execution of the program

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:09 239 sample.zip
-a---- 10-06-2021 19:21 429 zip.py

Directory structure after the execution of the program

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:09 239 sample.zip
-a---- 10-06-2021 19:24 239 sample2.zip
-a---- 10-06-2021 19:24 429 zip.py

Here we see that another zip file is created.

Create a zip archive of the directory

To zip selected files from a directory we need to check the condition on each file path while iteration before adding it to the zip file. As here we work on directory and file so we also have to import os module. Let see the code for this.

from zipfile import ZipFile
import os
from os.path import basename
# create a ZipFile object
dirName="../zip"
with ZipFile('sampleDir.zip', 'w') as zipObj:
   # Iterate over all the files in directory
   for folderName, subfolders, filenames in os.walk(dirName):
       for filename in filenames:
           #create complete filepath of file in directory
           filePath = os.path.join(folderName, filename)
           # Add file to zip
           zipObj.write(filePath, basename(filePath))

Output

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:09 239 sample.zip
-a---- 10-06-2021 19:24 239 sample2.zip
-a---- 10-06-2021 21:44 2796 sampleDir.zip
-a---- 10-06-2021 19:24 429 zip.py
-a---- 10-06-2021 21:44 506 zipdir.py

Here we see that the sampleDir.zip file is created.

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

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

Dictionaries in Python:

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:

Program to Check if a Date is Valid and Print the Incremented Date

Python Program to Check if a Date is Valid and Print the Incremented Date

Given a date , the task is to Check if a Date is Valid and increment the given date and print it in python

Examples:

Example1:

Input:

given date ="11/02/2001"

Output:

The incremented given date is:  12 / 2 / 2001

Example2:

Input:

 given date = "29/02/2001"

Output:

The given date 29/02/2001 is not valid

Program to Check and Print the Incremented Date in Python

Below are the ways to check and implement the increment the given date in 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)By using if..elif..else Conditional Statements  and split() function(Static Input)

Approach:

  • Give the date in the format dd/mm/yyyy as static input
  • Separate the date by storing the day, month, and year in different variables.
  • Check the validity of the day, month, and year using various if-statements.
  • If the date is valid, increment it .
  • Print the increment date.
  • Exit of Program.

Below is the implementation:

# given given_data
given_date = "11/02/2001"
# splitting the given_data by / character to separate given_data,month and year
day, month, year = given_date.split('/')
day = int(day)
month = int(month)
year = int(year)
if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
    maxdays = 31
elif(month == 4 or month == 6 or month == 9 or month == 11):
    maxdays = 30
elif(year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
    maxdays = 29
else:
    maxdays = 28
if(month < 1 or month > 12):
    print("The given date", given_date, "is not valid")
elif(day < 1 or day > maxdays):
    print("The given date", given_date, "is not valid")
elif(day == maxdays and month != 12):
    day = 1
    month = month+1
    print("The incremented given date is: ", day, month, year)
elif(day == 31 and month == 12):
    day = 1
    month = 1
    year = year+1
    print("The incremented given date is: ", day, '/', month, '/', year)
else:
    day = day + 1
    print("The incremented given date is: ",  day, '/', month, '/', year)

Output:

The incremented given date is:  12 / 2 / 2001

Explanation:

  • Give the date in the format dd/mm/yyyy as static input.
  • The date is then divided, with the day, month, and year recorded in separate variables.
  • The date is invalid if it is not between 1 and 30 in the months of April, June, September, and November.
  • The date is invalid if it is not between 1 and 31 for the months of January, March, April, May, July, August, October, and December.
  • If the month is February, the day should be between 1 and 28 for non-leap years and between 1 and 29 for leap years.
  • If the date is correct, it should be increased.
  • The final incremented date is printed

2)By using if..elif..else Conditional Statements  and split() function(User Input)

Approach:

  • Scan the date, month and year as int(input()).
  • Separate the date by storing the day, month, and year in different variables.
  • Check the validity of the day, month, and year using various if-statements.
  • If the date is valid, increment it .
  • Print the increment date.
  • Exit of Program.

Below is the implementation:

# Scan the date, month and year as int(input()).
day = int(input("Enter some random day = "))
month = int(input("Enter some random month = "))
year = int(input("Enter some random year = "))
if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
    maxdays = 31
elif(month == 4 or month == 6 or month == 9 or month == 11):
    maxdays = 30
elif(year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
    maxdays = 29
else:
    maxdays = 28
if(month < 1 or month > 12):
    print("The given date", given_date, "is not valid")
elif(day < 1 or day > maxdays):
    print("The given date", given_date, "is not valid")
elif(day == maxdays and month != 12):
    day = 1
    month = month+1
    print("The incremented given date is: ", day, month, year)
elif(day == 31 and month == 12):
    day = 1
    month = 1
    year = year+1
    print("The incremented given date is: ", day, '/', month, '/', year)
else:
    day = day + 1
    print("The incremented given date is: ",  day, '/', month, '/', year)

Output:

Enter some random day = 11
Enter some random month = 2
Enter some random year = 2001
The incremented given date is: 12 / 2 / 2001

Related Programs:

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 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

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:

Program to Print all Numbers in a Range Divisible by a Given Number

Python Program to Print all Numbers in a Range Divisible by a Given Number

Given three integers, the task is to print all values in the given range that are divisible by the third number, where the first number specifies the lower limit and the second number specifies the upper limit.

Examples:

Example1:

Input:

lower limit = 1 
upper limit = 263 
given number = 5

Output:

The numbers which are divisible by 5 from 17 to 263 are:
20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135 140 145 150 155 160 165 
170 175 180 185 190 195 200 205 210 215 220 225 230 235 240 245 250 255 260

Example2:

Input:

Enter the lower limit = 37 
Enter the upper limit = 217 
Enter the given number = 3

Output:

The numbers which are divisible by 3 from 37 to 217 are:
39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 102 105 108 111
114 117 120 123 126 129 132 135 138 141 144 147 150 153 156 159 162 165 168 
171 174 177 180 183 186 189 192 195 198 201 204 207 210 213 216

Example3:

Input:

Enter the lower limit = 128
Enter the upper limit = 659
Enter the given number = 7

Output:

The numbers which are divisible by 7 from 128 to 659 are:
133 140 147 154 161 168 175 182 189 196 203 210 217 224 231 238 245 252 259 266 273 280 287 294 301 308 
315 322 329 336 343 350 357 364 371 378 385 392 399 406 413 420 427 434 441 448 455 462 469 476 483 490 
497 504 511 518 525 532 539 546 553 560 567 574 581 588 595 602 609 616 623 630 637 644 651 658

Program to Print all Numbers in a Range Divisible by a Given Number in Python

There are several ways to print all the numbers in the given range which are divisible by the given number 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 for loop(Static Input)

Approach:

  • Give three numbers as static input.
  • Using for loop, loop from lower limit to upper limit.
  • Using an if conditional statement, determine whether the iterator value is divisible by the given number.
  • If it is divisible then print the iterator value.
  • Exit of program

Below is the implementation:

# given lower limit
lower_limit = 17
# given upper limit
upper_limit = 263
# given number
numb = 5
print("The numbers which are divisible by", numb,
      "from", lower_limit, "to", upper_limit, "are:")
# Using for loop, loop from lower limit to upper limit
for val in range(lower_limit, upper_limit):
    # Using an if conditional statement, determine whether
    # the iterator value is divisible by the given number.
    if(val % numb == 0):
        print(val, end=" ")

Output:

The numbers which are divisible by 5 from 17 to 263 are:
20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115 120 125 130 135 140 145 150 155 160 165 170 175 180 185 190 195 200 205 210 215 220 225 230 235 240 245 250 255 260

Method #2:Using for loop(User Input)

Approach:

  • Scan the lower limit, upper limit and the given number using int(input()).
  • Using for loop, loop from lower limit to upper limit.
  • Using an if conditional statement, determine whether the iterator value is divisible by the given number.
  • If it is divisible then print the iterator value.
  • Exit of program

Below is the implementation:

# Scanning the lower limit
lower_limit = int(input("Enter the lower limit = "))
# Scanning the upper limit
upper_limit = int(input("Enter the upper limit = "))
# Scanning the given number
numb = int(input("Enter the given number = "))
print("The numbers which are divisible by", numb,
      "from", lower_limit, "to", upper_limit, "are:")
# Using for loop, loop from lower limit to upper limit
for val in range(lower_limit, upper_limit):
    # Using an if conditional statement, determine whether
    # the iterator value is divisible by the given number.
    if(val % numb == 0):
        print(val, end=" ")

Output:

Enter the lower limit = 37
Enter the upper limit = 217
Enter the given number = 3
The numbers which are divisible by 3 from 37 to 217 are:
39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 102 105 108 111 114 117 120 123 126 129 132 135 138 141 144 147 150 153 156 159 162 165 168 171 174 177 180 183 186 189 192 195 198 201 204 207 210 213 216

Explanation:

  • The user must enter the upper and lower range limits.
  • The user is next required to provide the number to be divided from the user.
  • The value of i is between the lower and upper bounds.
  • Whenever the remainder of an integer divided by numb equals zero, the i is printed.

Method #3:Using While loop (User Input)

Approach:

  • Scan the lower limit, upper limit and the given number using int(input()).
  • Take a variable tempo and initialize it with lower limit.
  • Loop till tempo is less than upper limit using while loop.
  • Using an if conditional statement, determine whether the tempo value is divisible by the given number.
  • If it is divisible then print the iterator value.
  • Increment the tempo by 1
  • Exit of program

Below is the implementation:

# Scanning the lower limit
lower_limit = int(input("Enter the lower limit = "))
# Scanning the upper limit
upper_limit = int(input("Enter the upper limit = "))
# Scanning the given number
numb = int(input("Enter the given number = "))
# Take a variable tempo and initialize it with lower limit.
tempo = lower_limit
print("The numbers which are divisible by", numb,
      "from", lower_limit, "to", upper_limit, "are:")
# Loop till tempo is less than upper limit using while loop.
while(tempo < upper_limit):
    # Using an if conditional statement, determine whether
    # the tempo value is divisible by the given number.
    if(tempo % numb == 0):
        print(tempo, end=" ")
    # Increment the tempo by 1
    tempo = tempo+1

Output:

Enter the lower limit = 128
Enter the upper limit = 659
Enter the given number = 7
The numbers which are divisible by 7 from 128 to 659 are:
133 140 147 154 161 168 175 182 189 196 203 210 217 224 231 238 245 252 259 266 273 280 287 294 301 308 315 322 329 336 343 350 357 364 371 378 385 392 399 406 413 420 427 434 441 448 455 462 469 476 483 490 497 504 511 518 525 532 539 546 553 560 567 574 581 588 595 602 609 616 623 630 637 644 651 658

Related Programs:

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

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: Find Unique Values in a Numpy Array With Frequency and Indices

Methods to find unique values in a numpy array with frequency and indices

In this article, we will discuss how to find unique values, rows, and columns in a 1D & 2D Numpy array. Before going to the methods first we see numpy.unique() method because this method is going to be used.

numpy.unique() method

numpy.unique() method help us to get the unique() values from given array.

syntax:numpy.unique(array, return_index=False, return_inverse=False, return_counts=False, axis=None)

Parameters

  1. array-Here we have to pass our array from which we want to get unique value.
  2. return_index- If this parameter is true then it will return the array of the index of the first occurrence of each unique value. By default it is false.
  3. return_counts-If this parameter is true then it will return the array of the count of the occurrence of each unique value. By default it is false.
  4. axis- It is used in the case of nd array, not in 1d array. axis=1 means we have to do operation column-wise and axis=0 means we have to do operation row-wise.

Now we will see different methods to find unique value with their indices and frequencies in a numpy array.

case 1-When our array is 1-D

  • Method 1-Find unique value from the array

As we only need unique values and not their frequencies and indices hence we simply pass our numpy array in the unique() method because the default value of other parameters is false so we don’t need to change them. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values=np.unique(arr)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
  • Method 2-Find unique value from the array along with their indices

In this method, as we want to get unique values along with their indices hence we make the return_index parameter true and pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values,index=np.unique(arr,return_index=True)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)
print("First index of unique values are:")
print(index)

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
First index of unique values are:
[0 2 3 4 5 6 7]
  • Method 3-Find unique value from the array along with their frequencies

In this method, as we want to get unique values along with their frequencies hence we make the return_counts parameter true and pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values,count=np.unique(arr,return_counts=True)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)
print("Count of unique values are:")
for i in range(0,len(unique_values)):
  print("count of ",unique_values[i]," is ",count[i])

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
Count of unique values are:
count of  1  is  3
count of  2  is  2
count of  3  is  2
count of  4  is  2
count of  5  is  1
count of  6  is  1
count of  7  is  2

Case 2: When our array is 2-D

  • Method 1-Find unique value from the array

Here we simply pass our array and all the parameter remain the same. Here we don’t make any changes because we want to work on both rows and columns. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique values are
[1 2 3 6]

Method 2-Get unique rows

As here want to want to work only on rows so here we will make axis=0 and simply pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr,axis=0)
print("Original array is")
print(arr)
print("------------------")
print("Unique rows are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique rows are
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]]

Method 3-Get unique columns

As here want to want to work only on columns so here we will make axis=1 and simply pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr,axis=1)
print("Original array is")
print(arr)
print("------------------")
print("Unique columns are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique columns are
[[1 1 2]
 [1 3 2]
 [1 6 2]
 [1 1 2]]

so these are the methods to find unique values in a numpy array with frequency and indices.

 

Random Choice of Random Module in Python with no Repeat

Random Choice of Random Module in Python with 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:

Python Program to Union of Set of Tuples

Python Program to Union of Set of Tuples

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: