# Python Coding Challenge Beginner’s Guide

Python is a computer programming language often used to build websites and software, automate tasks, and conduct data analysis. Python programming challenges contain high-level requirement specifications. In this article, we have covered most frequently asked challenges during Coding Interview.

### Challenge 1: Convert Degreesinto Radians

Write a function that accepts one numeric parameter. This parameter will be the measure of an angle in degrees. The function should convert the degrees into radians and then return that value.

```Test Data:
Degree : 15

Solution:

``````pi=22/7
degree = float(input("Input degrees: "))
``````

Sample Output:

```Input degrees: 90
1.5714285714285714```

### Challenge 2: Morse code translator

Write a code in Python to create a Morse code translator. The string can also have any special characters as a part of the Morse code. The python code should return the Morse code that is equivalent to the string.

Morse code is a method of transmitting text information as a series of on-off tones, lights, or clicks that can be directly understood by a skilled listener or observer without special equipment. It is named for Samuel F. B. Morse, an inventor of the telegraph.

### Algorithm:

The algorithm is very simple. Every character in the English language is substituted by a series of ‘dots’ and ‘dashes’ or sometimes just singular ‘dot’ or ‘dash’ and vice versa.

### Solution:

Python provides a data structure called a dictionary which stores information in the form of key-value pairs which is very convenient. We will save the morse code chart in a dictionary where (key-value pairs) => (English Characters-Morse Code). The plaintext (English characters) takes the place of keys and the Morse code forms the values of the corresponding keys. The values of keys can be accessed from the dictionary in the same way we access the values of an array through their index and vice versa.

``````# Python program to implement Morse Code Translator

'''
VARIABLE KEY
'cipher' -> 'stores the morse translated form of the english string'
'decipher' -> 'stores the english translated form of the morse string'
'citext' -> 'stores morse code of a single character'
'i' -> 'keeps count of the spaces between morse characters'
'message' -> 'stores the string to be encoded or decoded'
'''

# Dictionary representing the morse code chart
MORSE_CODE_DICT = {
'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':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-', '(':'-.--.', ')':'-.--.-'}

def encrypt(message):
cipher = ''
for letter in message:
if letter != ' ':
cipher += MORSE_CODE_DICT[letter] + ' '
else:
cipher += ' '
return cipher

def decrypt(message):
message += ' '
decipher = ''
citext = ''
for letter in message:
if (letter != ' '):
i = 0
citext += letter
else:
i += 1

if i == 2 :

# adding space to separate words
decipher += ' '
else:

# accessing the keys using their values (reverse of encryption)
decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT
.values()).index(citext)]
citext = ''

return decipher

# Hard-coded driver function to run the program
def main():
message = "hello"
result = encrypt(message.upper())
print (result)

message = ".... . .-.. .-.. ---"
result = decrypt(message)
print (result)

# Executes the main function
if __name__ == '__main__':
main()
``````

### Challenge 3: Duplicate Letter Checker

Create a function in Python that accepts one parameter: a string that’s a sentence. This function should return True if any word in that sentence contains duplicate letters and False if not.

Examples:

```Input : hello
Output : true
```

Solution:

1. Create a dictionary using the Counter method having strings as keys and their frequencies as values.
2. Declare a temp variable.
3. Print all the indexes from the keys which have values greater than 1.
``````from collections import Counter

def find_dup_char(input):

# now create dictionary using counter method
# which will have strings as key and their
# frequencies as value
WC = Counter(input)

# Finding no. of occurrence of a character
# and get the index of it.
for letter, count in WC.items():
if (count > 1):
print(true)

return false

# Driver program
if __name__ == "__main__":
input = 'thisistest'
find_dup_char(input)
``````

### Challenge 4: Convert a decimal number into binary

Write a function in Python that accepts a decimal number and returns the equivalent binary number. The decimal number will always be less than 1,024, so the binary number returned will always be less than ten digits long.

Given a decimal number as input, the task is to write a Python program to convert the given decimal number into an equivalent binary number.

Examples :

```Input : 7
Output :111

Input :10
Output :1010```

```DecimalToBinary(num):
if num >= 1:
DecimalToBinary(num // 2)
print num % 2 ```

Below is the implementation of the above recursive solution:

``````# Function to convert decimal number# to binary using recursion
def
# Function to convert decimal number
# to binary using recursion
def DecimalToBinary(num):

if num >= 1:
DecimalToBinary(num // 2)
print(num % 2, end = '')

# Driver Code
if __name__ == '__main__':

# decimal value
dec_val = 10

# Calling function
DecimalToBinary(dec_val)
``````

Output

`1010`

### Challenge 5: Convert a decimal to a hex

Write a function in Python to convert a decimal to a hex. It must accept a string of ASCII characters as input. The function should return the value of each character as a hexadecimal string.

Conversion table of remainders to hexadecimal equivalent

```conversion_table =
{0: '0', 1: '1', 2: '2', 3: '3',
4: '4', 5: '5', 6: '6', 7: '7',
8: '8', 9: '9', 10: 'A', 11: 'B',
12: 'C', 13: 'D', 14: 'E', 15: 'F'}```

#### function which converts decimal value to hexadecimal value

``````def decimalToHexadecimal(decimal):
if(decimal <= 0):
return ''
remainder = decimal % 16

decimal_number = 69

The hexadecimal form of 69 is 45``````

The IP address: Write a function to find the domain name from the IP address. The function will accept an IP address, and return the domain name that maps to that IP address while using records of PTR DNS.

Given an IP address as input, write a Python program to check whether the given IP Address is Valid or not.

Examples:

```Input:  192.168.0.1

Input: 110.234.52.124

Input: 666.1.2.2

Input:25.99.208.255

Let’s see the Python program to validate an IP address :

```# Python program to validate an Ip address
# re module provides support
# for regular expressionsimport re
# Make a regular expression
# for validating an Ip-addressregex = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\$"
# Define a function for
# validate an Ip addressdef check(Ip):
# pass the regular expression
# and the string in search() method
if(re.search(regex, Ip)):
else:
# Driver Code
if __name__ == '__main__' :
Ip = "192.168.0.1"
# calling run function
Ip = "192.168.0.1"
check(Ip)
Ip = "110.234.52.124"
check(Ip)
Ip = "366.1.2.2"
check(Ip)```

Output:

```Valid Ip address

Create a calculator function: Write a Python function that accepts three parameters. The 1st parameter is an integer. The 2nd mathematical operator. The 3rd also be an integer. The function should perform a calculation and return the results.

Simple Calculator by Using Functions

``````# Program make a simple calculator

# This function adds two numbers
return x + y

# This function subtracts two numbers
def subtract(x, y):
return x - y

# This function multiplies two numbers
def multiply(x, y):
return x * y

# This function divides two numbers
def divide(x, y):
return x / y

print("Select operation.")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")

# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))

# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break

else:
print("Invalid Input")
Output

Select operation.
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
Let's do next calculation? (yes/no): no``````

Hide the credit card number: Write a function in Python that accepts a credit card number. It should return a string where all the characters are hidden with an asterisk except the last four.

Your task is to write a function `maskify`, which changes all but the last four characters into `'#'`.

```Maskify.Maskify("4556364607935616");
// should return
"############5616
// should return
"#######5616"
// should return "1"
// should return ""
// "What was the name of your first pet?"
``````Python Solution