Intermediate Coding Problems in Python
Last Updated :
25 Nov, 2024
Python, being a very dynamic and versatile programming language, is used in almost every field. From software development to machine learning, it covers them all. This article will focus on some interesting coding problems which can be used to sharpen our skills a bit more and at the same time, have fun solving this list of specially curated problems. Although this article will focus on solving these problems using Python, one can feel free to use any other language of their choice. So let’s head right into it!
Infinite Monkey Theorem
The theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, such as the complete works of William Shakespeare. Well, suppose we replace a monkey with a Python function. How long would it take for a Python function to generate just one sentence? The sentence we will go for is: “a computer science portal for geeks”.
The way we will simulate this is to write a function that generates a string that is 35 characters long by choosing random letters from the 26 letters in the alphabet plus space. We will write another function that will score each generated string by comparing the randomly generated string to the goal. A third function will repeatedly call generate and score, then if 100% of the letters are correct we are done. If the letters are not correct then we will generate a whole new string. To make it easier to follow, our program should keep track of the best string generated so far.
Example:
Python
import random
# function to generate
# a random string
def generateOne(strlen):
# string with all the alphabets
# and a space
alphabet = "abcdefghijklmnopqrstuvwxyz "
res =""
for i in range(strlen):
res+= alphabet[random.randrange(27)]
return res
# function to determine the
# score of the generated string
def score(goal, testString):
numSame = 0
for i in range(len(goal)):
if goal[i] == testString[i]:
numSame+= 1
return numSame / len(goal)
# main function to call the previous
# two functions until the goal is achieved
def main():
goalString = "a computer science portal for geeks"
newString = generateOne(35)
best = 0
newScore = score(goalString, newString)
while newScore<1:
if newScore>best:
print(newString)
best = newScore
newString = generateOne(35)
newScore = score(goalString, newString)
# Driver code
main()
Output:
pxwvkdfwpbzneycy rifcrnczxqtsfowgjm
wfgytnakffjty ggfy trylljfhurazyxow
docujzolvswarzqszridmejyluhwviujlkj
qbtvqanrbwsximmnlhjgkaacufhskiooxm
w jnlhvvinzrlimtesllsroqqqf wwteela
mjcevludro yoigewqudxjsad bxrl qnlv
f pomksbzrjizegcjwyoqftjz wwx ges
Here, we wrote three functions. One will generate a random string using the 26 characters of the alphabet and space. The second function will then score the generated string by comparing each letter of it with the goalString. The third function will repeatedly call the first two functions until the task is completed. It will also take note of the best string generated so far by comparing their scores. The one with the highest score will be the best one. Finally, we run this program in our IDE and see it work.
The substring dilemma
This is a really interesting program as it generates some really funny outputs. It is also a healthy practice problem for beginners who want to understand the “string” type more clearly. Let’s look into the problem.
Given a string, find a substring based on the following conditions:
- The substring must be the longest one of all the possible substring in the given string.
- There must not be any repeating characters in the substring.
- If there is more than one substring satisfying the above two conditions, then print the substring which occurs first.
- If there is no substring satisfying all the aforementioned conditions then print -1.
Although there can be many methods of approach to this problem, we will look at the most basic one.
Example:
Python
def test_1(string =""):
# initializing the substring
substring = ""
testList = []
initial = 0
for char in string:
for i in range(initial, len(string)):
substring+= string[i]
# checking conditions
if substring.count(string[i])>1:
testList.append(substring[:-1])
initial+= 1
substring = ""
break
maxi =""
for word in testList:
if len(word)>len(maxi):
maxi = word
if len(maxi)<3:
return "-1"
else:
return maxi
# Driver code
print(test_1("character"))
print(test_1("standfan"))
print(test_1("class"))
Here, we write a single function that will carry out the entire task. First it will initialize variables called substring and testList to store the substring and a list of possible outputs respectively. Then it will loop over the entire string provided and break every time it finds a repetition and appends that word to testList. Finally, the longest word out of the possible outputs is returned.
Output:
racte
standf
class
Mastermind
A low-level implementation of the classic game “Mastermind”. We need to write a program that generates a four-digit random code and the user needs to guess the code in 10 tries or less. If any digit out of the guessed four-digit code is wrong, the computer should print out “B”. If the digit is correct but at the wrong place, the computer should print “Y”. If both the digit and position is correct, the computer should print “R”. Example:

Example:
Python
import random
# generates a four-digit code
def gen_code():
set_code = []
for i in range(4):
val = random.randint(0, 9)
set_code.append(val)
return set_code
# asks for input from the user
def input_code():
code = input("Enter your four digit guess code: ")
return code
# plays the game
def mastermind():
genCode = gen_code()
i = 0
while i < 10:
result = ""
inputCode = [int(c) for c in input_code()]
if len(inputCode) != 4:
print("Enter only 4 digit number")
continue
if inputCode == genCode:
print("You guessed it !", genCode)
break
for element in inputCode:
if element in genCode:
if inputCode.index(element) == genCode.index(element):
result+="R"
else:
result+="Y"
else:
result+="B"
print(result)
i += 1
else:
print("You ran out of trys !", genCode)
# Driver Code
mastermind()
First, we write a function to generate a random four-digit code using Python’s random module. Next, we define a function that asks for user input. Finally, we write a function that compares the generated code to the guessed code and gives appropriate results.
Direction Catastrophe
A very simple problem with many different solutions, but the main aim is to solve it in the most efficient way. A man was given directions to go from point A to point B. The directions were: “SOUTH”, “NORTH”, “WEST”, “EAST”. Clearly “NORTH” and “SOUTH” are opposite, “WEST” and “EAST” too. Going to one direction and coming back in the opposite direction is a waste of time and energy. So, we need to help the man by writing a program that will eliminate the useless steps and will contain only the necessary directions.
For example: The directions [“NORTH”, “SOUTH”, “SOUTH”, “EAST”, “WEST”, “NORTH”, “WEST”] should be reduced to [“WEST”]. This is because going “NORTH” and then immediately “SOUTH” means coming back to the same place. So we cancel them and we have [“SOUTH”, “EAST”, “WEST”, “NORTH”, “WEST”]. Next, we go “SOUTH”, take “EAST” and then immediately take “WEST”, which again means coming back to the same point. Hence we cancel “EAST” and “WEST” to giving us [“SOUTH”, “NORTH”, “WEST”]. It’s clear that “SOUTH” and “NORTH” are opposites hence canceled and finally we are left with [“WEST”].
Example:
Python
def reduce_dir(directions):
# Define opposites
opposite = {
"NORTH": "SOUTH",
"SOUTH": "NORTH",
"EAST": "WEST",
"WEST": "EAST"
}
stack = []
for d in directions:
if stack and opposite[d] == stack[-1]:
# If current direction is opposite
# to last one in the stack, remove last one
stack.pop()
else:
# Otherwise, add current direction to stack
stack.append(d)
return stack
directions = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
res = reduce_dir(directions)
print(res)
In the above solution, The idea is to iterate through the list of directions and use the stack to keep track of the valid directions. Whenever you encounter a direction that is opposite to the one at the top of the stack, we remove (pop) the top direction from the stack since they cancel each other out. Otherwise, we add (push) the current direction to the stack.
Comparing arrays
This problem helps one to understand the key concepts of an array(list) in Python. Two arrays are said to be the same if they contain the same elements and in the same order. However, in this problem, we will compare two arrays to see if they are same, but with a slight twist. Here, two arrays are the same if the elements of one array are squares of elements of other arrays and regardless of the order. Consider two arrays a and b.
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]
Here b can be written as:
b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19]
which is a square of every element of a. Hence, they are same. If a or b are None, our program should written False
Example:
Python
# function to compare the arrays
def comp(array1, array2):
# checking if any array is None
if array1 is None or array2 is None:
return False
# checking if any of the array
# is a square of the other
if (sorted(array1) == sorted([i ** 2 for i in array2])) or (sorted(array2) == sorted([i ** 2 for i in array1])):
return True
return False
# Driver Code
comp([1,2,3,4], [1,4,9,16])
Output:
True
Similar Reads
Python Coding Practice Problems
This collection of Python coding practice problems is designed to help you improve your overall programming skills in Python. The links below lead to different topic pages, each containing coding problems, and this page also includes links to quizzes. You need to log in first to write your code. You
1 min read
Python List Coding Practice Problems
This article brings us a curated collection of problems on list in Python ranging from easy to hard. Practice popular problems like finding the second largest element, moving zeroes to the end, solving the trapping rainwater problem and more. Whether you're a beginner or an advanced programmer, thes
2 min read
Python Set Coding Practice Problems
Welcome to this article on Python set practice problems! Here, weâll explore a variety of engaging Python set practice questions, including topics like Set Operations, Multiset Operations and more. Youâll also practice solving problems like replacing elements with the least greater element, finding
1 min read
Python Fundamentals Coding Practice Problems
Welcome to this article on Python basic problems, featuring essential exercises on coding, number swapping, type conversion, conditional statements, loops and more. These problems help beginners build a strong foundation in Python fundamentals and problem-solving skills. Letâs start coding! Python B
1 min read
Python Conditional Statement and Loops Coding Problems
Welcome to this article on Python conditional statements problems, where weâll practice solving a variety of coding challenges that focus on conditional statements and loops. Youâll work on problems like If Conditional Statement, Mark Even and Odd, The FizzBuzz Program, Leap Year, Factorial, GCD, LC
1 min read
List As Input in Python in Single Line
Python provides several ways to take a list as input in Python in a single line. Taking user input is a common task in Python programming, and when it comes to handling lists, there are several efficient ways to accomplish this in just a single line of code. In this article, we will explore four com
3 min read
Output of Python Programs | (Dictionary)
Prerequisite: Dictionary Note: Output of all these programs is tested on Python3 1.What is the output of the following of code? a = {i: i * i for i in range(6)} print (a) Options: a) Dictionary comprehension doesnât exist b) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36} c) {0: 0, 1: 1, 4: 4, 9: 9, 16
2 min read
Python New Line - Add/Print a new line
Adding or printing a new line in Python is a very basic and essential operation that can be used to format output or separate the data for better readability. Let's see the different ways to add/print a new line in Python Using \n escape characterThe \n is a escape character and is the simplest way
2 min read
Output of Python programs | Set 10 (Exception Handling)
Pre-requisite: Exception Handling in PythonNote: All the programs run on python version 3 and above. 1) What is the output of the following program? [GFGTABS] Python data = 50 try: data = data/0 except ZeroDivisionError: print('Cannot divide by 0 ', end = '') else: print('Divisio
3 min read
Divide Two Integers to get Float in Python
Python, a versatile and widely used programming language, offers various ways to perform mathematical operations. When it comes to dividing two integers and obtaining a float result, there are multiple approaches to achieve this task. In this article, we'll explore five different methods to divide i
2 min read