0% found this document useful (0 votes)
24 views21 pages

Semestrul 2

The document discusses functions in Python including creating, using, and passing parameters to functions. It also covers recursive functions, importing modules, working with matrices and random numbers, and using yield. Various examples are provided to demonstrate different function concepts.

Uploaded by

serband658
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views21 pages

Semestrul 2

The document discusses functions in Python including creating, using, and passing parameters to functions. It also covers recursive functions, importing modules, working with matrices and random numbers, and using yield. Various examples are provided to demonstrate different function concepts.

Uploaded by

serband658
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Semestrul 2

Lectia 1- Functii
# Task 1 - Creating and using a simple function
def printer():
print("Hello World")

printer()

# Task 2 - Is it a prime number

def isItPrime():
number = int(input("Enter a number:\n"))
prime = True
for i in range(2,number):
if number % i == 0:
prime = False
if prime:
print(number, "is a prime number.")
else:
print(number, "is not a prime number.")

isItPrime()

# Task 3 - Function parameter

def parameter(this_is_the_parameter):
print(this_is_the_parameter)

# Function argument
parameter("This is the argument")
parameter(3+4)

# Task 4 - Is it a prime number with parameter

def isItPrimeWithParameter(num):
prime = True
for i in range(2,num):
if num % i == 0:
prime = False
if prime:
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")

isItPrimeWithParameter(73)
isItPrimeWithParameter(12)

# Task 5 - Is that a right triangle?

def right_triangle(a,b,c):
if (a**2 + b**2 == c**2) or (b**2 + c**2 == a**2) or (c**2 + a**2 ==
b**2):
print("It is a right triangle.")
else:
print("It is not a right triangle.")

right_triangle(3, 4, 5)
right_triangle(4, 5, 6)

# Task 6 - Send argument with keyword

def func_numbers(q, r, p):


a = p + q**2 + r**3
print(a)

func_numbers(p=3, q=2, r=1)

# Task 6 - scope and lifetime of function variables

def func_num():
x = 10
print(x)

x = 20
print(x)
func_num()
print(x)

# Task 7 - Return

def func_return(p):
if p >= 0:
return p
else:
return -p
print(func_return(6))
print(func_return(-5))

# Task 8-9 - Car's fuel consumption


def liters_100km_to_miles_gallon(liters):
gallon = liters/3.785411
miles = 100/1.609344
return miles/gallon

print(liters_100km_to_miles_gallon(6.3))

def miles_gallon_to_liters_100km(miles):
km = miles*1.609344
liters = 3.785411
return 100*liters/km
print(miles_gallon_to_liters_100km(62))

# Task 10 - Return exits the function


def ExitFunction():
for i in range(1,10):
if i > 5:
return "Run is over"
print(i)

print(ExitFunction())

Lectia 2- Functii recursive

# Task 1 - Recursion
def recursion(num):
print(num)
if num > 0:
num -= 1
recursion(num)
recursion(10)

# Task 2 - Factorial recursively


def factorial_recursive(n):
if n == 1:
return 1
else:
return n * factorial_recursive(n-1)
number = int(input("Give me a number:"))
f = factorial_recursive(number)
print(number, "factorial is:", f)

# Task 3 - Fibonacci
def fibonacci_recursive(n):
print(f"Calculating F({n})", end=", ")
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
fibonacci_recursive(3)

# Task 4 - Harmonic sum


# Note: The harmonic sum is the sum of reciprocals of the positive integers.
def harmonic_sum(n):
if n < 2:
return 1
else:
return 1 / n + (harmonic_sum(n - 1))
print(harmonic_sum(7))
print(harmonic_sum(4))

# Task 5 - Write a Python program to calculate the value of 'a' to the power
'b', e.g.: (power(3,4) -> 3*3*3*3 = 81
def power(a, b):
if b == 0:
return 1
elif a == 0:
return 0
elif b == 1:
return a
else:
return a * power(a, b - 1)
p = power(3, 4)
print(p)

# Task 6 - Write a Python program to calculate the sum of a list of numbers


def list_sum(num_List):
if len(num_List) == 1:
return num_List[0]
else:
return num_List[0] + list_sum(num_List[1:])
numbers = [44, 54, 35, 43, 67, 33, 70, 47, 52]
print(list_sum(numbers))

# Task 7 - Caesar Cipher


sentence = []
def encryptWord(statement, shift):
size = len(statement)
encrypt(statement, size, shift)
def encrypt(statement, length, shifts, count = 0):
if count == length:
temp = ""
new_word = temp.join(sentence)
print(new_word)
else:
asci = (ord(statement[0]) + shifts) % 122
if asci == 0:
sentence.append(chr(122))
elif asci < 97:
sentence.append(chr(asci+96))
else:
sentence.append(chr(asci))
encrypt(statement[1:], length, shifts, count+1)

message = input("Enter a statement to encrypt: ") # goodmorning


n = int(input("Enter a number to shift characters : ")) # 5
encryptWord(message, n) # -> lttirtwsnsl

# Task 8 - Insertion sorting recursively


def insertion_sort(arr, n):
if n <= 1:
return

insertion_sort(arr, n - 1)

last = arr[n - 1]
j = n - 2
while(j >= 0 and arr[j] > last):
arr[j + 1] = arr[j]
j = j - 1

arr[j + 1] = last

arr = [72, 13, 25, 85, 56]


n = len(arr)
insertion_sort(arr, n)
for i in arr:
print(i, end=', ')
print("")

# Task 9 - Pascal Triangle


def pascalTriangle(rows):
if rows == 0:
return []
elif rows == 1:
return [1]
else:
next_row = [1]
prev_row = pascalTriangle(rows - 1)
for i in range(0, len(prev_row) - 1):
next_row.append(prev_row[i] + prev_row[i + 1])
next_row += [1]
return next_row

for i in range(1, 6):


print(pascalTriangle(i))

Lectia 3- Import
# Task 1 - math module and constants
import math
import random
import matplotlib.pyplot as plt

print(math.pi)
print(math.tau)
print(math.e)
print(math.inf)
print(math.nan)

# Task 2 - Circle with math.pi

def circle(radius):
print("The circumference of this circle is", round(radius*math.tau, 3),
"cm.")
print("The area of this circle is", round(radius ** 2 * math.pi, 4),
"cm2.")

circle(3)
print(math.factorial(5))
print(math.sqrt(4))

# Task 3 - random numbers

numbers = []
for i in range(0, 100):
numbers.append(random.randrange(0, 10, 2))
print(numbers)
print(math.fabs(-5))

# Task 4 - I thought of a number...

chances = 7
solution = random.randint(1,101)
tip = 0
def check(num):
if num > solution:
return "I thought of a smaller number."
elif num < solution:
return "I thought of a greater number."
else:
return "The game will end now..."

while tip != solution and chances > 0:


tip = int(input("Guess a number:\n"))
print(check(tip))
chances -= 1
if tip == solution:
print("Congratulations, the number was", tip, "indeed.")
else:
print("Maybe next time, the number was" + str(tip) + ".")

# Task 5 - Using a package and creating a pie chart

def piechart(size, lab):


plt.pie(size, labels=lab, autopct='%.2f%%')
plt.show()

n = int(input("How many games do you like?\n"))


games = [] # games names
likes = [] # data in values
data = [] # data in %
db = s = 0
for i in range(n):
game_name = input("Give me the game name:\n")
like = int(input("How much do you like that game, in 1-10 scale?\n"))
db += like
games.append(game_name)
likes.append(like)
for i in range(n):
s = likes[i] / db * 100
s = round(s, 1)
data.append(s)

piechart(data, games)

# Task 6 - Body fat percentage calculator


def bmi(weight, height):
m = height / 100
h = m * m
bmi = round(weight / h, 2)
return bmi

w = int(input("What is your weight?"))


h = int(input("What is your height?"))
eva = bmi(w, h)
print(f"Your body mass index is: {eva}")

# Task 7 - Random numbers chart

numbers = []
for i in range(0, 200):
numbers.append(random.randrange(0, 10, 2))
names = ['Zero', 'Two', 'Four', 'Six', 'Eight']
quantity = []
for i in range(0,5):
quantity.append(numbers.count(i*2))
plt.pie(quantity, labels=names, autopct='%.0f%%')
plt.show()

# Task 8 - Roll a dice


dices = int(input("How many dices do you need?\n"))
max_value = int(input("What is the maximum value on the dices?\n"))
while True:
input("Press Enter to roll the dice(s)...")
dice_values = []
for i in range(0, dices):
dice_values.append(random.randint(1,max_value))
for i in range(0, dices):
print("The value of dice", i+1, "is", dice_values[i])

Lectia 4- Yield
def nextSquare():
k = 1
# An Infinite loop to generate squares
while True:
yield k * k # return the data, but not stop the process
k += 1 # Next execution resumes from this point

for num in nextSquare():


if num > 100:
break
print(num)
print("")

# Task 2 - yield command and random list


def print_even(test):
for i in test:
if i % 2 == 0:
yield i

Lectia 5- Matrice
import random
# Task 1 - Creating a matrix
def createMatrix():
matrix_1 = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
print(matrix_1)
createMatrix()

# Task 2 - Creating a matrix by generating numbers


def createMatrix2():
matrix_2 = []
for i in range(4):
temp_list = []
for j in range(3):
temp_list.append(j)
matrix_2.append(temp_list)
print(matrix_2)

def createMatrix3():
matrix_2 = []
for i in range(3):
temp_list = []
for j in range(4):
temp_list.append(j)
matrix_2.append(temp_list)
print(matrix_2)

createMatrix2()
createMatrix3()

# Task 3 - Change a matrix element to something else


# - string to number
# - number to string
# - number to boolean
def modifyMatrix():
matrix = [
[1, True, 3, 'd', 5],
[45.4, 2, 9, 'b', 6],
[99, 22, 'a', 4, 'g'],
[5, 12, 3, 'k', 'e'],
[0, 21, 35, False, 56],
]
print("Before:")
for i in range(len(matrix)):
print(matrix[i])
row = -1
while row < 0 or row > 4:
row = int(input("Give me a number to change the matrix ROW value:"))
col = -1
while col < 0 or col > 4:
col = int(input("Give me a number to change the matrix COLUMN
value:"))
change_to = input("Change the item to:\n")
change_type = input("Which type(str, int, bool)?\n")
if change_type == "str":
change_to = str(change_to)
elif change_type == "int":
change_to = int(change_to)
elif change_type == "bool":
change_to = bool(change_to)
else:
print("Wrong type selected")
return
matrix[row][col] = change_to
print("After:")
for i in range(len(matrix)):
print(matrix[i])
modifyMatrix()

# Task 4 - Get values from a matrix


data = ["shirt number", "name", "age", "height", "weight"]
team = [[1, "Nora", 24, 176, 62],
[4, "Noemie", 25, 180, 67],
[13, "Emily", 22, 178, 60],
[42, "Lisa", 23, 179, 63],
[99, "Greta", 27, 176, 81]]

print(team[2]) # third row


print(team[-1]) # last row
print(team[2][1]) # third row, second column
print(team[2][-1]) # third row, last column
column = []
for i in team:
column.append(i[1]) # second column
print(column)
for i in range(len(team)):
for j in range(len(team[0])):
print(team[i][j]) # each item from the matrix by index
for row in team:
for item in row:
print(item) # each item from the matrix by item

# Task 5 - Sorting a matrix elements


def sortingMatrix():
matrix = []
for i in range(5):
temp = []
for i in range(5):
temp.append(random.randint(0,10))
matrix.append(temp)
print(matrix)

matrix.sort() # How will it settle?


print(matrix)
for item in matrix: # How will it settle?
item.sort()
print(matrix)
sortingMatrix()

Lectia 7- Sudoku
# Task 1 - Sudoku solver
board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7]
]

def solve(bo):
find = find_empty(bo)
if not find:
return True
else:
row, col = find

for i in range(1, 10):


if valid(bo, i, (row, col)):
bo[row][col] = i
if solve(bo):
return True
bo[row][col] = 0
return False

def valid(bo, num, pos):


# Check row
for i in range(len(bo[0])):
if bo[pos[0]][i] == num and pos[1] != i:
return False
# Check column
for i in range(len(bo)):
if bo[i][pos[1]] == num and pos[0] != i:
return False
# Check box
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if bo[i][j] == num and (i, j) != pos:
return False
return True

def print_board(bo):
for i in range(len(bo)):
if i % 3 == 0 and i != 0:
print("- - - - - - - - - - - - - ")
for j in range(len(bo[0])):
if j % 3 == 0 and j != 0:
print(" | ", end="")
if j == 8:
print(bo[i][j])
else:
print(str(bo[i][j]) + " ", end="")

def find_empty(bo):
for i in range(len(bo)):
for j in range(len(bo[0])):
if bo[i][j] == 0:
return (i, j)
return None

print_board(board)
solve(board)
print("############################")
print_board(board)

Lectia 8- Conversie binara+shiftare de biti


# Task 1 - Basic operators

def basicOp():
print(2 ** 2 ** 3)
print((-2 / 4), (2 / 4), (2 // 4), (-2 // 4))
print(5 % 4, -5 % 4, 5 % -4, -5 % -4)
print((5 * ((25 % 13) + 100) / (2 * 13)) // 2)
print(5 * 25 % 13 + 100 / 2 * 13 // 2)
print(2 * 3 % 5)
x = 0
y = 10
print(x < y and y % 2 == 0)

# basicOp()

# Task 2 - Bitwise operators


def bitwiseOp():
print(bin(14)) # 1110
print(bin(6)) # 110
print(14 & 6) # bits that are in 14 and 6 too
print(bin(14 & 6))
print(14 | 6) # bits that are in 14 or 6 or both
print(bin(14 | 6))
print(14 ^ 6) # bits that are in 14 or 6 but not both
print(bin(14 ^ 6))
print(~14) # -(1110+1) = -1111 = -15

print(14 >> 2) # shift 14 right by 2: 1110 -> 11 = 3


print(bin(14 >> 2))
print(14 << 2) # shift 14 left by 2: 1110 -> 111000 = 56
print(bin(14 << 2))

# bitwiseOp()

# Task 3 - Comparing bitwise and arithmetic operators


def comparsion():
if 6 % 2 == 0:
print("Yes")
if 6 & 1 == 0: # 110 & 001 -> no bits are matching, so it equals to 0
print("Still yes")

# comparsion()

# Task 4 - Arithmetic operators with bitwise


def arithmeticToBitwise(n):
# Multiply with 2
n <<= 1
print(n)
# Multiply again with 8 (n will be 4, so 4 * 8 will be 32)
n <<= 3
print(n)
# Divide by 4
n >>= 2
print(n)

# Check if an integer is even or odd


if n & 1 == 0: # n % 2 == 0
print("even")
else:
print("odd")
# arithmeticToBitwise(2)

# Task 5 - Check that the input number is power of 2 using bitwise


def powerOfTwo(num):
a = num
if a > 0 and (a & (a - 1)) == 0:
print("%d is a power of 2" % a)
else:
print("%d is NOT a power of 2" % a)

# powerOfTwo(32)

# Task 6 - Number systems


def numberSystemSwap():
num = int(input("Give me a number to convert it\n")) # 28
con = int(input("Covert to?(binary(2), octal(8), hexadecimal(16))\n")) #
2, 8, 16
converted_num = 0
if con == 2:
converted_num = bin(num).replace("0b", "")
elif con == 8:
converted_num = oct(num).replace("0o", "")
elif con == 16:
converted_num = hex(num).replace("0x", "")
else:
print("Wrong data")

print(converted_num)

# numberSystemSwap()

# Task 7 -> Using the 'sep' parameters to print out roles


def sepEnd():
specialization = ['Druid', 'Barbarian', 'Wizard', 'Pirate', 'Engineer']
for role in specialization:
print(role, end='; ')
print('')
print('Hello', 'Logiscool', 'Programming', end=':')
print('')
print('Hello', 'Logiscool', 'Coding', sep=',', end=';')

# sepEnd()

# Task 8 - Sum of different number systems


def sum():
print(123 + 0b1011101 + 0o723 + 0x51da)

# sum()

# Task 9 - Practicing bitwise operators


a = 13 # 1101
b = 6 # 110
c = 0
c = a & b # 100
print(f"The result is {c}")

c = a | b # 1111
print(f"The result is {c}")

c = a ^ b # 1011
print(f"The result is {c}")

c = ~a # -1110 <- negative of 1101+1


print(f"The result is {c}")
c = ~b # -111 <- negative of 110+1
print(f"The result is {c}")

# Task 10 - Shifting values

c = a<<2 # 110100
print(f"The result is {c}")
c = b>>2 # 1
print(f"The result is {c}")
c = a<<2 | b>>2 # 110100 + 1
print(f"The result is {c}")
Lectia 9- Tuple
# Task 1 - Creating tuples

empty_tuple = ()
tuple1 = (1, 2, 3, 4)
tuple2 = (1, "sth", True, [1, 2, 3], tuple1)
print(empty_tuple, tuple1, tuple2)
tuple3 = (1)
print(type(tuple3))
tuple4 = (4,)
print(type(tuple4))
tuple5 = 1, 10, 20
print(tuple5)
tuple6 = tuple((1, 2, 3))
print(tuple6)

# Task 2 - List-tuples converter

list1 = [1, 2, 3]
print(type(list1))
tuple1 = tuple(list1)
print(type(tuple1))
list2 = list(tuple1)
print(type(list2))

# Task 3/a - Cannot change tuples

list1 = [1, 2, 3]
tuple1 = (1, 2, 3)
list1.append(4)
del list1[3]
list1.insert(1, 10)
list1[2] = 20
print(list1)

# Comment this section to remove errors


tuple1.append(4)
del tuple1[3]
tuple1.insert(1,10)
tuple1[2] = 20

del tuple1

# Task 3/b - Slicing and indexing


list1 = [1, 2, 3, 4, 5]
tuple1 = (1, 2, 3, 4, 5)
print(list1[1], tuple1[1])
print(list1[:2], tuple1[:2])
print(list1[-3:-1], tuple1[-3:-1])
print(list1[3:], tuple1[3:])
print(len(list1), len(tuple1))

# Task 4 - Even and odd

import random
list1 = [random.randint(1, 100) for i in range(10)]
tuple1 = tuple(random.randint(1, 100) for j in range(10))
even_list = []
odd_list = []
even_tuple = []
odd_tuple = []
for i in range(len(list1)):
if list1[i] % 2 == 0:
even_list.append(list1[i])
else:
odd_list.append(list1[i])
if tuple1[i] % 2 == 0:
even_tuple.append(tuple1[i])
else:
odd_tuple.append(tuple1[i])
print(list1, even_list, odd_list)
print(tuple1, even_tuple, odd_tuple)

# Task 5 - Comparison

tuple1 = (1, 2, 3)
tuple2 = (1, 4, 5)
print(tuple1 == tuple2)

tuple3 = (3, 2, 1)
tuple4 = (1, 2, 3)
print(tuple3 == tuple4)

tuple5 = (6, 6, 5)
tuple6 = (6, 6, 5)
print(tuple5 == tuple6)

# Task 6 - Addition and multiplication


import random
tuple1 = tuple(random.randint(1, 10) for i in range(5))
tuple2 = tuple(random.randint(1, 10) for i in range(5))
print(tuple1, tuple2)
print(tuple1+tuple2)
print(3*tuple1)

# Task 7 - Element multiplication

import random
tuple1 = tuple(random.randint(1, 10) for i in range(5))
print(tuple1)
for i in tuple1:
print(i*3, end=" ")

# Task 8 - Append the square of every element

import random
list1 = [random.randint(1, 10) for i in range(5)]
print(list1)
for i in range(len(list1)):
list1.append(list1[i]**2)
print(list1)

# Task 9 - Add two one-length tuple

tup1 = (1,)
tup2 = (1,)
tup3 = tup1+tup2
print(tup3)

# Task 10 - Contain

tup1 = ("asd", 10, None)


list1 = [13, "tuple", tup1]
if 10 in tup1:
print("It is in tup1")
if None in tup1:
print("None is here")
if None not in list1:
print("None is not here")

# Task 11 - Contain competition

import random
tup1 = (3, 6, 1, 5, 9)
list1 = [2, 6, 4, 8, 1]
inTuple = 0
inList = 0
numbers = [] # collect the numbers
for i in range(10):
number = random.randint(1, 20)
numbers.append(number)
if number in list1:
inList += 1
if number in tup1:
inTuple += 1
print("numbers: ", numbers, "in list: ", inList, " in tuple: ", inTuple)

# Task 12 - Change tuple values


tup1 = (1, 2, 3)
tup2 = (3, 4, 5)
tup3 = 1, 4, 5
print(tup1, tup2, tup3)
tup1, tup2, tup3 = tup3, tup2, tup1
print(tup1, tup2, tup3)

tup2 = (1, 2, 3, 4)
print(tup2)
tup2 = tup2[::-1]
print(tup2)

# Task 13 - Change tuple elements


tup1 = (1, 2, 3, 4)
print(tup1)
list_tup = list(tup1)
list_tup[2] = "Logiscool"
tup1 = tuple(list_tup)
print(tup1)
tup1 = tup1[:1]+(33,)+tup1[1:]
print(tup1)
list_tup = list(tup1)
del list_tup[4]
tup1 = tuple(list_tup)
print(tup1)

tup2 = (1, [3, 4])


tup2[1][0] = 111
print(tup2)

# Task 14 - Count and index


tup1 = (1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 1, 1, 1, 2, 3, 2, 1, 2, 3)
print(tup1.count(2))
print(tup1.index(2))

# Task 15 - Save elements to variables


tup1 = 2, 4, 5
a, b, c = tup1
print(a*b*c)

# Task 16 - Not tuple


list1 = [(1, 2), "asd", 113, (1, 3, 4, 5), None, True]
not_tuple = 0
for i in list1:
if type(i) != tuple:
not_tuple += 1
print(not_tuple)

# Task 17 - Averages
tup1 = ((1, 2, 3), (3, 4), (10, 20, 60), (3, 4, 5))
averages = []
for i in tup1:
average = sum(i)/len(i)
averages.append(average)
print(averages)

You might also like