<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Python Archives - Python Programs</title>
	<atom:link href="https://python-programs.com/category/python/python-python/feed/" rel="self" type="application/rss+xml" />
	<link>https://python-programs.com/category/python/python-python/</link>
	<description>Python Programs with Examples, How To Guides on Python</description>
	<lastBuildDate>Fri, 10 Nov 2023 06:51:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.5</generator>
<site xmlns="com-wordpress:feed-additions:1">196068054</site>	<item>
		<title>Python: Add a Column to an Existing CSV File</title>
		<link>https://python-programs.com/python-add-a-column-to-an-existing-csv-file/</link>
		
		<dc:creator><![CDATA[Mayank Gupta]]></dc:creator>
		<pubDate>Tue, 07 Nov 2023 13:02:22 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=9179</guid>

					<description><![CDATA[<p>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 [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-add-a-column-to-an-existing-csv-file/">Python: Add a Column to an Existing CSV File</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Methods to add a column to an existing CSV File</h2>
<p>In this article, we will discuss how to add a column to an existing CSV file using <code>csv.reader</code> and <code>csv.DictWriter</code>  classes. Apart from appending the columns, we will also discuss how to insert columns in between other columns of the existing CSV file.<span id="more-4283"></span></p>
<h3>Original CSV file content</h3>
<div class="cell code_cell rendered selected">
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_html rendered_html output_result">
<table class="dataframe" border="1">
<thead>
<tr>
<th></th>
<th>total_bill</th>
<th>tip</th>
<th>sex</th>
<th>smoker</th>
<th>day</th>
<th>time</th>
<th>size</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>16.99</td>
<td>1.01</td>
<td>Female</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>2</td>
</tr>
<tr>
<th>1</th>
<td>10.34</td>
<td>1.66</td>
<td>Male</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>3</td>
</tr>
<tr>
<th>2</th>
<td>21.01</td>
<td>3.50</td>
<td>Male</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>3</td>
</tr>
<tr>
<th>3</th>
<td>23.68</td>
<td>3.31</td>
<td>Male</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>2</td>
</tr>
<tr>
<th>4</th>
<td>24.59</td>
<td>3.61</td>
<td>Female</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>4</td>
</tr>
</tbody>
</table>
<ul>
<li>
<h3>Method 1-Add a column with the same values to an existing CSV file</h3>
</li>
</ul>
<p>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.</p>
<p>Steps will be to append a column in CSV file are,</p>
<ol>
<li>Open ‘input.csv’ file in read mode and create csv.reader object for this CSV file</li>
<li>Open ‘output.csv’ file in write mode and create csv.writer object for this CSV file</li>
<li>Using reader object, read the ‘input.csv’ file line by line</li>
<li>For each row (read like a list ), append default text in the list.</li>
<li>Write this updated list / row in the ‘output.csv’ using csv.writer object for this file.</li>
<li>Close both input.csv and output.csv file.</li>
</ol>
<p>Let see this with the help of an example</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">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()</pre>
<p>Output</p>
<table class="dataframe" border="1">
<thead>
<tr>
<th></th>
<th>total_bill</th>
<th>tip</th>
<th>sex</th>
<th>smoker</th>
<th>day</th>
<th>time</th>
<th>size</th>
<th>New column</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>16.99</td>
<td>1.01</td>
<td>Female</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>2</td>
<td>New column</td>
</tr>
<tr>
<th>1</th>
<td>10.34</td>
<td>1.66</td>
<td>Male</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>3</td>
<td>New column</td>
</tr>
<tr>
<th>2</th>
<td>21.01</td>
<td>3.50</td>
<td>Male</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>3</td>
<td>New column</td>
</tr>
<tr>
<th>3</th>
<td>23.68</td>
<td>3.31</td>
<td>Male</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>2</td>
<td>New column</td>
</tr>
<tr>
<th>4</th>
<td>24.59</td>
<td>3.61</td>
<td>Female</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>4</td>
<td>New column</td>
</tr>
</tbody>
</table>
<p>Here we see that new column is added but all value in this column is same.</p>
<p>Now we see how we can add different values in the column.</p>
<ul>
<li>
<h3> Method 2-Add a column to an existing CSV file, based on values from other columns</h3>
</li>
</ul>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">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()</pre>
<p>Output</p>
<table class="dataframe" border="1">
<thead>
<tr>
<th></th>
<th>total_bill</th>
<th>tip</th>
<th>sex</th>
<th>smoker</th>
<th>day</th>
<th>time</th>
<th>size</th>
<th>total_bill__tip</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>16.99</td>
<td>1.01</td>
<td>Female</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>2</td>
<td>16.99__1.01</td>
</tr>
<tr>
<th>1</th>
<td>10.34</td>
<td>1.66</td>
<td>Male</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>3</td>
<td>10.34__1.66</td>
</tr>
<tr>
<th>2</th>
<td>21.01</td>
<td>3.50</td>
<td>Male</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>3</td>
<td>21.01__3.5</td>
</tr>
<tr>
<th>3</th>
<td>23.68</td>
<td>3.31</td>
<td>Male</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>2</td>
<td>23.68__3.31</td>
</tr>
<tr>
<th>4</th>
<td>24.59</td>
<td>3.61</td>
<td>Female</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>4</td>
<td>24.59__3.61</td>
</tr>
</tbody>
</table>
<p>Here we see the new column is formed as the combination of the values of the 1st and 2nd column.</p>
<p>Explanation:</p>
<p>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.</p>
<ul>
<li>
<h3>Method 3-Add a list as a column to an existing csv file</h3>
</li>
</ul>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">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()</pre>
<p>Output</p>
<div class="cell code_cell rendered selected">
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_html rendered_html output_result">
<div>
<table class="dataframe" border="1">
<thead>
<tr>
<th></th>
<th>total_bill</th>
<th>tip</th>
<th>sex</th>
<th>smoker</th>
<th>day</th>
<th>time</th>
<th>size</th>
<th>New Column</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>16.99</td>
<td>1.01</td>
<td>Female</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<th>1</th>
<td>10.34</td>
<td>1.66</td>
<td>Male</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>3</td>
<td>2</td>
</tr>
<tr>
<th>2</th>
<td>21.01</td>
<td>3.50</td>
<td>Male</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>3</td>
<td>3</td>
</tr>
<tr>
<th>3</th>
<td>23.68</td>
<td>3.31</td>
<td>Male</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>2</td>
<td>4</td>
</tr>
<tr>
<th>4</th>
<td>24.59</td>
<td>3.61</td>
<td>Female</td>
<td>No</td>
<td>Sun</td>
<td>Dinner</td>
<td>4</td>
<td>5</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<p>Explanation</p>
<p>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 <em>list l </em>are added as a column in the CSV.</p>
<p>So these are some of the methods to add new column in csv.</p>
</div>
</div>
</div>
</div>
</div>
<p>The post <a href="https://python-programs.com/python-add-a-column-to-an-existing-csv-file/">Python: Add a Column to an Existing CSV File</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">9179</post-id>	</item>
		<item>
		<title>Python: How to create a zip archive from multiple files or Directory</title>
		<link>https://python-programs.com/python-how-to-create-a-zip-archive-from-multiple-files-or-directory/</link>
		
		<dc:creator><![CDATA[Mayank Gupta]]></dc:creator>
		<pubDate>Tue, 07 Nov 2023 13:02:20 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8598</guid>

					<description><![CDATA[<p>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 [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-how-to-create-a-zip-archive-from-multiple-files-or-directory/">Python: How to create a zip archive from multiple files or Directory</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Method to create zip archive from multiple files or directory in python</h2>
<p>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.</p>
<h3>ZipFile class</h3>
<p>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.</p>
<p><code>syntax: zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True)</code></p>
<h3>Create a zip archives of multiples file</h3>
<ul>
<li>
<ul>
<li>
<h3>Method 1:Without using with statement</h3>
</li>
</ul>
</li>
</ul>
<p>Let us first write the program and then see how code works.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">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()</pre>
<p>Output</p>
<p>Directory structure before the execution of the program</p>
<pre>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</pre>
<p>Directory structure after the execution of the program</p>
<pre>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</pre>
<p>Here we clearly see that a zip file is created.</p>
<p>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.</p>
<ul>
<li>
<h3>Method 2:Using with statement</h3>
</li>
</ul>
<p>The difference between this and the previous method is that when we didn&#8217;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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">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')</pre>
<p>Output</p>
<p>Directory structure before the execution of the program</p>
<pre>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</pre>
<p>Directory structure after the execution of the program</p>
<pre>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</pre>
<p>Here we see that another zip file is created.</p>
<h3>Create a zip archive of the directory</h3>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">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))</pre>
<p>Output</p>
<pre>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</pre>
<p>Here we see that the sampleDir.zip file is created.</p>
<p>The post <a href="https://python-programs.com/python-how-to-create-a-zip-archive-from-multiple-files-or-directory/">Python: How to create a zip archive from multiple files or Directory</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8598</post-id>	</item>
		<item>
		<title>Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary</title>
		<link>https://python-programs.com/python-program-to-count-the-frequency-of-words-appearing-in-a-string-using-a-dictionary/</link>
		
		<dc:creator><![CDATA[Vikram Chiluka]]></dc:creator>
		<pubDate>Sat, 04 Nov 2023 05:41:45 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8830</guid>

					<description><![CDATA[<p>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 [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-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</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><strong>Dictionaries in Python:</strong></p>
<p>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.</p>
<p><strong>Examples:</strong></p>
<p><strong>Example1:</strong></p>
<p><strong>Input:</strong></p>
<pre>given string ="hello this is hello BTechGeeks BTechGeeks BTechGeeks this python programming python language"</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">{'hello': 2, 'this': 2, 'is': 1, 'BTechGeeks': 3, 'python': 2, 'programming': 1, 'language': 1}</pre>
<p><strong>Example2:</strong></p>
<p><strong>Input:</strong></p>
<pre>given string ="good morning this is good this python python BTechGeeks good good python online coding platform"</pre>
<p><strong>Output:</strong></p>
<pre>{'good': 4, 'morning': 1, 'this': 2, 'is': 1, 'python': 3, 'BTechGeeks': 1, 'online': 1, 'coding': 1, 'platform': 1}</pre>
<h2>Program to Count the Frequency of Words Appearing in a String Using a Dictionary</h2>
<p>There are several ways to count the frequency of all words in the given string using dictionary some of them are:</p>
<ul>
<li><a href="#Using_count_and_zip_function_(Static_Input)">Using count and zip function (Static Input)</a></li>
<li><a href="#Using_count_and_zip_function_(User_Input)">Using count and zip function (User Input)</a></li>
</ul>
<p>Drive into <a href="https://python-programs.com/python-programming-examples-with-output/">Python Programming Examples</a> and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.</p>
<h3 id="Using_count_and_zip_function_(Static_Input)">Method #1:Using count and zip function (Static Input)</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Give the string input as static and store it in a variable</li>
<li>Split the given string into words using split() function</li>
<li>Convert this into list using list() function.</li>
<li>Count the frequency of each term using count() function and save the results in a separate list using list Comprehension.</li>
<li>Merge the lists containing the terms and the word counts into a dictionary using the zip() function.</li>
<li>The resultant dictionary is printed</li>
<li>End of Program</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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)
</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">{'hello': 2, 'this': 2, 'is': 1, 'BTechGeeks': 3, 'python': 2, 'programming': 1, 'language': 1}</pre>
<p><strong>Explanation:<br />
</strong></p>
<ul>
<li>A string must be entered by the user and saved in a variable.</li>
<li>The string is divided into words and saved in the list using a space as the reference.</li>
<li>Using list comprehension and the count() function, the frequency of each word in the list is counted.</li>
<li>The complete dictionary is printed after being created with the zip() method.</li>
</ul>
<h3 id="Using_count_and_zip_function_(User_Input)">Method #2:Using count and zip function (User Input)</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Scan the string using <strong>input()</strong> function.</li>
<li>Split the given string into words using split() function</li>
<li>Convert this into list using list() function.</li>
<li>Count the frequency of each term using count() function and save the results in a separate list using list Comprehension.</li>
<li>Merge the lists containing the terms and the word counts into a dictionary using the zip() function.</li>
<li>The resultant dictionary is printed</li>
<li>End of Program</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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)
</pre>
<p><strong>Output:</strong></p>
<pre>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}</pre>
<p><strong>Related Programs</strong>:</p>
<ul>
<li style="list-style-type: none"></li>
<li><a href="https://python-programs.com/python-program-to-read-a-file-and-capitalize-the-first-letter-of-every-word-in-the-file/">Python Program to Read a File and Capitalize the First Letter of Every Word in the File</a></li>
<li><a href="https://python-programs.com/python-program-to-map-two-lists-into-a-dictionary/">Python Program to Map Two Lists into a Dictionary</a></li>
<li><a href="https://python-programs.com/python-program-to-generate-a-dictionary-that-contains-numbers-between-1-and-n-in-the-form-x-xx/">Python Program to Generate a Dictionary that Contains Numbers (between 1 and n) in the Form (x, x*x).</a></li>
<li><a href="https://python-programs.com/python-program-to-add-a-key-value-pair-to-the-dictionary/">Python Program to Add a Key, Value Pair to the Dictionary</a></li>
<li><a href="https://python-programs.com/python-program-to-sum-all-the-items-in-a-dictionary/">Python Program to Sum All the Items in a Dictionary</a></li>
</ul>
<p>The post <a href="https://python-programs.com/python-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</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8830</post-id>	</item>
		<item>
		<title>Python Program to Check if a Date is Valid  and Print the Incremented Date</title>
		<link>https://python-programs.com/python-program-to-check-if-a-date-is-valid-and-print-the-incremented-date/</link>
		
		<dc:creator><![CDATA[Vikram Chiluka]]></dc:creator>
		<pubDate>Sat, 04 Nov 2023 05:41:33 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8790</guid>

					<description><![CDATA[<p>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 [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-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</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Given a date , the task is to Check if a Date is Valid and increment the given date and print it in python</p>
<p><strong>Examples:</strong></p>
<p><strong>Example1:</strong></p>
<p><strong>Input:</strong></p>
<pre>given date ="11/02/2001"</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">The incremented given date is:  12 / 2 / 2001</pre>
<p><strong>Example2:</strong></p>
<p><strong>Input:</strong></p>
<pre> given date = "29/02/2001"</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">The given date 29/02/2001 is not valid</pre>
<h2>Program to Check and Print the Incremented Date in Python</h2>
<p>Below are the ways to check and implement the increment the given date in Python:</p>
<ul>
<li><a href="#By_using_if..elif..else_Conditional_Statements_and_split()_function(Static_Input)">By using if..elif..else Conditional Statements and split() function(Static Input)</a></li>
<li><a href="#By_using_if..elif..else_Conditional_Statements_and_split()_function(User_Input)">By using if..elif..else Conditional Statements and split() function(User Input)</a></li>
</ul>
<p>Drive into <a href="https://python-programs.com/python-programming-examples-with-output/">Python Programming Examples</a> and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.</p>
<h3 id="By_using_if..elif..else_Conditional_Statements_and_split()_function(Static_Input)">1)By using if..elif..else Conditional Statements  and split() function(Static Input)</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Give the date in the format <strong>dd/mm/yyyy</strong> as static input</li>
<li>Separate the date by storing the day, month, and year in different variables.</li>
<li>Check the validity of the day, month, and year using various if-statements.</li>
<li>If the date is valid, increment it .</li>
<li>Print the increment date.</li>
<li>Exit of Program.</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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 &lt; 1 or month &gt; 12):
    print("The given date", given_date, "is not valid")
elif(day &lt; 1 or day &gt; 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)
</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">The incremented given date is:  12 / 2 / 2001</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>Give the date in the format <strong>dd/mm/yyyy</strong> as static input.</li>
<li>The date is then divided, with the day, month, and year recorded in separate variables.</li>
<li>The date is invalid if it is not between 1 and 30 in the months of April, June, September, and November.</li>
<li>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.</li>
<li>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.</li>
<li>If the date is correct, it should be increased.</li>
<li>The final incremented date is printed</li>
</ul>
<h3 id="By_using_if..elif..else_Conditional_Statements_and_split()_function(User_Input)">2)By using if..elif..else Conditional Statements  and split() function(User Input)</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Scan the date, month and year as<strong> int(input()).</strong></li>
<li>Separate the date by storing the day, month, and year in different variables.</li>
<li>Check the validity of the day, month, and year using various if-statements.</li>
<li>If the date is valid, increment it .</li>
<li>Print the increment date.</li>
<li>Exit of Program.</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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 &lt; 1 or month &gt; 12):
    print("The given date", given_date, "is not valid")
elif(day &lt; 1 or day &gt; 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)
</pre>
<p><strong>Output:</strong></p>
<pre>Enter some random day = 11
Enter some random month = 2
Enter some random year = 2001
The incremented given date is: 12 / 2 / 2001</pre>
<p><strong>Related Programs</strong>:</p>
<ul>
<li><a href="https://python-programs.com/python-program-to-check-if-a-string-is-palindrome-or-not/">Python program to check if a string is palindrome or not</a></li>
<li><a href="https://python-programs.com/the-difference-between-and-is-in-python/">The difference between == and is in Python</a></li>
<li><a href="https://python-programs.com/python-program-to-find-whether-a-number-is-a-power-of-two/">Python Program to Find Whether a Number is a Power of Two</a></li>
<li><a href="https://python-programs.com/python-program-to-check-whether-the-given-number-is-strong-number-or-not/">Python Program to Check Whether the given Number is Strong Number or Not</a></li>
<li><a href="https://python-programs.com/python-program-to-check-whether-the-given-number-is-perfect-number-or-not/">Python Program to Check Whether the given Number is Perfect Number or Not</a></li>
</ul>
<p>The post <a href="https://python-programs.com/python-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</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8790</post-id>	</item>
		<item>
		<title>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</title>
		<link>https://python-programs.com/python-program-to-form-an-integer-that-has-the-number-of-digits-at-tens-place-and-the-least-significant-digit-of-the-entered-integer-at-ones-place/</link>
		
		<dc:creator><![CDATA[Vikram Chiluka]]></dc:creator>
		<pubDate>Sat, 04 Nov 2023 05:41:28 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8771</guid>

					<description><![CDATA[<p>Given a number which is integer , the task is to create an integer with the number of digits at ten&#8217;s place and the least significant digit of the entered integer at one&#8217;s place. Examples: Example1: Input: given number = 37913749 Output: The required number = 89 Example2: Input: given number =78329942 Output: The required [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-program-to-form-an-integer-that-has-the-number-of-digits-at-tens-place-and-the-least-significant-digit-of-the-entered-integer-at-ones-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</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Given a number which is integer , the task is to create an integer with the number of digits at ten&#8217;s place and the least significant digit of the entered integer at one&#8217;s place.</p>
<p><strong>Examples:</strong></p>
<p><strong>Example1:</strong></p>
<p><strong>Input:</strong></p>
<p>given number = 37913749</p>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">The required number = 89</pre>
<p><strong>Example2:</strong></p>
<p><strong>Input:</strong></p>
<pre> given number =78329942</pre>
<p><strong>Output:</strong></p>
<pre>The required number = 82</pre>
<h2>Create an integer with the number of digits at ten&#8217;s place and the least significant digit of the entered integer at one&#8217;s place in Python</h2>
<p>There are several ways to create an integer with the number of digits at ten&#8217;s place and the least significant digit of the entered integer at one&#8217;s place some of them are:</p>
<ul>
<li><a href="#Using_while_loop_and_String_Conversion_(_Static_Input)">Using while loop and String Conversion ( Static Input)</a></li>
<li><a href="#Using_while_loop_and_String_Conversion_(_User_Input)">Using while loop and String Conversion ( User Input)</a></li>
<li><a href="#Using_len()_and_indexing_by_converting_number_to_string_(Static_Input)">Using len() and indexing by converting number to string (Static Input)</a></li>
</ul>
<p>Drive into <a href="https://python-programs.com/python-programming-examples-with-output/">Python Programming Examples</a> and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.</p>
<h3 id="Using_while_loop_and_String_Conversion_(_Static_Input)">Method #1:Using while loop and String Conversion ( Static Input)</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Give a number as static input and store it in a variable.</li>
<li>Make a duplicate of the integer.</li>
<li>Take a variable which stores the count of digits and initialize it with 0</li>
<li>Using a while loop, calculate the number of digits in the given integer.</li>
<li>Convert the integer copy and the number of digits count to string.</li>
<li>Concatenate the integer&#8217;s last digit with the count.</li>
<li>The newly created integer should be printed.</li>
<li>Exit of program.</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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 &gt; 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)
</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">The required number = 89</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li>Give a number as static input and store it in a variable.</li>
<li>Because the original value of the variable would be modified for counting the number of digits, a copy of the variable is created.</li>
<li>The while loop is employed, and the modulus operator is utilized to get the last digit of the number.</li>
<li>The count value is incremented each time a digit is obtained.</li>
<li>The variable&#8217;s number of digits and the number are transformed to string for simplicity of concatenation.</li>
<li>The string&#8217;s final digit is then retrieved and concatenated to the count variable.</li>
<li>The newly generated number is then printed.</li>
</ul>
<h3 id="Using_while_loop_and_String_Conversion_(_User_Input)">Method #2:Using while loop and String Conversion ( User Input)</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Scan the given number using <strong>int(input())</strong> and store it in a variable.</li>
<li>Make a duplicate of the integer.</li>
<li>Take a variable which stores the count of digits and initialize it with 0</li>
<li>Using a while loop, calculate the number of digits in the given integer.</li>
<li>Convert the integer copy and the number of digits count to string.</li>
<li>Concatenate the integer&#8217;s last digit with the count .</li>
<li>The newly created integer should be printed.</li>
<li>Exit of program.</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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 &gt; 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)
</pre>
<p><strong>Output:</strong></p>
<pre>enter any number = 78329942
The required number = 82</pre>
<h3 id="Using_len()_and_indexing_by_converting_number_to_string_(Static_Input)">Method #3: Using len() and indexing by converting number to string (Static Input)</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Give a number as static input and store it in a variable.</li>
<li>Using the<strong> str()</strong> method, convert the given number to a string.</li>
<li>Determine the number of digits in the given number by computing the length of the string with the len() function.</li>
<li>Concatenate the integer&#8217;s last digit with the count.</li>
<li>The newly created integer should be printed.</li>
<li>Exit of program.</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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)
</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">The required number = 59</pre>
<p><strong>Related Programs</strong>:</p>
<ul>
<li><a href="https://python-programs.com/python-program-to-count-the-number-of-digits-present-in-a-number/">Python Program to Count the Number of Digits Present In a Number</a></li>
<li><a href="https://python-programs.com/python-program-to-accept-three-digits-and-print-all-possible-combinations-from-the-digits/">Python Program to Accept Three Digits and Print all Possible Combinations from the Digits</a></li>
<li><a href="https://python-programs.com/python-program-to-form-an-integer-that-has-the-number-of-digits-at-tens-place-and-the-least-significant-digit-of-the-entered-integer-at-ones-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</a></li>
<li><a href="https://python-programs.com/python-program-to-find-the-sum-of-the-digits-of-the-number-recursively/">Python Program to Find the Sum of the Digits of the Number Recursively</a></li>
<li><a href="https://python-programs.com/python-program-to-find-all-numbers-in-a-range-which-are-perfect-squares-and-sum-of-all-digits-in-the-number-is-less-than-10/">Python Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10</a></li>
</ul>
<p>The post <a href="https://python-programs.com/python-program-to-form-an-integer-that-has-the-number-of-digits-at-tens-place-and-the-least-significant-digit-of-the-entered-integer-at-ones-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</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8771</post-id>	</item>
		<item>
		<title>Python Program to Print all Numbers in a Range Divisible by a Given Number</title>
		<link>https://python-programs.com/python-program-to-print-all-numbers-in-a-range-divisible-by-a-given-number/</link>
		
		<dc:creator><![CDATA[Vikram Chiluka]]></dc:creator>
		<pubDate>Sat, 04 Nov 2023 05:41:19 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8734</guid>

					<description><![CDATA[<p>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 [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-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</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>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.</p>
<p><strong>Examples:</strong></p>
<p><strong>Example1:</strong></p>
<p><strong>Input:</strong></p>
<pre>lower limit = 1 
upper limit = 263 
given number = 5</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">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</pre>
<p><strong>Example2:</strong></p>
<p><strong>Input:</strong></p>
<pre>Enter the lower limit = 37 
Enter the upper limit = 217 
Enter the given number = 3</pre>
<p><strong>Output:</strong></p>
<pre>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</pre>
<p><strong>Example3:</strong></p>
<p><strong>Input:</strong></p>
<pre>Enter the lower limit = 128
Enter the upper limit = 659
Enter the given number = 7</pre>
<p><strong>Output:</strong></p>
<pre>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</pre>
<h2>Program to Print all Numbers in a Range Divisible by a Given Number in Python</h2>
<p>There are several ways to print all the numbers in the given range which are divisible by the given number some of them are:</p>
<ul>
<li><a href="#Using_for_loop(Static_Input)">Using for loop(Static Input)</a></li>
<li><a href="#Using_for_loop(User_Input)">Using for loop(User Input)</a></li>
<li><a href="#Using_While_loop_(User_Input)">Using While loop (User Input)</a></li>
</ul>
<p>Drive into <a href="https://python-programs.com/python-programming-examples-with-output/">Python Programming Examples</a> and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.</p>
<h3 id="Using_for_loop(Static_Input)">Method #1:Using for loop(Static Input)</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Give three numbers as static input.</li>
<li>Using for loop, loop from lower limit to upper limit.</li>
<li>Using an if conditional statement, determine whether the iterator value is divisible by the given number.</li>
<li>If it is divisible then print the iterator value.</li>
<li>Exit of program</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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=" ")
</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">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</pre>
<h3 id="Using_for_loop(User_Input)">Method #2:Using for loop(User Input)</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Scan the lower limit, upper limit and the given number using <strong>int(input()</strong>).</li>
<li>Using for loop, loop from lower limit to upper limit.</li>
<li>Using an if conditional statement, determine whether the iterator value is divisible by the given number.</li>
<li>If it is divisible then print the iterator value.</li>
<li>Exit of program</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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=" ")
</pre>
<p><strong>Output:</strong></p>
<pre>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</pre>
<p><strong>Explanation:</strong></p>
<blockquote>
<ul>
<li>The user must enter the upper and lower range limits.</li>
<li>The user is next required to provide the number to be divided from the user.</li>
<li>The value of i is between the lower and upper bounds.</li>
<li>Whenever the remainder of an integer divided by numb equals zero, the i is printed.</li>
</ul>
</blockquote>
<h3 id="Using_While_loop_(User_Input)">Method #3:Using While loop (User Input)</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Scan the lower limit, upper limit and the given number using <strong>int(input()</strong>).</li>
<li>Take a variable tempo and initialize it with lower limit.</li>
<li>Loop till tempo is less than upper limit using while loop.</li>
<li>Using an if conditional statement, determine whether the tempo value is divisible by the given number.</li>
<li>If it is divisible then print the iterator value.</li>
<li>Increment the tempo by 1</li>
<li>Exit of program</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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 &lt; 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
</pre>
<p><strong>Output:</strong></p>
<pre>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</pre>
<p><strong>Related Programs</strong>:</p>
<ul>
<li><a href="https://python-programs.com/python-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</a></li>
<li><a href="https://python-programs.com/program-to-determine-all-pythagorean-triplets-in-the-range-in-cpp-and-python/">Program to Determine all Pythagorean Triplets in the Range in C++ and Python</a></li>
<li><a href="https://python-programs.com/python-program-to-find-those-numbers-which-are-divisible-by-7-and-multiple-of-5-in-a-given-range-of-numbers/">Python Program to Find Those Numbers which are Divisible by 7 and Multiple of 5 in a Given Range of Numbers</a></li>
<li><a href="https://python-programs.com/python-program-to-sort-a-list-of-tuples-in-increasing-order-by-the-last-element-in-each-tuple/">Python Program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple</a></li>
<li><a href="https://python-programs.com/python-program-to-form-an-integer-that-has-the-number-of-digits-at-tens-place-and-the-least-significant-digit-of-the-entered-integer-at-ones-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</a></li>
</ul>
<p>The post <a href="https://python-programs.com/python-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</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8734</post-id>	</item>
		<item>
		<title>Program to Print Collatz Conjecture for a Given Number in C++ and Python</title>
		<link>https://python-programs.com/program-to-print-collatz-conjecture-for-a-given-number-in-cpp-and-python/</link>
		
		<dc:creator><![CDATA[Vikram Chiluka]]></dc:creator>
		<pubDate>Sat, 04 Nov 2023 05:39:52 +0000</pubDate>
				<category><![CDATA[CPP Programming]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8668</guid>

					<description><![CDATA[<p>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. [&#8230;]</p>
<p>The post <a href="https://python-programs.com/program-to-print-collatz-conjecture-for-a-given-number-in-cpp-and-python/">Program to Print Collatz Conjecture for a Given Number in C++ and Python</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In the previous article, we have discussed about <a href="https://python-programs.com/program-to-read-a-number-n-and-compute-n-nn-nnn-in-cpp-and-python/" target="_blank" rel="noopener">Program to Read a Number n and Compute n+nn+nnn in C++ and Python</a>. Let us learn Program to Print Collatz Conjecture for a Given Number in C++ Program.</p>
<p>Given a number , the task is to print Collatz Conjecture of the given number in C++ and Python.</p>
<p><strong>Collatz Conjecture:</strong></p>
<ul>
<li>The Collatz Conjecture states that a specific sequence will always reach the value 1.</li>
<li>It is given as follows, beginning with some integer n:</li>
<li>If n is an even number, the following number in the sequence is n/2.</li>
<li>Otherwise, the following number is 3n+1 (if n is odd).</li>
</ul>
<p><strong>Examples:</strong></p>
<p><strong>Example1:</strong></p>
<p><strong>Input:</strong></p>
<pre>given number =5425</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">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</pre>
<p><strong>Example2:</strong></p>
<p><strong>Input:</strong></p>
<pre>given number=847</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">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</pre>
<h2>Program to Print Collatz Conjecture for a Given Number in C++ and Python</h2>
<ul>
<li><a href="#Printing_Collatz_Conjecture_sequence_of_the_given_number_in_Python">Printing Collatz Conjecture sequence of the given number in Python</a></li>
<li><a href="#Printing_Collatz_Conjecture_sequence_of_the_given_number_in_C++">Printing Collatz Conjecture sequence of the given number in C++</a></li>
</ul>
<p>Drive into <a href="https://python-programs.com/python-programming-examples-with-output/">Python Programming Examples</a> and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.</p>
<h3 id="Printing_Collatz_Conjecture_sequence_of_the_given_number_in_Python">1)Printing Collatz Conjecture sequence of the given number in Python</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Scan the given number or give number as static input.</li>
<li>Iterate till the given number is not equal to 1 using while loop.</li>
<li>Print the number <strong>numb</strong>.</li>
<li>If the number is even then set n to n/2.</li>
<li>If the number is odd then set  n to 3*n+1.</li>
<li>Print 1 after end of while loop.</li>
<li>The Exit of the Program.</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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 &gt; 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)
</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">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</pre>
<h3 id="Printing_Collatz_Conjecture_sequence_of_the_given_number_in_C++">2)Printing Collatz Conjecture sequence of the given number in C++</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Scan the given number using cin or give number as static input</li>
<li>Iterate till the given number is not equal to 1 using while loop.</li>
<li>Print the number <strong>numb</strong>.</li>
<li>If the number is even then set n to n/2.</li>
<li>If the number is odd then set  n to 3*n+1.</li>
<li>Print 1 after end of while loop.</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="cpp">#include &lt;bits/stdc++.h&gt;
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 &gt; 1) {
        // Print the number numb
        cout &lt;&lt; numb &lt;&lt; " ";
        // 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 &lt;&lt; " 1";
}
int main()
{

    // given number
    int numb = 179;
    cout &lt;&lt; "The Collatz Conjecture of the number :"
         &lt;&lt; endl;
    // passing the given numb to printCollatz function to
    // print collatzConjecture sequence of the given number
    printCollatz(numb);
    return 0;
}</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">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</pre>
<p><strong>Related Programs</strong>:</p>
<ul>
<li><a href="https://python-programs.com/python-program-to-print-without-newline/">Python Program to Print Output Without a Newline</a></li>
<li><a href="https://python-programs.com/python-program-to-print-the-natural-numbers-summation-pattern/">Python Program to Print the Natural Numbers Summation Pattern</a></li>
<li><a href="https://python-programs.com/python-program-to-accept-three-digits-and-print-all-possible-combinations-from-the-digits/">Python Program to Accept Three Digits and Print all Possible Combinations from the Digits</a></li>
<li><a href="https://python-programs.com/python-program-to-print-binary-representation-of-a-number/">Python Program to Print Binary Representation of a Number</a></li>
<li><a href="https://python-programs.com/python-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</a></li>
</ul>
<p>The post <a href="https://python-programs.com/program-to-print-collatz-conjecture-for-a-given-number-in-cpp-and-python/">Program to Print Collatz Conjecture for a Given Number in C++ and Python</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8668</post-id>	</item>
		<item>
		<title>Python: Find Unique Values in a Numpy Array With Frequency and Indices</title>
		<link>https://python-programs.com/python-find-unique-values-in-a-numpy-array-with-frequency-and-indices/</link>
		
		<dc:creator><![CDATA[Mayank Gupta]]></dc:creator>
		<pubDate>Fri, 03 Nov 2023 02:49:26 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=8297</guid>

					<description><![CDATA[<p>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 &#38; 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() [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-find-unique-values-in-a-numpy-array-with-frequency-and-indices/">Python: Find Unique Values in a Numpy Array With Frequency and Indices</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Methods to find unique values in a numpy array with frequency and indices</h2>
<p>In this article, we will discuss how to find unique values, rows, and columns in a 1D &amp; 2D Numpy array. Before going to the methods first we see numpy.unique() method because this method is going to be used.</p>
<h3>numpy.unique() method</h3>
<p>numpy.unique() method help us to get the unique() values from given array.</p>
<p><code>syntax:<span class="enlighter-text">numpy.</span><span class="enlighter-m1">unique</span><span class="enlighter-g1">(</span><span class="enlighter-text">array, return_index=</span><span class="enlighter-e0">False</span><span class="enlighter-text">, return_inverse=</span><span class="enlighter-e0">False</span><span class="enlighter-text">, return_counts=</span><span class="enlighter-e0">False</span><span class="enlighter-text">, axis=</span><span class="enlighter-e1">None</span><span class="enlighter-g1">)</span></code></p>
<h3>Parameters</h3>
<ol>
<li>array-Here we have to pass our array from which we want to get unique value.</li>
<li>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.</li>
<li>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.</li>
<li>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.</li>
</ol>
<p>Now we will see different methods to find unique value with their indices and frequencies in a numpy array.</p>
<h3>case 1-When our array is 1-D</h3>
<ul>
<li>
<h3>Method 1-Find unique value from the array</h3>
</li>
</ul>
<p>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&#8217;t need to change them. Let see this with the help of an example.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">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)</pre>
<p>Output</p>
<pre class="jqconsole jqconsole-blurred"><span class="">Original array is
</span><span class="">[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]</span></pre>
<ul>
<li>
<h3>Method 2-Find unique value from the array along with their indices</h3>
</li>
</ul>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">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)</pre>
<p>Output</p>
<pre class="jqconsole jqconsole-blurred"><span class="">Original array is
</span><span class="">[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]</span></pre>
<ul>
<li>
<h3>Method 3-Find unique value from the array along with their frequencies</h3>
</li>
</ul>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">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])</pre>
<p>Output</p>
<pre class="jqconsole jqconsole-blurred"><span class="">Original array is
</span><span class="">[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</span></pre>
<h3>Case 2: When our array is 2-D</h3>
<ul>
<li>
<h3>Method 1-Find unique value from the array</h3>
</li>
</ul>
<p>Here we simply pass our array and all the parameter remain the same. Here we don&#8217;t make any changes because we want to work on both rows and columns. Let see this with the help of an example.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">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)
</pre>
<p>Output</p>
<pre class="jqconsole jqconsole-blurred"><span class="">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]</span></pre>
<h3>Method 2-Get unique rows</h3>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">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)
</pre>
<p>Output</p>
<pre class="jqconsole jqconsole-blurred"><span class="">Original array is
</span><span class="">[[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]]</span></pre>
<h3>Method 3-Get unique columns</h3>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python">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)
</pre>
<p>Output</p>
<pre class="jqconsole jqconsole-blurred"><span class="">Original array is
</span><span class="">[[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]]</span></pre>
<p>so these are the methods to find unique values in a numpy array with frequency and indices.</p>
<p>&nbsp;</p>
<p>The post <a href="https://python-programs.com/python-find-unique-values-in-a-numpy-array-with-frequency-and-indices/">Python: Find Unique Values in a Numpy Array With Frequency and Indices</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8297</post-id>	</item>
		<item>
		<title>Random Choice of Random Module in Python with no Repeat</title>
		<link>https://python-programs.com/random-choice-of-random-module-in-python-with-no-repeat/</link>
		
		<dc:creator><![CDATA[Vikram Chiluka]]></dc:creator>
		<pubDate>Fri, 01 Oct 2021 05:30:47 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=13074</guid>

					<description><![CDATA[<p>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 [&#8230;]</p>
<p>The post <a href="https://python-programs.com/random-choice-of-random-module-in-python-with-no-repeat/">Random Choice of Random Module in Python with no Repeat</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Given the upper limit and lower limit, the task is to generate n natural numbers which are not repeating in Python.</p>
<p><strong>Examples:</strong></p>
<p><strong>Example1:</strong></p>
<p><strong>Input:</strong></p>
<pre>Given N=13
Given lower limit range =19
Given upper limit range =45</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">The random numbers present in the range from 19 to 45 are :
28 40 24 25 20 44 38 29 21 31 43</pre>
<p><strong>Example2:</strong></p>
<p><strong>Input:</strong></p>
<pre>Given N=19
Given lower limit range =23
Given upper limit range =41</pre>
<p><strong>Output:</strong></p>
<pre>The random numbers present in the range from 23 to 41 are : 26 27 40 38 37 41 30 35 36 23 25</pre>
<h2>Random choice of Random module in Python with no Repeat</h2>
<p>Below are the ways to generate n natural numbers which are not repeating in Python.</p>
<ul>
<li><a href="#Using_For_loop(Static_Input)">Using For loop and randint function(Static Input)</a></li>
<li><a href="#Using_For_loop(User_Input)">Using For loop </a><a href="#Using_For_loop(Static_Input)">and randint function</a><a href="#Using_For_loop(User_Input)">(User Input)</a></li>
</ul>
<p>Practice Java programming from home without using any fancy software just by tapping on this <a href="https://python-programs.com/python-programming-examples-with-output/">Simple Java Programs for Beginners</a> tutorial.</p>
<h3 id="Using_For_loop(Static_Input)">Method #1: Using For Loop and randint function (Static Input)</h3>
<p><strong>Approach:<br />
</strong></p>
<ul>
<li>Import the random module using the import keyword.</li>
<li>Give the number n as static input and store it in a variable.</li>
<li>Give the lower limit range and upper limit range as static input and store them in two separate variables.</li>
<li>Take an empty list (say rndmnumbs) and initialize it with an empty list using [] or list().</li>
<li>Loop till n times using For loop.</li>
<li>Generate a random number using randint(lowerlimitrange,upperlimitrange) and store it in a variable.</li>
<li>Check whether the above random number is present in the list or not using not in operator.</li>
<li>If it is not in the list then append the element to the rndmnumbs list using the append() function.</li>
<li>Print the rndmnumbs.</li>
<li>The Exit of the Program.</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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=' ')
</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">The random numbers present in the range from 19 to 45 are :
28 40 24 25 20 44 38 29 21 31 43</pre>
<h3>Method #2: Using For Loop and randint function (User Input)</h3>
<p><strong>Approach:<br />
</strong></p>
<ul>
<li>Import the random module using the import keyword.</li>
<li>Give the number n as user input using int(input()) and store it in a variable.</li>
<li>Give the lower limit range and upper limit range as user input using map(),int(),split(),input() functions.</li>
<li>Store them in two separate variables.</li>
<li>Take an empty list (say rndmnumbs) and initialize it with an empty list using [] or list().</li>
<li>Loop till n times using For loop.</li>
<li>Generate a random number using randint(lowerlimitrange,upperlimitrange) and store it in a variable.</li>
<li>Check whether the above random number is present in the list or not using not in operator.</li>
<li>If it is not in the list then append the element to the rndmnumbs list using the append() function.</li>
<li>Print the rndmnumbs.</li>
<li>The Exit of the Program.</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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=' ')
</pre>
<p><strong>Output:</strong></p>
<pre>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</pre>
<p><strong>Related Programs</strong>:</p>
<ul>
<li><a href="https://python-programs.com/python-program-to-remove-the-ith-occurrence-of-the-given-word-in-a-list-where-words-can-repeat/">python program to remove the ith occurrence of the given word in a list where words can repeat</a></li>
<li><a href="https://python-programs.com/create-numpy-array-of-different-shapes-initialize-with-identical-values-using-numpy-full-in-python/">create numpy array of different shapes initialize with identical values using numpy full in python</a></li>
<li><a href="https://python-programs.com/python-program-to-print-each-word-of-a-sentence-along-with-number-of-vowels-in-each-word/">python program to print each word of a sentence along with number of vowels in each word</a></li>
<li><a href="https://python-programs.com/how-to-web-scrape-with-python-in-4-minutes/">how to web scrape with python in 4 minutes</a></li>
<li><a href="https://python-programs.com/how-to-create-and-initialize-a-list-of-lists-in-python/">how to create and initialize a list of lists in python</a></li>
<li><a href="https://python-programs.com/python-how-to-find-all-indexes-of-an-item-in-a-list/">python how to find all indexes of an item in a list</a></li>
<li><a href="https://python-programs.com/basics-of-python-built-in-types/">basics of python built in types</a></li>
</ul>
<p>The post <a href="https://python-programs.com/random-choice-of-random-module-in-python-with-no-repeat/">Random Choice of Random Module in Python with no Repeat</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">13074</post-id>	</item>
		<item>
		<title>Python Program to Union of Set of Tuples</title>
		<link>https://python-programs.com/python-program-to-union-of-set-of-tuples/</link>
		
		<dc:creator><![CDATA[Vikram Chiluka]]></dc:creator>
		<pubDate>Fri, 01 Oct 2021 05:30:34 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://python-programs.com/?p=12890</guid>

					<description><![CDATA[<p>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 [&#8230;]</p>
<p>The post <a href="https://python-programs.com/python-program-to-union-of-set-of-tuples/">Python Program to Union of Set of Tuples</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>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.<br />
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&#8217; represents the union.<br />
This problem is centered on finding the union of sets of tuples, which indicates that the set is made up of tuple elements.</p>
<p><strong>Examples:</strong></p>
<p><strong>Example1:</strong></p>
<p><strong>Input:</strong></p>
<pre>first = {('hello', 5), ('this', 100)}
second = {('this', 100), ('is', 200)}
third = {('hello', 5), ('btechgeeks', 461), ('python', 234)}</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">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)}</pre>
<h2>Program to Union of Set of Tuples in Python</h2>
<p>Below are the ways to find the union of the set of tuples in Python.</p>
<ul>
<li><a href="#Using_or(_|_)_operator">Using or( | ) operator</a></li>
<li><a href="#Using_union()_method">Using union() method</a></li>
</ul>
<p>Are you new to the java programming language? We recommend you to ace up your practice session with these <a href="https://python-programs.com/python-programming-examples-with-output/">Basic Java Programs Examples</a></p>
<h3 id="Using_or(_|_)_operator">Method #1: Using  or( | ) operator</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Give the set of tuples as static input and store them in Separate Variables.</li>
<li>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.</li>
<li>Calculate the union using | operator and store it in a variable.</li>
<li>Print the union.</li>
<li>The Exit of the Program.</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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)
</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">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)}</pre>
<h3 id="Using_union()_method">Method #2: Using union() method</h3>
<p><strong>Approach:</strong></p>
<ul>
<li>Give the set of tuples as static input and store them in Separate Variables.</li>
<li>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.</li>
<li>Calculate the union using the union() method and store it in a variable.</li>
<li>Print the union.</li>
<li>The Exit of the Program.</li>
</ul>
<p><strong>Below is the implementation:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python"># 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)
</pre>
<p><strong>Output:</strong></p>
<pre id="codeOutputPre">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)}</pre>
<p><strong>Related Programs</strong>:</p>
<ul>
<li><a href="https://python-programs.com/program-to-clear-the-rightmost-set-bit-of-a-number-in-cpp-and-python/">program to clear the rightmost set bit of a number in cpp and python</a></li>
<li><a href="https://python-programs.com/python-program-to-sort-a-list-of-tuples-in-increasing-order-by-the-last-element-in-each-tuple/">python program to sort a list of tuples in increasing order by the last element in each tuple</a></li>
<li><a href="https://python-programs.com/python-program-to-create-a-list-of-tuples-with-the-first-element-as-the-number-and-second-element-as-the-square-of-the-number/">python program to create a list of tuples with the first element as the number and second element as the square of the number</a></li>
<li><a href="https://python-programs.com/python-program-to-group-words-with-the-same-set-of-characters/">python program to group words with the same set of characters</a></li>
<li><a href="https://python-programs.com/7-ways-to-add-all-elements-of-list-to-set-in-python/">7 ways to add all elements of list to set in python</a></li>
<li><a href="https://python-programs.com/python-how-to-sort-a-list-of-tuples-by-second-item/">python how to sort a list of tuples by second item</a></li>
<li><a href="https://python-programs.com/python-read-csv-into-a-list-of-lists-or-tuples-or-dictionaries-import-csv-to-list/">python read csv into a list of lists or tuples or dictionaries import csv to list</a></li>
</ul>
<p>The post <a href="https://python-programs.com/python-program-to-union-of-set-of-tuples/">Python Program to Union of Set of Tuples</a> appeared first on <a href="https://python-programs.com">Python Programs</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">12890</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: python-programs.com @ 2026-04-18 18:39:51 by W3 Total Cache
-->