Python Challenges

Python Challenges


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)

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

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")

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


%d bloggers like this: