Hello everyone. I hope you are doing well. I have coded the following five questions. Hope it prove beneficial.
1. Prime Numbers
Create a function that returns a list of all prime numbers up to a given number.
Solution:
import math
def prime_finder(x):
is_prime = True
for i in range(2, math.floor(math.sqrt(x)) + 1):
if x % i == 0:
# print(f’{x} is not a prime number’)
is_prime = False
break
return is_prime
def prime_printer_up_to_x(x):
prime_numbers =
for number in range(2, x+1):
is_prime = prime_finder(number)
if is_prime:
prime_numbers.append(number)
print(prime_numbers)
number = input('Please enter your number: ')
prime_printer_up_to_x(int(number))
2. List Overlap
Write a program that returns a list containing only the common elements between two lists.
Solution:
def string_list_to_int_list(string):
list_string = string[1:-1].split(‘,’)
list_int = [int(i) for i in list_string]
return list_int
first_list = input("Enter first list using brackets: ")
first_list = string_list_to_int_list(first_list)
second_list = input("Enter second list using brackets: ")
second_list = string_list_to_int_list(second_list)
common_list =
for item in first_list:
if item in second_list:
common_list.append(item)
print(common_list)
3. List Remove Duplicates
Write a function that removes duplicates from a list. For example, given the list [1, 2, 2, 3, 4, 4, 5], the function should return [1, 2, 3, 4, 5].
Solution:
def string_list_to_int_list(string):
list_string = string[1:-1].split(‘,’)
list_int = [int(i) for i in list_string]
return list_int
my_list = input("Enter a list using brackets: ")
my_list = string_list_to_int_list(my_list)
my_list.sort()
uniques =
for item in my_list:
if item not in uniques:
uniques.append(item)
print(uniques)
4. Fibonacci Sequence
Write a function that generates the first 10 numbers in the Fibonacci sequence. (Also I have written a code that can give you the sentence you want without itterating over the past sentences.)
Solution:
fib = [0, 1]
number = int(input("Enter the number of sentences you want to print: "))
for i in range(2, number):
fib.append(fib[i - 1] + fib[i - 2])
print(fib)
def fib(n):
fib_n=(((1+(5**0.5))/2)n - ((1-(50.5))/2)n) / (50.5)
return fib_n
number = int(input("Enter the sentence number you want to print: "))
print(int(fib(number-1)))
5. Palindrome Checker
Write a function that checks if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). For example, “radar” and “level” are palindromes.
Solution:
word = input("Enter a word: ")
length = len(word)
word_chars =
for letter in word:
word_chars.append(letter)
for i in range(0, round((length / 2) + 1)):
if word_chars[i].lower() != word_chars[length - i-1].lower():
print(f’{word} is not a palindrome’)
break
else:
print(f’{word} is a palindrome’)