Skip to content

Commit 30e29eb

Browse files
author
Sahil
committed
Add comprehensions and grid example
1 parent b0bbca1 commit 30e29eb

File tree

3 files changed

+58
-1
lines changed

3 files changed

+58
-1
lines changed

day3/comprehensions.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# given a list of strings, find lengths of each of them
2+
names = ["scaler", "interviewbit"]
3+
len_list = []
4+
for name in names:
5+
len_list.append(len(name))
6+
print(len_list)
7+
8+
# using list comprehension
9+
len_list = [len(name) for name in names]
10+
len_list = [("length", len(name)) for name in names]
11+
print(len_list)
12+
# with odd lengths
13+
len_list = [("length", len(name)) for name in names if len(name) % 2 == 1]
14+
print(len_list)
15+
16+
# sum of all even numbers from 1 to 100
17+
sum_even = sum([num for num in range(1, 101) if num % 2 == 0])
18+
print(sum_even)

day3/grid_city.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# take a m * n grid (matrix) as input
2+
# print the sum of all the elements, max,
3+
# and the sum of left_diagonal
4+
5+
n, m = map(int, input().split())
6+
7+
matrix = []
8+
for r in range(n):
9+
row = list(map(int, input().split()))
10+
matrix.append(row)
11+
12+
print(matrix)

lecture3.md

+28-1
Original file line numberDiff line numberDiff line change
@@ -509,4 +509,31 @@ print(day_mapping.keys())
509509

510510
## Mutability Summary
511511
- Basic Types: `int`, `float`, `decimal`, `str`, `bool` all are immutable
512-
- Container Types: `list`, `set` and `dict` are mutable while `tuple` is not
512+
- Container Types: `list`, `set` and `dict` are mutable while `tuple` is not
513+
514+
## List Comprehensions
515+
516+
```py
517+
# given a list of strings, find lengths of each of them
518+
names = ["scaler", "interviewbit"]
519+
len_list = []
520+
for name in names:
521+
len_list.append(len(name))
522+
print(len_list)
523+
```
524+
525+
```py
526+
# using list comprehension
527+
len_list = [len(name) for name in names]
528+
len_list = [("length", len(name)) for name in names]
529+
print(len_list)
530+
# with odd lengths
531+
len_list = [("length", len(name)) for name in names if len(name) % 2 == 1]
532+
print(len_list)
533+
```
534+
535+
```py
536+
# sum of all even numbers from 1 to 100
537+
sum_even = sum([num for num in range(1, 101) if num % 2 == 0])
538+
print(sum_even)
539+
```

0 commit comments

Comments
 (0)