Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions #dec12list comprehension.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#list comprehension
expression for variable in sequence (optional predicate)
my_list=[]
for i in range(1,10,2):
my_list.append(i**2)

my_list2=[i**2 for i in range(1,10,2)]
print(my_list)
print(my_list2)

odd_square=[]
for x in range(1,11):
if x % 2==1:
odd_square.append(x**2)

odd_square2 = [x**2 for x in range(1,11) if x %2 ==1]
print(odd_square2)


def dec(func, n):
def wrapper():
for _ in range(n):
func()
return wrapper

@dec
('say_hello', 5)
def say_hello():
print('hello')

#say_hello = dec(say_hello, 5)
say_hello()

133 changes: 126 additions & 7 deletions 12_09_practice.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,148 @@
#Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". Example: make_it_big([-1, 3, 5, -5]) returns that same list, #changed to [-1, "big", "big", -5].

list1=[-1, 3, 5, -5]

def make_it_big(list1):
list=[]
for i,a in enumerate(list1):
if a < 0:
list.append("big")
else:
list.append(a)
print(list)
make_it_big(list1)

#Count Positives - Given a list of numbers, create a function to replace last value with number of positive values. Example, count_positives([-1,1,1,1]) changes list #to [-1,1,1,3] and returns it. (Note that zero is not considered to be a positive number).

#SumTotal - Create a function that takes a list as an argument and returns the sum of all the values in the list. For example sum_total([1,2,3,4]) should return 10
list1=[-1,1,1,1]

#Average - Create a function that takes a list as an argument and returns the average of all the values in the list. For example multiples([1,2,3,4]) should return #2.5
def count_positives(list1):
list=[]
sum=0
for i,a in enumerate(list1):
if a < 0:
list.append(a)
else:
sum+=a
list.append(a)
list[-1]=sum
print(list)
count_positives(list1)

#SumTotal - Create a function that takes a list as an argument and returns the sum of all the values in the list. For example sum_total([1,2,3,4]) should return 10
list1=[1,2,3,4]
def sum_total(list1):
sum=0
for i in list1:
sum+=i
print (sum)
return sum
sum_total(list1)
#Average - Create a function that takes a list as an argument and returns the average of all the values in the list. For example multiples([1,2,3,4]) should return #2.5
list1=[1,2,3,4]
def average(list1):
sum=0
for i in list1:
sum+=i
avg1=sum/len(list1)
print (avg1)
return avg1
average(list1)
#Length - Create a function that takes a list as an argument and returns the length of the list. For example length([1,2,3,4]) should return 4

list1=[1,2,3,4]
def length(list1):
count=0
for i in list1:
count+=1
print (count)
return count
length(list1)
#Minimum - Create a function that takes a list as an argument and returns the minimum value in the list. If the passed list is empty, have the function return false. #For example minimum([1,2,3,4]) should return 1; minimum([-1,-2,-3]) should return -3.
#
list1=[0,-3, 5,2]
def minimum(list1):
if len(list1)==0:
print("False")
else:
return min(list1)
print(min(list1))
minimum(list1)
#Maximum - Create a function that takes a list as an argument and returns the maximum value in the list. If the passed list is empty, have the function return false. #For example maximum([1,2,3,4]) should return 4; maximum([-1,-2,-3]) should return -1.

list1=[0,-3, 5,2]
def maximum(list1):
if len(list1)==0:
print("False")
else:
return max(list1)
print(max(list1))
maximum(list1)
#Ultimateaalyze - Create a function that takes a list as an argument and returns a dictionary that has the sumTotal, average, minimum, maximum ad length of the list.

lis1=[0,-3, 5,2]
def ultimateaalyze(list1):
dict={
"sum_total":sum_total(list1),
"average":average(list1),
"minimum":minimum(list1),
"maximum":maximum(list1),
"length":length(list1)
}
print(dict)
ultimateaalyze(list1)

#ReverseList - Create a function that takes a list as a argument and return a list in a reversed order. Do this without creating a empty temporary list. For example #reverse([1,2,3,4]) should return [4,3,2,1]. This challenge is known to appear during basic technical interviews.
list1=[1,2,3,4]
def reverse(list1):
print (list1[::-1])
return list1[::-1]
reverse(list1)

#Ispalindrome- Given a string, write a python function to check if it is palindrome or not. A string is said to be palindrome if the reverse of the string is the same as string. For example, “radar” is a palindrome, but “radix” is not a palindrome.
#string1="radar"
def ispalindrome(string1):
if string1==string1[::-1]:
print(f"{string1} is palindrome")
else:
print(f"{string1} is not palindrome")
string1 = input('Enter any string ')
ispalindrome(string1)


#Fizzbuzz- Create a function that will print numbers from 1 to 100, with certain exceptions:
#If the number is a multiple of 3, print “Fizz” instead of the number.
#If the number is a multiple of 5, print “Buzz” instead of the number.
#If the number is a multiple of 3 and 5, print “FizzBuzz” instead of the number.

def fizzbuzz():
for num in range(0,101):
if num%3==0 and num%5==0:
print("FizzBuzz")
elif num%3== 0:
print("Fizz")
elif num%5==0:
print("Buzz")
else:
print(num)
fizzbuzz()

#Fibonacci- The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, #starting from 0 and 1. That is,
#F(0) = 0, F(1) = 1
#F(n) = F(n - 1) + F(n - 2), for n > 1.
#Create a function that accepts any number and will create a sequence based on the fibonacci sequence.
#Create a function that accepts any number and will create a sequence based on the fibonacci sequence.

def fibonacci(num):
num1 = 0
num2 = 1
seq = 0
if num == 0:
return 0
elif num== 1:
return 1
for i in range(num):
print(seq, end=' ')
num1 = num2
num2 = seq
seq = num1 + num2

num = int(input('Enter any number '))
fibonacci(num)


80 changes: 80 additions & 0 deletions 12_12_pythonpractice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#practice on Generator,lamda
from functools import reduce
#1. Use list comprehension to create a list containing a solution for the
#famous FizzBuzz problem. For integers 1 to 100, inclusively, the value
#should be:
# 'Fizz' if divisible by 3
# 'Buzz' if divisible by 5
# 'FizzBuzz' if divisible by both 3 and 5
# The integer itself if not divisible by both 3 and 5
list2=['FizzBuzz' if (num%3==0 and num%5==0) else "Fizz" if (num%3==0)else "Buzz"if (num%5==0) else num for num in range(1,101)]
print(list2)

#1. Create a generator, primes_gen that generates prime numbers
#starting from 2.
def primes_gen():
i = 2
while i < 100 :
prime = True # reset the `prime` variable before the inner loop
for a in range(2, i):
if i%a == 0:
prime = False
break
if prime:
yield i
i += 1 # don't forget to advance `i`

gen = primes_gen()
for _ in range(10):
print(next(gen), end=' ')
print(end='\n')
#2. Create a generator, unique_letters that generates unique letters from
#the input string. It should generate the letters in the same order as
#from the input string.
def unique_letters(str1):
unique=""
for i in str1:
if i not in unique:
unique=unique+' '+i
yield unique
for letter in unique_letters('hello'):
print(letter, end=' ')
print(end='\n')

#Consider the list:

#1. Sort the list by each language's version in ascending order.
prog_lang = [('Python', 3.8),
('Java', 13),
('JavaScript', 2019),
('Scala', 2.13)]
list1=prog_lang
list1.sort(key=lambda x: x[1])
print(list1)
#2. Sort the list by the length of the name of each language in descending
##order.
list2=prog_lang
list2.sort(key=lambda x: len(x[0]),reverse=True)
print(list2)
#3. Filter the list so that it only contains languages with 'a' in it.
prog_lang = [('Python', 3.8),
('Java', 13),
('JavaScript', 2019),
('Scala', 2.13)]
list3=list(filter(lambda x: 'a' in x[0], prog_lang))
print(list3)
#4. Filter the list so that it only contains languages whose version is in int
list4=list(filter(lambda x: type(x[1])== int, prog_lang))
print(list4)
#5. Transform the list so that it contains the tuples in the form,
#("language in all lower case", length of the language string)
list5=list(map(lambda x : (x[0].lower(),len(x[0])), prog_lang))
print(list5)
#6. Generate a tuple in theform,
#("All languages separated by commas",
#"All versions separated by commas")
print(reduce(lambda x,y :(f'{x[0]},{y[0]}',f'{x[1]},{y[1]}'),prog_lang))




121 changes: 121 additions & 0 deletions 12_13_python_decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
#Using a closure, create a function, multiples_of(n) which we can use to
#create generators that generate multiples of n less than a given
#number.

def multiples_of(n):
def multiply(k):
print([i for i in range(n, k, n)])
return multiply

m3 = multiples_of(3)
m3_under30 = m3(30)
m7_under30 = multiples_of(7)(30)

print(type(m3_under30))
print(m3(60))
print(m3_under30)
print(m7_under30)

#Create following decorators:
#1. make_upper – make every letter of a string returned from the decorated
#function uppercase.

def make_upper(f):
def wrapper():
str1=f()
return str1.upper()

return wrapper
@make_upper
def hello_world():
return 'hello young, good day!!'
print(hello_world()) # output: HELLO YOUNG, GOOD DAY!!
#2. print_func_name: Anynt the name of the decorated function before
#executing the function.
def print_func_name(f):
def wrapper():
print(f.__name__,"is running...")
f()
return wrapper

@print_func_name
def my_func():
print('Python is fun!!')
my_func() # output: my_func is running...

#3. give_name(name) – concatenate the given name at the end of a string
#returned from the decorated function.

def give_name(str1):
def wrapper(f):
return f()+" "+str1
return wrapper
@give_name('Theresa')
def greeting():
return 'Hello'

print(greeting) # output: Hello Theresa

print("---------------------------------------------------------------------------------------------------------")



#4. print_input_type – print a data type of the input argument before executing the decorated function.
def print_input_type(func):
def typer(n):
return f'The input data type is {type(func)}\nThe {func.__name__} of {n} is {func(n)}'
return typer

@print_input_type
def square(n):
return n**2

print(square(3.5)) # output: The input data type is <class 'float'>


#5. check_return_type(return_type) – check if the return type of the decorated function is return_type and print the result before executing the function.

def check_return_type(return_type):
def wrapper(func):
def inner(*args):
print(func(*args))
if type(func(*args)) == return_type:
return f'The return type is {type(func(*args))}'
else:
return f'=========Error!!=========The return type is NOT {return_type}'
return inner
return wrapper

@check_return_type(float)
def square(n):
return n ** 2

print(square(6)) # output: =========Error!!=========The return type is NOT <class 'str'>


print(square(2.9)) # output: The return type is <class 'float'>


#6. execute_log – write a function execution log on the log file.
from datetime import datetime

def execute_log(func):
def wrapper(*args):
return f'{datetime.now()} {func.__name__}'
return wrapper

@execute_log
def multiply(*nums):
mult = 1
for n in nums:
mult *= n
return mult

@execute_log
def hello_world():
return 'hello world!!'

print(multiply(6, 2, 3)) # 36
print(hello_world()) # hello world!!
print(multiply(2.2, 4)) # 8.8
print(hello_world()) # hello world!!
Loading