Python Challenges

Python Challenges

Table of Contents


Calculate the difference between the maximum and minimum of numbers in a list.

Write a function that gets a list of numbers (as a list) from the user and calculates the difference between the max and min of the numbers. For ex., a list of numbers like so.. [ -1,20,34,-25,12,90 ] . The minimum number in this list is -25 and the maximum is 90. The difference between the minimum and maximum is 90 – (-25 ) = 115.
def diff (num) :
    return max(num) - min(num)

Munged Password – Create a python function that takes in a user’s password and suggests a stronger version using character substitution.

Passwords need to be complex. In theory that is OK, but remembering them for humans is a chore. So, simple substitutions like ! , & or @ for specific alphabets can make the password a bit more secure. Here is what our function has to do. A more elaborate version of munging can be found here.

Given a password (string) as input to a function, substitute the following letters with the corresponding symbols (based on the following table) and return the new password.

Original CharacterNew Character
o0 (zero)
Character Substitution

def munged_password (password) :
    # munged character map
    munged_chars = {"a" : "@", 
                    "i": "!", 
                    "s" : "$"}
    # convert the string to a list (since string is immutable)
    password_list = list(password)
    # iterate over list and substitute
    for index, char in enumerate(password_list) :
        # attempt to get the substitution
        char_sub = munged_chars.get(char)
        # if found, do the substitution
        if char_sub != None :
            password_list[index] = char_sub   
    # convert the list back to string 
    password_str = "".join(password_list)
    return password_str

nth greatest/ least number in a list

Given a list of numbers, there are inbuilt functions that can given you the minimum or maximum elements in a list. However, what if you wanted to find out the nth largest of smallest number ?

Let’s take an example. Say we have a list of numbers like so

[9, 4, 9, 3 , 5, 7, 2]

If we wanted to find out the second largest number, it would be 7. The third largest number would be 5. Similarly, the third smallest number is 4.

Create a function nth_number(numbers, n, large_small) that takes in 3 arguments.

numbers– The list of numbers

n – The nth number

large_small – A string with a value of “small” or “large”

For example, nth_number(list, 3, “small”) would return the 3rd smallest number in the list.

def nth_number (numbers, n, large_small) :
        Method : Sort list and start counting forward or backward
        based on the value large_small
    # counts the occurrence of the nth number
    count = 0
    # numbers in the list could repeat. Keep track of repeated numbers
    number_repeat = None
    # The actual nth (largest or smallest) number
    nth_number = None
    # sorting is a O(n^2) or O(n log(n)) in the worst case.
    if large_small == "large" :
    elif large_small == "small" :
    for number in numbers :
        if number == number_repeat :
        else :
            number_repeat = number
            count = count + 1
        if count == n :
            nth_number = number
    return nth_number

swap case

Given a string, swap the case of each of the letters in the string without using the built-in swapcase() function.
code - Convert to list
def swap_case(text) :
    text_list = list(text)
    text_list_converted = []
    for char in text_list :
        if char.isupper() :
        else :
    return "".join(text_list_converted)    

code - Using list comprehension
def swap_case(text) :
    text_converted = "".join(c.lower() if c.isupper() else c.upper() for c in text)
    return text_converted

code - Using Python's built-in swapcase() method
def swap_case(text) :

    return text.swapcase()    

Write a simple number guessing game. The program has a number that the user needs to guess.

This is a computer version of the game we used to play as kids – I hold a secret number between 1 and 100 and you have to guess what it is. Every time you make a guess, I give you a clue – if your guess is greater than the secret I tell you that it is greater and if it is less I tell you it is less. How fast you get to the secret number is how you win the game. For now, just hard code the number. The purpose of this game is to learn the basic program blocks, logical operations and simple loops.
# In this program we will learn about
# 1. Functions
# 2. while Loop
# 3. break statement
# 4. if statement
# 5. boolean values
# 6. type conversion
secret_num = 59
print ( " Guess a number between 1 and 100")
num = input ()
while ( True ):
    if   int(num) > secret_num :
        print ( " guess a lower number " )
        num = input ()
    if int(num) < secret_num : 
        print ( " guess a higher number" )
        num = input ()
    if int(num) == secret_num : 
        print ( " Hurray !! you guessed it ")

Find the maximum & minimum of numbers in a list without using the built-in functions max(), min() or sort()

Hint : Without using the in-built functions, to find out the min or max of numbers in a list, iterate through all the elements, mark if the element is higher or lower than a preset min/max. Finally after the loop is over you will know the marked elements as min or max.
numbers = [1,3,4,2,1,4,5,7,5,2]

min = numbers[0]
max = numbers[0]

for number in numbers : 
    if number < min :
        min = number
    if number > max :
        max = number 
print ( "max number is ", max)
print ( "min number is ", min)

case insensitive equality of strings

Write a function that compares two strings and returns True if they are equal. However, make sure you do a case insensitive comparison. For example, the following strings are equal if you ignore the case.

name_1 = “Ajay”
name_2 = “ajay”
def compare (str1, str2) :
    if str1.lower() == str2.lower():
        return True
    else : 
        return False

Check if a sentence contains spaces

Write a function that takes in a string and returns True if the string has spaces. A space could be a blank space or a tab ( \t ) character.
def compare (str1, str2) :
def isspace ( sentence) :
    if " " in sentence or "\t" in sentence : 
        return True
    else :
        return False

All substrings starting with a character

Write a function that takes in a string and a character. Return all the substrings of the string that start with the character. Assume there are no spaces in the string.

For example, consider a string – song and we want to find all the substrings that start with the letter o . They would be

“o” , “on”, “ong”

def all_substrings(text, letter) :
        Returns all the possible substrings that start with the
        letter - 'letter' in the text. Assuming that the text has no blanks.
    # will hold the final list of substrings
    words = set()
    # loop through each of the letters in the text
    for start in range(len(text)) :
        # if the character is equal to 'letter'
        if text[start] == letter :
            # start making words (till the end )
            for word_start in range(start-1, len(text)+1) :
                words.add(text[start: word_start])
    return words

Count the occurrences of a word in a sentence.

Get a sentence and a word from the user. Find out how many times the word occurs in the sentence.
sentence = input("enter sentence => ")
word = input ("enter word or substring to search => ")

count = 0 

for i in range(len(sentence)) :
    print ( sentence[i : len(word) + i] , word)
    if sentence[i : len(word) + i] == word : 
        count = count + 1

print ( count )

Check if a string is contained in the keys or values of a dictionary

Write a function that takes in a string/number/float as the first argument and a dictionary as the second argument. The function should verify if the first argument is there as a key or value in the dictionary. If yes, return the corresponding key value pair.
def checkKeyValue(key, dictionary) :
    keys = dictionary.keys()
    values = dictionary.values()
    if key in keys : 
        return key, dictionary[key]
    if key in values : 
        return list(keys)[list(values).index(key)] , key

# Try it with a simple dictionary like this
dictionary = {"India"             : 1.3, 
              "China"             : 1.4,
              "United States"     : 0.3,
              "Vietnam"           : 0.1 }


Find the number of digits in a number

Write a function that takes in a number and returns the number of digits in a number. For example, if you pass in the number 12345 should return 5.
def findDigits(num) :
    count = 0
    while num> 0 :
        num = num // 10
        count = count + 1
    return count

Reverse a list ( without using the reversed() or .reverse() functions

Write a function that takes in a list and returns a reversed list. Doing this using the standard reversed() function or list.reverse() is a one-liner. However, try to do it without using these functions. This requires you to essentially navigate the list element by element in reverse order to re-build it.
def findDigits(num) :
def reverse(li):
    i = len(li)
    new_list = []
    while i > 0 :
        i = i - 1
    return new_list

# if you could use the built-in functions, this would be much easier. 
# like 
# OR get a reverse iterator using 

valid zip codes

Write a function that takes in a zip code and returns if if it a valid zip code. Assume US zip codes in the following formats.

Format 1 –
– Should only contains 5 numbers

Format 2 –
– Should look like this XXXXX-XXXX where X is always a number
def us_zip_code ( zip_code ) :
    # assume zip_code is a string
    if zip_code.isnumeric() and len(zip_code) == 5 :
        return True
    if zip_code[0:5].isnumeric() and zip_code[5] == "-" and zip_code[6:10].isnumeric() and len(zip_code) == 10:
        return True
    return False

Swap case of letters in a sentence without using the swapcase ( ) function

Take a sentence from the user. Swap the case of all the letters in the sentence.
sentence = input("enter sentence => ")

new_sentence = ""

for char in sentence : 
    if char.islower() :
        new_sentence = new_sentence + char.upper()
    if char.isupper() :
        new_sentence = new_sentence + char.lower()
    if char == " " :
        new_sentence = new_sentence + char

Reverse a string

For example, if you are given a string “Ajay”, you have reverse the characters in the string and return a new string as “yajA”.
text = input("enter string -")
i = len(text)
r_text = ""
while i > 0  :
    r_text = r_text + text[i-1]
    i = i - 1
print ( r_text)

Split a user entered string into its words and print each of the word with the initial letter capitalized

Take a string from the user as input and split the string into its words. Loop through each of the words and print them out on the console with the initial letter capitalized.
text = input ( "enter string - ")
for word in text.split() :
    print ( word.title())

Convert a string to upper case

Take a string from the user as input and convert it to upper case. This has quite a lot of use cases. Forms on the web are a good example of this. When the user enters their name, it is capitalized and stored in the database for consistency
user_input = input ( "Enter your name - ")
print ( user_input.capitalize() )

Check if all the characters in a string are alpha-numeric

Take a string from the user as input and verify if all the characters in the string are alphanumeric. user ids for websites are a good example of this. We don’t want strange characters in the user id, right ? We want them to be either alphabetic or numeric.
user_input = input ( "Choose a user id - ")
if user_input.isalnum() == False :
    print ( "Make sure all the characters are either alphabetic or numeric")

Display credit card number by showing only the last 4 digits and masking the others with a *

Take a credit card number from the user and display only the last 4 numbers and show the remaining numbers as a *. The format for the different credit card numbers is like below
– All visa card numbers are either 13 or 16 numbers
– All Master card numbers have exactly 16 digits
– All Amex have exactly 15 digits

The card could be entered by the user with spaces or without spaces/dashes. There could be spaces before or after the card numbers. Insert dashes after every 4th number to make it look pretty.
card_number = input ("Enter Credit card number > ")
card_number = card_number.replace("-", "").replace("\t","").replace(" ","")

length = len(card_number)
masked_card_number = ""
pretty_card_number = ""

for index,char in enumerate(card_number) :
    if index < length - 4 :
        masked_card_number += char
    else : 
        masked_card_number += "*"

for index, char in enumerate(masked_card_number) :
    pretty_card_number += char
    if ( index + 1 ) % 4 == 0 and index != length-1:
        pretty_card_number += "-"    
print ( "Masked Card Number = ", pretty_card_number)

Encode text to Morse code

Morse code is a method used in telecommunication to encode text characters as standardized sequences of two different signal duration, called dots and dashes. Here is a dictionary of all the letters along with their encoding. Write a function to convert a text (passed as an argument) to convert it to Morse code with spaces in between each letter.
morse_code = {"a" : ".-"   ,   "b" : "-..." ,  "c" : "-.-." ,
              "d" : "-.."  ,   "e" : "."    ,  "f" : "..-." ,
              "g" : "--."  ,   "h" : "...." ,  "i" : ".."   ,
              "j" : ".---" ,   "k" : "-.-"  ,  "l" : ".-.." ,
              "m" : "--"   ,   "n" : "-."   ,  "o" : "---"  ,
              "p" : ".--." ,   "q" : "--.-" ,  "r" : ".-."  ,
              "s" : "..."  ,   "t" : "-"    ,  "u" : "..-"  ,
              "v" : "...-" ,   "w" : ".--"  ,  "x" : "-..-" ,
              "y" : "-.--" ,   "z" : "--.."}
def encode (text ) :
    encoded_text= ""

    for char in text :
        char = char.lower()
        if char.isalpha() and char != " ":        
            encoded_text += morse_code.get(char)
            encoded_text += " "
    return encoded_text 

Get the first and last digits in a string.

Write a function that takes in a string and returns the first and last digits in it.

def encode (text ) :

    first_digit = 0
    last_digit  = 0
    digits      = []

    for char in text :

        if char.isnumeric() :
    return digits[0], digits [len(digits)-1]

Return a zip of lists without using the zip function

Python has a zip function that returns a list of tuples from the first and second lists. If the length of the lists are unequal, the shorter list is picked up for iteration. Write a function for the zip equivalent in python.

def zip_lists ( list_1, list_2 ) :

    ''' This function is essentially a zip function. 
    list_3 = []  # return a set of typle in a list.

    # if the length of the lists are unequal, pick the shorter list to iterate.
    list_iter = 0
    if len(list_1) &gt;= len(list_2) :
        list_iter = len(list_2)
    else :
        list_iter = len(list_1)
    for i in range(list_iter) :
        tup = (list_1[i], list_2[i])
    return list_3

Find the greater of 3 numbers

Without using a data structure (for ex., a list ), find the greatest of 3 numbers. This will let you practice your if-else skills.
print ( "Enter 3 numbers - ")
first   = int( input ( "Enter first number - ") )
second  = int( input ( "Enter second number - ") )
third   = int( input ( "Enter third number - ") )
if first &gt; second :
    greater = first
else :
    greater = second
if third &gt; greater :
    print ("The largest number is - ", third)
else :
    print ( "The largest number is - ", greater)

Find the number of occurrences of a character in a user entered string

You will have to traverse a string in a loop and increment a counter to find the number of occurrences. Do not use the count() function. Check for both capital or small letters.
s = input ( "Enter the string to be searched - ").upper()
a = input ( "Enter the alphabet to be searched - ").upper()
counter = 0
for i in range(len(s)) :
    if a == s[i] :
        counter = counter + 1
print ("The character ",a," occurs ", counter, " number of times")
# Using the count() function - This becomes just a one liner.
# print ("The character ",a," occurs ", s.count(a), " number of times")

Find the number of occurrences of a lower case and upper case characters in a string

In a user entered string, find the number of occurrences of lower case and upper case characters
s = input ( "Enter the string to be searched - ")
counter_l = 0   # counter for lower case
counter_u = 0   # counter for upper case
for i in range(len(s)) :
    if s[i].islower() == True :
        counter_l = counter_l + 1
    elif s[i].isupper() == True:
        counter_u = counter_u + 1
print ( "The number of upper case characters is ", counter_u)
print ( "The number of lower case characters is ", counter_l)

Shift the characters in an alphabet by n number of characters

Write a function that takes in a string and a number. Shift the characters of a string by as many numbers as n. For example, if the first letter of the string is “a” and n is 3, make that letter as “d”.
from string import ascii_letters

def swap (string, number) :
    letters = ""
    new_string = ""
    small_letters = ascii_letters[0:26]
    capital_letters = ascii_letters[26:52]
    for char in string :
        if char in small_letters :
            letters = small_letters
        elif char in capital_letters :
            letters = capital_letters
        if char in letters :
            curr_index = letters.index(char)
            required_index = curr_index + number
        if required_index &amp;amp;amp;amp;amp;amp;amp;amp;gt; 25 :
            required_index = (required_index % 25) - 1
        print ( required_index)
        new_string = new_string + letters[required_index]
    return new_string

persons = [["Ajay", 23, "Hyderabad"],
           ["Stacy", 25, "Los Angeles"],
           ["Xing", 21, "Shanghai"]]

Sort a list based on the second parameter of each of the sub-elements in the list

For example, in the example above, each element of the list is again a list with name, age and location. Sort the list based on age.

#sample list
persons = [["Ajay", 23, "Hyderabad"],
           ["Stacy", 25, "Los Angeles"],
           ["Xing", 21, "Shanghai"]]

# function to return the second element in the list element
def sort_age (element) :
    return element[1]

# Use python's sorted function and set the key parameter to the custom function defined above.
sorted(persons, key = sort_age)

Sum of all alternate odd numbers

Create a function that takes in an integer and finds out the sum of all the alternate odd numbers between 1 and the given input integer.

For example, the function should return 15 for n = 10 as the alternate odd numbers are 1 5 9 . so 1 + 5 + 9 = 15

def alternate_odd (n) :
    sum = 0
    alternate = True

    for number in range(n+1) :
        if number % 2 == 0 :

        if alternate == True :
            sum = sum + number
            alternate = False

        alternate = True
    return sum

Combine Logical Operators

Write a logical condition such that only candidates with at least an age of 21, and a qualification of either “Bachelors” or “Masters”  and at least an experience of 2 years.

Say there are 3 variables to filter out candidates for a job interview.
age = 21
qualification = "Bachelors"
experience = 2
write a logical condition such that only candidates with at least an age of 21, and a qualification of either “Bachelors” or “Masters”  and at least an experience of 2 years.

# characteristics of a probable candidate for a job opening
age = 21
qualification = "Bachelors"
experience = 2

# Let the variable "hired" be a Logical variable. So, it takes a True or False.
# Write an if statement such that based on the following conditions the program should determine if the 
# candidate is can be considered for a job interview or not. 
# 1. candidates with at least an age of 21 and 
# 2. a qualification of either "Bachelors" or "Masters"  
# 3. and at least an experience of 2 years.

match = True

if age == 21 and ( qualification == "Bachelors" or qualification == "Masters" ) and experience &amp;amp;amp;gt;= 2 :
    match = True
else : 
    match = False


%d bloggers like this: