Post

Day 11 of 100 Days of Python

Practising Matrix and Dictionary

Today is June 30 and 11th Day. I practised Tranpose Matrix in Python.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Transpose Matrix
m = [
    [1, 2, 3],
    [4, 5, 6]
]
r = len(m)
c = len(m[0])
r2, c2 = c, r

# FIX: Build a grid where every single row is completely independent in memory
b = []
for i in range(0, r2):
    b.append([0] * c2)

# Your loop logic here is 100% PERFECT!
for i in range(0, r2):
    for j in range(0, c2):
        b[i][j] = m[j][i]

# Print out the final matrix line by line
print("Transposed Matrix:")
for i in range(0, r2):
    print(b[i])  # Changed from b[0] to b[i] to print each distinct row

I have also started learning Dictionary in Python. It is very easy to understand and by using it, the programes based on lists become easier.

image.png

1
2
3
4
5
6
7
8
9
# Write a program that takes a string of text and counts exactly how many times each individual character appears, storing the results in a dictionary.
txt = "success"
f = {}
for ch in txt:
    if ch in f:
        f[ch] += 1
    else:
        f[ch] = 1
print(f"Frequency of each character: {f}")

Output:

1
Frequency of each character: {'s': 3, 'u': 1, 'c': 2, 'e': 1}

The third program is to find the first non-repeatable character in a string using Dictionary in Python.

1
2
3
4
5
6
7
8
9
10
11
12
13
# Write a program that looks at a string and finds the very first character that does not repeat anywhere else in the string.
txt = "racecar"
f ={}
for ch in txt:
    if ch in f:
        f[ch]+=1
    else:
        f[ch] = 1
for ch in txt:
    if f[ch] ==1:
        print(f"First non-repeatable character: {ch}")
        break

Output:

1
First non-repeatable character: e
This post is licensed under CC BY 4.0 by the author.

Trending Tags