Python Program to Print nth Iteration of Lucas Sequence

Program to Print nth Iteration of Lucas Sequence

In the previous article, we have discussed Python Program to Find Sum of Geometric Progression Series

Definition of Lucas sequence:

We’ve all heard of the Fibonacci sequence. It is a sequence in which each term is the sum of the two preceding terms. The Lucas sequence is the same as the previous one, but with different starting values. A Fibonacci sequence starts with 0 and 1, whereas a Lucas sequence in python starts with 2 and 1. The other terms in the Lucas sequence are 3, 4, 7, 11, Nth Lucas Number In Python, Lucas Series In Python, Lucas Series In Java and so on.

Given a number ‘n’ and the task is to print the given nth iteration of Lucas Sequence.

Examples:

Example1:

Input:

n = 6

Output:

The above Given nth iteration of Lucas Sequence =  18

Example 2:

Input:

n = 10

Output:

The above Given nth iteration of Lucas Sequence =  123

Program to Print nth Iteration of Lucas Sequence

Below are the ways to get the given nth Iteration of the Lucas Sequence.

Method #1: Using For Loop  (Static Input)

Approach:

  • Give the First term =2 (since the first term in Lucas Sequence is 2 which is a constant) as static input and store it in a variable.
  • Give the Second term =1 (since the second term in Lucas Sequence is 1 which is a constant) as static input and store it in another variable.
  • Give the number as static input and store it in another variable.
  • Loop from ‘1’ to the above given n+1 value (since doesn’t include the last term) range using For loop.
  • Inside the loop, get the third term which is the sum of the first and the second term, and store it in a variable.
  • Assign the value of the second term to the first term.
  • Assign the value of the third term to the second term and come out of For Loop.
  • Print the Value of the above given nth iteration of Lucas Sequence(i.e. first term).
  • The Exit of the program.

Below is the implementation:

# Give the First term =2 (since the first term in Lucas Sequence is 2 which is a constant)
# as static input and store it in a variable.
fst_trm = 2
# Give the Second term =1 (since the second term in Lucas Sequence is 1 which is a constant)
# as static input and store it in another variable.
secnd_trm = 1
# Give the number as static input and store it in another variable.
gvn_n_vlue = 6
# Loop from '1' to the above given n+1 value (since doesn't include last term) range
# using For loop.
for i in range(1, gvn_n_vlue+1):
 # Inside the loop , get the third term which is the sum of first and the second term
    # and store it in a variable.
    third_trm = fst_trm+secnd_trm
 # Assign the value of second term to the first term.
    fst_trm = secnd_trm
  # Assign the value of the third term to the second term and come out of For Loop.
    secnd_trm = third_trm
# Print the Value of above given nth iteration of Lucas Sequence(i.e. first term).
print("The above Given nth iteration of Lucas Sequence = ", fst_trm)

Output:

The above Given nth iteration of Lucas Sequence =  18

Method #2: Using For Loop  (User Input)

Approach:

  • Give the First term =2 (since the first term in Lucas Sequence is 2 which is a constant) as static input and store it in a variable.
  • Give the Second term =1 (since the second term in Lucas Sequence is 1 which is a constant) as static input and store it in another variable.
  • Give the number as User input and store it in another variable.
  • Loop from ‘1’ to the above given n+1 value (since doesn’t include the last term) range using For loop.
  • Inside the loop, get the third term which is the sum of the first and the second term, and store it in a variable.
  • Assign the value of the second term to the first term.
  • Assign the value of the third term to the second term and come out of For Loop.
  • Print the Value of the above given nth iteration of Lucas Sequence(i.e. first term).
  • The Exit of the program.

Below is the implementation:

# Give the First term =2 (since the first term in Lucas Sequence is 2 which is a constant)
# as static input and store it in a variable.
fst_trm = 2
# Give the Second term =1 (since the second term in Lucas Sequence is 1 which is a constant)
# as static input and store it in another variable.
secnd_trm = 1
# Give the number as User input and store it in another variable.
gvn_n_vlue = int(input("Enter Some Random number = "))
# Loop from '1' to the above given n+1 value (since doesn't include last term) range
# using For loop.
for i in range(1, gvn_n_vlue+1):
 # Inside the loop , get the third term which is the sum of first and the second term
    # and store it in a variable.
    third_trm = fst_trm+secnd_trm
 # Assign the value of second term to the first term.
    fst_trm = secnd_trm
  # Assign the value of the third term to the second term and come out of For Loop.
    secnd_trm = third_trm
# Print the Value of above given nth iteration of Lucas Sequence(i.e. first term).
print("The above Given nth iteration of Lucas Sequence = ", fst_trm)

Output:

Enter Some Random number = 10
The above Given nth iteration of Lucas Sequence = 123

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

Read more: Python Program to Find Vertex, Focus and Directrix of Parabola

Solve these:

  1. Print The Nth Lucas Number In Python?
  2. Given A Number N, Print The Nth Lucas Numbers python. Numbering Starts From 0?

Related Posts On:

Negative numbers in python – Python Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers in a List

Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers in a List

Negative numbers in python: Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

List in Python :

The list data type is one of the most often used data types in Python. The square brackets [ ] easily identify a Python List. Lists are used to store data items, with each item separated by a comma (,). A Python List can include data elements of any data type, including integers and Booleans.

One of the primary reasons that lists are so popular is that they are mutable. Any data item in a List can be replaced by any other data item if it is mutable. This distinguishes Lists from Tuples, which are likewise used to store data elements but are immutable.

Given a list the task is to print the sum of all positive even numbers ,odd numbers and negative numbers in the given list in python.

Examples:

Example1:

Input:

given list =[23, 128, -4, -19, 233, 726, 198, 199, 203, -13]

Output:

The sum of all positive even numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 1052
The sum of all positive odd numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 658
The sum of all positive negative numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = -36

Example2:

Input:

given list =[-4, 23, 12, -13, 234, 198, 55, -19, 87, 45]

Output:

The sum of all positive even numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45]  = 444 
The sum of all positive odd numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  210 
The sum of all positive negative numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  -36

Python Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers in a List

Below are the ways to print the sum of all positive even numbers ,odd numbers and negative numbers in the given list 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.

Method #1:Using append() and Conditional Statements (User Input separated by newline)

Approach:

  • Take the user’s input on the number of elements to include in the list.
  •  Using a for loop, Scan the elements from the user and append them to a list.
  • Using a for loop, retrieve the elements from the list one at a time, determine whether they are positive odd, positive even or negative numbers and append them to various lists say posEven, posOdd ,negNum.
  • Calculate the sum of posEven, posOdd ,negNum and print them
  • Exit of program

Below is the implementation:

# scanning the total number of elements of the given list
totalCount = int(
    input("Enter the total number of elements of the given list = "))
# Taking a empty list
given_list = []
# Using for loop to loop totalCount times
for i in range(totalCount):
    eleme = int(input("Enter some random element(integer) = "))
    given_list.append(eleme)
# Taking three empty lists which stores positive
# ven numbers ,positive odd numbers and negative numbers
posEven = []
posOdd = []
negNum = []
# Traversing the list using for loop
for element in given_list:
    # checking if the number is greater than 0
    if(element > 0):
        # if the element is even then add this element to posEven using append() function
        if(element % 2 == 0):
            posEven.append(element)
    # if the element is even then add this element to posOdd using append() function
        else:
            posOdd.append(element)
    # else if the number is less than 0 then add to negNum list using append() function
    else:
        negNum.append(element)
        

# Calculating sum
posEvensum = sum(posEven)
posOddsum = sum(posOdd)
negNumsum = sum(negNum)
# printing the respectve sum's
print("The sum of all positive even numbers in thee given list = ",
      given_list, posEvensum)
print("The sum of all positive odd numbers in thee given list = ", given_list, posOddsum)
print("The sum of all positive negative numbers in thee given list = ",
      given_list, negNumsum)

Output:

Enter the total number of elements of the given list = 10
Enter some random element(integer) = -4
Enter some random element(integer) = 23
Enter some random element(integer) = 12
Enter some random element(integer) = -13
Enter some random element(integer) = 234
Enter some random element(integer) = 198
Enter some random element(integer) = 55
Enter some random element(integer) = -19
Enter some random element(integer) = 87
Enter some random element(integer) = 45
The sum of all positive even numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45]  = 444
The sum of all positive odd numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  210
The sum of all positive negative numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  -36

Method #2:Using append() and Conditional Statements (Static Input separated by spaces)

Approach:

  • Given the input of the list as static.
  • Using a for loop, retrieve the elements from the list one at a time, determine whether they are positive odd, positive even or negative numbers and append them to various lists say posEven, posOdd ,negNum.
  • Calculate the sum of posEven, posOdd ,negNum and print them
  • Exit of program

Below is the implementation:

# given list
given_list = [23, 128, -4, -19, 233, 726, 198, 199, 203, -13]
# Taking three empty lists which stores positive
# even numbers ,positive odd numbers and negative numbers
posEven = []
posOdd = []
negNum = []
# Traversing the list using for loop
for element in given_list:
    # checking if the number is greater than 0
    if(element > 0):
        # if the element is even then add this element to posEven using append() function
        if(element % 2 == 0):
            posEven.append(element)
    # if the element is even then add this element to posOdd using append() function
        else:
            posOdd.append(element)
    # else if the number is less than 0 then add to negNum list using append() function
    else:
        negNum.append(element)


# Calculating sum
posEvensum = sum(posEven)
posOddsum = sum(posOdd)
negNumsum = sum(negNum)
# printing the respectve sum's
print("The sum of all positive even numbers in thee given list ",
      given_list, "=", posEvensum)
print("The sum of all positive odd numbers in thee given list ",
      given_list, "=", posOddsum)
print("The sum of all positive negative numbers in thee given list ",
      given_list, "=", negNumsum)

Output:

The sum of all positive even numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 1052
The sum of all positive odd numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 658
The sum of all positive negative numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = -36

Related Programs:

Python number to binary string – Python Program to Flipping the Binary Bits

Program to Flipping the Binary Bits

Python number to binary string: Given a binary string, the task is to flip the bits in the given binary string in Python.

Examples:

Example1:

Input:

Given Binary string =1101010001001

Output:

The given binary string before flipping bits is [ 1101010001001 ]
The given binary string after flipping bits is [ 0010101110110 ]

Example2:

Input:

Given Binary string =00110011111

Output:

The given binary string before flipping bits is [ 00110011111 ]
The given binary string after flipping bits is [ 11001100000 ]

Program to Flipping the Binary Bits in Python

Below are the ways to flip the bits in the given binary string in Python.

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the binary string as static input and store it in a variable.
  • Take an empty string(say flipbinary) which is the result after flipping the bits and initialize its value to a null string using “”.
  • Traverse the given binary string using For loop.
  • If the bit is 1 then concatenate the flipbinary with 0.
  • Else concatenate the flipbinary with 1.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as static input and store it in a variable.
gvnbinstring = '1101010001001'
# Take an empty string(say flipbinary) which is the result after flipping the bits
# and initialize its value to a null string using "".
flipbinary = ""
# Traverse the given binary string using For loop.
for bitval in gvnbinstring:
    # If the bit is 1 then concatenate the flipbinary with 0.
    if bitval == '1':
        flipbinary += '0'
    # Else concatenate the flipbinary with 1.
    else:
        flipbinary += '1'
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

The given binary string before flipping bits is [ 1101010001001 ]
The given binary string after flipping bits is [ 0010101110110 ]

Method #2: Using For Loop (User Input)

Approach:

  • Give the binary string as user input using input() and store it in a variable.
  • Take an empty string(say flipbinary) which is the result after flipping the bits and initialize its value to a null string using “”.
  • Traverse the given binary string using For loop.
  • If the bit is 1 then concatenate the flipbinary with 0.
  • Else concatenate the flipbinary with 1.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as user input using input() and store it in a variable.
gvnbinstring = input('Enter some random binary string = ')
# Take an empty string(say flipbinary) which is the result after flipping the bits
# and initialize its value to a null string using "".
flipbinary = ""
# Traverse the given binary string using For loop.
for bitval in gvnbinstring:
    # If the bit is 1 then concatenate the flipbinary with 0.
    if bitval == '1':
        flipbinary += '0'
    # Else concatenate the flipbinary with 1.
    else:
        flipbinary += '1'
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

Enter some random binary string = 0011100110101010
The given binary string before flipping bits is [ 0011100110101010 ]
The given binary string after flipping bits is [ 1100011001010101 ]

Method #3: Using replace() function (Static Input)

Approach:

  • Give the binary string as static input and store it in a variable.
  • Replace all 1’s present in the given binary string with some random character like p.
  • Replace all 0’s present in the given binary string with 1.
  • Replace all p’s present in the given binary string with 0.
  • Here ‘p’ acts as a temporary variable.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as static input and store it in a variable.
gvnbinstring = '1101010001001'

# Replace all 1's present in the given binary string
# with some random character like p.
flipbinary = gvnbinstring.replace('1', 'p')
# Replace all 0's present in the given
# binary string with 1.
flipbinary = flipbinary.replace('0', '1')
# Replace all p's present in the given
# binary string with 0.
# Here 'p' acts as a temporary variable.
flipbinary = flipbinary.replace('p', '0')
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

The given binary string before flipping bits is [ 1101010001001 ]
The given binary string after flipping bits is [ 0010101110110 ]

Method #4: Using replace() function (User Input)

Approach:

  • Give the binary string as user input using input() and store it in a variable.
  • Replace all 1’s present in the given binary string with some random character like p.
  • Replace all 0’s present in the given binary string with 1.
  • Replace all p’s present in the given binary string with 0.
  • Here ‘p’ acts as a temporary variable.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as user input using input() and store it in a variable.
gvnbinstring = input('Enter some random binary string = ')

# Replace all 1's present in the given binary string
# with some random character like p.
flipbinary = gvnbinstring.replace('1', 'p')
# Replace all 0's present in the given
# binary string with 1.
flipbinary = flipbinary.replace('0', '1')
# Replace all p's present in the given
# binary string with 0.
# Here 'p' acts as a temporary variable.
flipbinary = flipbinary.replace('p', '0')
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

Enter some random binary string = 00110011111
The given binary string before flipping bits is [ 00110011111 ]
The given binary string after flipping bits is [ 11001100000 ]

Related Programs:

Pattern program in python – Python Program to Print an Inverted Star Pattern | Python code to create an inverted Pyramid start pattern

Program to Print an Inverted Star Pattern

Pattern program in python: Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Python Program to Print the pattern of an Inverted Star: Given a number, the task is to print an Inverted Star Pattern in Python. In our python programming articles, you can also learn how to print a program of Inverted pyramid pattern and print inverted pyramid star pattern in python language.

Let’s see the examples of python program to print inverted star pattern from here

Example1:

Input:

given rows = 8

Output:

********
 *******
  ******
   *****
    ****
     ***
      **
       *

Example2:

Input:

given rows=10

Output:

**********
 *********
  ********
   *******
    ******
     *****
      ****
       ***
        **
         *

Here is the program to print Inverted Star Pattern:

# python 3 code to print inverted star
# pattern 
  
# n is the number of rows in which
# star is going to be printed.
n=11
  
# i is going to be enabled to
# range between n-i t 0 with a
# decrement of 1 with each iteration.
# and in print function, for each iteration,
# ” ” is multiplied with n-i and ‘*’ is
# multiplied with i to create correct
# space before of the stars.
for i in range (n, 0, -1):
    print((n-i) * ' ' + i * '*')

python 3 code to print inverted star pattern

Program to Print an Inverted Star Pattern in Python

Below are the ways to print an Inverted Star Pattern 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)Using for loop printing the inverted star pattern in Python(Static Input)

Using for loop printing the inverted star pattern in Python(Static Input)

Approach:

  • Give the number as static and store it in a variable
  • Use a for loop in which the value of k varies between n-1 and 0 and is decremented by one with each iteration.
  • Multiply empty spaces by n-i and ‘*’ by k then print both of them.
  • Exit of program.

Below is the implementation:

# given number numb
numb = 8
# Use a for loop in which the value of k varies
# between n-1 and 0 and is decremented by one with each iteration.
for k in range(numb, 0, -1):
  # Multiply empty spaces by n-i and '*' by k then print both of them.
    print((numb-k) * ' ' + k * '*')

Output:

********
 *******
  ******
   *****
    ****
     ***
      **
       *

Explanation:

  • Give the number as static and stored it in  a variable numb
  • The for loop allows I to range between n-1 and 0, with each iteration decrementing by one.
  • To maintain proper star spacing, ” ” is multiplied by n-i and ‘*’ is multiplied by I for each iteration.
  • The requisite pattern has been printed.

2)Using for loop printing the inverted star pattern in Python(User Input)

Using for loop printing the inverted star pattern in Python(User Input)

Approach:

  • Scan the given number using int(input()) and store it in a variable.
  • Use a for loop in which the value of k varies between n-1 and 0 and is decremented by one with each iteration.
  • Multiply empty spaces by n-i and ‘*’ by k then print both of them.
  • Exit of program.

Below is the implementation:

# given number numb
numb = int(input("enter the number of rows required = "))
# Use a for loop in which the value of k varies
# between n-1 and 0 and is decremented by one with each iteration.
for k in range(numb, 0, -1):
  # Multiply empty spaces by n-i and '*' by k then print both of them.
    print((numb-k) * ' ' + k * '*')

Output:

enter the number of rows required = 10
**********
 *********
  ********
   *******
    ******
     *****
      ****
       ***
        **
         *

3)Using while loop printing the inverted star pattern in Python(Static Input)

Using while loop printing the inverted star pattern in Python(Static Input)

Approach:

  • Give the number as static and store it in a variable
  • Using while loop iterate till number is greater than 0.
  • Multiply empty spaces by tem-i and ‘*’ by numb then print both of them.
  • Decrement the number by 1.
  • The Exit of the program.

Below is the implementation:

# given number numb
numb = 10
# Make a duplicate of the integer by storing it in a variable
tem = numb
# Use a for loop in which the value of k varies
# between n-1 and 0 and is decremented by one with each iteration.
while(numb > 0):
  # Multiply empty spaces by n-i and '*' by k then print both of them.
    print((tem-numb) * ' ' + numb * '*')
    # decrement the number by 1
    numb = numb-1

Output:

**********
 *********
  ********
   *******
    ******
     *****
      ****
       ***
        **
         *

4)Using while loop printing the inverted star pattern in Python(User Input)

Using while loop printing the inverted star pattern in Python(User Input)

Approach:

  • Scan the given number using int(input()) and store it in a variable.
  • Using while loop iterate till number is greater than 0.
  • Multiply empty spaces by tem-i and ‘*’ by numb then print both of them.
  • Decrement the number by 1.
  • Exit of program.

Below is the implementation:

# given number numb
numb = int(input("enter the number of rows required = "))
# Make a duplicate of the integer by storing it in a variable
tem = numb
# Use a for loop in which the value of k varies
# between n-1 and 0 and is decremented by one with each iteration.
while(numb > 0):
  # Multiply empty spaces by n-i and '*' by k then print both of them.
    print((tem-numb) * ' ' + numb * '*')
    # decrement the number by 1
    numb = numb-1

Output:

enter the number of rows required = 10
**********
 *********
  ********
   *******
    ******
     *****
      ****
       ***
        **
         *

Programs to print inverted half pyramid using *

This instance is similar to an upright pyramid but that here we begin from the total number of rows and in each iteration, we decrease the number of rows by 1.

Programs to print inverted half pyramid using star

Source Code:

rows = int(input("Enter number of rows: "))

for i in range(rows, 0, -1):
    for j in range(0, i):
        print("* ", end=" ")
    
    print("\n")

output: 

* * * * *
* * * *
* * *
* *
*

Related Programs:

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

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

Python zip multiple files: 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

Create zip file python: 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

Python create zip file: 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

Python zip 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.

Pandas read csv delimeter – Read Csv File to Dataframe With Custom Delimiter in Python

Different methods to read CSV files with custom delimiter in python

Pandas read csv delimeter: In this article, we will see what are CSV files, how to use them in pandas, and then we see how and why to use custom delimiter with CSV files in pandas.

CSV file

Pandas read csv separator: A simple way to store big data sets is to use CSV files (comma-separated files).CSV files contain plain text and is a well know format that can be read by everyone including Pandas. Generally, CSV files contain columns separated by commas, but they can also contain content separated by a tab, or underscore or hyphen, etc. Generally, CSV files look like this:-

total_bill,tip,sex,smoker,day,time,size
16.99,1.01,Female,No,Sun,Dinner,2
10.34,1.66,Male,No,Sun,Dinner,3
21.01,3.5,Male,No,Sun,Dinner,3
23.68,3.31,Male,No,Sun,Dinner,2
24.59,3.61,Female,No,Sun,Dinner,4

Here we see different columns and their values are separated by commas.

Use CSV file in pandas

Read csv separator: read_csv() method is used to import and read CSV files in pandas. After this step, a CSV file act as a normal dataframe and we can use operation in CSV file as we use in dataframe.

syntax:  pandas.read_csv(filepath_or_buffer, sep=‘, ‘, delimiter=None, header=‘infer’, names=None, index_col=None, ….)

',' is default separator in read_csv() method.

Let see this with an example

import pandas as pd
data=pd.read_csv('example1.csv')
data.head()

Output

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

Why use separator or delimiter with read_csv() method

Read_csv separator: Till now we understand that generally, CSV files contain data separated data that is separated by comma but sometimes it can contain data separated by tab or hyphen, etc. So to handle this we use a seperator. Let understand this with the help of an example. Suppose we have a CSV file separated by an underscore and we try to read that CSV file without using a separator or with using default separator i.e. comma. So let see what happens in this case.

"total_bill"_tip_sex_smoker_day_time_size
16.99_1.01_Female_No_Sun_Dinner_2
10.34_1.66_Male_No_Sun_Dinner_3
21.01_3.5_Male_No_Sun_Dinner_3
23.68_3.31_Male_No_Sun_Dinner_2
24.59_3.61_Female_No_Sun_Dinner_4
25.29_4.71_Male_No_Sun_Dinner_4
8.77_2_Male_No_Sun_Dinner_2

Suppose this is our CSV file separated by an underscore.

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.5_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

Now see when we didn’t use a default separator here how unordered our data look like. So to solve this issue we use Separator. Now we will see when we use a separator to underscore how we get the same data in an ordered manner.

import pandas as pd 
data=pd.read_csv('example2.csv',sep = '_',engine = 'python') 
data.head()

Output

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

So this example is sufficient to understand why there is a need of using a separator of delimiter in pandas while working on a CSV file.

Now suppose there is a CSV file in while data is separated by multiple separators. For example:-

totalbill_tip,sex:smoker,day_time,size
16.99,1.01:Female|No,Sun,Dinner,2
10.34,1.66,Male,No|Sun:Dinner,3
21.01:3.5_Male,No:Sun,Dinner,3
23.68,3.31,Male|No,Sun_Dinner,2
24.59:3.61,Female_No,Sun,Dinner,4
25.29,4.71|Male,No:Sun,Dinner,4

Here we see there are multiple seperator used. So here we can not use any custom delimiter. To solve this problem regex or regular expression is used. Let see with the help of an example.

import pandas as pd 
data=pd.read_csv('example4.csv',sep = '[:, |_]') 
data.head()

Output

totalbill 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

When we notice we pass a list of separators in the sep parameter that is contained in our CSV file.

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Max element in list python – Python Program to Get the Position of Max Value in a List

Program to Get the Position of Max Value in a List

Max element in list python: In the previous article, we have discussed Python Program to Find Vertex, Focus and Directrix of Parabola
max() function :

max() is a built-in function that returns the maximum value in a list.

index() function:

This function searches the lists. It returns the index where the value is found when we pass it as an argument that matches the value in the list. If no value is found, Value Error is returned.

Given a list, the task is to Get the position of Max Value in a List.

Examples:

Example 1 :

Input :

Given List = [1, 5, 9, 2, 7, 3, 8]

Output:

Maximum Value in the above Given list = 9
Position of Maximum value of the above Given List = 3

Example 2 :

Input : 

Given List = [4, 3, 7, 1, 2, 8, 9]

Output:

Maximum Value in the above Given list = 9
Position of Maximum value of the above Given List = 7

Program to Get the Position of Max Value in a List

Below are the ways to Get the Position of Max value in a List.

Method #1: Using Max(),Index() functions  (Static Input)

Approach:

  • Give the List as static input and store it in a variable.
  • Get the maximum value of the given list using the built-in max() function and store it in another variable.
  • Print the maximum value of the above-given List.
  • Get the position of the maximum value of the given List using the built-in index() function and store it in another variable.
  • Print the position of the maximum value of the given List i.e. maximum position+1( since list index starts from zero).
  • The Exit of the program.

Below is the implementation:

# Give the List as static input and store it in a variable.
Gvn_lst = [1, 5, 9, 2, 7, 3, 8]
# Get the maximum value of the given list using the built-in max() function and
# store it in another variable
maxim_vle = max(Gvn_lst)
# Print the maximum value of the above given List.
print("Maximum Value in the above Given list = ", maxim_vle)
# Get the position of the maximum value of the List using the built-in index() function
# and store it in another variable.
maxim_positn = Gvn_lst.index(maxim_vle)
# Print the position of the maximum value of the given List i.e. maximum position+1
# ( since list index starts from zero).
print("Position of Maximum value of the above Given List = ", maxim_positn+1)

Output:

Maximum Value in the above Given list =  9
Position of Maximum value of the above Given List =  3

Method #2: Using Max(),Index() functions  (User Input)

Approach:

  • Give the list as User input using list(),map(),input(),and split() functions and store it in a variable.
  • Get the maximum value of the given list using the built-in max() function and store it in another variable.
  • Print the maximum value of the above-given List.
  • Get the position of the maximum value of the given List using the built-in index() function and store it in another variable.
  • Print the position of the maximum value of the given List i.e. maximum position+1( since list index starts from zero).
  • The Exit of the program.

Below is the implementation:

#Give the list as User input using list(),map(),input(),and split() functions and store it in a variable.
Gvn_lst = list(map(int, input('Enter some random List Elements separated by spaces = ').split()))
# Get the maximum value of the given list using the built-in max() function and
# store it in another variable
maxim_vle = max(Gvn_lst)
# Print the maximum value of the above given List.
print("Maximum Value in the above Given list = ", maxim_vle)
# Get the position of the maximum value of the List using the built-in index() function
# and store it in another variable.
maxim_positn = Gvn_lst.index(maxim_vle)
# Print the position of the maximum value of the given List i.e. maximum position+1
# ( since list index starts from zero).
print("Position of Maximum value of the above Given List = ", maxim_positn+1)

Output:

Enter some random List Elements separated by spaces = 4 3 7 1 2 8 9
Maximum Value in the above Given list = 9
Position of Maximum value of the above Given List = 7

Here we printed the index of the maximum element of the given list.

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

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

Program to Read Two Numbers and Print Their Quotient and Remainder

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

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

Examples:

i)Floating Division

Example1:

Input:

first number =45
second number =17

Output:

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

ii)Integer Division

Input:

first number =45
second number =17

Output:

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

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

Below are the ways to print the quotient and Remainder:

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

Approach:

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

Below is the implementation:

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

Output:

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

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

Approach:

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

Below is the implementation:

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

Output:

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

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

Approach:

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

Below is the implementation:

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

Output:

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

Related Programs:

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

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

Dictionaries in Python:

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

Examples:

Example1:

Input:

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

Output:

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

Example2:

Input:

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

Output:

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

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

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

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

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

Approach:

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

Below is the implementation:

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

Output:

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

Explanation:

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

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

Approach:

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

Below is the implementation:

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

Output:

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

Related Programs:

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

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

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

Examples:

Example1:

Input:

given number = 37913749

Output:

The required number = 89

Example2:

Input:

 given number =78329942

Output:

The required number = 82

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

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

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

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

Approach:

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

Below is the implementation:

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

Output:

The required number = 89

Explanation:

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

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

Approach:

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

Below is the implementation:

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

Output:

enter any number = 78329942
The required number = 82

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

Approach:

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

Below is the implementation:

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

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

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

Output:

The required number = 59

Related Programs: