Python Challenges

Python Challenges

Table of Contents


Easy

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.
code
def diff (num) :
    return max(num) - min(num)

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.
code
# 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 ")
        break

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.
code
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”
code
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.
code
def compare (str1, str2) :
def isspace ( sentence) :
    if " " in sentence or "\t" in sentence : 
        return True
    else :
        return False

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.
code
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.
code
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 }

checkKeyValue(1.3,dictionary)

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.
code
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.
code
def findDigits(num) :
    
def reverse(li):
    
    i = len(li)
    new_list = []
    
    while i > 0 :
        new_list.append(li[i-1])
        i = i - 1
    
    return new_list

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

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
code
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.
code
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”.
code
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.
code
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
code
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.
code
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.
code
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" : "--.."}
code
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.
code

def encode (text ) :

    first_digit = 0
    last_digit  = 0
    digits      = []

    for char in text :

        if char.isnumeric() :
            digits.append(char)
    
    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.
code

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) >= 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])
        list_3.append(tup)
       
    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.
code
print ( "Enter 3 numbers - ")
 
first   = int( input ( "Enter first number - ") )
second  = int( input ( "Enter second number - ") )
third   = int( input ( "Enter third number - ") )
 
if first > second :
    greater = first
else :
    greater = second
 
if third > 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.
code
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
code
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”.
code
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 > 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.
code

#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 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
code

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

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

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

        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.
code

# 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 >= 2 :
    match = True
else : 
    match = False

Medium

%d bloggers like this: