Top 5 python programs you must know

Top 5 Python programs you must know before entering a Python interview. Let’s start.

Fibonacci series: Program to Print the Fibonacci Sequence

The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 and then 1.

The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21
# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms
n1, n2 = 0, 1
count = 0

# check if the number of terms is valid
if nterms <= 0:
   print("Please enter a positive integer")
elif nterms == 1:
   print("Fibonacci sequence upto",nterms,":")
   print(n1)
else:
   print("Fibonacci sequence:")
   while count < nterms:
       print(n1)
       nth = n1 + n2
       # update values
       n1 = n2
       n2 = nth
       count += 1

Output

How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8

Explanation

This program is designed to display the Fibonacci sequence up to the nth term, where the value of n is entered by the user. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers.

The program starts by prompting the user to input the number of terms they want to see in the sequence. It then initializes the variables n1 and n2 to 0 and 1 respectively, representing the first two terms in the sequence. The variable count is also initialized to 0.

Next, the program checks if the number of terms entered by the user is valid. If it is less than or equal to zero, the program prints a message asking the user to enter a positive integer. If nterms equals 1, the program prints the first term in the sequence (which is 0).

If the number of terms entered is greater than 1, the program enters a while loop that runs until the count variable reaches the value of nterms. Inside the loop, the program first prints the current value of n1, representing the current term in the sequence. It then calculates the next term in the sequence (nth) by adding the current value of n1 and n2. Finally, the values of n1 and n2 are updated to prepare for the next iteration of the loop, and the count variable is incremented by 1.

The loop continues to execute until the desired number of terms (nterms) have been displayed, at which point the program terminates. Overall, this program is a simple but effective way to display the Fibonacci sequence up to a specified number of terms.

Armstrong number: Program to Check Armstrong Number

We call a positive integer an Armstrong number (of order n) if

abcd... = an + bn + cn + dn + 

In the case of an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself. For example, 153 is an Armstrong number because

153 = 1*1*1 + 5*5*5 + 3*3*3 
num = 1634

# Changed num variable to string, 
# and calculated the length (number of digits)
order = len(str(num))

# initialize sum
sum = 0

# find the sum of the cube of each digit
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** order
   temp //= 10

# display the result
if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")

Explanation

This code is designed to determine whether a given number is an Armstrong number or not. An Armstrong number is a number that is equal to the sum of its own digits raised to the power of the number of digits.

The code starts by initializing the variable num to the value 1634. It then converts this value to a string using the str() function and calculates the length (number of digits) of the resulting string using the len() function, assigning the result to the variable order.

Next, the program initializes the variable sum to 0, which will be used to calculate the sum of the cubes of each digit in the number. It then creates a temporary variable temp that is initialized to the value of num.

The program enters a while loop that will execute as long as temp is greater than 0. Inside the loop, the program first calculates the value of the rightmost digit in temp using the modulus operator (%) and assigns it to the variable digit. It then adds the cube of digit raised to the power of order to the variable sum. Finally, the program uses integer division (//) to remove the rightmost digit from temp and update its value.

Once the loop has finished executing, the program checks whether num is equal to sum. If they are equal, the program prints a message indicating that num is an Armstrong number. Otherwise, the program prints a message indicating that num is not an Armstrong number.

Overall, this code is a straightforward implementation of the algorithm for determining whether a given number is an Armstrong number or not, and can be easily adapted to work with other input values.

Anagram: Check if a given string is an anagram of another string

We call two strings anagrams if they contain the same set of characters but in a different order.

“keep? peek”, “Mother In Law – Hitler Woman”.

# Python program to check whether two strings are
# anagrams of each other
 
# function to check whether two strings are anagram
# of each other
 
 
def areAnagram(str1, str2):
# Get lengths of both strings
    n1 = len(str1)
    n2 = len(str2)
 
    # If lenght of both strings is not same, then
    # they cannot be anagram
    if n1 != n2:
        return 0
 
    # Sort both strings
    str1 = sorted(str1)
    str2 = sorted(str2)
 
# Compare sorted strings
for i in range(0, n1):
    if str1[i] != str2[i]:
        return 0
 
return 1
 
 
# Driver code
str1 = "test"
str2 = "ttew"
 
# Function Call
if areAnagram(str1, str2):
    print("The two strings are anagram of each other")
else:
    print("The two strings are not anagram of each other") 

Explanation

This code is designed to determine whether two given strings are anagrams of each other or not. An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once.

The code defines a function named areAnagram that takes two parameters, str1 and str2, which represent the two strings to be compared. The first part of the function calculates the length of each string and checks whether they are the same length. If they are not, then the function immediately returns 0, indicating that the two strings cannot be anagrams of each other.

If the lengths of the two strings are the same, the function sorts both strings using the sorted() function. This will rearrange the letters in each string so that they are in alphabetical order. The function then iterates over both strings, comparing each character in str1 with the corresponding character in str2. If any of the characters do not match, the function immediately returns 0, indicating that the two strings are not anagrams.

If the function completes the iteration without finding any non-matching characters, it returns 1, indicating that the two strings are anagrams of each other.

The code also includes a driver code section that initializes two string variables, str1 and str2, with the values “test” and “ttew”, respectively. The areAnagram function is then called with these two strings as arguments, and the program prints a message indicating whether the two strings are anagrams of each other or not.

Overall, this code provides a simple and efficient way to check whether two given strings are anagrams of each other, which can be useful in a variety of applications.

Palindrome numbers: How to check if a number is a palindrome?

A number is a palindrome if it reads the same forward and backward. For example, the number 1233321 is a palindrome.

 n = 353
 temp=n
 rev=0
 while(n>0):
     dig=n%10
     rev=rev*10+dig
     n=n//10
 if(temp==rev):
     print("The number is a palindrome!")
 else:
     print("The number isn't a palindrome!")

Explanation

This Python code checks whether a given integer number is a palindrome or not.

The code first initializes the variable n with the value 353. It then creates a copy of n and stores it in the variable temp. It also initializes another variable rev with the value 0.

Then, the code enters a while loop that continues as long as n is greater than 0. Inside the loop, the code first calculates the last digit of n using the modulus operator % and stores it in the variable dig. It then updates the value of rev by appending dig to the end of rev after multiplying it by 10. It then updates the value of n by dividing it by 10 using the floor division operator //.

After the loop ends, the code checks whether the original number temp is equal to the reversed number rev. If they are equal, the code prints the message “The number is a palindrome!”, otherwise it prints “The number isn’t a palindrome!”. In this case, since the original number n is 353, which is the same when read from left to right or from right to left, the code prints “The number is a palindrome!”.

Co-prime numbers: Check if two numbers are co-prime or not.

We say two numbers A and B as Co-Prime or mutually prime if the Greatest Common Divisor of them is 1.

Given two numbers A and B, find if they are Co-prime or not.

Input : 2 3
Output : Co-Prime

Input : 4 8
Output : Not Co-Prime
# Python3 program to check if two 
# numbers are co-prime or not
 
# Recursive function to
# return gcd of a and b
def __gcd(a, b):
 
    # Everything divides 0 
    if (a == 0 or b == 0): 
        return 0
 
# base case
if (a == b): 
    return a
 
# a is greater
if (a > b): 
    return __gcd(a - b, b)
 
return __gcd(a, b - a)
 
# Function to check and print if 
# two numbers are co-prime or not 
def coprime(a, b):
    if ( __gcd(a, b) == 1):
         print("Co-Prime")
    else:
         print("Not Co-Prime")     
 
# Driver code
a = 5; b = 6
coprime(a, b) 
 
a = 8; b = 16
coprime(a, b)

Explanation

This code checks whether two given numbers are co-prime or not. The code defines a recursive function called __gcd to calculate the Greatest Common Divisor (GCD) of two given numbers, a and b. The __gcd function works by first checking if either a or b is 0. If either of them is 0, then the GCD is 0. If both a and b are the same, then the GCD is a. If a is greater than b, then the GCD is calculated by recursively calling the __gcd function with the parameters a-b and b. If b is greater than a, then the GCD is calculated by recursively calling the __gcd function with the parameters a and b-a.

The code then defines another function called coprime that takes two parameters a and b and checks if they are co-prime or not by checking if their GCD is 1. If the GCD is 1, the numbers are co-prime and the function prints “Co-Prime”. Otherwise, the function prints “Not Co-Prime”.

The driver code calls the coprime function twice with different values of a and b to check if the implementation works correctly. In the first call, a is assigned the value 5 and b is assigned the value 6. Since 5 and 6 are co-prime, the function should print “Co-Prime”. In the second call, a is assigned the value 8 and b is assigned the value 16. Since 8 and 16 are not co-prime, the function should print “Not Co-Prime”.

Conclusion

In this post, we discussed the list of the top 5 Python programs you must know before entering a Python interview.

By mastering these essential Python programs and many more, you’ll be better equipped to tackle the challenges of a Python interview with confidence and set yourself up for success in a wide range of programming and data science roles.

I highly recommend checking out this incredibly informative and engaging professional certificate Training by Google on Coursera:

Google Advanced Data Analytics Professional Certificate

There are 7 Courses in this Professional Certificate that can also be taken separately.

  1. Foundations of Data Science: Approx. 21 hours to complete. SKILLS YOU WILL GAIN: Sharing Insights With Stakeholders, Effective Written Communication, Asking Effective Questions, Cross-Functional Team Dynamics, and Project Management.
  2. Get Started with Python: Approx. 25 hours to complete. SKILLS YOU WILL GAIN: Using Comments to Enhance Code Readability, Python Programming, Jupyter Notebook, Data Visualization (DataViz), and Coding.
  3. Go Beyond the Numbers: Translate Data into Insights: Approx. 28 hours to complete. SKILLS YOU WILL GAIN: Python Programming, Tableau Software, Data Visualization (DataViz), Effective Communication, and Exploratory Data Analysis.
  4. The Power of Statistics: Approx. 33 hours to complete. SKILLS YOU WILL GAIN: Statistical Analysis, Python Programming, Effective Communication, Statistical Hypothesis Testing, and Probability Distribution.
  5. Regression Analysis: Simplify Complex Data Relationships: Approx. 28 hours to complete. SKILLS YOU WILL GAIN: Predictive Modelling, Statistical Analysis, Python Programming, Effective Communication, and regression modeling.
  6. The Nuts and Bolts of Machine Learning: Approx. 33 hours to complete. SKILLS YOU WILL GAIN: Predictive Modelling, Machine Learning, Python Programming, Stack Overflow, and Effective Communication.
  7. Google Advanced Data Analytics Capstone: Approx. 9 hours to complete. SKILLS YOU WILL GAIN: Executive Summaries, Machine Learning, Python Programming, Technical Interview Preparation, and Data Analysis.

It could be the perfect way to take your skills to the next level! When it comes to investing, there’s no better investment than investing in yourself and your education. Don’t hesitate – go ahead and take the leap. The benefits of learning and self-improvement are immeasurable.

You may also like:

Check out the table of contents for Product Management and Data Science to explore the topics. Curious about how product managers can utilize Bhagwad Gita’s principles to tackle difficulties? Give this super short book a shot. This will certainly support my work. After all, thanks a ton for visiting this website.

Leave a Reply