0% found this document useful (0 votes)
8 views4 pages

Hints AI - Python - Session 4.ipynb - Colab

The document outlines various Python functions and their implementations for tasks such as counting even and odd numbers, reversing words in a sentence, finding minimum and maximum values, removing duplicates, and identifying the most frequent character in a string. It also discusses the use of sets for operations like union and intersection, along with examples for each function. Overall, it serves as a guide for writing efficient and pythonic code for common programming tasks.

Uploaded by

medo1234432144
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)
8 views4 pages

Hints AI - Python - Session 4.ipynb - Colab

The document outlines various Python functions and their implementations for tasks such as counting even and odd numbers, reversing words in a sentence, finding minimum and maximum values, removing duplicates, and identifying the most frequent character in a string. It also discusses the use of sets for operations like union and intersection, along with examples for each function. Overall, it serves as a guide for writing efficient and pythonic code for common programming tasks.

Uploaded by

medo1234432144
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/ 4

1.

Write a function count_even_odd(numbers) that takes a list of integers and returns a tuple (even_count, odd_count), where:

even_count is the number of even numbers


odd_count is the number of odd numbers

Write the steps of your program.

a. Find all even numbers, for each even number increase the counter for even by 1.

Iterates over the group of elements and for each element check the condition.

number%2 == 0 ==> Check this condition using if.

b.The same is done for odd numbers.`

x = [55, 66, 77, 99, 100]


counter_even = 0
counter_odd = 0
for i in x:
if i%2 == 0:
counter_even += 1
else:
counter_odd += 1
print(counter_even, counter_odd)

2 3

Write this in a pythonic way.

even_numbers = [i for i in x if i%2 == 0]


odd_numbers = [i for i in x if i%2 != 0]
print((len(even_numbers), len(odd_numbers)))

(2, 3)

even_numbers = [k for k in x if k%2 == 0]


even_numbers = []
for k in x:
if k%2 == 0:
even_numbers.append(i)
print(len(even_numbers))

Write a function reverse_words(sentence) that takes a string and returns a new string where the order of words is reversed.

print(reverse_words("Hello world Python")) # Expected output: "Python world Hello"

Steps:

1. Break the sentence to a list of its words. ==> split()


2. Reverse the order of the list. ==> [::-1]
3. Join the words in the list to form a sentence again. " ".join()

sentence = "Hello World Python"


sentence = sentence.split()
sentence = sentence[::-1]
sentence = " ".join(sentence)
print(sentence)

Python World Hello

Write a function find_min_max(values) that takes a tuple of numbers and returns a tuple (min_value, max_value).

1. Sort the elements and then get the last element and the first element.

x = [55, 66, 44, 33, 77]


x.sort()
print(x[0], x[-1])

33 77

Write a function remove_duplicates(lst) that takes a list and returns a new list with duplicates removed (while maintaining order).

x = [55 66 55, 77 88 88 99]

x = [55 66 77 88 99]
1. Create an empty list.
2. Iterate over the first list, then check if the current element is in the second one if not append, if use skip and go to the next element.
3. Keep doing this till iterating over all elements.

x = [55, 66, 55, 77, 88, 88, 99]


y = []
for i in x:
if i in y:
continue
else:
y.append(i)

print(y)

[55, 66, 77, 88, 99]

Write a function most_frequent_char(s) that takes a string and returns the character that appears the most times.

‫تقدر تشيل كل حرف و معاه عدد مرات تكراره‬...‫محتاج حاجة معينة‬.

dictionary:

{"char1": Frequency, ...}

aaabbcc

Iterates over the sentence, for each character check if it is already in the dictionary, if yes ==> increase its count by 1 (value). If no initialize its
value by 1.

dict1 = {"a": 1, "b": 2}


if "a" in dict1.keys(): # ['a', 'b']
print("Okay")

dict_keys(['a', 'b'])

word = "aaa bb cc cc c"


dict_1 = {}
for i in word: # i = "a"
if i == " ":
continue
if i not in dict_1.keys():
dict_1[i] = 1
else:
dict_1[i] += 1
print(dict_1)

{'a': 3, 'b': 2, 'c': 5}

dict1 = {"A": [70, 80, 90],


"B": [50, 40, 50],
"C": [60, 90, 90]}
dict_pass_or_fail = {}
for i, j in dict1.items(): # i, j = ('A', [70, 80, 90])
dict_pass_or_fail[i] = "Pass" if sum(j)/len(j) >= 50 else "Fail"
print(dict_pass_or_fail)

{'A': 'Pass', 'B': 'Fail', 'C': 'Pass'}

dict1 = {'a': 20}


dict1['b'] = 50

x = 60
print("Qualified" if x > 50 else "Not Qualified")

Qualified

Write a function common_elements(list1, list2) that takes two lists and returns a new list containing only the elements that appear in both
lists (no duplicates).

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

y = [2, 3, 6, 7, 8]

iterates over x, if there was an element in x and also found in y append to list called common list.
x = [1, 2, 3, 4, 5]
y = [2, 3, 6, 7, 8]
common = []
for i in x: # i = 2
if i in y:
common.append(i)

common

[2, 3]

keyboard_arrow_down Sets
Functions, exceptions, map, filter, reduce and Lambda Functions.

set1 = {True, 2, 3, 3, 3, 4, "welcome", "welcome", 1}


print(set1)

{True, 2, 3, 4, 'welcome'}

print(set1[0]) # Sets is unordered.

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-25-ca90c6e7048b> in <cell line: 0>()
----> 1 print(set1[0])

TypeError: 'set' object is not subscriptable

 

print(len(set1))

for i in set1:
print(i)

True
2
3
4
welcome

print("welcome" not in set1)

False

set1.add("orange")
print(set1)

{True, 2, 3, 4, 'orange', 'welcome'}

set1 = {1, 2, 3}
set2 = {4, 5, 6}
set1.update(set2)
# set1 = set1.union(set2)
print(set1) # Union
print(set1 | set2) # Union

{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}

set1 = {2, 3, 4, 5}
set2 = {4, 5, 6}
set1&set2 # & Intersection ==> common

{4, 5}

lst1 = [2, 3, 4, 5]
lst2 = [4, 5, 6]
set(lst1) & set(lst2)

{4, 5}
set(lst1) - set(lst2)

{2, 3}

set1.remove(7)

---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-36-beb694c72006> in <cell line: 0>()
----> 1 set1.remove(7)

KeyError: 7

 

set1.discard(7)

set1.clear()

set1 = {4, 5, 6}
set2 = {4, 7, 9}
set1 & set2
set1.intersection(set2)

{4}

set1 = {4, 5, 6}
set2 = {4, 7, 9}
set1.union(set2)

{4, 5, 6, 7, 9}

Start coding or generate with AI.

You might also like