No Fluff Guide to Python - P8 - Advanced Functions

 You must fly before you can learn to walk!

 


#Zip Unzip

  • parse two lists together
for item in zip([10, 20, 30], ['x', 'y', 'z']):
    print(item)


(10, 'x')
(20, 'y')
(30, 'z')

The zip() function is used to combine multiple iterables (such as lists, tuples, or strings) into a single iterable object. It pairs corresponding elements from each input iterable and returns an iterator of tuples containing those pairs.

 

 

On the other hand, to "unzip" or separate the elements of a zipped iterable, you can use the zip() function in combination with the * operator. This is commonly known as "unzipping" the iterable.

Here's an example:

pairs = [(1, 'a'), (2, 'b'), (3, 'c')]

numbers, letters = zip(*pairs)

print(numbers)
print(letters)

Output:

(1, 2, 3)
('a', 'b', 'c')



Evaluate Expression given in String

certain computations in string format and we need to formulate its result.

test_str = "45 + 98-10"



import re

# initializing string
test_str = "45 + 98-10"

# printing original string
print("The original string is : " + test_str)

# Expression evaluation in String
# Using regex + map() + sum()
res = sum(map(int, re.findall(r'[+-]?\d+', test_str)))

# printing result
print("The evaluated result is : " + str(res))


or

# initializing string
test_str = "45 + 98-10"

# printing original string
print("The original string is : " + test_str)

res = eval(test_str)
print("The evaluated result is : " + str(res))


Output : 

The original string is : 45+98-10
The evaluated result is : 133



another example

x = 10
y = 5


print(eval('x + y', {'x':x, 'y': y}))

--15



#MAP


map(function, iterables)
  • there can be as many iterables as possible
  • passes each element in the iterable through a function and returns the result of all elements having passed through the function



numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
  
result = map(lambda x, y: x + y, numbers1, numbers2)
print(list(result))


--[5, 7, 9]



with if condition

# Define a function that doubles even numbers and leaves odd numbers as is
def double_even(num):
	if num % 2 == 0:
		return num * 2
	else:
		return num

numbers = [1, 2, 3, 4, 5]

result = list(map(double_even, numbers))
print(result) # [1, 4, 3, 8, 5]


-[1, 4, 3, 8, 5]



my_pets = ['alfred', 'tabitha', 'william', 'arla']
uppered_pets = []

for pet in my_pets:
    pet_ = pet.upper()
    uppered_pets.append(pet_)

print(uppered_pets)

#['ALFRED', 'TABITHA', 'WILLIAM', 'ARLA']

#using MAP
my_pets = ['alfred', 'tabitha', 'william', 'arla']
uppered_pets = list(map(str.upper, my_pets))

print(uppered_pets)


note that we did not call the str.upper function (doing this: str.upper()), as the map function does that for us on each element in the my_pets list.


#Filter

  • filter(func, iterable)
  • requires the function to return boolean values (true or false)
  • then passes each element in the iterable through the function,
  • "filtering" away those that are false
  • only one iterable is required
my_strings = ['a', 'b', 'c', 'd', 'e']
my_numbers = [1, 2, 3, 4, 5]
results = list(zip(my_strings, my_numbers))
print(results)


my_strings = ['a', 'b', 'c', 'd', 'e']
my_numbers = [1, 2, 3, 4, 5]
results = list(map(lambda x, y: (x, y), my_strings, my_numbers))
print(results)


scores = [66, 90, 68, 59, 76, 60, 88, 74, 81, 65]
def is_A_student(score):
    return score > 75
over_75 = list(filter(is_A_student, scores))
print(over_75)




dromes = ("demigod", "rewire", "madam", "freer", "anutforajaroftuna", "kiosk")
palindromes = list(filter(lambda word: word == word[::-1], dromes))
print(palindromes)


[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]

[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]

[90, 76, 88, 81]

['madam', 'anutforajaroftuna']




#Reduce

  • reduce(func, iterable[, initial])
  • applies a function of two arguments cumulatively to the elements of an iterable
  • function on which each element in the iterable gets cumulatively applied to
  • func requires two arguments


# Python 3
from functools import reduce
numbers = [3, 4, 6, 9, 34, 12]


def custom_sum(first, second):
    return first + second


result = reduce(custom_sum, numbers)
print(result)


#-------------
numbers = [3, 4, 6, 9, 34, 12]


def custom_sum(first, second):
    return first + second


result = reduce(custom_sum, numbers, 10)
print(result)

#68

#78


  • explain
  • 1st and 2nd element from numbers
  • pass them to func
  • sum returned → goes to REDUCE
  • this sum → used as 1st element of next run
  • 2nd element comes from numbers
  • It does this continuously (cumulatively) until numbers is exhausted

Comments

Popular posts from this blog

Index Clean-Up Scripts

forgot sa password and no logins are added

The SQL Server DBA’s Guide to Teradata