Python Challenges
Table of Contents
- Difference between the maximum and minimum of numbers
- Sum of all alternate odd numbers
- Munged Password
- nth greatest / least number in a list
- swap case
- number guessing game
- Find minimum & maximum of numbers in list without using inbuilt functions
- Case insensitive equality of strings
- Check if a sentence contains spaces
- All substrings starting with a character
- Count the occurrences of a word in a sentence.
- Shift the characters in an alphabet by n number of characters
- Check if a string is contained in the keys or values of a dictionary
- Find the number of digits in a number
- Reverse a list ( without using the reversed() or .reverse() functions
- Valid zip codes
- Swap case of letters in a sentence without using the swapcase ( ) function
- Reverse a string
- Split a user entered string into its words and print each of the word with the initial letter capitalized
- Convert a string to upper case
- Check if all the characters in a string are alpha-numeric
- Display credit card number by showing only the last 4 digits and masking the others with a *
- Encode text to Morse code
- Get the first and last digits in a string.
- Return a zip of lists without using the zip function
- Find the greater of 3 numbers
- Find the number of occurrences of a character in a user entered string
- Find the number of occurrences of a lower case and upper case characters in a string
- Sort a list based on the second parameter in the sub-element of a list
- Combine Logical operators
Easy
codeCalculate 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. https://en.wikipedia.org/wiki/Munged_password
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 Character | New Character |
---|---|
a | @ |
i | ! |
o | 0 (zero) |
s | $ |
def munged_password (password) : # munged character map munged_chars = {"a" : "@", "i": "!", "o":"0", "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.
codedef 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" : numbers.sort(reverse=True) elif large_small == "small" : numbers.sort() for number in numbers : if number == number_repeat : pass else : number_repeat = number count = count + 1 if count == n : nth_number = number break return nth_number
code - Convert to listswap case
Given a string, swap the case of each of the letters in the string without using the built-in swapcase() function.
def swap_case(text) : text_list = list(text) text_list_converted = [] for char in text_list : if char.isupper() : text_list_converted.append(char.lower()) else : text_list_converted.append(char.upper()) return "".join(text_list_converted)
def swap_case(text) : text_converted = "".join(c.lower() if c.isupper() else c.upper() for c in text) return text_converted
def swap_case(text) : return text.swapcase()
codeWrite 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 ") break
codeFind 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)
codecase 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
codeCheck 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”
codedef 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
codeCount 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 )
codeCheck 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 } checkKeyValue(1.3,dictionary)
codeFind 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
codeReverse 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 : 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)
codevalid 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
codeSwap 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
codeReverse 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)
codeSplit 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())
codeConvert 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() )
codeCheck 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")
codeDisplay 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 &amp;amp;amp;amp;amp;gt; ") 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
codeGet 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() : digits.append(char) return digits[0], digits [len(digits)-1]
codeReturn 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) >= 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
codeFind 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)
codeFind 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")
codeFind 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)
codeShift 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;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"]]
codeSort 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
codeCreate 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 : continue if alternate == True : sum = sum + number alternate = False continue alternate = True return sum
Combine Logical Operators
codeWrite 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;gt;= 2 : match = True else : match = False