Python exercises from 1 to 15

parent 77cebc13
# Hello World
print ('Hello World')
# 1. Command Line Arguments
def hello_world():
inputname = input("Knock knock, who's there? ") # inputname receive the input asked to the user
names = inputname.split(" ") # names receive inputname splited into a list
if inputname == "": # if the inicial string is an empty string print "Hello Unknown!"
print("Hello Unknown!")
elif len(names) == 1: # if there is only one name on the input list print "Hello (name)!"
print("Hello " + str(*names) + "!")
else: # else print "Hello (name)!" for each name after an space in a new line
for eachname in names:
print("Hello " + eachname + "!")
hello_world()
# 2. List of all files and directories names
import os # import module
def files_and_dirlist(arg):
argList = os.listdir(path = arg) # method to get the list of all file/directory names from the given path pass as an argument into a variable
for argPath in argList:
print(argPath)
files_and_dirlist('.')
# 3. Arrays are equal
import numpy as np # import numpy
def are_two_arrays_equal(arg1, arg2):
if len(arg1) != len(arg2):
print(False)
else:
comparison = np.sort(arg1) == np.sort(arg2) # Sort arrays and compare if they are equal in each index
print(comparison.all())
arr1 = [2, 5, 7, 9, 11]
arr2 = [2, 5, 7, 8, 11]
arr3 = [2, 5, 11, 9, 7]
are_two_arrays_equal(arr1, arr2) # False
are_two_arrays_equal(arr1, arr3) # True
# 4. Middle character of a string
def get_middle_character(string):
numbersArray = []
for letter in string: # put the numbers of the string in an array
numbersArray.append(letter)
if len(string) % 2 == 0: # if the string is even
print(numbersArray[int(len(string)/2 - 1):int(len(string)/2 + 1)]) # print 2 middle numbers
else: # if the string is odd
print(numbersArray[int(len(string)/2)]) # print middle number
get_middle_character("31811") # 8
get_middle_character("342111") # 21
get_middle_character("Natayra") # a
# 5. Vowels in a string
def count_of_vowels(args):
counter = 0
for letter in args:
letter = letter.lower()
if letter == "a" or letter == "e" or letter == "i" or letter == "o" or letter == "u":
counter = counter + 1
print(counter)
count_of_vowels("Propulsion Academy") # 7
count_of_vowels("AaBbCc12e") # 3
# 6. Check valid password
def is_valid_password():
password = input("Please write a password: ") # receive the password asked to the user
if len(password) < 10:
print("A password must have at least ten characters.Please try again.")
is_valid_password()
else:
var = []
for char in password:
if char.isdigit() or char.isalpha():
var.append(0)
else:
var.append(1)
if sum(var) != 0:
print("A password consists of only letters and digits. Please try again.")
is_valid_password()
else:
if password == password.lower():
print("A password must contain at least a capital letter in it. Please try again.")
is_valid_password()
else:
print("Password is valid!")
is_valid_password()
# 7. Find the second smallest element in an array
import numpy as np # import numpy
def find_second_smallest(args):
orderedArray = np.sort(args) # sort the array from the smallest to the biggest number
print(orderedArray[1]) # print the second smallest number
find_second_smallest([0, 3, -2, 4, 3, 2]) # 0
find_second_smallest([10, 22, 10, 20, 11, 22]) # 10
# 8. Remove duplicate elements from an array
def unique_array(args):
for arg in args:
if args.count(arg) > 1: # check if arg it's duplicated on the array
args.remove(arg) # if the arg it's duplicated, remove it
print(args)
unique_array([0, 3, -2, 4, 3, 2]) # [0, -2, 4, 3, 2]
unique_array([10, 22, 10, 20, 11, 22]) # [10, 20, 11, 22]
# 9. Pentagonal numbers
def get_pentagonal_number(number):
for n in range(number + 1):
if n >= 1: # pentagonal numbers are defined to n >= 1
print(int((3 * n**2 - n)/2)) # formula to a pentagonal number
get_pentagonal_number(50)
# 1 5 12 22 35 51 70 92 117 145 176 210 247 287 330 376 425 477 532 590
# 651 715 782 852 925 1001 1080 1162 1247 1335 1426 1520 1617 1717 1820 1926 2035 2147 2262 2380
# 2501 2625 2752 2882 3015 3151 3290 3432 3577 3725
# 10. Length of the longest sequence of zeros in binary representation of an integer
def get_size_of_longest_sequence_of_zeros(args):
binaryArray = [char for char in bin(args)]
binaryArray = binaryArray[2:]
counter = 0
finalZeros = 0
for arg in binaryArray:
number = int(arg)
if number == 0:
counter += 1
else:
counter = 0
if finalZeros < counter:
finalZeros = counter
print (finalZeros)
get_size_of_longest_sequence_of_zeros(7) # binary representation: 111 - 0
get_size_of_longest_sequence_of_zeros(8) # binary representation: 1000 - 3
get_size_of_longest_sequence_of_zeros(457) # binary representation: 111001001 - longest 2
get_size_of_longest_sequence_of_zeros(40) # binary representation: 101000 - longest 3
get_size_of_longest_sequence_of_zeros(12546) # binary representation: 11000100000010 - longest 6
# 11. Fibonacci
print("PAUSA")
def fibonacci(arg):
first = 1
second = 1
if arg < 0:
print("Error: you must supply which Fibonacci number to compute")
elif arg == 0:
print(0)
elif arg == 1:
print(1)
else:
for i in range(arg-1):
total = first + second
second = first
first = total
print(second)
fibonacci(0) # 0
fibonacci(1) # 1
fibonacci(2) # 1
fibonacci(3) # 2
fibonacci(7) # 13
fibonacci(12) # 144
# 12. Factorial
def factorial(n):
factorial = n
n2 = n
counter = 0
if n == 0 or n == 1:
print("%i! = 1" % (n))
else:
while counter < n:
factorial *= (n-1)
n -= 1
counter += 1
print("%i! = %i" % (n2, factorial))
factorial(0) # 1
factorial(1) # 1
factorial(2) # 2
factorial(3) # 6
factorial(4) # 24
factorial(5) # 120
# 14. Sorting an Array
import math
import numpy as np
def sort_it(theArray):
evenArray = []
oddArray = []
for num in theArray:
if math.floor(num) % 2 == 0:
evenArray.append(num)
else:
oddArray.append(num)
evenArraySorted = np.sort(evenArray)[::-1]
oddArraySorted = np.sort(oddArray)
print(np.concatenate((oddArraySorted, evenArraySorted), axis=None))
sort_it([1, 2, 3, 4, 5, 6, 7, 8, 9]) # [1.0, 3.0, 5.0, 7.0, 9.0, 8.0, 6.0, 4.0, 2.0]
sort_it([26.66, 24.01, 52.00, 2.10, 44.15, 1.02, 11.15]) # [1.02, 11.15, 52.0, 44.15, 26.66, 24.01, 2.1]
# 15. Find the Digit
import functools as fu
def find(number, count=0):
string = str(number)
arr = list(string)
arr = list(map(lambda stri: int(stri), arr))
finalNumber = 1
if len(arr) == 1:
print(count)
else:
finalNumber = fu.reduce(lambda x, y: x*y, arr)
find(finalNumber, count +1)
find(57) # 3
find(5923) # 2
find(90) # 1
find(7) # 0
find(999) # 4
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment