1) Cel mai mare divizor comun a mai multor numere (definiti o functie cu numar variabil de parametri care sa rezolve acest lucru)
In [1]:
def gcd(a,b):
while b:
a,b = b,a%b
return a
def gcdMultiple(*args):
#print(len(args))
#for i in args:
#print(i)
if len(args) < 2:
return -1
for i in range(2,len(args)+1,2):
res = gcd(args[i-2],args[i-1])
fin = gcd(res,args[i-2])
return fin
'''
def all_cmmdc(*args):
if len(args) == 0:
return -1
cm = cmmdc(args[0],args[1])
for i in args[2:]:
cm = cmmdc(cm,1)
return cm
print(all_cmmdc(2,8,6))
'''
#easier with functools reduce
#gcd(6,9) #is good
gcdMultiple(3,7,8,9)
Out[1]:
2) Scrieti o functie care calculeaza cate vocale sunt intr-un sir de caractere.
In [9]:
def count_vowels(string):
num_vowels=0
for char in string:
if char in "aeiouAEIOU":
num_vowels = num_vowels+1
return num_vowels
print count_vowels("This is a sentence.") #6
3) Scrieti o functie care returneaza numarul de cuvinte care exista intr-un string. Cuvintele sunt separate de spatii, semne de punctuatie (, ;, ? ! . )
In [73]:
def countWords(text):
#you should take into account various separators
# oneliner example:
wordList = ''.join(ch if ch.isalnum() else ' ' for ch in text).split()
#wordList = text.split(' ')
return len(wordList)
print countWords("Hello, hello; gigi ?") #3
In [ ]:
In [80]:
def special_chars_str(special_str):
print special_str.find('\t')
special_str = "\t Ceva si inca ceva\n"
special_chars_str(special_str)
In [2]:
def camelcase_to_underscores(code):
code = list(code)
print code
print range(len(code))
for i in range(len(code)):
if code[i].isupper():
code.insert(i, '_')
print code
code = ''.join(code)
code.lower()
print code
return code
'''for ch in code:
if ch.isupper():
code.insert(counter, '_')
counter += 1'''
camelcase_to_underscores('UpperCamelCase') #upper_camel_case
Out[2]:
In [ ]:
8) Se da un sir de caractere care reprezinta un polinom (Ex: "3x^3 + 5x^2 - 2x - 5") si un numar (intreg sau float). Sa se evalueze polinomul respectiv pentru valoarea data.
In [ ]:
In [4]:
def bigPrime(string):
#cifre = ['0', '1', '2']
number = []
numbers = []
for i in range(0, len(string)):
if string[i].isdigit():
number.append(string[i])
elif not number:
print 'number ready: ', number
numbers.append(''.join(number))
return numbers
print bigPrime('Ceva01ceffa212kjsda1') #01, 212, 1
1) Sa se scrie o functie care sa returneze o lista cu primele n numere din sirul lui Fibonacci.
In [14]:
def fibonacci(n):
fibo_list = [0, 1]
for i in range(2, n):
fibo_list.append(fibo_list[i-1] + fibo_list[i-2])
return fibo_list
fibo_list = fibonacci(6)
print fibo_list, ", length =", len(fibo_list)
2) Sa se scrie o functie care primeste o lista de numere si returneaza o lista cu numerele prime care se gasesc in ea.
In [84]:
def isPrime(n):
if n==2 or n==3: return True
if n%2==0 or n<2: return False
for i in range(3,int(n**0.5)+1,2): # only odd numbers
if n%i==0:
return False
return True
def prime_sublist(numbers):
sublist = []
for i in numbers:
if isPrime(i):
sublist.append(i)
return sublist
prime_sublist([0, 1, 2, 3, 4, 5])
Out[84]:
In [15]:
def lines():
pass
points = [(1,2), (0,1), (3,1)]
In [ ]:
5) Sa se scrie o functie care primeste ca parametru o lista x, si un numar k. Sa se returneze o lista cu tuple care sa reprezinte combinari de len(x) luate cate k din lista x. Exemplu: pentru lista x = [1,2,3,4] si k = 3 se va returna [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)].
In [88]:
import itertools
def combinations(x,k):
return list(itertools.combinations(x,k))
x = [1, 2, 3, 4]
k = 3
print combinations(x,k)
In [ ]:
In [ ]:
In [ ]:
9) Să se scrie o funție ce va ordona o listă de tuple de string-uri în funcție de al 3-lea caracter al celui de-al 2-lea element din tuplă. Exemplu: [('abc', 'bcd'), ('abc', 'zza')] ==> [('abc', 'zza'), ('abc', 'bcd')]
In [66]:
def sort_special(tpl):
pass
sort_special([('abc', 'bcd'), ('abc', 'zza')])
1) Sa se scrie o functie care primeste ca parametri doua liste a si b si returneaza un tuplu de seturi care sa contina: (a intersectat cu b, a reunit cu b, a - b, b - a)
In [1]:
def makeOperations(a,b):
operations = []
join = a | b
print('join: ', join)
operations.append(join)
intersection = a & b
print('intersection: ', intersection)
operations.append(intersection)
diffA = a - b
diffB = b - a
print('a-b: ', diffA)
print('b-a: ', diffB)
operations.append(diffA)
operations.append(diffB)
return tuple(operations)
a = set([1,2,3,4])
b = set([3,4,5,6])
makeOperations(a,b)
Out[1]:
2) Scrieti o functie care primeste ca parametru un sir de caractere si returneaza un dictionar in care cheile sunt caracterele dn componenta sirului de caractere iar valorile sunt reprezentate de numarul de aparitii ale caracterului respectiv in textul dat. Exemplu: Pentru sirul "Ana are mere." dat ca parametru functia va returna dictionarul: {'A': 1, ' ': 2, 'n': 1, 'a': 2, 'r': 2, 'e': 3, 'm': 1, '.': 1}.
In [16]:
def createFreqDict(phrase):
#chList = phrase.split(' ')
#print(dict(chList))
freqDict = {}
for i in phrase:
freqDict[i] = 0
print(freqDict)
for i in phrase:
freqDict[i] += 1
print(freqDict)
createFreqDict('Ana are mere')
In [8]:
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
dict2 = {'c': 3, 'd': 5, 'e': 5}
dict1Keys = set(dict1.keys())
dict2Keys = set(dict2.keys())
intersection = dict1Keys & dict2Keys
print intersection
build_xml_element("a", "Hello there", href="http://python.org", _class="my-link", id="someid") => "<a href=\"http://python.org\" _class=\"my-link\" id=\"someid\">Hello there</a>"
In [11]:
def build_xml_element(tag, content, **Kwargs):
string = []
#return string.join()
build_xml_element("a", "Hello there", href="http://python.org", _class="my-link", id="someid")
Exemplu: regulile [("key1", "", "inside", ""), ("key2", "start", "middle", "winter")] si dictionarul {"key2": "starting the engine in the middle of the winter", "key1": "come inside, it's too cold outside", "key3": "this is not valid"} => False deoarece desi regulile sunt respectate pentru "key1" si "key2", apare "key3" care nu apare in reguli.
In [ ]:
6) Fie un dictionar global
{
"+": lambda a, b: a + b,
"*": lambda a, b: a * b,
"/": lambda a, b: a / b,
"%": lambda a, b: a % b
}
Sa se construiasca o functie apply_operator(operator, a, b)
care va aplica peste a si b regula specificata de dictionarul global. Sa se implementeze astfel incat, in cazul adaugarii unui operator nou, sa nu fie necesara modificarea functiei.
In [65]:
rules = {
"+": lambda a, b: a + b,
"*": lambda a, b: a * b,
"/": lambda a, b: a / b,
"%": lambda a, b: a % b
}
def apply_operator(operator, a, b):
return rules[operator](a,b)
apply_operator("+", 2, 3)
Out[65]:
Un exemplu de dictionar global ar putea fi urmatorul:
{
"print_all": lambda *a, **k: print(a, k),
"print_args_commas": lambda *a, **k: print(a, k, sep=", "),
"print_only_args": lambda *a, **k: print(a),
"print_only_kwargs": lambda *a, **k: print(k)
}
In [ ]:
8) Sa se scrie o functie care primeste ca parametru un set si returneaza un tuplu (a, b), a reprezentand numarul de elemente unice din set iar b reprezentand numarul de elemente duplicate din set.
obs: Elementele din set-uri sunt in mod implicit unice. De exemplu, daca declar setul my_set = {1,1,2,2,3,3,4,5,5}, atunci cand il voi afisa imi va aparea doar {1,2,3,4,5}.
In [2]:
def tuple_unique(my_set):
return (len(my_set),0)
my_set = {1,1,2,2,3,3,4,5,5}
print tuple_unique(my_set)
9) Sa se scrie o functie care primeste un numar variabil de seturi si returneaza un dictionar cu urmatoarele operatii dintre toate seturile doua cate doua: reuniune, intersectie, a-b, b-a. Cheia va avea urmatoarea forma: "a op b", unde a si b sunt doua seturi, iar op este operatorul aplicat: |, &, -. Ex: {1,2}, {2, 3} =>
{
"{1, 2} | {2, 3}": 3,
"{1, 2} & {2, 3}": 1,
"{1, 2} - {2, 3}": 1,
...
}
In [56]:
import json
def set_operations_serialize(*args):
if len(args) < 2:
print 'You need at least 2 operands'
return
operations = {}
a = args[0]
b = args[1]
str_a = "{" + ", ".join(str(elem) for elem in a) + "}"
str_b = "{" + ", ".join(str(elem) for elem in b) + "}"
join = a | b
operations[str_a + " | " + str_b] = list(join)
print 'join: ', join
intersection = a & b
operations[str_a + " & " + str_b] = list(intersection)
print 'intersection: ', intersection
diffA = a - b
diffB = b - a
operations[str_a + " - " + str_b] = list(diffA)
operations[str_b + " - " + str_a] = list(diffB)
print 'a-b: ', diffA
print 'b-a: ', diffB
return operations
result = set_operations_serialize({1,2}, {2,3})
print result, type(result)
with open('data.json', 'w+') as fp:
json.dump(result, fp, sort_keys=True, indent=4)
In [ ]: