This commit is contained in:
2024-09-14 11:30:16 +02:00
parent 69d21bf28e
commit 148cd55409
5 changed files with 165 additions and 0 deletions

View File

@ -4,3 +4,61 @@
# When an iteration over a set of item starts using the for statement, the generator is run. Once the generator's function code reaches a "yield" statement, the generator yields its execution back to the for loop, returning a new value from the set. The generator function can generate as many values (possibly infinite) as it wants, yielding each one in its turn.
# Here is a simple example of a generator function which returns 7 random integers:
import random
def lottery():
# returns 6 numbers between 1 and 40
for i in range(6):
yield random.randint(1, 40)
# returns a 7th number between 1 and 15
yield random.randint(1, 15)
for random_number in lottery():
print("And the next number is... %d!" %(random_number))
import os
pathofcars = os.path.abspath("cars.csv")
def lineofCars(loc):
with open(loc,'r') as file:
for line in file:
yield line
text = lineofCars(pathofcars)
print(next(text))
print(next(text))
print(next(text))
#Change the values of two variables
a = 1
b = 2
a, b = b, a
print(a, b)
# Exercise
# Write a generator function which returns the Fibonacci series. They are calculated using the following formula: The first two numbers of the series is always equal to 1, and each consecutive number returned is the sum of the last two numbers. Hint: Can you use only two variables in the generator function? Remember that assignments can be done simultaneously. The code
# fill in this function
def fib():
pass #this is a null statement which does nothing when executed, useful as a placeholder.
a, b = 1, 1
for num in range(6):
a, b = b, a+b
yield a + b
# testing code
import types
if type(fib()) == types.GeneratorType:
print("Good, The fib function is a generator.")
counter = 0
for n in fib():
print(n)
counter += 1
if counter == 10:
break

View File

@ -0,0 +1,25 @@
# List Comprehensions is a very powerful tool, which creates a new list based on another list, in a single, readable line.
# For example, let's say we need to create a list of integers which specify the length of each word in a certain sentence, but only if the word is not the word "the".
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = []
for word in words:
if word != "the":
word_lengths.append(len(word))
print(words)
print(word_lengths)
#Using a list comprehension, we could simplify this process to this notation
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = [len(word) for word in words if word != "the"]
print(words)
print(word_lengths)
# Exercise
# Using a list comprehension, create a new list called "newlist" out of the list "numbers", which contains only the positive numbers from the list, as integers.
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
newlist = [int(number) for number in numbers if number > 0]
print(newlist)

View File

@ -0,0 +1,31 @@
#Normally we define a function using the def keyword somewhere in the code and call it whenever we need to use it.
def sum(a,b):
return a + b
a = 1
b = 2
c = sum(a,b)
print(c)
# Now instead of defining the function somewhere and calling it, we can use python's lambda functions, which are inline functions defined at the same place we use it. So we don't need to declare a function somewhere and revisit the code just for a single time use.
# They don't need to have a name, so they also called anonymous functions. We define a lambda function using the keyword lambda.
a = 1
b = 2
sum = lambda x,y : x + y
c = sum(a,b)
print(c)
summarize = lambda a, b : a + b
print(summarize(3, 5))
# Exercise
# Write a program using lambda functions to check if a number in the given list is odd. Print "True" if the number is odd or "False" if not for each element.
l = [2,4,7,3,14,19]
for i in l:
odd = lambda num : num % 2 == 0
print(odd(i))

View File

@ -0,0 +1,51 @@
# Every function in Python receives a predefined number of arguments, if declared normally, like this:
def myfunction(first, second, third):
# do something with the 3 variables
pass
# It is possible to declare functions which receive a variable number of arguments, using the following syntax:
def foo(first, second, third, *therest):
print("First: %s" % first)
print("Second: %s" % second)
print("Third: %s" % third)
print("And all the rest... %s" % list(therest))
#The "therest" variable is a list of variables, which receives all arguments which were given to the "foo" function after the first 3 arguments.
foo('a', "b", "c", "d", 'e', 'f', "g")
#It is also possible to send functions arguments by keyword, so that the order of the argument does not matter, using the following syntax. The following code yields the following output: The sum is: 6 Result: 1
def bar(first, second, third, **options):
if options.get("action") == "sum":
print("The sum is: %d" %(first + second + third))
if options.get("action") == "multiply":
print("The multiplied value is: %d" %(first * second * third))
if options.get("number") == "first":
return first
result = bar(1, 2, 3, action = "sum", number = "first")
print("Result: %d" %(result))
print("Other result: ", bar(1, 2, 3, action = "multiply", number = "first"))
# Exercise
# Fill in the foo and bar functions so they can receive a variable amount of arguments (3 or more) The foo function must return the amount of extra arguments received. The bar must return True if the argument with the keyword magicnumber is worth 7, and False otherwise.
def foo(one, two, three, *args):
return len(args)
def bar(one, two, three, **args):
if args.get("magicnumber") == 7:
return True
else:
return False
print(foo(1, 2, 3, 4, 5, 6))
print(bar(1, 2, 3, asd = 5, magicnumber = 7))