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 f-strings with Examples

f-strings with Examples

Python f string examples: PEP 498 created a new string formatting mechanism known as Literal String Interpolation, or F-strings (because of the leading f character preceding the string literal). The goal of f-strings is to make string interpolation easier.

Prefix the string with the letter ” f ” to make an f-string. The string itself can be formatted in the same way that str.format() does. f-strings are a simple and convenient approach to format python expressions by embedding them inside string literals.

Requirement for f-strings in Python:

Python f string example: The Python f-string is mostly used for string formatting. Prior to the advent of “f-strings,” we had the following methods for formatting strings in Python:

1) ‘%’ Operator:

The Python percentile(%) operator is incompatible with Objects and attributes. It cannot be used with objects and attributes. This is the main disadvantage of it.

2)format() Method:

Although the string.format() function was able to overcome the disadvantage of the ‘%’ operator, it proved to be a lengthy method of formatting. This is the main disadvantage of the format() method.

As a result, Python f-strings were created, allowing strings to be interpolated and formatted with considerably simpler and minimum syntax. The Python interpreter formats the strings at runtime.

f-strings with Examples

The f-string, also known as formatted strings, is used for Literal String Interpolation, which is the injection of strings and formatting of the specified string.

Syntax:

f '{string}'

Example

Approach:

  • Give the first string as static input and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Format the given two strings using ‘f’ as the preceding character (f-string).
  • Store it in another variable.
  • Print the above-obtained formatted string.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as static input and store it in a variable.
gvn_fststr = 'Btechgeeks'
# Give the second string as static input and store it in another variable.
gvn_scndstr = 'Hello'
# Format the given two strings using 'f' as the preceding character(f-string).
# Store it in another variable.
rslt_str = f'{gvn_scndstr} this is {gvn_fststr}'
# Print the above-obtained formatted string
print("The above-obtained formatted string is:\n", rslt_str)

Output:

The above-obtained formatted string is:
 Hello this is Btechgeeks

Here, f-string is used to inject or interpolate the input strings gvn_fststr and gvn_scndstr between string statements.

f-strings with Raw Strings:

Python raw strings treat special characters known as ‘escape sequences’ as literal characters. It is utilized when we wish escape sequences, such as ‘\n’ or backslash(\), to be literal sequences of characters.

Syntax: (raw string)

r 'string'

Python f-strings can be used simultaneously with raw strings.

Syntax: (f-strings with Raw Strings)

fr 'string or {string}'

Example

# Give the first string as static input and store it in a variable.
gvn_fststr = 'Btechgeeks'
# Give the second string as static input and store it in another variable.
gvn_scndstr = 'Hello'
# Format the given two strings using 'fr' as the preceding characters(f-string with
# the raw-string).
# Store it in another variable.
rslt_str = fr'{gvn_scndstr}\n this is {gvn_fststr}'
# Print the above-obtained formatted string
print("The above-obtained formatted string is:\n", rslt_str)

Output:

The above-obtained formatted string is:
 Hello\n this is Btechgeeks

Explanation:

Here, '\n' is considered as a literal character.

Functions Calling Using f-string

Python f-strings allow us to call functions from within them. As a result, the code has been optimized to some extent. A similar method can be used to create lambda functions inside f-string braces.

Syntax:

f'{func()}'

Example

Approach:

  • Create a function say ‘addition’ which accepts two numbers as the argument and returns the addition of two numbers.
  • Inside the function add both the given numbers and store it in a variable.
  • Return the above result i.e, the sum of both the given numbers.
  • Pass two random numbers to the above-created function ‘addition’ with ‘f’ as the preceding character.
  • Store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Create a function say addition which accepts two numbers as the argument and
# returns the addition of two numbers.


def addition(num_1, num_2):
    # Inside the function add both the given numbers and store it in a variable.
    rsltsum = num_1+num_2
    # Return the above result i.e, the sum of both the given numbers.
    return rsltsum


# Pass two random numbers to the above-created function 'addition' with 'f'
# as the preceding character.
# Store it in another variable.
addtn_rslt = f'{addition(30,40)}'
# Print the above result.
print("The sum of given two numbers = ", addtn_rslt)

Output:

The sum of given two numbers =  70

f-string in Python with blank or white-spaces

The f-strings in python can also work with whitespaces and blanks. The trailing and leading white spaces are ignored, and the spaces between the literal string are unchanged.

Example

addtn_rslt = f'  The sum of given two numbers: { 30 + 40 }  '
print(addtn_rslt)

Output:

The sum of given two numbers: 70

f-string in Python with Expressions

Expressions can be used with Python f-string. As a result, simple modifications can be carried out directly within the f-string.

Syntax:

f '{expression}'

Example

# Give the first number as static input and store it in a variable.
num_1 = 50
# Give the second number as static input and store it in another variable.
num_2 = 30
# Using f-string with the expression and printing it
print(f'The sum of 30 and 50 = {num_1+num_2}')

Output:

The sum of 30 and 50 = 80

f-string in Python with Dictionary

The Python dictionary data structure operates with key-value pairs. Along with the dictionaries, Python f-strings can be framed.

Syntax:

f"{dictionary['key']}"

Example

# Give the dictionary as static input and store it in a variable.
gvn_dictnry = {'hello': 100, 'btechgeeks': 200}
# Print the value of the key of the dictionary(btechgeeks) using the f-string
print(f"{gvn_dictnry['btechgeeks']}")

Output:

200

 

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:

Python program to calculate the average of numbers in a given list – Python Program to Calculate the Average of Numbers in a Given List

Program to Calculate the Average of Numbers in a Given List

Python program to calculate the average of numbers in a given list: 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.

List in Python :

List average 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 Calculate the average of all the numbers in the given list in python.

Examples:

Example1:

Input:

given list = [8, 9, 1, 23, 15, 20, 19, 13, 8, 7, 5, 2, 7, 10, 14, 16]

Output:

The average value of the given list [8, 9, 1, 23, 15, 20, 19, 13, 8, 7, 5, 2, 7, 10, 14, 16] = 11.0625

Example2:

Input:

given list = [  47 24.5 27 28 11 23 34.8 33 31 29 45 37 39 ]

Output:

The average value of the given list [47.0, 24.5, 27.0, 28.0, 11.0, 23.0, 34.8, 933.0, 31.0, 29.0, 45.0, 37.0, 39.0] = 100.71538461538461

Program to Calculate the Average of Numbers in a Given List in Python

Python average list: There are several ways to calculate the average of all numbers in the given list 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: Counting sum manually ( Static Input separated by spaces)

Approach:

  • Give the list input as static
  • Take a variable say sumOfList which stores the sum of all list elements and initialize it to 0.
  • Traverse the list using for loop
  • For each iteration add the  iterator value to the sumOfList.
  • Calculate the length of list using len() function.
  • Calculate the average of given list by Dividing sumOfList with length.
  • Print the Average

Below is the implementation:

# given list
given_list = [8, 9, 1, 23, 15, 20, 19, 13, 8, 7, 5, 2, 7, 10, 14, 16]
# Take a variable say sumOfList which stores the
# sum of all list elements and initialize it to 0.
sumOfList = 0
# Traverse the given list using for loop
for eleme in given_list:
    # Add the iterator value to the sumOfList after each iteration.
    sumOfList = sumOfList+eleme
# calculating the length of given list using len() function
length = len(given_list)
# Calculate the average value of the given list by Dividing sumOfList with length
listAvg = sumOfList/length
# printng the  the average value of the given list
print("The average value of the given list", given_list, "=", listAvg)

Output:

The average value of the given list [8, 9, 1, 23, 15, 20, 19, 13, 8, 7, 5, 2, 7, 10, 14, 16] = 11.0625

Method #2:Using sum() function ( Static Input separated by spaces)

Approach:

  • Give the list input as static
  • Calculate the sum of list using sum() function and store it in variable sumOfList.
  • Calculate the length of list using len() function.
  • Calculate the average of given list by Dividing sumOfList with length.
  • Print the Average

Below is the implementation:

# given list
given_list = [8, 9, 1, 23, 15, 20, 19, 13, 8, 7, 5, 2, 7, 10, 14, 16]
# Calculating the sum of list using sum() function and store it in variable sumOfList.
sumOfList = sum(given_list)

# calculating the length of given list using len() function
length = len(given_list)
# Calculate the average value of the given list by Dividing sumOfList with length
listAvg = sumOfList/length
# printng the  the average value of the given list
print("The average value of the given list", given_list, "=", listAvg)

Output:

The average value of the given list [8, 9, 1, 23, 15, 20, 19, 13, 8, 7, 5, 2, 7, 10, 14, 16] = 11.0625

Method #3:Using sum() function ( User Input separated by spaces)

Approach:

  • Scan the list separated by spaces using map, list(),split() and float functions (Because list values can be decimal also).
  • Calculate the sum of list using sum() function and store it in variable sumOfList.
  • Calculate the length of list using len() function.
  • Calculate the average of given list by Dividing sumOfList with length.
  • Print the Average

Below is the implementation:

# Scan the list separated by spaces using map and float functions (Because list values can be decimal also)
given_list =list(map(float,input("Enter some random elements of the list : ").split()))
# Calculating the sum of list using sum() function and store it in variable sumOfList.
sumOfList = sum(given_list)

# calculating the length of given list using len() function
length = len(given_list)
# Calculate the average value of the given list by Dividing sumOfList with length
listAvg = sumOfList/length
# printng the  the average value of the given list
print("The average value of the given list", given_list, "=", listAvg)

Output:

Enter some random elements of the list : 47 24.5 27 28 11 23 34.8 33 31 29 45 37 39
The average value of the given list [47.0, 24.5, 27.0, 28.0, 11.0, 23.0, 34.8, 933.0, 31.0, 29.0, 45.0, 37.0, 39.0] = 100.71538461538461

Explanation :

We used the split function to split the input string separated by spaces, then used the map function to convert all of the strings to floats and placed all of the items in a list.

Related Articles:

Numpy var – Python NumPy var() Function

Python NumPy var() Function

NumPy var() Function:

Numpy var: The variance along the specified axis is calculated using the NumPy var() function. The variance is a measure of the spread of the distribution. By default, the variance is calculated for the flattened array, but it can also be done for the given axis.

Syntax:

numpy.var(a, axis=None, dtype=None, out=None, keepdims=<no value>)

Parameters

a: This is required. It is an array given as input.

axis: This is optional. Indicate which axis or axes will be used to determine the variance. The default, axis=None, computes the flattened array’s variance.

dtype: This is optional. Indicate the type that will be used to calculate the variance. The default for integer arrays is float64, but the default for float arrays is the same as the array type.

out: This is optional. Indicate the output array in which the result will be stored. It must be the same shape as the desired result.

keepdims: The reduced axes are left in the output as dimensions with size one if this is set to True. The result will broadcast correctly against the input array if you use this option.

Return Value:

np var: If out=None, an array containing the variance is returned; otherwise, a reference to the output array is returned.

NumPy var() Function in Python

Example1

Approach:

  • Import numpy module using the import keyword
  • Pass some random list as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Pass the given array as an argument to the var() function of numpy module to calculate the variance of all values in the given array
  • Store it in another variable.
  • Print the variance of all values in the given array.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([[5,25],[35, 40]])              
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the given array as an argument to the var() function of numpy module 
# to calculate the variance of all values in the given array 
# Store it in another variable.
rslt = np.var(gvn_arry)
# Print the variance of all values in the given array 
print("The variance of all values in the given array =", rslt)

Output:

The above given array is:
[[ 5 25]
[35 40]]
The variance of all values in the given array = 179.6875

Example2

np.var: variance is calculated over the specified axes when the axis parameter is defined.

Approach:

  • Import numpy module using the import keyword
  • Pass some random list as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Pass the given array, axis=0 as the arguments to the var() function of numpy module to calculate the variance of all values in the given array along axis=0.
  • Store it in another variable.
  • Print the variance of all values the given array along axis=0
  • Pass the given array, axis=0 as the arguments to the var() function of numpy module to calculate the variance of all values in the given array along axis=1.
  • Store it in another variable.
  • Print the variance of all values the given array along axis=1
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([[5, 25, 50],[35, 40, 60]])              
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the given array, axis=0 as the arguments to the var() function of numpy module 
# to calculate the variance of all values in the given array along axis=0
# Store it in another variable.
rslt_1 = np.var(gvn_arry, axis=0)
# Print the variance of all values the given array along axis=0
print("The variance of all values in the given array along axis=0: ", rslt_1)
# Pass the given array, axis=1 as the arguments to the var() function of numpy module 
# to calculate the variance of all values in the given array along axis=1
# Store it in another variable.
rslt_2 = np.var(gvn_arry, axis=1)
# Print the variance of all values the given array along axis=1
print("The variance of all values in the given array along axis=1: ", rslt_2)

Output:

The above given array is:
[[ 5 25 50]
[35 40 60]]
The variance of all values in the given array along axis=0: [225. 56.25 25. ]
The variance of all values in the given array along axis=1: [338.88888889 116.66666667]

Example3

The variance can be calculated in float64 for a more accurate result.

Approach:

  • Import numpy module using the import keyword
  • Pass some random list as an argument to the array() function to create an array.
  • Store it in a variable.
  • Pass the given array, datatype float32 as the arguments to the var() function of numpy module to calculate the variance of all values in the given array with float32 and print it.
  • Pass the given array, datatype float64 as the arguments to the var() function of numpy module to calculate the variance of all values in the given array with float64 and print it.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([10, 5, 55, 200])              
# Pass the given array, datatype float32 as the arguments to the var() function of numpy module 
# to calculate the variance of all values in the given array with float32 and print it
print("The variance of all values in the given array with float32:")
print(np.var(gvn_arry, dtype=np.float32))
# Pass the given array, datatype float64 as the arguments to the var() function of numpy module 
# to calculate the variance of all values in the given array with float64 and print it
print("The variance of all values in the given array with float64:")
print(np.var(gvn_arry, dtype=np.float64))

Output:

The variance of all values in the given array with float32:
6231.25
The variance of all values in the given array with float64:
6231.25

Python loop over dict – Python: Iterate Over Dictionary (All Key-Value pairs)

Python loop over dict: Python’s implementation of an associative array, which is a data structure, is dictionaries. A dictionary is a collection of key-value pairs. Each key-value pair represents a key and its associated value.

Enclosing a comma-separated list of key-value pairs in curly braces defines a dictionary { }. A colon ‘ : ‘ separates each key from its associated value.

Note:

  • Keys are mapped to values in dictionaries, which are then stored in an array or series.
  • The keys must be of the hashable form, which means that their hash value must remain constant over their lifetime.

The keys and values of a dictionary are iterated over in the same order as they were generated in Python 3.6 and later. However, this behaviour varies between Python versions and is dependent on the dictionary’s insertion and deletion history.

Examples:

Input :

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

Output:

This 100
is 200
BTechGeeks 300

Traverse the dictionary

Iterate over key value pairs python: There are several ways to traverse the dictionary some of them are:

Method #1: Using for loop

Iterate over dictionary python: To iterate over all keys in a dictionary, a dictionary object may also be used as an iterable object. As a result, we can apply for loop on a dictionary with ease. It loops through all the keys in the dictionary by using for in the dictionary. We will pick the value associated with each key and print it.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Using for loop to traverse the dictionary
for key in dictionary:
    # here key gives the key of the dictionary
    # Getting value at key
    value = dictionary[key]
    # printing values and keys
    print(key, value)

Output:

This 100
is 200
BTechGeeks 300

Method #2:Using items()

Iterate over keys and values python: When dealing with dictionaries, you’ll almost certainly want to use both the keys and the values. .items(), a method that returns a new view of the dictionary’s items, is one of the most useful ways to iterate through a dictionary in Python.

This sequence is an iterable View object that contains all of the dictionary’s key,value elements. It is supported by the original dictionary. Let’s use this to iterate over all of the dictionary’s key-value pairs.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Using items and converting dictionary to list
dictlist = list(dictionary.items())
# Traverse the dictlist and print key and values of dictionary
for i in dictlist:
  # printing key and value
    print(i[0], i[1])

Output:

This 100
is 200
BTechGeeks 300

Method #3:Using List Comprehension

Python iterate over a dictionary: Since the items() function of a dictionary returns an iterable sequence of key-value pairs, we may use this list comprehension to iterate over all diction pairs.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Using list comprehension
[print(key, value) for key, value in dictionary.items()]

Output:

This 100
is 200
BTechGeeks 300

Filtering Items in dictionary

Python for loop over dictionary: You can find yourself in a situation where you have an existing dictionary and want to construct a new one to store only the data that meets a set of criteria. This can be accomplished using an if statement inside a for loop, as shown below:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Create a new empty dictionary
newdictionary = dict()
# Traverse the original dictionary and check the condition
for key, value in dictionary.items():
    # If value meets the criteria, it should be saved in new dict.
    if value <= 200:
        newdictionary[key] = value
# printing the new dictionary
print(newdictionary)

Output:

{'This': 100, 'is': 200}

Related Programs:

Find the volume of the ellipsoid – Python Program to Calculate Volume of Ellipsoid

Program to Calculate Volume of Ellipsoid

Find the volume of the ellipsoid: In the previous article, we have discussed Python Program for Maximize Volume of Cuboid with Given Sum of Sides
Given the three radius values of an ellipsoid and the task is to calculate the volume of a given ellipsoid in python.

Ellipsoid :

Ellipsoid is a closed surface whose plane cross-sections are all ellipses or circles. An ellipsoid has three mutually perpendicular axes that intersect at the center. It is a three-dimensional, closed geometric shape with all of its planar sections being ellipses or circles.

An ellipsoid has three independent axes and is usually defined by the lengths of the three semi-axes, a, b, and c. If an ellipsoid is formed by rotating an ellipse about one of its axes, the ellipsoid’s two axes are the same, and it is known as an ellipsoid of revolution or spheroid. It is a sphere if the lengths of all three of its axes are the same.

Formula:

Volume = (4/3) * pi * r1 * r2 * r3

where pi = 3.1415…

r1 = first radius

r2 = second radius

r3 =  third radius

Examples:

Example1:

Input:

Given first radius = 1
Given second radius = 3
Given third radius = 6.5

Output:

The Volume of given ellipsoid with given radii { 1 3 6.5 } =  81.4772054708513

Example2:

Input:

Given first radius = 2
Given second radius = 4.5
Given third radius = 8

Output:

The Volume of given ellipsoid with given radii { 2 4.5 8 } =  300.8389125077586

Program to Calculate Volume of Ellipsoid in Python

Below are the ways to calculate the volume of a given ellipsoid in python:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Import math module using the import keyword.
  • Give the first radius as static input and store it in a variable.
  • Give the second radius as static input and store it in another variable.
  • Give the third radius as static input and store it in another variable.
  • Create a function to say Ellipsoid_volume() which takes the given three radii as the arguments and returns the volume of a given ellipsoid.
  • Inside the function, calculate the volume of the ellipsoid using the above given mathematical formula, math. pi and store it in a variable.
  • Return the above result.
  • Pass the given three radii as the arguments to the Ellipsoid_volume() function and print it.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math

# Create a function to say Ellipsoid_volume() which takes the given three radii as
# the arguments and returns the volume of a given ellipsoid.


def Ellipsoid_volume(fst_radiuss, scnd_radiuss, thrd_radiuss):
    # Inside the function, calculate the volume of the ellipsoid using the above given
    # mathematical formula, math.pi and store it in a variable.
    rslt_vol = 1.33 * math.pi * fst_radiuss * scnd_radiuss * thrd_radiuss
    # Return the above result.
    return rslt_vol


# Give the first radius as static input and store it in a variable.
fst_radiuss = 1
# Give the second radius as static input and store it in another variable.
scnd_radiuss = 3
# Give the third radius as static input and store it in another variable.
thrd_radiuss = 6.5
# Pass the given three radii as the arguments to the Ellipsoid_volume() function
# and print it.
print("The Volume of given ellipsoid with given radii {", fst_radiuss, scnd_radiuss, thrd_radiuss, "} = ",
      Ellipsoid_volume(fst_radiuss, scnd_radiuss, thrd_radiuss))
#include <iostream>
#include <cmath>

using namespace std;

int main() {
  double fst_radiuss = 1;
   double scnd_radiuss = 3;
   double thrd_radiuss = 6.5;
   double rslt_vol = 1.33 * M_PI * fst_radiuss * scnd_radiuss * thrd_radiuss;
 cout << "The Volume of given ellipsoid with given radii {" << fst_radiuss << ", " << scnd_radiuss << ", " << thrd_radiuss << "} = " << rslt_vol << rslt_vol;

}

Output:

The Volume of given ellipsoid with given radii { 1 3 6.5 } =  81.4772054708513

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Import math module using the import keyword.
  • Give the first radius as user input using the float(input()) function and store it in a variable.
  • Give the second radius as user input using the float(input()) function and store it in another variable.
  • Give the third radius as user input using the float(input()) function and store it in another variable.
  • Create a function to say Ellipsoid_volume() which takes the given three radii as the arguments and returns the volume of a given ellipsoid.
  • Inside the function, calculate the volume of the ellipsoid using the above given mathematical formula, math. pi and store it in a variable.
  • Return the above result.
  • Pass the given three radii as the arguments to the Ellipsoid_volume() function and print it.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math

# Create a function to say Ellipsoid_volume() which takes the given three radii as
# the arguments and returns the volume of a given ellipsoid.


def Ellipsoid_volume(fst_radiuss, scnd_radiuss, thrd_radiuss):
    # Inside the function, calculate the volume of the ellipsoid using the above given
    # mathematical formula, math.pi and store it in a variable.
    rslt_vol = 1.33 * math.pi * fst_radiuss * scnd_radiuss * thrd_radiuss
    # Return the above result.
    return rslt_vol


# Give the first radius as user input using the float(input()) function and 
# store it in a variable.
fst_radiuss = float(input("Enter some random number = "))
# Give the second radius as user input using the float(input()) function and 
# store it in another variable.
scnd_radiuss = float(input("Enter some random number = "))
# Give the third radius as user input using the float(input()) function and 
# store it in another variable.
thrd_radiuss = float(input("Enter some random number = "))
# Pass the given three radii as the arguments to the Ellipsoid_volume() function
# and print it.
print("The Volume of given ellipsoid with given radii {", fst_radiuss, scnd_radiuss, thrd_radiuss, "} = ",
      Ellipsoid_volume(fst_radiuss, scnd_radiuss, thrd_radiuss))

Output:

Enter some random number = 2
Enter some random number = 4.5
Enter some random number = 8
The Volume of given ellipsoid with given radii { 2.0 4.5 8.0 } = 300.8389125077586

 

Area of circle in python – Python Program for Area of a Circumscribed Circle of a Square

Program for Area of a Circumscribed Circle of a Square

Area of circle in python: In the previous article, we have discussed Python Program to Check if a given Circle lies Completely Inside the Ring formed by Two Concentric Circles
Given the side length of a square, the task is to calculate the area of a circumscribed circle around the given square.

Formula:

(pi * s* s)/2

where pi= 3.14159265

s = side length of square.

Examples:

Example1:

Input:

Given side of square = 5

Output:

The area of an circumscribed circle is for a given square of side { 5 } =  39.27

Example2:

Input:

Given side of square = 8

Output:

The area of an circumscribed circle is for a given square of side { 8 } =  100.53

Program for Area of a Circumscribed Circle of a Square in Python

Below are the ways to calculate the area of a circumscribed circle around the given square in python:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Give the side of a square as static input and store it in a variable.
  • Take a variable and initialize it with the pi value of 3.14159265.
  • Create a function to say Find_areacircumscribdcirle() which takes the given side length of the square as an argument, and returns the area of a circumscribed circle around the given square.
  • Inside the function, calculate the area of a circumscribed circle around the given square using the above mathematical formula and store it in a variable.
  • Return the above result.
  • Pass the given side length of the square as an argument to the Find_areacircumscribdcirle() function and store it in another variable.
  • Print the above result by rounding off to the 2 places after the decimal point using the round() function.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say Find_areacircumscribdcirle() which takes the given side
# length of the square as an argument, and returns the area of a circumscribed
# circle around the given square.


def Find_areacircumscribdcirle(sideof_sqre):
    # Inside the function, calculate the area of a circumscribed circle around the given
    # square using the above mathematical formula and store it in a variable.
    circl_area = (sideof_sqre * sideof_sqre * (pi / 2))
    # Return the above result.
    return circl_area


# Give the side of a square as static input and store it in a variable.
sideof_sqre = 5
# Take a variable and initialize it with the pi value of 3.14159265.
pi = 3.14159265
# Pass the given side length of the square as an argument to the
# Find_areacircumscribdcirle() function and store it in another variable.
fnl_rsltarea = Find_areacircumscribdcirle(sideof_sqre)
# Print the above result by rounding off to the 2 places after the decimal point using
# the round() function.
print("The area of an circumscribed circle is for a given square of side {", sideof_sqre, "} = ",
      round(fnl_rsltarea, 2))

Output:

The area of an circumscribed circle is for a given square of side { 5 } =  39.27

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Give the side of a square as user input using the float(input()) function and store it in a variable.
  • Take a variable and initialize it with the pi value of 3.14159265.
  • Create a function to say Find_areacircumscribdcirle() which takes the given side length of the square as an argument, and returns the area of a circumscribed circle around the given square.
  • Inside the function, calculate the area of a circumscribed circle around the given square using the above mathematical formula and store it in a variable.
  • Return the above result.
  • Pass the given side length of the square as an argument to the Find_areacircumscribdcirle() function and store it in another variable.
  • Print the above result by rounding off to the 2 places after the decimal point using the round() function.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say Find_areacircumscribdcirle() which takes the given side
# length of the square as an argument, and returns the area of a circumscribed
# circle around the given square.


def Find_areacircumscribdcirle(sideof_sqre):
    # Inside the function, calculate the area of a circumscribed circle around the given
    # square using the above mathematical formula and store it in a variable.
    circl_area = (sideof_sqre * sideof_sqre * (pi / 2))
    # Return the above result.
    return circl_area


# Give the side of a square as user input using the float(input()) function and
# store it in a variable.
sideof_sqre = float(input("Enter some random number = "))
# Take a variable and initialize it with the pi value of 3.14159265.
pi = 3.14159265
# Pass the given side length of the square as an argument to the
# Find_areacircumscribdcirle() function and store it in another variable.
fnl_rsltarea = Find_areacircumscribdcirle(sideof_sqre)
# Print the above result by rounding off to the 2 places after the decimal point using
# the round() function.
print("The area of an circumscribed circle is for a given square of side {", sideof_sqre, "} = ",
      round(fnl_rsltarea, 2))

Output:

Enter some random number = 8
The area of an circumscribed circle is for a given square of side { 8.0 } = 100.53

Access the big list of Python Programming Code Examples with actual logical code asked in Programming and Coding Interviews for Python and stand out from the crowd.