asm8 – Python Pandas Timedelta.asm8 Attribute

Python Pandas Timedelta.asm8 Attribute

asm8: Timedelta is a subclass of datetime.timedelta, and it performs similarly. It’s Pandas’ version of Python’s datetime.timedelta. In most circumstances, it is interchangeable with it.

Pandas Timedelta.asm8 Attribute:

This property Timedelta.asm8 of the pandas module returns a numpy timedelta64 array view.

Syntax:

Timedelta.asm8

Parameters: It has no arguments

Return Value:

A numpy timedelta64 array view is returned by the Timedelta.asm8 of the pandas module.

Pandas Timedelta.asm8 Attribute in Python

Example1

Approach:

  • Import pandas module using the import keyword.
  • Pass some random Timestamp in the format(days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) to the Timedelta() function of the pandas module to get the Timedelta object.
  • Store it in a variable
  • Print the above obtained Timedelta object
  • Apply asm8 attribute on the above Timedelta object to get the numpy timedelta64 array view of the given Timedelta object.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random Timestamp in the format(days, hours, minutes, seconds,
# milliseconds, microseconds, nanoseconds) to the Timedelta() function of 
# the pandas module to get the Timedelta object.
# Store it in a variable
timedelta_obj = pd.Timedelta('7 days 10:15:08.13010') 
# Print the above obtained Timedelta object
print("The above obtained Timedelta object:", timedelta_obj) 

# Apply asm8 attribute on the above Timedelta object to get the 
# numpy timedelta64 array view of the given Timedelta object.
print("The numpy timedelta64 array view of the given Timedelta object:")
print(timedelta_obj.asm8)

Output:

The above obtained Timedelta object: 7 days 10:15:08.130100
The numpy timedelta64 array view of the given Timedelta object:
641708130100000 nanoseconds

Example2

Here only days, minutes are passed as arguments.

Approach:

  • Import pandas module using the import keyword.
  • Pass some random Timestamp in the format(days, minutes) to the Timedelta() function of the pandas module to get the Timedelta object.
  • Store it in a variable
  • Print the above obtained Timedelta object.
  • Apply asm8 attribute on the above Timedelta object to get the numpy timedelta64 array view of the given Timedelta object.
  • The Exit of the Program.

Below is the implementation:

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random Timestamp in the format(days, minutes) to the Timedelta() 
# function of the pandas module to get the Timedelta object.
# Store it in a variable
timedelta_obj = pd.Timedelta('6 days 30 minutes') 
# Print the above obtained Timedelta object
print("The above obtained Timedelta object:", timedelta_obj) 
print()
# Apply asm8 attribute on the above Timedelta object to get the 
# numpy timedelta64 array view of the given Timedelta object.
print("The numpy timedelta64 array view of the given Timedelta object:")
print(timedelta_obj.asm8)

Output:

The above obtained Timedelta object: 6 days 00:30:00

The numpy timedelta64 array view of the given Timedelta object:
520200000000000 nanoseconds

Example3

# Import pandas module using the import keyword.
import pandas as pd
# Pass some random Timestamp in the format(days, minutes, seconds) to the Timedelta() 
# function of the pandas module to get the Timedelta object.
# Store it in a variable
timedelta_obj = pd.Timedelta(days=12,  minutes=15, seconds=20) 
# Print the above obtained Timedelta object
print("The above obtained Timedelta object:", timedelta_obj) 
print()
# Apply asm8 attribute on the above Timedelta object to get the 
# numpy timedelta64 array view of the given Timedelta object.
print("The numpy timedelta64 array view of the given Timedelta object:")
print(timedelta_obj.asm8)

Output:

The above obtained Timedelta object: 12 days 00:15:20

The numpy timedelta64 array view of the given Timedelta object:
1037720000000000 nanoseconds

Python capitalize each word – Python: Capitalize the First Letter of Each Word in a String?

Python capitalize each word: A sequence of characters is referred to as a string.

Characters are not used by computers instead, numbers are used (binary). Characters appear on your computer, but they are internally stored and manipulated as a sequence of 0s and 1s.

In Python, a string is a set of Unicode characters. Unicode was designed to include every character in every language and to introduce encoding uniformity to the world. Python Unicode will tell you all about Unicode you need to know.

Example:

Input:

string = "this is btech geeks"

Output:

This Is Btech Geeks

Given a string, the task is to convert each word first letter to uppercase

Capitalize the First Letter of Each Word in a String

Python capitalize first letter: There are several ways to capitalize the first letter of each word in a string some of them are:

Method #1:Using capitalize() function

Syntax: given_string.capitalize()
Parameters: No parameters will be passed
Return : Each word’s first letter is capitalised in the string.

Approach:

  • Because spaces separate all of the words in a sentence.
  • We must use split to divide the sentence into spaces ().
  • We separated all of the words with spaces and saved them in a list.
  • Using the for loop, traverse the wordslist and use the capitalise feature to convert each word to its first letter capital.
  • Using the join function, convert the wordslist to a string.
  • Print the string.

Below is the implementation of above approach:

# given string
string = "this is btech geeks"
# convert the string to list and split it
wordslist = list(string.split())
# Traverse the words list and capitalize each word in list
for i in range(len(wordslist)):
  # capitizing the word
    wordslist[i] = wordslist[i].capitalize()
# converting string to list using join() function
finalstring = ' '.join(wordslist)
# printing the final string
print(finalstring)

Output:

This Is Btech Geeks

Method #2:Using title() function

Before returning a new string, the title() function in Python converts the first character in each word to Uppercase and the remaining characters in the string to Lowercase.

  • Syntax: string_name.title()
  • Parameters: string in which the first character of each word must be converted to uppercase
  • Return Value: Each word’s first letter is capitalised in the string.

Below is the implementation:

# given string
string = "this is btech geeks"
# using title() to convert all words first letter to capital
finalstring = string.title()
# print the final string
print(finalstring)

Output:

This Is Btech Geeks

Method #3:Using string.capwords() function

Using the spilt() method in Python, the string capwords() method capitalises all of the words in the string.

  • Syntax: string.capwords(given_string)
  • Parameters: The givenstring that needs formatting.
  • Return Value: Each word’s first letter is capitalised in the string.

Break the statement into words, capitalise each word with capitalise, and then join the capitalised words together with join. If the optional second argument sep is None or missing, whitespace characters are replaced with a single space and leading and trailing whitespace is removed.

Below is the implementation:

# importing string
import string
# given string
givenstring = "this is btech geeks"
# using string.capwords() to convert all words first letter to capital
finalstring = string.capwords(givenstring)
# print the final string
print(finalstring)

Output:

This Is Btech Geeks

Method #4:Using Regex

We’ll use regex to find the first character of each word and convert it to uppercase.

Below is the implementation:

# importing regex
import re

# function which converts every first letter of each word to capital

def convertFirstwordUpper(string):
    # Convert the group 2 to uppercase and join groups 1 and 2 together. 
    return string.group(1) + string.group(2).upper()


# given string
string = "this is btech geeks"

# using regex
resultstring = re.sub("(^|\s)(\S)", convertFirstwordUpper, string)
# print the final string
print(resultstring)

Output:

This Is Btech Geeks

Related Programs:

Python size of tuple – Python Program to Find the Size of a Tuple

Program to Find the Size of a Tuple

Python size of tuple: Given a tuple, the task is to find the size of the given tuple in Python.

Examples:

Example1:

Input:

Given tuple =(9, 11, 24, 19, 11, 23, 29, 23, 31)

Output:

The length of the given tuple (9, 11, 24, 19, 11, 23, 29, 23, 31) is [ 9 ]

Example2:

Input:

Given tuple =(11, 19, 45, 13, 23, 32, 46, 18, 49,58, 53, 75, 11, 19, 93, 99, 85, 68, 24)

Output:

The length of the given tuple (11, 19, 45, 13, 23, 32, 46, 18, 49, 58, 53, 75, 11, 19, 93, 99, 85, 68, 24) is [ 19 ]

Program to Find the Size of a Tuple in Python

Python tuple length: Below are the ways to find the size of the given tuple in Python.

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Method #1: Using len() function

Approach:

  • Give the tuple as static input and store it in a variable.
  • Finding the size or length of a tuple is a rather simple task. The number of objects in a tuple is represented by its size. The syntax for determining the size is len (). The number of elements/objects in the tuple is returned by this function.
  • Calculate the len() using len() function and store it in a variable.
  • Print the length of the tuple.
  • The Exit of the Program.

Below is the implementation:

# Give the tuple as static input and store it in a variable.
gvntuple = (9, 11, 24, 19, 11, 23, 29, 23, 31)
# Finding the size or length of a tuple is a rather simple task.
# The number of objects in a tuple is represented by its size.
# The syntax for determining the size is len ().
# The number of elements/objects in the tuple is returned by this function.
# Calculate the len() using len() function and store it in a variable.
tuplelength = len(gvntuple)
# Print the length of the tuple.
print('The length of the given tuple', gvntuple, 'is [', tuplelength, ']')

Output:

The length of the given tuple (9, 11, 24, 19, 11, 23, 29, 23, 31) is [ 9 ]

Method #2: Using For loop

Approach:

  • Give the tuple as static input and store it in a variable.
  • Take a variable say tuplelength that calculates the given tuple length and initializes its value to 0.
  • Loop through the elements of the tuple using For loop.
  • Inside the For loop increment the value of tuplelength by 1.
  • Print the length of the tuple.
  • The Exit of the Program.

Below is the implementation:

# Give the tuple as static input and store it in a variable.
gvntuple = (9, 11, 24, 19, 11, 23, 29, 23, 31)
# Take a variable say tuplelength that calculates the given tuple
# length and initializes its value to 0.
tuplelength = 0
# Loop through the elements of #Inside the For loop increment the value of tuplelength by 1.the tuple using For loop.
for elemen in gvntuple:
    # Inside the For loop increment the value of tuplelength by 1.
    tuplelength = tuplelength+1

# Print the length of the tuple.
print('The length of the given tuple', gvntuple, 'is [', tuplelength, ']')

Output:

The length of the given tuple (9, 11, 24, 19, 11, 23, 29, 23, 31) is [ 9 ]

Related Programs:

Replace word in file python – Python Program to Replace a Word with Asterisks in a Sentence

Program to Replace a Word with Asterisks in a Sentence

Replace word in file python: In the previous article, we have discussed Python Program to Find Sum of Odd Factors of a Number
Given a sentence and the task is to replace a word with asterisks in a given Sentence.

Examples:

Example1:

Input:

Given string = "hello this is btechgeeks btechgeeks"
Given word to be replaced = "btechgeeks"

Output:

The given string [ hello this is btechgeeks btechgeeks ] after replacing with a given word with an asterisk :
hello this is ********** **********

Example2:

Input:

Given string = "good morning this is btechgeeks good morning all"
Given word to be replaced = "good"

Output:

The given string [ good morning this is btechgeeks good morning all ] after replacing with a given word with an asterisk :
**** morning this is btechgeeks **** morning all

Program to Replace a Word with Asterisks in a Sentence in Python

Below are the ways to replace a word with asterisks in a given Sentence:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Give the replaceable word as static input and store it in another variable.
  • Split the given string into a list of words using the split() function and store it in another variable say “wrd_lst”.
  • Multiply the asterisk symbol with the length of the given input word using the len() function and store it in another variable say “replaced_word”.
  • Loop in the above-obtained word list using the for loop.
  • Check if the word at the iterator index is equal is given input word using the if conditional statement.
  • If the statement is true, replace the word at the iterator index with the replaced_word.
  • Convert the above-got word list to string using the join() function.
  • Print the above-obtained string to replace a word with an asterisk in a given input sentence.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "hello this is btechgeeks btechgeeks"
# Give the replaceable word as static input and store it in another variable.
gvn_wrd = "btechgeeks"
# Split the given string into a list of words using the split() function and
# store it in another variable say "wrd_lst".
wrd_lst = gvn_str.split()
# Multiply the asterisk symbol with the length of the given input word using
# the len() function and store it in another variable.
replacd_word = '*' * len(gvn_wrd)
# Loop in the above-obtained word list using the for loop.
for itr in range(len(wrd_lst)):
  # Check if the iterator value is equal to the given input word using the if
  # conditional statement.
 # check if thw word at the iterator index is equal is given
    if wrd_lst[itr] == gvn_wrd:
      # if it is truw thwn replce the word t the iterator index with the replaced word
        wrd_lst[itr] = replacd_word
# Convert the above-got word list to string using the join() function.
finl_str = ' '.join(wrd_lst)
# Print the above-obtained string to replace a word with an asterisk in a
# given input sentence.
print("The given string [", gvn_str,
      "] after replacing with a given word with an asterisk :")
print(finl_str)

Output:

The given string [ hello this is btechgeeks btechgeeks ] after replacing with a given word with an asterisk :
hello this is ********** **********

Method #2: Using For loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Give the replaceable word as user input using the input() function and store it in another variable.
  • Split the given string into a list of words using the split() function and store it in another variable say “wrd_lst”.
  • Multiply the asterisk symbol with the length of the given input word using the len() function and store it in another variable say “replaced_word”.
  • Loop in the above-obtained word list using the for loop.
  • Check if the word at the iterator index is equal is given input word using the if conditional statement.
  • If the statement is true, replace the word at the iterator index with the replaced_word.
  • Convert the above-got word list to string using the join() function.
  • Print the above-obtained string to replace a word with an asterisk in a given input sentence.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random sentence = ")
# Give the replaceable word as user input using the input() function and store it in another variable.
gvn_wrd = input("Enter some random word = ")
# Split the given string into a list of words using the split() function and
# store it in another variable say "wrd_lst".
wrd_lst = gvn_str.split()
# Multiply the asterisk symbol with the length of the given input word using
# the len() function and store it in another variable.
replacd_word = '*' * len(gvn_wrd)
# Loop in the above-obtained word list using the for loop.
for itr in range(len(wrd_lst)):
  # Check if the iterator value is equal to the given input word using the if
  # conditional statement.
 # check if thw word at the iterator index is equal is given
    if wrd_lst[itr] == gvn_wrd:
      # if it is truw thwn replce the word t the iterator index with the replaced word
        wrd_lst[itr] = replacd_word
# Convert the above-got word list to string using the join() function.
finl_str = ' '.join(wrd_lst)
# Print the above-obtained string to replace a word with an asterisk in a
# given input sentence.
print("The given string [", gvn_str,
      "] after replacing with a given word with an asterisk :")
print(finl_str)

Output:

Enter some random sentence = good morning this is btechgeeks good morning all
Enter some random word = good
The given string [ good morning this is btechgeeks good morning all ] after replacing with a given word with an asterisk :
**** morning this is btechgeeks **** morning all

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.

Binary representation python – Python Program to Print Binary Representation of a Number

Program to Print Binary Representation of a Number

Binary Representation:

Get binary representation python: Binary (or base-2) is a numeral system with only two digits — 0 and 1. Computers use binary to store data and execute calculations, which means they only use zeros and ones. In Boolean logic, a single binary digit can only represent True (1) or False (0). Any integer, in fact, can be represented in binary.

Given a decimal number the task is to convert the given decimal to binary

Examples:

Example1:

Input:

given number =200

Output:

The binary representation of the given number 200  : 
11001000

Example2:

Input:

given number =1

Output:

The binary representation of the given number 1: 
1

Example3:

Input:

given number =32

Output:

The binary representation of the given number 32  : 
100000

Python Program to Print Binary Representation of a Number

Binary representation python: There are several ways to print the binary representation of a given decimal number some of them are:

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

Method #1:Using recursive function

Binary representation python: To find a binary equivalent, divide the decimal number recursively by the value 2 until the decimal number hits zero. The remaining must be noted after each division. The binary equivalent of the decimal number is obtained by reversing the remaining values.

Algorithm:

  1. Get the given decimal number from the user or static input.
  2. If the input is larger than zero, divide it by 2 and record the remainder.
  3. Step 2 should be repeated until the decimal number reaches zero.
  4. The residual values should be printed.
  5. End of program

Below is the implementation:

def decitoBin(numb):
    # checking if the given number is greater than 1
    if numb > 1:
        # if it is greater than 1 then use recursive approach by dividing number by 2
        decitoBin(numb // 2)
    # printing the binary representation of the given number
    print(numb % 2, end='')


# Driver code
given_numb = 200
# passing given number to decitoBin function to print binary representation of the givennumb
print("The binary representation of the given number", given_numb, " : ")
decitoBin(given_numb)

Output:

The binary representation of the given number 200  : 
11001000

Method #2:Using while loop

Approach:

  • First we take a empty string say binstr.
  • We use while loop .
  • We will iterate till the number is greater than 0 (Condition of while statement)
  • We will get the last check bit whether it is set bit or not using % operator
  • Convert the set bit to string using str() function
  • Concatenate this bit(can be 1 or 0 ) to the binstr.
  • Reverse this binstr using slicing
  • Print the binary representation of the given number that is print binstr.

Below is the implementation:

def decitoBin(numb):
    # checking if the given number is greater than 1
    if numb > 1:
      # taking a empty string
        binastring = ""
        # looping till number greater than 0 using while loop
        while(numb > 0):
            # We will get the last check bit whether it is set bit or not using % operator
            checkbit = numb % 2
            # converting this checkbit to string using str() function
            checkbit = str(checkbit)
            # Concatenate this bit(can be 1 or 0 ) to the binstr.
            binastring = binastring+checkbit
            # divide the number by 2
            numb = numb//2
    # reverse the binary string
    binastring = binastring[::-1]
    # return the resultant binary string
    return binastring


# Driver code
given_numb = 200
# passing given number to decitoBin function to print binary representation of the givennumb
print("The binary representation of the given number", given_numb, " : ")
print(decitoBin(given_numb))

Output:

The binary representation of the given number 200  : 
11001000

Method #3:Using Built in Python function bin()

Approach:

  • We will use bin() function to convert the given decimal number to binary representation.
  • It will return the result in the form of  0bXXXXXXXXX where XXXXXXXX is binary representation.
  • To remove that 0b characters from the string we use two methods
  • Print the resultant binary representation.

i)Using replace function

We will replace the 0b in the binary string with empty string.

Below is the implementation:

def decitoBin(numb):
  # converting it to binary representation using bin() function
    binNumb = bin(numb)
    # replacing '0b' using replace function and replacing it with empty string
    binNumb = binNumb.replace('0b', '')
  # return the binary representation of the given number
    return binNumb


# Driver code
given_numb = 200
# passing given number to decitoBin function to print binary representation of the givennumb
print("The binary representation of the given number", given_numb, " : ")
print(decitoBin(given_numb))

Output:

The binary representation of the given number 200  : 
11001000

The binary representation of the given decimal number will be printed.

ii)Using slicing

We will slice from 2 index to last index of the result returned by binary string

Below is the implementation:

def decitoBin(numb):
  # converting it to binary representation using bin() function
    binNumb = bin(numb)
    # We will slice from 2 index to last index of the result returned by binary string
    binNumb = binNumb[2:]
  # return the binary representation of the given number
    return binNumb


# Driver code
given_numb = 200
# passing given number to decitoBin function to print binary representation of the givennumb
print("The binary representation of the given number", given_numb, " : ")
print(decitoBin(given_numb))

Output:

The binary representation of the given number 200  : 
11001000

The binary representation of the given decimal number will be printed.

Related Programs:

Fibonacci python recursion – Python Program to Find the Fibonacci Series Using Recursion

Program to Find the Fibonacci Series Using Recursion

Fibonacci python recursion: Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Fibonacci Sequence:

Fibonacci recursion python: The Fibonacci Sequence is a series of integers named after the Italian mathematician Fibonacci. It is merely a string of numbers that begins with 0 and 1 and is then followed by the addition of the two numbers before it.

Recursion:

Python fibonacci recursive: If you’re familiar with Python functions, you’ll know that it’s typical for one function to call another. It is also feasible for a function in Python to call itself! A recursive function calls itself, and the process of using a recursive function is known as recursion.

Although it may appear strange for a function to call itself, many sorts of programming challenges are better stated recursively.

Given a number, the task is to find the Fibonacci sequence till the given number using recursion.

Examples:

Example1:

Input:

given number = 23

Output:

The Fibonacci Sequence till the given number 23  = 
Number =  0
Number =  1
Number =  1
Number =  2
Number =  3
Number =  5
Number =  8
Number =  13
Number =  21
Number =  34
Number =  55
Number =  89
Number =  144
Number =  233
Number =  377
Number =  610
Number =  987
Number =  1597
Number =  2584
Number =  4181
Number =  6765
Number =  10946
Number =  17711

Example2:

Input:

given number =13

Output:

Enter some random number = 13
The Fibonacci Sequence till the given number 13 = 
Number = 0
Number = 1
Number = 1
Number = 2
Number = 3
Number = 5
Number = 8
Number = 13
Number = 21
Number = 34
Number = 55
Number = 89
Number = 144

Program to Find the Fibonacci Series Using Recursion

Fibonacci series using recursion in java: Below are the ways to find the Fibonacci Series using the recursive approach in Python:

1)Using Recursion(Static Input)

Approach:

  • The user must give the number as static input and store it in a variable.
  • Pass the given number as a parameter to the Fibonacci recursive function.
  • The base condition is defined as a value that is less than or equal to 1.
  • Otherwise, call the function recursively with the argument as the number minus 1 plus the function that was called recursively with the parameter as the number minus 2.
  • Use a for loop to return the Fibonacci sequence and return the result and print the result.
  • The exit of the program.

Below is the implementation:

# function which finds the fibonacci sequence recursively
def fibonacciRecursion(numb):
  # The base condition is defined as a value that is less than or equal to 1.
    if(numb <= 1):
        return numb
    else:
      # Otherwise, call the function recursively with the argument as the number minus 1 plus the function that was called
      # recursively with the parameter as the number minus 2.
        return(fibonacciRecursion(numb-1) + fibonacciRecursion(numb-2))


# The user must give the number as static input and store it in a variable.
numb = 23
print("The Fibonacci Sequence till the given number", numb, ' = ')
# Looping from 1 to given number using for loop
for n in range(numb):
  # passing the iterter value as argument to the recursive function fibonacciRecursion
    print('Number = ', fibonacciRecursion(n))

Output:

The Fibonacci Sequence till the given number 23  = 
Number =  0
Number =  1
Number =  1
Number =  2
Number =  3
Number =  5
Number =  8
Number =  13
Number =  21
Number =  34
Number =  55
Number =  89
Number =  144
Number =  233
Number =  377
Number =  610
Number =  987
Number =  1597
Number =  2584
Number =  4181
Number =  6765
Number =  10946
Number =  17711

In this way, we can print the Fibonacci sequence of the given number using recursion.

2)Using Recursion(User Input)

Approach:

  • The user must give the number as user input using the int(input()) function and store it in a variable.
  • Pass the given number as a parameter to the Fibonacci recursive function.
  • The base condition is defined as a value that is less than or equal to 1.
  • Otherwise, call the function recursively with the argument as the number minus 1 plus the function that was called recursively with the parameter as the number minus 2.
  • Use a for loop to return the Fibonacci sequence and return the result and print the result.
  • The exit of the program.

Below is the implementation of the above approach:

# function which finds the fibonacci sequence recursively
def fibonacciRecursion(numb):
  # The base condition is defined as a value that is less than or equal to 1.
    if(numb <= 1):
        return numb
    else:
      # Otherwise, call the function recursively with the argument as the number minus 1 plus the function that was called
      # recursively with the parameter as the number minus 2.
        return(fibonacciRecursion(numb-1) + fibonacciRecursion(numb-2))


# The user must give the number as user input using the
# int(input()) function and store it in a variable.
numb = int(input('Enter some random number = '))
print("The Fibonacci Sequence till the given number", numb, ' = ')
# Looping from 1 to given number using for loop
for n in range(numb):
  # passing the iterter value as argument to the recursive function fibonacciRecursion
    print('Number = ',fibonacciRecursion(n))

Output:

Enter some random number = 13
The Fibonacci Sequence till the given number 13 = 
Number = 0
Number = 1
Number = 1
Number = 2
Number = 3
Number = 5
Number = 8
Number = 13
Number = 21
Number = 34
Number = 55
Number = 89
Number = 144

Explanation:

  • The number of terms must be entered by the user and saved in a variable.
  • A recursive function takes the number as a parameter.
  • The number must be less than or equal to one as a starting point.
  • Otherwise, the function is run recursively with the number minus 1 as an input, which is added to the function that is called recursively with the number minus 2.
  • The result is returned, and the Fibonacci sequence is printed using a for statement.
  • In this way, we can print the Fibonacci sequence of the given number using recursion.

Related Programs:

Python convert json to csv – How To Convert JSON To CSV File in Python?

How To Convert JSON To CSV File in Python

What do you mean by CSV File?

Python convert json to csv: A CSV file, which stands for Comma Separated Values file, is a simple text file that maintains a list of data. CSV files are commonly used to exchange data between different applications. Contact Managers and Databases, for example, typically support CSV files.

These CSV files are also known as Comma Separated Values or Comma Delimited Files. These files primarily use the comma character to delimit or segregate data. However, other characters, such as semicolons, are sometimes used. The plan is to export complex data from one program to a CSV file and then import the data from the CSV file into another program.

A Comma Separated Values (CSV) file has a simple structure that contains some data that is listed and separated by commas. CSV files are constructed in such a way that they may simply import and export data from other applications. The resulting data is easily readable by humans and may be seen using a text editor like Notepad or a spreadsheet program like Microsoft Excel or Google Sheets.

What do you mean by JSON Array?

Convert json to csv python: JSON (JavaScript Object Notation) is a dictionary-like notation that may be utilized in Python by importing the JSON module. Every record (or row) is preserved as its own dictionary, with the column names serving as the dictionary’s Keys. To make up the whole dataset, all of these records are kept as dictionaries in a nested dictionary. It is saved together with the extension. geeksforgeeks.json

JSON format was actually based on a subset of JavaScript. It is, nevertheless, referred to as a language-independent format, and it is supported by a wide range of programming APIs. In most cases, JSON is used in Ajax Web Application Programming. Over the last few years, the popularity of JSON as an alternative to XML has gradually increased.

While many programs use JSON for data transfer, they may not keep JSON format files on their hard drive. Data is exchanged between computers that are linked via the Internet.

Convert JSON To CSV File in Python

Python write json to csv: Let us consider the below JSON file as an example:

samplefile.json:

{
   "Name":"Vikram",
   "Branch":"Cse",
   "year":2019,
   "gpa":[
      9.1,
      9.5,
      9.6,
      9.2
   ]
}

Now we create an empty CSV file say demo.csv.

Here, we convert the above-given JSON array file data into a CSV file and store it in demo.csv.

Approach:

  • Import csv module using the import keyword.
  • Import json module using the import keyword.
  • Open some random JSON file in read-only mode using the open() function and store it in a variable
  • Open an empty CSV file in write mode using the open() function and store it in another variable
  • Pass the above-given json file to the load() function of the json module to convert the json file data into a dictionary
  • Pass the above-given csv file to writer() function of the csv module to pass the given csv to the writer() function of csv file and store it in a variable to write content/data to csv file
  • Write all the key values of the json file using writerow() function and apply it to the above writing object
  • Write all the dictionary values of the json file using writerow() function and apply it to the above writing object
  • Close the given JSON file using the close() function.
  • Close the given CSV file using the close() function.
  • The Exit of the Program.

Below is the implementation:

# Import csv module using the import keyword.
import csv  
# Import json module using the import keyword.
import json  
# Open some random JSON file in read-only mode using the open() function 
# and store it in a variable
gvn_jsonfile =open('samplefile.json','r')
# Open an empty CSV file in write mode using the open() function 
# and store it in another variable
gvn_csvfile=open('demo.csv','w')

# Pass the above given json file to the load() function of the json module
# to convert the json file data into a dictionary
dictionary =json.load(gvn_jsonfile)
# Pass the above given csv file to writer() function of the csv module to 
# pass the given csv to writer() function of csv file and store it in a variable to write content/data to csv file
write=csv.writer(gvn_csvfile)
# Write all the key values of the json file using writerow() function and 
# apply it on the above writing object 
write.writerow(dictionary.keys())
# Write all the dictionary values of the json file using writerow() function and 
# apply it on the above writing object 
write.writerow(dictionary.values())

# Close the given JSON file using the close() function
gvn_jsonfile.close()
# Close the given CSV file using the close() function
gvn_csvfile.close()

Output:

csv output of the json file

Python dict pop vs del dict – Remove a key from Dictionary in Python | del vs dict.pop() vs comprehension

How to remove a key from dictionary using del vs dict.pop() vs comprehension in python ?

Python dict pop vs del dict: As we know, Dictionary plays an important role in python data structure.

  • The elements are written with in { }curly brackets, having keys and values.
  • Each key-value pair mapped with the key to its related value.
  • In Dictionaries duplicates are not allowed.
Syntax : mydict = {key1: value1, key2: value2}

In this article, we will discuss about different ways to remove a key from dictionary in python.

Let us assume we have a dictionary with correspondent keys and values:

#dictionary with keys with their correspondent values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}

Now we will see different method to delete an key from dictionary :

Method -1 : Using dict.pop( ) method :

Python dict pop: This pop() method is used to delete a key and its value in its place. The advantage over using del is that it provides a mechanism to print the desired value if you try to remove a non-existent spelling. Secondly it also returns the value of the key that is removed as well as performs a simple delete operation.

#Program :

#dictionary test_dict
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
#this key will be deleted
key_to_be_deleted = 'Sagar'
# As 'Sagar' key is present in dictionary, so pop() will delete
# its entry and return its value
result = test_dict.pop(key_to_be_deleted, None)
print("Deleted item's value = ", result)
print("Updated Dictionary :", test_dict)
Output
Deleted item's value = 36
Updated Dictionary : {'Ram': 32, 'Dhruv': 45}

In case the key does not exist :

Python pop vs del: We use try/except method to avoid error. We know key ‘Soni’ is not in dictionary. So, an error will generate. To avoid error try/except method will be used.

#Program :

#dictionary test_dict
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}

#Deleting key which does not exist i.e Soni
key_to_be_deleted = 'Soni'
try:
    test_dict.pop(key_to_be_deleted)
except KeyError:
    print('That Key is not in the dictionary')
Output :
That is not present in the dictionary

Method-2 : Using items() & for loop :

Python dict pop: By using item() method and for loop we will iterate over the dictionary. When the key that will be deleted will be matched then delete that key.

Let’s see a program how it’s implemented.

#Program :

# Dictionary with keys and values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# key that to be deleted
key_to_be_deleted = 'Dhruv'
new_dict = {}
#using for loop 
#Iterate one by one key#If found that key then delete
for key, value in test_dict.items():
 if key is not key_to_be_deleted:
  new_dict[key] = value
test_dict = new_dict
print(test_dict)
Output
{'Ram': 32, 'Dhruv': 45}

Here for deletion we used for loop and We created a new temporary dictionary and then duplicated it for all key-value pairs in the original dictionary. During iteration, we copy the key and value pair into a new temporary dictionary only if the key is not equal to the key to be deleted. Once the duplication finished, we copied the contents of the new temporary dictionary into the original dictionary.

Method-3: Using items() & Dictionary Comprehension :

Dict pop python: Utilizing the logic of the above example we use items() & dictionary comprehension.

#Program :

# Dictionary with keys and values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# key that to be deleted
key_to_be_deleted = 'Ram'
test_dict = {key: value for key, value\
                  in test_dict.items()\
                  if key is not key_to_be_deleted}
print(test_dict)
Output:
{'Ram': 32, 'Dhruv': 45}

Method-4: Using del keyword :

Remove from dict python: We can use the del statement to delete a key-value pair from the dictionary regarding on the key.

Syntax : del dict[key]

Let’s use it-

#Program :

# Dictionary of keys &values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# Deleting an item from dictionary using del
del test_dict['Dhruv']
print(test_dict)
Output:
{'Sagar': 36, 'Ram':32}

In case the key does not exist :
Suppose we want to delete key 'Soni', which does not exist then we can use try-except to avoid any exception.

Let’s see the implementation of it.

#Program :

# Dictionary of keys &values
test_dict= { 'Ram': 32, 'Sagar': 36, 'Dhruv': 45}
# If key exist in dictionary then delete it using del.
key_to_be_deleted = 'Soni'
try:
 del test_dict[key_to_be_deleted]
except KeyError:
 print('That key is not present in the dictionary')
Output:
That key is not present in the dictionary

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

Program to Find the Cumulative Sum of a List

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

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

Lists in Python

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

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

Cumulative Sum

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

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

Cumulative Sum in Python Examples

Example 1:

Input:

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

Output:

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

Example 2:

Input:

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

Output:

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

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

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

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

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

Approach:

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

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

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

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

Output:

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

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

Approach:

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

Below is the implementation:

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

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

Output:

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

Method #3:Using Slicing (Static Input)

Approach:

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

Below is the implementation:

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

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

Output:

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

Python iterate dictionary with index – Python: Iterate Over Dictionary with Index

Python iterate dictionary with index: Dictionaries are the implementation by Python of a knowledge structure associative array. A dictionary is a collection of pairs of key values. A key pair and its associated value represent each key pair.
The list of key value pairs in curly braces that’s separated by comma defines a dictionary. Column ‘:’ separates the value of each key.
A dictionary can’t be sorted only to urge a representation of the sorted dictionary. Inherently, dictionaries are orderless, but not other types, including lists and tuples. Therefore, you would like an ordered data type, which may be a list—probably an inventory of tuples.

Examples:

Input :

dictionary = {'This': 100, 'is':200, 'BTechGeeks':300}

Output:

index = 0  ; key = this  ; Value = 200
index = 1  ; key = is  ; Value = 100
index = 2  ; key = BTechGeeks  ; Value = 300

Traverse the Dictionary with Index

1)Enumerate() function:

How to iterate over a dictionary in python: When working with iterators, we frequently encounter the need to keep track of the number of iterations. Python makes it easier for programmers by providing a built-in function enumerate() for this purpose.
Enumerate() adds a counter to an iterable and returns it as an enumerate object. This enumerate object can then be utilized in for loops directly or converted into an inventory of tuples using the list() method.

Syntax:

enumerate(iterable, start=0)

Parameters:

iterable:  an iterator, a sequence, or objects that support iteration

start :   the index value from which the counter will be started; the default value is 0.

Return:

The method enumerate() adds a counter to an iterable and returns it. The object returned is an enumerate object.

2)Traverse over all key-value pairs of given dictionary by index

We can traverse over the dictionary by passing given dictionary as parameter in enumerate() function

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Traverse all key-value pairs of given dictionary by index
for i, key in enumerate(dictionary):
    print('index =', i, ' ; key =', key, ' ; Value =', dictionary[key])

Output:

index = 0  ; key = this  ; Value = 200
index = 1  ; key = is  ; Value = 100
index = 2  ; key = BTechGeeks  ; Value = 300

3)Traverse over all keys of given dictionary by index

The dictionary class’s keys() function returns an iterable sequence of all the dictionary’s keys. We can pass that to the enumerate() function, which will return keys as well as index position.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Traverse all keys of given dictionary by index
for i, key in enumerate(dictionary.keys()):
    print('index =', i, ' ; key =', key)

Output:

index = 0  ; key = this
index = 1  ; key = is
index = 2  ; key = BTechGeeks

4)Traverse over all values of given dictionary by index

The dictionary class’s values() function returns an iterable sequence of all the dictionary’s values. We can pass that to the enumerate() function, which will return values as well as index position.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Traverse all values of given dictionary by index
for i, value in enumerate(dictionary.values()):
    print('index =', i, ' ; value =', value)

Output:

index = 0  ; value = 200
index = 1  ; value = 100
index = 2  ; value = 300

Related Programs: