Initial Commit

This commit is contained in:
gparidhi51
2024-03-15 16:00:07 +05:30
committed by GitHub
parent 8662d179cf
commit 16e65a901d
98 changed files with 52995 additions and 0 deletions

View File

@@ -0,0 +1,505 @@
# Refresher: Iteration 1
---
### Question
What is the output of the following?
```python
a = 3
a *= 4
print(a)
```
**Choices***
- [ ] 3
- [ ] 4
- [ ] 7
- [x] 12
---
### Question
What is the output of the following?
```python
a = 5
if(a < 6):
print('Option 1')
if(a < 3):
print('Option 2')
else:
print('Option 3')
```
**Choices**
- [ ] Option 1
- [ ] Option 2
- [ ] Option 3
- [x] Option 1
Option 3
---
### Question
What is the output of the following?
```python
a = 1
b = 0
c = 1
if ( a and b):
print("Option 1")
elif (a and c):
print("Option 2")
else:
print("Option 3")
```
**Choices**
- [ ] Option 1
- [x] Option 2
- [ ] Option 3
- [ ] Option 4
---
### Question
What is the output of the following?
```python
count = 0
while(count < 10):
print(10, end = ' ')
```
**Choices**
- [ ] 0 1 2 3 4 5 6 7 8 9
- [ ] Infinite Loop
- [x] 10 10 10 10 10 10 10 10 10 10
---
## Introduction
* Imagine we wish to print the numbers from `1` to `1000`.
* So we can write the code as follows:
```python
print(1)
print(2)
..
..
..
print(1000)
```
* This is not an intelligent task to do. If the task is simple and we want to repeat it 5 times, we might write the same piece of code 5 times But this is not a practical approach if the repetition number is like `100` or `1000`.
* There is a principle in programming called **DRY**
Do you know the full form of it?
* **Don't Repeat Yourself**
* Even if you are writing the same code three times, you are not doing a good job at it. We can either use loops or functions.
* Before seeing loops, let us see why Python does things in a certain way.
* I have a friend Ramesh and I have to take `10` toffies from him. I will pick a chocolate and start counting from `1` until I reach `10` and then stop.
* Let us see in code what we are doing. Each time in a loop we will check if condition until we reach the else part.
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/355/original/upload_3c122a95efe68296140b852a2b3fdd5b.png?1708931051)
```python
count = 0
if(count < 10):
take toffee
count += 1
else
stop
```
* There are four things we always do in a loop:
1. Initialization
2. Condition
3. Action
4. Updation
* We will discuss the `while` loop in this class and the `for` loop in the next as it is different in different programming languages.
* The while loop will only run till the condition is true. As soon as the condition becomes false we exit the loop and execute the rest of the code.
### Syntax
```python
variable initialization
while (condition)
{
action
update variable
}
```
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/356/original/upload_5df881452fccdde7c6aeb1db1b70e8a0.png?1708931114)
This can be read as while this condition is **true** perform this action and update the variable.
Let us quickly move to an example to understand better.
---
## Print numbers from 1 to n
### Example 1 - Print Numbers from 1 to n
```python
n = input()
count = 1
while(count <= n): # can also be written as (count < n + 1)
print(count)
count += 1
print("end")
```
* Parenthesis are optional in while condition.
* Dry run for n = 5
If I do not write the incrementing `count` statement what will happen?
It will fall in the infinite loop and `1` will be printed forever.
* Always ensure you have all 4 things while writing a loop.
* In any programming language all the loops will always have these four things.
* An alternative way of writing this code is as follows:
```python
n = input()
count = 0
while count < n:
count += 1
print(count)
```
This is because counting in programming languages starts from `0`. Array indexing in most of the languages also starts from `0`. This is doing the same thing except the statements are shuffled.
---
## Print number from n to 1
### Example 2 - Print Number From n to 1
* Go grab your notebook, iPad, or laptop try writing code for the above question, and put the solution in the chat section.
* Writing in a book is best practice.
```python
n = int(input())
while n >= 1:
print(n)
n -= 1
```
* Dry run for n = 5
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/358/original/upload_075cfea2f2168b9130db73ee44a714da.png?1708931178)
---
## Print even numbers from 1 to 100
### Example 3 - Print Even Numbers From 1 to 100
* Once done paste it into the chat section
**Note:** Don't forget the updation of a variable. Also, some of the solutions have conditions where the loop doesn't run at all.
```python
n = int(input())
count = 1
while count <= n:
if count % 2 == 0:
print(count)
count += 1
```
* Write the updation statement in the beginning only.
**Alternative Solution:**
In each interaction, we can update the count by 2. Initially, instead of starting from 1, we can start from 2, and in each iteration, we can do `count += 2` this will always result in an even number.
```python
n = int(input()):
count = 2
while count <= n:
print(count)
count += 2
```
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/359/original/upload_1548f50a2f2023d5e00150ec29692b2f.png?1708931216)
This is an optimization of the above code as we are not checking the condition as well as the loop will only run half the times of `n`.
---
## Print the sum of all even numbers from 1 to 20
### Example 4 - Print the Sum of All Even Numbers From 1 to 20
We already know how to generate even numbers between `1` to `20`.
Instead of printing it, we need to store it in the bucket.
So we can keep adding these to a number and return the sum at the end.
```python
sum = 0
count = 2
while(count <= n):
sum += count
count += 2
print(sum)
```
---
## Print the digits of number `459`
### Example (VVIMP) - Print the Digits of Number 459 (order Doesn't Matter)
* How to get digits of a number in iteration
* Scraper -> extracts the last digit
* Scissors -> Cuts the last digit
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/360/original/upload_37782f2922540e6578503eb663cec769.png?1708931339)
We will scrape the last digit, print the result, and cut the last digit. This process is continued until all the digits are cut. This is a loop, right?
Is there any operation I told you in the past which takes `459` and returns `9`?
* taking `% 10` (modulo 10) will return the last digit.
* `459 % 10 -> 9`
* `45 % 10 -> 5`
* `4 % 10 -> 4`
Is there any operation that takes `459` and returns `45`, basically cutting the last digit?
* taking `/ 10` (integer division by 10) will return the last digit.
* `int(459 / 10) -> 45`
* `int(45 / 10) -> 4`
* `int(4 / 10) -> 0`
Only division will give the floor value such as `45.9`. Also, `459 // 10` doesn't work with negative integers as `-459` will give `-45.9 -> -46`. Thus, we can simply use `int(val)` to get the integer part of the remaining number.
```python
n = int(input())
while n > 0:
print(n % 10)
n = int(n / 10)
```
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/361/original/upload_45c12528520f54b65f85c663d69a343f.png?1708931386)
---
### Question
What is the output of the following?
```python
print(149 % 10)
```
**Choices**
- [ ] 14
- [x] 9
- [ ] 1
- [ ] 0
---
## Break and Continue Statements
### Break Statement
**Note:** Only for loops
If you want to break out of the loop if a certain condition is met then you use `break`. It will break the entire loop and execute the next statement.
**Definition** Whenever a break is executed inside a loop, it terminates the loop.
What will be the output of the following code?
```python
count = 1
while count <= 100:
if count == 4:
break
print(count, end=" ")
count += 1
```
**Output**
```plaintext
1 2 3
```
### Continue Statement
**Note:** Only for loops
**Definition** It skips the inside loop and continues the loop's execution.
```python
count = 1
while count <= 10:
count += 1
if count == 4:
continue
print(count, end=" ")
```
**Output**
```plaintext
1 2 3 5 6 7 8 9 10 11
```
* The continue statement simply skips the rest of the instructions of the current interaction and begins with the next iteration.
Look at the example below:
```python
count = 1
while count <= 10:
if count == 4:
continue
print(count, end=" ")
count += 1
```
* This will end up in an infinite loop. As the updation condition is never performed due to continue statment. So once it reaches 4, it keeps looping on 4.
---
## While-else
* Only and only in Python
* Else block will run only after the loop successfully terminates without a break.
```python
count = 1
while count <= 100:
if count == 4:
break
print(count, end=" ")
count += 1
else:
print("Yayy!")
```
* It will not print `Yayy!` as it is terminated via a `break` statement rather than terminating naturally.
---
## Check whether a number is prime or not
### Example - Check Whether a Number is Prime or Not
* Prime number is only divisible by `1` or the number itself.
* One is neither prime not consonant.
* We can say that `a` is divisible by `n` if `a % n == 0`.
* We can say that `24` is not prime as `24` divides `2, 4, 6, 8, etc.`
* We can say that `23` is a prime number cause it only divides `1` and `23`.
* Write a code to check if the number is prime or not. Start a loop from `2` to `n-1` if it is dividing any number then return `not prime` else `prime`. We are not required to use `break`, `continue`, or `while else`.
**Solution 1:**
Let us say our number is `25`.
We will use a variable `flag` to store whether a number is prime or not. It is simply a boolean variable initialized with `false`.
As soon as the number is divisible by some other number we can change its value to `true` and it is not prime. If the number is not divisible by any other number the `flag` remains `false` and we can conclude that it is a prime number.
```python
n = int(input())
count = 2
flag = False
while count < n:
if n % count == 0:
flag = True
count += 1
if flag:
print("Not Prime")
else:
print("Prime")
```
**Solution 2:**
* Is not very different from the previous solution.
* Now consider if the number is `9`, it is divisible by `3`. Do we need to check for other numbers? We don't! If the given number is divisible by any other number, we can break from the loop and declare that it is prime.
* This is a great situation where we can use `break`.
```python
n = int(input())
count = 2
flag = False
while count < n:
if n % count == 0:
flag = True
break
count += 1
if flag:
print("Not Prime")
else:
print("Prime")
```
**Solution 2:**
* We can remove the flag. We can use the `while else` statement.
* Instead of checking the flag, we can say that if we didn't break from the loop, it is a prime number.
* So as soon as we encounter that the number is divisible by some other number we print it is not prime. In the else part we print it is prime.
```python
n = int(input())
i = 2
while i < n:
if n % i == 0:
print("not prime")
break
i += 1
else:
print("prime number")
```
---
### Question
When can we say a number A is divisible by n?
**Choices**
- [x] A % n == 0
- [ ] A / n == 0
- [ ] A // n == 0
- [ ] A % n != 0
---
### Question
What is the output of the following?
```python
count = 1
while(count <= 5):
if(count == 2):
break
print(count, end = ' ')
count += 1
```
**Choices**
- [ ] 1 3 4 5
- [x] 1
- [ ] 1 2
- [ ] 0 1
---
### Question
What is the output of the following?
```python
count = 1
while(count <= 5):
if(count == 3):
continue
print(count, end = ' ')
count += 1
```
**Choices**
- [ ] 1 2 3 4 5
- [ ] 1 2 4
- [ ] 0 1 2 4 5
- [x] Infinite Loop

View File

@@ -0,0 +1,486 @@
# Refresher: Iteration 2
# Introduction
---
### Recap
* introduction to loop
* while, while else
* break and continue
* print 1 to n, n to 1
* print even numbers, sum
* prime numbers
* scrapers and scissors
---
### Question
What is the output of the following?
```python
count = 0
while(count < 10):
print(10, end = ' ')
count += 1
```
**Choices**
- [ ] 0 1 2 3 4 5 6 7 8 9
- [x] 10 10 10 10 10 10 10 10 10 10
- [ ] Infinite Loop
---
### Question
Which is true for an Odd number n?
**Choices**
- [ ] n % 2 == 0
- [x] n % 2 = = 1
---
### Question
What operation can be used to get the last digit of a number?
**Choices**
- [ ] n - 10
- [ ] n // 10
- [ ] int(n / 10)
- [x] n % 10
---
### Question
What will be the output of the following?
```python
count = 1
while(count <= 5):
if(count == 2):
break
print(count, end = ' ')
count += 1
```
**Choices**
- [ ] 1 3 4 5
- [x] 1
- [ ] 1 2
- [ ] 0 1
---
## Range Function
1. `range(n)` returns number from 0 to n-1.
* start = 0
* jump = 1
* number line example
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/362/original/upload_7f9c7eeebbf0c0d002f592640e888065.png?1708932201)
* range(-5) -> nothing as decrementing -5 we will never reach anywhere.
* range(1) -> 0
2. range(start, end) -> general numbers from [start, end-1]
* jump -> +1
* range(1,3) -> 1,2
* range(-5, -1) -> -5, -4, -3, -2
* range(-4, -10) -> nothing
* range(5, 1) -> nothing
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/363/original/upload_17b7f2a819543a855560aeb856b7c327.png?1708932266)
3. range(start, end, jump)
* start, end - 1
* range(1,6,2) -> 1, 3, 5
* range(0, -5, -1) -> 0, -1, -2, -3, -4
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/364/original/upload_2732cf5a66563800ba66530fac1d84fc.png?1708932301)
### Precautions
* jump can not be zero
* range always takes and returns an integer value
---
## Iterables an Iterators
* Assume that we have a bag of candies. I put my hand in the bag and take the candies out of the back one by one.
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/365/original/upload_e1c2e9662f5d17873ba95ed6134f2684.png?1708932357)
* Examples - list, dict, set, string, range, enumerate, tuple
* Iterables are groups of objects
* Iterator can be related to the hand that we are using to take candies out of the iterables(bag of candies).
### Range as an Iterable
* Range is iterable, it is a collection of integers. If the range returns nothing we can say the bag is empty it doesn't return anything.
`print(range(3))` What will this return?
* Print is not an iterator it will simply return `range(3)`.
* for loop is one of the best iterators.
---
## For Loop
**Syntax:**
```python
for variable in iterable:
action
```
* With for loop we can skip initialization, condition, and updation.
* It is an alternative to the `foreach` loop.
* The for loop can be used with iterables such as lists, dictionaries, etc. This will be covered when we will discuss lists and other iterables.
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/366/original/upload_cda895392e6a7ae96cbef51f67006f2e.png?1708932415)
### Question - Print 1 to 100?
```python
for i in range(1, 101):
print(i)
```
---
### Question
What will the sequence be generated by the following?
```python
range(5)
```
**Choices**
- [ ] 1 2 3 4 5
- [ ] 0 1 2 3 4 5
- [ ] 1 2 3 4
- [x] 0 1 2 3 4
---
### Question
What will the sequence be generated by the following?
```python
range(5,15, 2)
```
**Choices**
- [ ] 5,6,7,8,9,10,11,12,13,14,15
- [ ] 5,7,9,11,13,15
- [x] 5,7,9,11,13
- [ ] 5,6,7,8,9,10,11,12,13,14
---
### Question
What will the sequence be generated by the following?
```python
range(-5,0,1)
```
**Choices**
- [ ] -5,-4,-3,-2,-1,0
- [ ] Nothing
- [ ] 0,-1,-2,-3,-4,-5
- [x] -5,-4,-3,-2,-1
---
### Question
What will the sequence be generated by the following?
```python
range(-10,-5,-1)
```
**Choices**
- [ ] -10,-9,-8,-7,-6,-5
- [ ] -10,-9,-8,-7,-6
- [x] Nothing
- [ ] -6,-7,-8,-9,-10
---
### Question
What is the output of the following?
```python
for i in range(0,1):
print('Hello')
```
**Choices**
- [ ] Hello
Hello
- [ ] Hello
- [x] Nothing
- [ ] 0
1
How many values will be returned by this:
```python
range(n) -> n
```
If you want the loop to run `n` times just say range(n). The loop will run `n` times but start with zero till `n-1` therefore `n` values.
```python
range(5) -> 0, 1, 2, 3, 4 => 5 values
```
---
## Break and Continue in For Loop
* Break and Continue is same as we saw in while loop.
* If you want to break out of the loop if a certain condition is met then you use break. It will break the entire loop and execute the next statement.
* It skips the inside loop and continues the loops execution.
**[ASK THE LEARNERS]**
is `_`(underscore) a valid variable name?
* Variable should start with an alphabet or an `_`
* can only have underscore, alphabets, and numbers.
* It should not start with a number.
* Many programmers use underscore when they don't need a name for a variable in the for loop.
```python
for _ in range(10):
print("hello")
```
* If we use `_` it won't give a warning in case we are not using it. With any other variable name, it will give a warning in Python.
* What will be the output of the following:
```python
for i in range(10):
if(i == 4):
break
print(i)
```
**Output:**
```plaintext
0
1
2
3
```
* What will be the output of the following:
```python
for i in range(6):
if(i % 2 == 0):
continue
print(i)
```
**Output:**
```plaintext
1
3
5
```
---
## Pass Statement
* It is not to be used in competitive programming or interviews. It is usually used in testing.
* The `pass` does nothing. It signifies that the programmer will later add some code to it. Right now ignore this block.
```python
for i in range(6):
if(i % 2 == 0):
pass
print(i)
```
* Pass will still print the `i`. In case of continuing it will directly begin with a new iteration.
---
## For Else Loop
* Else statement will execute if the loop terminates successfully i.e. without a break
* Write a code for the prime number in the for loop.
```python
n = int(input())
for i in range(2,n):
if(n % i == 0):
print("Not Prime")
break
else:
print("Prime")
```
---
### Question
What is the output of the following?
```python
for i in range(0,10):
if(i % 3 == 0):
continue
print(i, end = ' ')
```
**Choices**
- [ ] 0 1 2 3 4 5 6 7 8 9
- [ ] 0 1 2
- [ ] 0 1 2 4 5 7 8 9
- [x] 0 1 2 4 5 7 8
---
### Question
What is the output of the following?
```python
for i in range(1,10):
if(i % 3 == 0):
break
print(i, end = ' ')
```
**Choices**
- [ ] 1 2 3 4 5 6 7 8 9
- [x] 1 2
- [ ] 1 2 4 5 7 8 9
- [ ] 1 2 4 5 6 7 8
---
## Nested Loops
* If we write a loop inside a loop it is a nested loop.
* Look at the pattern below and write a code to generate this pattern.
```plaintext
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
```
If I want to print `1 to 5`, how will I write the code?
```python
for i in range(1,6):
print(1, end = " ")
```
Now if I want to do this 5 times will I do this?
```python
for i in range(1,6):
print(1, end = " ")
print()
for i in range(1,6):
print(1, end = " ")
print()
for i in range(1,6):
print(1, end = " ")
print()
for i in range(1,6):
print(1, end = " ")
print()
for i in range(1,6):
print(1, end = " ")
print()
```
* No right? What principle it is not following?
* DRY (Do not repeat yourself).
* I will use a nested loop.
```python
for _ in range(5):
for i in range(1,6):
print(1, end = " ")
print()
```
* Single for loop gives 1D data, 2 loops nested will give 2D, and so on.
* Similarly we can write nested while loop
---
## Difference b/w For and While Loop
| For | While |
| :------------------------------------------------------------------------------: | :--------------: |
| It is simple to use. Initialization, condition, and updation in a single line. | Complex to use |
| Only for simple iteration | Complex tasks such as scrapper and Scissors can be performed |
**Note:** Never update the iteration variable in the for loop.
---
## Pattern Printing Problems
```plaintext
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
```
Write a code to print this pattern.
:::warning
Please take some time to think about the solution on your own before reading further.....
:::
**Solution 1**
```python
for i in range(5):
for j in range(5):
print("*", end = " ")
print()
```
**Solution 2**
We are using string to integer multiplication. The statement `print("* "*5)` will generate a line with 5 stars and a space in between.
```python
for _ in range(5):
print("* " * 5)
```
### Staircase Binding
```plaintext
*
* *
* * *
* * * *
* * * * *
```
:::warning
Please take some time to think about the solution on your own before reading further.....
:::
**Solution 1**
When `i` is `1` we print `1` star, when `i` is `2` we print `2` star, and so on.
```python
n = int(input())
for i in range(1, n + 1):
print("* " * i)
```
**Solution 2**
We can do it with the nested loop as well
```python
for i in range(1, n + 1):
for j in range(i):
print("*", end = " ")
print()
```
### Reverse Staircase
```python
*
* *
* * *
* * * *
* * * * *
```
* Can you guys do it or should I give you a hint?
**No spaces between stars**
* Assuming that there is no space between starts. What we are doing is `4 spaces 1 star`, `3 spaces 2 stars`, `2 spaces 3 stars` and so on.
```python
for i in range(1,6):
spaces = " " * (n - i)
stars = "*" * (i)
print(spaces + stars)
```
### Homework Problem
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/368/original/upload_5703b40bbef52803b280818dfa61dbff.png?1708932888)

View File

@@ -0,0 +1,936 @@
# Refresher: List 1
## Defining a List
### Definition
A list is a built-in data type that represents an ordered collection of items. It is a mutable, dynamic array, meaning you can modify its elements and size after creation.
### Syntax
```python
my_list = [element1, element2, element3, ...]
```
### Examples
- The provided code snippets demonstrate various aspects of working with lists in Python.
**Code 1**:
```python
a = [1, 2, 3]
```
- Initializes a list `a` with three integer elements.
**Code 2**:
```python
a = [1, "a"]
```
- Initializes a list `a` with two elements: an integer `1` and a string `"a"`.
**Output 2**:
```plaintext
# SyntaxError: closing parenthesis '}' does not match opening parenthesis '['
a = [1, "a"]
```
- This part of the code seems incomplete and might be causing a syntax error. The specific error is related to unmatched parentheses.
**Code 3**:
```python
a = ["a", 1, 3.14, True] # Lists can be heterogeneous
```
- Demonstrates that lists in Python can contain elements of different data types.
**Code 4**:
```python
a = list(range(10))
print(a)
```
**Output 4**:
```plaintext
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
- Uses the `list()` constructor to create a list containing elements from `0` to `9` (result of `range(10)`).
**Code 5**:
```python
students = ['Kusum', 'Shubham', 'Pooja']
print(students)
```
**Output 5**:
```plaintext
['Kusum', 'Shubham', 'Pooja']
```
- Prints the list of student names.
### Indexing in a List
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/375/original/upload_f402ef9034ec28e26319f0e940031598.png?1708936235)
**Code**:
```python
print(students[1])
```
**Output**:
```plaintext
Shubham
```
**Code**:
```python
print(students[5])
```
**Output**:
```plaintext
# IndexError: list index out of range
```
**Explanation**:
- Accessing elements in a list using indices.
- An IndexError occurs when trying to access an index beyond the list's length.
### Reverse Indexing
![image](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/066/376/original/upload_e92b207fe616514bb9f3004786722d51.png?1708936520)
**Code**:
```python
students = ['Kusum', 'Shubham', 'Pooja']
print(students[-1])
```
**Output**:
```plaintext
Pooja
```
**Code**:
```python
students = ['Kusum', 'Shubham', 'Pooja']
print(students[-100])
```
**Output**:
```plaintext
# IndexError: list index out of range
```
### Updating an Index in A List
```python
students = ['Kusum', 'Shubham', 'Pooja']
print(students)
```
**Output**:
```python
['Kusum', 'Shubham', 'Pooja']
```
- Updating user at index 3
**Code**:
```python
students[3] = 'Ruben'
print(students)
```
**Output**:
```python
['Kusum', 'Shubham', 'Pooja', 'Ruben']
```
**Code**:
```python
students[-100]
```
**Output**:
```python
# IndexError: list index out of range
```
**Code**:
```python
print(type(students))
```
**Output**:
```python
<class 'list'>
```
- Print even numbers till 10
**Code**:
```python
a = list(range(0, 11, 2))
print(a)
```
**Output**:
```python
[0, 2, 4, 6, 8, 10]
```
- Print first 10 even numbers
**Code**:
```python
a = list(range(0, 20, 2))
print(a)
```
**Output**:
```python
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
```
**Explanation**:
- Lists can be modified by assigning new values to specific indices.
- Negative indices count from the end of the list.
### Iteration in a List
```python
students = ['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth', 'Veerendra']
```
- `len()` gives you the number of elements in a list
**Code**:
```python
print(len(students))
```
**Output**:
```python
7
```
**Code**:
```python
# Solution 1
n = len(students)
for i in range(0, n):
print(students[i])
```
**Output**:
```python
Kusum
Shubham
Pooja
Ruben
Aarushi
Vinoth
Veerendra
```
**Code**:
```python
# Solution 2
for student in students:
print(student)
```
**Output**:
```python
Kusum
Shubham
Pooja
Ruben
Aarushi
Vinoth
Veerendra
```
### Quiz 1
**Code**:
```python
# quiz
li = [-1, 0, 4]
for i in li:
if i > 0:
print(i, end=' ')
```
**Output**:
```python
4
```
**Explanation**:
- Iterating through a list and printing positive numbers.
### Functions in a List
### len()
- Returns the number of elements in a list.
**Code**:
```python
a = list(range(2, 6))
print(len(a))
```
**Output**:
```plaintext
4
```
### append()
- Appends an object to the end of the list.
**Code**:
```python
students = ['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth', 'Veerendra']
students.append('Vicky')
print(students)
```
**Output**:
```plaintext
['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth', 'Veerendra', 'Vicky']
```
**Code**:
```python
a = []
a.append('Hi')
print(a)
```
**Output**:
```plaintext
['Hi']
```
### insert()
- The `insert` method is used to insert an element before the specified index in a list.
**Code**:
```python
a = [1, 2, 3, 4]
a.insert(1, 'Aakar')
print(a)
```
**Output**:
```plaintext
[1, 'Aakar', 2, 3, 4]
```
**Explanation**:
- The element 'Aakar' is inserted at index 1, shifting the original elements to the right.
**Code**:
```python
a = [1, 2, 3, 4]
a.insert(-3, 'Aakar')
print(a)
```
**Output**:
```plaintext
[1, 'Aakar', 2, 3, 4]
```
**Explanation**:
- The negative index `-3` is interpreted as counting from the end of the list, so 'Aakar' is inserted at index 2 from the end.
**Code**:
```python
a = [1, 2, 3, 4]
a.insert(100, 'Aakar')
print(a)
```
**Output 3**:
```plaintext
[1, 2, 3, 4, 'Aakar']
```
**Explanation**:
- If the specified index is greater than the length of the list, the element is inserted at the end.
**Code**:
```python
a = [1, 2, 3, 4]
a.insert(-100, 'Aakar')
print(a)
```
**Output**:
```plaintext
['Aakar', 1, 2, 3, 4]
```
**Explanation**:
- The negative index `-100` is interpreted as counting from the end of the list, so 'Aakar' is inserted at the beginning of the list.
### pop()
- Removes and returns an item at the specified index (default last).
- Raises `IndexError` if the list is empty or the index is out of range.
**Code**:
```python
students = ['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth', 'Veerendra']
print(students.pop())
print(students)
```
**Output**:
```plaintext
Veerendra
['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth']
```
**Code**:
```python
a = [1, 2, 3, 4]
print(a.pop(5))
print(a)
```
**Output**:
```plaintext
# IndexError: pop index out of range
```
**Code**:
```python
a = []
print(a.pop())
print(a)
```
**Output**:
```plaintext
# IndexError: pop from an empty list
```
**Explanation**:
- The `pop()` function removes and returns an item at a specified index.
- Raises an `IndexError` if the index is out of range.
### remove()
- Removes the first occurrence of a value.
- Raises `ValueError` if the value is not present.
**Code**:
```python
students = ['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth', 'Veerendra']
students.remove('Shubham')
print(students)
```
**Output**:
```plaintext
['Kusum', 'Pooja', 'Ruben', 'Aarushi', 'Vinoth', 'Veerendra']
```
**Code**:
```python
a = [1, 2, 3, 2, 4]
a.remove(2)
print(a)
```
**Output**:
```plaintext
[1, 3, 2, 4]
```
**Code**:
```python
a = [1, 2, 3, 4]
a.remove(5)
print(a)
```
**Output**:
```plaintext
# ValueError: list.remove(x): x not in the list
```
**Explanation**:
- The `remove()` function removes the first occurrence of a specified value.
- Raises a `ValueError` if the value is not present.
### Quiz
### Quiz 1
```python
li = [1, 2, 3]
li.append('4')
print(li)
```
**Answer**: [1, 2, 3, '4']
### Quiz 2
```python
li = []
print(len(li))
```
**Answer**: 0
### Quiz 3
```python
li = [1, 2]
print(li.pop())
```
**Answer**: 2
### Quiz 4
```python
li = [1, 3, 4]
li.insert(0, 2)
print(li)
```
**Answer**: [2, 1, 3, 4]
### Quiz 5
```python
li = [1, 2]
print(li.remove(2))
```
**Answer**: None
## Reverse
**Code**:
```python
a = [1, 2, 3]
print(a.reverse())
print(a)
```
**Output**:
```plaintext
[3, 2, 1]
```
**Code**:
```python
a = []
print(a.reverse())
print(a)
```
**Output**:
```plaintext
None
[]
```
**Explanation**:
- The `reverse()` method reverses the elements of a list in place.
## + operator
- Concatenating two lists.
- Creates a new list.
**Code**:
```python
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
print(a)
print(b)
```
**Output**:
```plaintext
[1, 2, 3, 4, 5, 6]
[1, 2, 3]
[4, 5, 6]
```
### extend()
- Extend list by appending elements from the iterable.
**Code**:
```python
a = [1,2,3]
b = [4,5,6]
a.append(b)
print(a)
print(a[-1]) # not what we want
```
**Output**:
```plaintext
[1, 2, 3, [4, 5, 6]]
[4, 5, 6]
```
**Explanation**:
- The append() method is used, but it appends the entire list b as a single element at the end of list a.
**Code**:
```python
a = [1,2,3]
b = [4,5,6]
a.extend(b)
print(a)
print(b)
print(a[-1]) # not what we want
```
**Output**:
```plaintext
[1, 2, 3, 4, 5, 6]
[4, 5, 6]
6
```
**Explanation**:
- The extend() method is used, adding each element from list b individually to the end of list a.
**Code**:
```python
a = [1,2,3]
a.extend(a)
print(a)
```
**Output**:
```plaintext
[1, 2, 3, 1, 2, 3]
```
**Explanation**:
- The extend() method is used to add elements of list a to the end of list a, effectively doubling its content.
## in Operator
- return True or False after searching list
**Code**:
```python
students = ['Kusum', 'Shubham', 'Pooja', 'Ruben', 'Aarushi', 'Aakar', 'Veerendra']
print('Aakar' in students)
print('Kusum' in students)
```
**Output**:
```plaintext
False
True
```
**Explanation**:
- The `in` operator is used to check if an element is present in a list.
- The first print statement checks if 'Aakar' is in the list of students, resulting in `False`.
- The second print statement checks if 'Kusum' is in the list of students, resulting in `True`.
### How to take List as Input?
**Code**:
```python
n = int(input())
a = []
for i in range(n):
item = input()
a.append(item)
print(a)
```
**Output**:
```plaintext
5
a
b
c
d
e
['a', 'b', 'c', 'd', 'e']
```
**Explanation**:
- The code takes an integer `n` as input, then uses a loop to take `n` input items and appends them to a list `a`, resulting in a list of items.
## Split
**Code**:
```python
s = 'I-love-bananas'
li = s.split('-')
print(li)
print(type(li))
```
**Output**:
```plaintext
['I', 'love', 'bananas']
<class 'list'>
```
**Explanation**:
- The `split` method is used to split a string `s` into a list of substrings based on the specified delimiter ('-'), creating a list `li`.
**Code**:
```python
s = 'I--love--bananas'
li = s.split('--')
print(li)
print(type(li))
```
**Output**:
```plaintext
['I', 'love', 'bananas']
<class 'list'>
```
**Explanation**:
- Even if there are multiple consecutive delimiters, `split` correctly handles them and produces the desired list.
**Code**:
```python
n = int(input())
s = input() # always returns string "a b c d e"
li = s.split(' ')
print(li)
```
**Output**:
```plaintext
5
a b c d e
['a', 'b', 'c', 'd', 'e']
```
**Explanation**:
- The code takes an integer `n` and a space-separated string as input, then uses `split` to create a list `li` of individual items.
**Code**:
```python
# INPUT
# 5
# 12 14 15 16 17
n = int(input())
s = input() # always returns string "a b c d e"
li = s.split(' ')
new_li = []
for item in li:
new_li.append(int(item))
print(new_li)
```
**Output**:
```plaintext
5
1 2 3 4 5
[1, 2, 3, 4, 5]
```
**Explanation**:
- The code converts a space-separated string of numbers into a list of integers, demonstrating the use of `split` and conversion to integers.
**Code**:
```python
# INPUT
# 5
# 12 14 15 16 17
n = int(input())
s = input() # always returns string "a b c d e"
li = s.split(' ')
for index in range(len(li)):
li[index] = int(li[index])
print(li)
```
**Output**:
```plaintext
5
1 2 3 4 5
[1, 2, 3, 4, 5]
```
**Explanation**:
- Similar to the previous example, this code converts a space-separated string of numbers into a list of integers using a loop.**Explanation**:
### Problem
Given a List of Student Marks, Count the Number of Student Who Failed
:::info
Please take some time to think about the solution approach on your own before reading further.....
:::
**Code**:
```python
n = int(input())
s = input() # always returns string "a b c d e"
marks = s.split(' ')
for index in range(len(marks)):
marks[index] = float(marks[index])
print(marks)
# ------------------------
count = 0
for index in range(len(marks)):
if marks[index] <= 30:
count += 1
print(count)
```
**Output**:
```plaintext
5
10 20 30 40 50
[10.0, 20.0, 30.0, 40.0, 50.0]
3
```
**Explanation**:
- The code first takes an integer `n` as input, representing the number of students. Then, it takes a string `s` as input, which contains space-separated marks of students in the form of "a b c d e".
- The string of marks is split into a list of strings using the `split` method, and then each element in the list is converted to a floating-point number using a loop.
- The list of marks is printed as output.
- The code initializes a variable `count` to 0 and then iterates through the list of marks. For each mark, if it is less than or equal to 30, the `count` is incremented.
- Finally, the count of students who failed (marks <= 30) is printed as output.
**Output Explanation**:
- For the given input "5" and "10 20 30 40 50", the list of marks after conversion to float is `[10.0, 20.0, 30.0, 40.0, 50.0]`.
- Among these marks, three students have marks less than or equal to 30 (10.0, 20.0, and 30.0). Therefore, the count of students who failed is printed as `3`.

View File

@@ -0,0 +1,284 @@
# Refresher: List 2
## Builtin Functions
### Index
- Given a value and a list, find the element and print "Found" else "Not found"
**Code**:
```python
# Solution 1
li = list(map(int, input().split(' ')))
value = int(input())
for index in range(len(li)):
if li[index] == value:
print('Found at', index)
break
else:
print('Not found')
```
**Output**:
```plaintext
1 2 3 4 5 6
3
Found at 2
```
- Displaying index
**Code**:
```python
# Solution 2
li = list(map(int, input().split(' ')))
value = int(input())
if value in li:
print('Found at', li.index(value))
else:
print('Not found')
```
**Output**:
```plaintext
1 2 3 4 5 6
3
Found at 2
```
**Explaination**:
- Solution 1 uses a for loop to iterate through the list and check if each element is equal to the given value. If found, it prints the index and breaks out of the loop. If not found, it prints "Not found."
- Solution 2 uses the `in` operator to check if the value is present in the list. If found, it prints the index using the `index()` function. If not found, it prints "Not found."
### max
- Given a list, you have to find the maximum element in this list.
**Code**:
```python
li = [-13, -53, -23, -21, -55]
max_value = li[0]
for item in li:
if max_value < item:
max_value = item
print(max_value)
```
**Output**:
```plaintext
-13
```
**Code**:
```python
li = [-13, -53, -23, -21, -55]
max_value = None
for item in li:
if max_value is None or max_value < item:
max_value = item
print(max_value)
```
**Output**:
```plaintext
-13
```
**Explaination**:
- The first solution initializes `max_value` with the first element of the list and iterates through the list, updating `max_value` if a larger element is found.
- The second solution initializes `max_value` to `None` and iterates through the list, updating `max_value` if a larger element is found. The `is None` check is used to handle an empty list case.
### Printing max Value
**Code**:
```python
li = [-13, -53, -23, -21, -55]
print(max(li))
print(max(1, 2, 3, 4, 5, 3, 4, 5, 1))
```
**Output**:
```plaintext
-13
5
```
**Explaination**:
- The `max()` function is used to directly find the maximum value in the list or a set of values.
### Printing min Value
**Code**:
```python
li = [-13, -53, -23, -21, -55]
print(min(li))
print(min(1, 2, 3, 4, 5, 3, 4, 5, 1))
```
**Output**:
```plaintext
-55
1
```
**Explaination**:
- The `min()` function is used to directly find the minimum value in the list or a set of values.
### Slicing
In this section, we will learn how to slice the list `[49, 6, 71]` from the given list
**Code**:
```python
li = [2, 23, 49, 6, 71, 55]
def sub_list(li, startIndex, endIndex):
new_li = []
for i in range(startIndex, endIndex + 1):
new_li.append(li[i])
return new_li
print(sub_list(li, 2, 4))
```
**Output**:
```plaintext
[49, 6, 71]
```
**Explaination**:
- The `sub_list` function takes a list and two indices as input and returns a new list containing elements from the start index to the end index.
### More slicing examples
#### li[:end]
**Code**:
```python
a = list(range(10))
print(a)
print(a[::-2])
```
**Output**:
```plaintext
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 7, 5, 3, 1]
```
**Explanation**:
- `a[::-2]` creates a new list by slicing `a` with a step of -2, starting from the end.
- It includes every second element in reverse order, resulting in `[9, 7, 5, 3, 1]`.
#### li[start:end]
**Code**:
```python
a = [5, 2, 3, 9, 8]
print(a[1:5])
```
**Output**:
```plaintext
[2, 3, 9, 8]
```
**Explanation**:
- The slice `a[1:5]` extracts elements starting from index 1 up to (but not including) index 5 from list `a`.
#### li[start:]
**Code**:
```python
a = [5, 2, 3, 9, 8]
print(a[2:])
```
**Output**:
```python!
[3, 9, 8]
```
**Explanation**:
- The slice `a[2:]` extracts elements starting from index 2 till the end of the list `a`.
#### li[start\:end:range]
**Code**:
```python
a = [5, 2, 3, 9, 8]
print(a[1:4:2])
```
**Output**:
```python
[2, 9]
```
**Explanation**:
- The slice `a[1:4:2]` extracts elements starting from index 1 up to (but not including) index 4 with a step of 2.
- It includes every second element in the specified range, resulting in `[2, 9]`.
---
## Problem Solving
### Question
Right shift the given array:
**li = [2,3,4,5,6]
n = [0,n - 1]
Output = [3,4,5,6,2]**
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Solution 1
**Code**:
```python
li = [2,3,4,5,6]
n = int(input())
for i in range(n):
a = li.pop(0)
li.append(a)
print(li)
```
**Output**:
```python
3
[5, 6, 2, 3, 4]
```
## Solution 2
**Code**:
```python
li = [2,3,4,5,6]
n = int(input())
print(li[n:] + li[:n])
```
**Output**:
```python
3
[5, 6, 2, 3, 4]
```

View File

@@ -0,0 +1,222 @@
# Refresher: List 3
## Nested List
### Introduction
- A nested list in Python is a list that can contain other lists as elements.
- It allows you to create a two-dimensional structure, also known as a 2D list, where each element in the outer list can be a list itself.
**Code**:
```python
maths = [1, 1, 1]
science = [2, 2, 2]
history = [3, 3, 3]
subjects = [maths, science, history]
print(subjects)
```
**Output**:
```python
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
```
**Explanation of code**:
- Three separate lists, `maths`, `science`, and `history`, are created.
- These lists are then combined into a single list named `subjects`.
- The `print(subjects)` statement displays the resulting nested list.
---
## Indexing in a 2D List
- Indexing in a 2D list involves accessing elements using two indices: one for the outer list (row) and another for the inner list (column).
**Code**:
```python
print(subjects[0][2])
# row major form
print(subjects)
```
**Output**:
```python
1
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
```
**Explanation of code**:
- The expression `subjects[0][2]` accesses the element in the first row (index 0) and the third column (index 2) of the 2D list.
- The second `print(subjects)` statement displays the entire 2D list.
---
## Iterating a 2D List
### Example 1
**Code**:
```python
for row_index in range(len(subjects)):
for col_index in range(len(subjects[row_index])):
print(subjects[row_index][col_index], end = ' ')
```
**Output**:
```python
1 1 1 2 2 2 3 3 3
```
**Explanation of code**:
- Nested loops iterate through each element of the 2D list, printing them horizontally.
### Example 2
**Code**:
```python
for row_index in range(len(subjects)):
for col_index in range(len(subjects[row_index])):
print(subjects[row_index][col_index], end=' ')
print()
```
**Output**:
```python
1 1 1
2 2 2
3 3 3
```
**Explanation of code**:
- Similar to Example 1, but with an additional `print()` to create a new line after each row.
### Example 3
**Code**:
```python
for col_index in range(len(subjects[0])):
for row_index in range(len(subjects)):
print(subjects[row_index][col_index], end = ' ')
print()
```
**Output**:
```python
1 2 3
1 2 3
1 2 3
```
**Explanation of code**:
- This example transposes the 2D list by iterating through columns first and then rows.
---
### Input in a 2D List
### Example
**Code**:
```python
def take_list_as_input():
li = list(map(int, input().split()))
return li
a = []
for i in range(3):
a.append(take_list_as_input())
print(a)
```
**Output**:
```python
12 13 14
45 46 47
34 35 36
[[12, 13, 14], [45, 46, 47], [34, 35, 36]]
```
**Explanation of code**:
- The `take_list_as_input()` function reads a line of space-separated integers and converts them into a list.
- The loop collects three such lists to create a 2D list named `a`.
### Row Wise Sum
**Code**:
```python
def take_list_as_input():
li = list(map(int, input().split()))
return li
a = []
for i in range(3):
a.append(take_list_as_input())
print(a)
for row_index in range(len(a)):
row_sum = sum(a[row_index])
print(row_sum)
```
**Output**:
```python
1 1 1
2 2 2
3 3 3
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
3
6
9
```
**Explanation of code**:
- Calculates and prints the sum of each row in the 2D list.
---
## Matrix Addition
**Code**:
```python
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
c = []
for row_index in range(len(a)):
temp = []
for col_index in range(len(a[row_index])):
temp.append(a[row_index][col_index] + b[row_index][col_index])
c.append(temp)
print(c)
```
**Output**:
```python
[[2, 4, 6], [8, 10, 12], [14, 16, 18]]
```
**Explanation of code**:
- Performs matrix addition on two 2D lists (`a` and `b`) and stores the result in the list `c`.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,677 @@
# Refresher: Strings 2
### Question
What is the output of the following?
```python
a = "Age:"
print(a + 23)
```
**Choices**
- [ ] Age:23
- [ ] Age:
- [x] Error
- [ ] Age: 23
In the given code, there is an attempt to concatenate a string ("Age:") with an integer (23). This operation is not allowed in Python without explicit conversion and hence will output an error.
---
### Question
What is the output of the following?
```python
a = "Hello"
b = a * 3
print(len(b) == (len(a) * 3))
```
**Choices**
- [x] True
- [ ] False
- [ ] Error
The output is True, because the length of the string `b` is compared to the result of multiplying the length of `a` by 3, and they are equal.
---
### Question
What is the output of the following?
```python
s = 'Name : {}, Age : {}'
print(s.format(25, 'John'))
```
**Choices**
- [ ] Name : John, Age : 25
- [x] Name : 25, Age : John
- [ ] Error
The `format` method replaces the `{}` placeholders in the string with the provided values in the order they appear. In this case, `25` is placed where the first `{}` is, and `'John'` is placed where the second `{}` is, resulting in the output "Name : 25, Age : John".
---
### Question
What is the output of the following?
```python
s = 'Name : {name}, Gender : {}, Age : {age}'
print(s.format('Male', age = 25, name = 'John'))
```
**Choices**
- [x] Name : John, Gender : Male, Age : 25
- [ ] Name : Male, Gender : John, Age : 25
- [ ] Error
The `format` method is used to substitute values into the placeholders `{}`, `{name}`, and `{age}` in the string `s`. The values provided in the `format` method are 'Male' for the first placeholder, 'John' for the `{name}` placeholder, and 25 for the `{age}` placeholder. The resulting string is "Name : John, Gender : Male, Age : 25".
---
## Count Uppercase Letters
## Count Number of Uppercase Letters
### Problem
Given a string, the task is to count the number of uppercase letters in the string.
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Solution
The solution involves iterating through each character in the string and checking if its ASCII value falls within the range of uppercase letters (A-Z) using the `if` case. Specifically, it ensures that the character is greater than or equal to the ASCII value of 'A' and less than or equal to the ASCII value of 'Z'. For each uppercase letter found, a counter is incremented.
```python
def count_upper(a):
count = 0
for char in a:
if ord('A') <= ord(char) <= ord('Z'):
count += 1
return count
# Example Usage
result = count_upper("ThisIsAString")
print(result)
```
### Output
```plaintext
4
```
### Explanation
In this example, the function `count_upper` takes the input string "ThisIsAString" and iterates through each character. For each character that is an uppercase letter, the counter is incremented. The final count is returned, indicating that there are 4 uppercase letters in the input string.
---
## More Functions in Strings
## More Functions
### join()
### Explanation
The `join()` method concatenates elements of an iterable using a specified separator.
### Example
```python
# Example
separator = '.'
result = separator.join(['Hi', 'there'])
print(result) # Output: 'Hi.there'
# Example 2
result = '.'.join(['2', '31'])
print(result) # Output: '2.31'
result = '.'.join([2, 3])
print(result) # Error
```
#### Explanation
In this example, the elements 'Hi' and 'there' are joined with a dot (`.`) as the separator, resulting in the string 'Hi.there'.
### upper()
### Explanation
The `upper()` method converts all characters in a string to uppercase.
### Example
```python
# Example
a = 'ThisIsAString'
result = a.upper()
print(result) # Output: 'THISISASTRING'
# Example 2
a = 'ThisIsAString12348$#'
result = a.upper()
print(result) # Output: 'THISISASTRING12348S#'
```
### Explanation
The `upper()` function transforms all characters in the string 'ThisIsAString' to uppercase, resulting in 'THISISASTRING'.
### lower()
### Explanation
The `lower()` method converts all characters in a string to lowercase.
### Example
```python
# Example
a = 'ThisIsAString'
result = a.lower()
print(result) # Output: 'thisisastring'
# Example 2
a = 'ThisIsAString12348$#'
result = a.lower()
print(result) # Output: 'thisisastring12348$#'
```
### Explanation
The `lower()` function transforms all characters in the string 'ThisIsAString' to lowercase, resulting in 'thisisastring'.
### isupper()
### Explanation
The `isupper()` method checks if all characters in a string are uppercase.
### Example
```python
# Example
a = 'AbC1234sg'
result = a.isupper()
print(result) # Output: False
# Example 2
a = 'ABC1234SG'
result = a.isupper()
print(result) # Output: True
```
### Explanation
The `isupper()` function returns `False` because not all characters in the string 'AbC1234sg' are uppercase. Numbers and special characters are ignored.
### islower()
### Explanation
The `islower()` method checks if all characters in a string are lowercase, ignoring numbers and special characters.
### Example
```python
# Example 1
a = 'abc1234$#'
result = a.islower()
print(result) # Output: True
# Example 2
a = 'ABC1234$#'
result = a.islower()
print(result) # Output: False
```
### Explanation
The `islower()` function returns `True` because all characters in the string 'abc1234$#' are lowercase.
### isalpha()
### Explanation
The `isalpha()` method checks if all characters in a string are alphabetic.
### Example
```python
# Example
a = 'Scaler Academy'
result = a.isalpha()
print(result) # Output: False
# Example
a = 'Scal3rAcademY'
result = a.isalpha()
print(result) # Output: False
```
### Explanation
The `isalpha()` function returns `False` because the string 'Scaler Academy' contains spaces and is not purely alphabetic. The next example has a number in between and hence is not alphabetic.
### isdigit()
### Explanation
The `isdigit()` method checks if all characters in a string are digits.
### Example
```python
# Example
a = '123'
result = a.isdigit()
print(result) # Output: True
# Example
a = '1a2b3'
result = a.isdigit()
print(result) # Output: False
```
### Explanation
The `isdigit()` function returns `True` because all characters in the string '123' are digits. The next example returns `False` because of the alphabetic characters in the string.
### isalnum()
### Explanation
The `isalnum()` method checks if all characters in a string are alphanumeric.
### Example
```python
# Example
a = 'Abc1234'
result = a.isalnum()
print(result) # Output: True
# Example 2
a = 'Abc12348S#'
result = a.isalnum()
print(result) # Output: False
```
### Explanation
The `isalnum()` function returns `True` because all characters in the string 'Abc1234' are alphanumeric. The second example has special character, `#` and hence returns `False`.
### endswith()
### Explanation
The `endswith()` method checks if a string ends with a specified suffix.
### Example
```python
# Example
a = 'Scaler Academy'
result = a.endswith('Academy')
print(result) # Output: True
# Example 2
a = 'Python Programming'
result = a.endswith('Academy')
print(result) # Output: False
```
### Explanation
The `endswith()` function returns `True` because the string 'Scaler Academy' ends with the specified suffix 'Academy'.
```python
# Program to Count Alphabets and Digits in a String
# User input
s = input()
# Initialize counters
alpha_count = 0
digit_count = 0
# Iterate through each character in the input string
for char in s:
if char.isalpha():
alpha_count += 1
elif char.isdigit():
digit_count += 1
# Print the result
print(f'Alphabet count is {alpha_count} and digit count is {digit_count}')
```
### Explanation
- The program takes user input as a string `s`.
- Two counters (`alpha_count` and `digit_count`) are initialized to keep track of the number of alphabets and digits.
- The program iterates through each character in the input string using a `for` loop.
- For each character, it checks if it is an alphabet using `char.isalpha()` and increments the `alpha_count` accordingly.
- Similarly, if the character is a digit (`char.isdigit()`), the `digit_count` is incremented.
- Finally, the program prints the counts using an f-string.
### Example
**Input:**
```python
Hello123World
```
**Output:**
```plaintext
Alphabet count is 10 and digit count is 3
```
In the input string "Hello123World," there are 10 alphabets (H, e, l, l, o, W, o, r, l, d) and 3 digits (1, 2, 3).
---
### Question
What is the output of the following?
```python
a = [1, 2, 3, 4, 5]
print('|'.join(a))
```
**Choices**
- [ ] 1|2|3|4|5
- [x] Error
- [ ] |1|2|3|4|5|
The `join` method in Python is used to concatenate a list of strings with a specified delimiter. However, in the given code, the list `a` contains integers, not strings. The `join` method expects a list of strings, so attempting to join a list of integers will result in a TypeError.
---
### Question
What is the output of the following?
```python
a = 'Scaler123'
print(a.upper())
```
**Choices**
- [ ] Error
- [ ] Scaler123
- [ ] sCALER123
- [x] SCALER123
The `upper()` method in Python is used to convert all characters in a string to uppercase. In this case, the string 'Scaler123' is assigned to variable `a`, and `a.upper()` is then called, resulting in 'SCALER123' as the output.
---
### Question
What is the output of the following?
```python
a = 'scaler123'
print(a.islower())
```
**Choices**
- [x] True
- [ ] False
The output of the given Python code is `True`. The `islower()` method checks if all the characters in the string are lowercase, and in this case, all characters in the string 'scaler123' are lowercase.
---
### Question
What is the output of the following?
```python
a = 'scaler123'
print(a.isalpha())
```
**Choices**
- [ ] True
- [x] False
The output of the given Python code is `False`. This is because the `isalpha()` method checks if all the characters in the string are alphabetic (letters) and does not allow for numbers or other characters. In the given string 'scaler123', the presence of '123' makes the method return `False`.
---
### Question
What is the output of the following?
```python
a = 'scaler123'
print(a.endswith('ler'))
```
**Choices**
- [ ] True
- [x] False
The output of the given Python code is `False`. This is because the string assigned to variable `a` ('scaler123') does not end with the substring 'ler'. Therefore, the `endswith()` method returns `False`.
---
## List and String Comparison
### List Comparison
List comparison in Python involves comparing two lists element-wise. The comparison starts from the first elements of both lists, and the result is determined based on the comparison of corresponding elements.
### Example 1
```python
[1, 2, 3, 4, 5] < [1, 3]
# Output: True
```
### Explanation
In this example, the comparison evaluates to `True` because the first list is considered "less than" the second list. The comparison is element-wise, and it stops as soon as a pair of elements is found where the first element is less than the second element.
### Example 2
```python
[1, 3, 0] > [1, 3]
# Output: True
```
### Explanation
Here, the comparison evaluates to `True` because the first list is considered "greater than" the second list. Again, the comparison is element-wise, and it stops as soon as a pair of elements is found where the first element is greater than the second element.
### Example 3
```python
[1, 3] == [1, 3]
# Output: True
```
### Explanation
The comparison `[1, 3] == [1, 3]` checks if both lists are equal element-wise. In this case, the result is `True` because every corresponding pair of elements is the same.
### Example 4
```python
[1, 2, 3] > [1, 1000, 2000, 3000]
# Output: True
```
### Explanation
The comparison `[1, 2, 3] > [1, 1000, 2000, 3000]` evaluates to `True` because the first list is considered "greater than" the second list. The comparison is still element-wise, and it stops as soon as a pair of elements is found where the first element is greater than the second element.
### String Comparison
String comparison in Python involves comparing two strings lexicographically, character by character. The comparison is case-sensitive, with uppercase letters considered "less than" their lowercase counterparts. The comparison stops as soon as a pair of characters is found where the condition (e.g., less than, greater than, equal to) is satisfied. The overall result of the string comparison reflects the outcome of these character-wise comparisons.
### Example 1
```python
'A' > 'a'
# Output: False
```
### Explanation
In this example, the comparison `'A' > 'a'` evaluates to `False` because, in the ASCII table, uppercase 'A' has a lower ASCII value than lowercase 'a'.
### Example 2
```python
'Aakar' > 'Sudip'
# Output: False
```
### Explanation
Here, the comparison `'Aakar' > 'Sudip'` evaluates to `False` because, in the lexicographic order, the substring 'Aakar' is considered "less than" the substring 'Sudip'. The comparison stops at the first differing character.
---
## List Comprehension
List comprehension is a concise way to create lists in Python. It offers a more readable and efficient alternative to traditional loops. The syntax involves expressing the creation of a list in a single line.
### Example 1
```python
# Create a list of squares till n-1
n = 5
li = [i ** 2 for i in range(1, n)]
print(li) # Output: [1, 4, 9, 16]
```
This example uses list comprehension to create a list of squares for values from 1 to n-1.
### Example 2
```python
# Create a list of squares for values from 1 to n
n = 5
li = [i ** 2 for i in range(1, n + 1)]
print(li) # Output: [1, 4, 9, 16, 25]
```
Here, the list comprehension creates a list of squares for values from 1 to n.
### Example 3
```python
# Create a list of all even elements
n = 5
li = [i for i in range(1, n * 2) if i % 2 == 0]
print(li) # Output: [2, 4, 6, 8, 10]
```
This example creates a list of all even elements from 1 to n*2 using list comprehension.
### Example 4
```python
# Create a list of tuples (i, j) for values of i and j in the given range
n = 3
li = [(i, j) for i in range(n) for j in range(i)]
print(li) # Output: [(1, 0), (2, 0), (2, 1)]
```
This example creates a list of tuples (i, j) using nested list comprehension. It includes pairs where j is less than i.
---
## Pattern Printing
### Pattern 1: Increasing Rows of Stars
Print the following pattern ?
```python
*
* *
* * *
* * * *
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
### Code
```python
n = int(input())
for i in range(1, n + 1):
print('*' * i)
```
This code takes an input `n` and uses a loop to print rows of stars. The number of stars in each row increases from 1 to `n`.
### Pattern 2: Right-aligned Triangle
Print the following pattern ?
```python
*
* *
* * *
* * * *
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
To print the given pattern, you can use two nested loops. The outer loop controls the rows, and the inner loop controls the columns. For each row, you need to print spaces followed by asterisks in a specific pattern. Consider the number of spaces needed before each asterisk to achieve the desired right-aligned triangular pattern.
### Code
```python
n = int(input())
for i in range(1, n + 1):
print(' ' * (n - i) + '* ' * i)
```
This code prints a right-aligned triangle of stars. The number of spaces before the stars decreases, and the number of stars in each row increases.
### Pattern 3: Diamond Pattern
Print the following diamond pattern ?
```python
*
***
*****
*******
*********
*******
*****
***
*
```
:::warning
Please take some time to think about the solution approach on your own before reading further.....
:::
To print the given diamond pattern, you can follow these steps:
1. Observe the pattern carefully, especially how the number of spaces and stars change in each row.
2. Divide the pattern into two parts: the upper half and the lower half.
3. For the upper half, start with fewer spaces and more stars, incrementing the number of stars in each row.
4. For the lower half, start with fewer spaces and more stars, decrementing the number of stars in each row.
### Code
```python
n = int(input())
m = n // 2
for i in range(1, m + 1):
print(' ' * (m - i) + '*' * (2 * i - 1), sep = '')
for i in range(m, 0, -1):
print(' ' * (m - i) + '*' * (2 * i - 1), sep = '')
```
This code prints a diamond pattern. The first loop prints the upper half, and the second loop prints the lower half of the diamond.

View File

@@ -0,0 +1,684 @@
# Refresher: Tuples + Strings 1
# Introduction to Tuples
### Introduction
We delve into the fundamentals of Tuples and Strings in Python, two powerful data types that play a crucial role in various programming scenarios. Let's start by understanding the essence of Tuples.
## Planets Example
Let's start with an example using an array to store the names of all the planets in our solar system.
```python
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
```
### Adding the Sun
Now, imagine we someone is trying to include the Sun in our list of planets. Since arrays in Python are mutable, someone might be tempted to do this:
```python
planets.append("Sun")
```
However, this is where mutability can lead to errors. While the code above will add "Sun" to the list, it's not accurate to consider the Sun a planet. This illustrates a potential problem with mutable structures when trying to maintain data integrity.
## Tuples
### Definition
Now, let's explore tuples - a different kind of data structure. Tuples are similar to arrays but are immutable. This immutability provides certain advantages, especially in situations where data integrity is crucial.
### Creating Tuples with Numbers
We can create a tuple with numbers like this:
```python
# Definition
a = (1, 2, 3, 4)
print(type(a)) # Output: <class 'tuple'>
# Exception
b = (1,)
print(type(b)) # Output: <class 'tuple'>
c = (1, 2)
print(type(c)) # Output: <class 'tuple'>
d = ()
print(type(d)) # Output: <class 'tuple'>
```
#### Explanation
- In the first example, `a` is a tuple containing the numbers 1 through 4. The `type` function confirms that it's indeed a tuple.
- The second example, `b`, demonstrates the need for a comma even when creating a tuple with a single element. Without the comma, Python interprets it as a different data type.
- The third example, `c`, is a tuple with two elements.
- The fourth example, `d`, is an empty tuple.
### Creating Tuples with the range Keyword
Tuples can also be created using the `range` keyword:
```python
a = tuple(range(10))
print(type(a)) # Output: <class 'tuple'>
print(a) # Output: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
```
#### Explanation
In this example, `a` is a tuple created using the `tuple` constructor with the `range(10)` function, resulting in a tuple with the numbers 0 through 9.
### Tuples in Functions
Consider the following function that swaps the values of two variables:
```python
def swap(a, b):
return b, a
a, b = swap(2, 3)
```
#### Explanation
In this example, the `swap` function takes two parameters `a` and `b`. Then the function creates and returns a tuple. When the function is called with `swap(2, 3)`, it returns a tuple containing the values of `b` and `a`. This tuple is then unpacked into the variables `a` and `b` on the left side of the assignment statement.
After this line executes, `a` will have the value `3`, and `b` will have the value `2`. This is a powerful and elegant way to swap the values of two variables without needing a temporary variable.
### Partially Immutable Tuples
Consider the following example of a partially immutable tuple:
```python
# Partially Immutable
a = (1, 2, 3, ['a', 'b'])
a[3].append('c')
print(a)
```
### Output
The output of this code will be:
```plaintext
(1, 2, 3, ['a', 'b', 'c'])
```
### Explanation
Tuples themselves are immutable, but the elements within them may be mutable. In this case, the list inside the tuple is mutable. The line `a[3].append('c')` accesses the fourth element of the tuple (which is a list) and appends the string 'c' to it. Even though the tuple is partially immutable, the list inside it can be modified.
---
### Question
What will be the output of the following?
```python
t = (1, 2, 3)
t[0] = 4
print(t)
```
**Choices**
- [ ] (4, 2, 3)
- [ ] (1, 2, 3)
- [x] Error
Tuples in Python are immutable, meaning their elements cannot be modified after creation. In the given code, attempting to assign a new value (`4`) to the first element of the tuple (`t[0]`) will result in an error.
---
### Question
What will be the output of the following?
```python
a = 23
t = (a)
print(type(t))
```
**Choices**
- [ ] tuple
- [ ] list
- [ ] str
- [x] int
The code assigns the value 23 to the variable 'a' and then creates a tuple 't' with a single element, which is the value of 'a'. When the type of 't' is printed, it will output 'int' because the tuple contains only one integer element.
---
### Question
What will be the output of the following?
```python
t = (10, 20, 30, 40)
print(t[1:-1])
```
**Choices**
- [ ] 10, 20, 30
- [ ] Nothing
- [ ] 20, 30, 40
- [x] 20, 30
The slice `t[1:-1]` extracts elements from index 1 to one position before the last index (-1) in the tuple `t`, resulting in the elements 20 and 30 being printed.
---
## Strings in Python
## Strings
### String Literals
Strings in Python can be created using single quotes (`'`) or double quotes (`"`). Both forms are equivalent, and you can choose the one that suits your preference. Here's an example:
```python
a = "abc"
b = 'abc'
print(type(a))
print(type(b))
```
### Output
```plaintext
<class 'str'>
<class 'str'>
```
### Explanation
In this example, both `a` and `b` are strings with the content "abc." The `type` function confirms that they are indeed string objects. Python treats single and double quotes as equivalent for defining strings.
### ASCII and Related Functions
ASCII (American Standard Code for Information Interchange) is a character encoding standard that represents each character with a unique number. Python provides `ord` and `chr` functions to work with ASCII values.
```python
print(ord('A'))
print(ord('0'))
print(ord('9'))
print(chr(129))
```
### Output
```plaintext
65
48
57
ü
```
### Explanation
- `ord('A')` returns the ASCII value of the character 'A', which is 65.
- `ord('0')` returns the ASCII value of the digit '0', which is 48.
- `ord('9')` returns the ASCII value of the digit '9', which is 57.
- `chr(129)` returns the character corresponding to the ASCII value 129, which is 'ü'.
These functions are useful for working with character encodings and converting between characters and their ASCII representations. Keep in mind that ASCII values are integers representing characters in the ASCII table.
### Properties of Strings
Strings in Python possess several important properties, including mutability, homogeneity, iterability, and case sensitivity.
```python
# Variable
a = 'Scaler Academy'
```
### Mutability
Strings in Python are **immutable**, meaning their values cannot be changed after creation.
```python
# Attempt to modify a character in the string
a[0] = 's'
```
#### Output
```plaintext
TypeError: 'str' object does not support item assignment
```
#### Explanation
The attempt to modify the first character of the string `a` raises a `TypeError`. This demonstrates the immutability of strings.
### Homogeneity
Strings are **homogeneous**, meaning they can only contain characters of the same type.
```python
# Concatenating string and integer
result = a + 42
```
#### Output
```plaintext
TypeError: can only concatenate str (not "int") to str
```
#### Explanation
Attempting to concatenate a string (`a`) with an integer (`42`) raises a `TypeError`, emphasizing the homogeneity requirement of strings.
### Iterability
Strings are **iterable**, allowing you to loop through each character.
```python
# Iterating through each character
for char in a:
print(char)
```
#### Output
```plaintext
S
c
a
l
e
r
A
c
a
d
e
m
y
```
#### Explanation
The `for` loop iterates through each character in the string `a`, printing them one by one.
### Case Sensitivity
Strings are **case-sensitive**, distinguishing between uppercase and lowercase characters.
```python
# Comparing strings
b = 'scaler academy'
print(a == b)
```
#### Output
```plaintext
False
```
#### Explanation
The comparison between `a` and `b` returns `False` because of case sensitivity. The uppercase 'S' in `a` is not equal to the lowercase 's' in `b`.
---
### Question
Which one of the following is a valid string?
**Choices**
- [ ] "ScaLer#'
- [ ] %adfa"
- [x] "^&abc#"
- [ ] 'academy'
The correct answer is "^&abc#". This is a valid string because it is enclosed in double quotation marks, and its contents consist of a combination of letters, numbers, and symbols.
---
### Question
What will be the output of the following?
```python
print(ord('c'))
```
**Choices**
- [ ] 98
- [x] 99
- [ ] 100
- [ ] 101
The correct answer is 99. The `ord` function in Python returns the Unicode code point of a given character. In this case, it prints the Unicode code point of the character 'c', which is 99.
---
### Question
What will be the output of the following?
```python
print(chr(70))
```
**Choices**
- [ ] C
- [ ] E
- [x] F
- [ ] G
The `chr()` function in Python returns a string representing a character whose Unicode code point is the integer passed to it. In this case, `chr(70)` returns the character with Unicode code point 70, which is 'F'.
---
### Question
What will be the output of the following?
```python
s = 'Scaler Academy'
print(s[0:5])
```
**Choices**
- [ ] Sae
- [ ] Scaler
- [x] Scale
- [ ] cale
The code `s[0:5]` extracts the substring from index 0 to 4 (5 exclusive) from the string 'Scaler Academy', resulting in the output 'Scale'.
---
### Question
What will be the output of the following?
```python
a = '1'
b = '2'
c = a + b
print(c)
```
**Choices**
- [ ] 3
- [ ] '3'
- [x] 12
- [ ] 1 2
The correct answer is: 12
In Python, when you use the `+` operator with two strings, it concatenates them. So, `a + b` where `a` is '1' and `b` is '2' results in the string '12', and that is what will be printed.
---
### Question
What will be the output of the following?
```python
a = 'abcd'
a += 'e'
print(len(a))
```
**Choices**
- [ ] 3
- [ ] 4
- [x] 5
- [ ] 6
The code initializes a string variable 'a' with the value 'abcd', then concatenates 'e' to it using the `+=` operator. Finally, it prints the length of the modified string 'a', which is now 'abcde'. The length of 'abcde' is 5, so the output is 5.
---
## Functions in Strings
### capitalize()
The `capitalize()` method in Python is used to capitalize the first letter of a string.
```python
# Example
'john doe'.capitalize()
```
### Output
```plaintext
'John doe'
```
### Explanation
In this example, the `capitalize()` function capitalizes the first letter of the string, transforming 'john doe' into 'John doe'.
### title()
The `title()` method capitalizes the first letter of each word in a string.
```python
# Example
'sneha sudam'.title()
```
### Output
```plaintext
'Sneha Sudam'
```
### Explanation
The `title()` function capitalizes the first letter of each word in the string, resulting in 'Sneha Sudam'.
### count(substring)
The `count(substring)` method counts the occurrences of a substring in the string.
```python
# Example
'pooja nikam'.count('ni')
```
### Output
```plaintext
2
```
### Explanation
The `count()` function counts the occurrences of the substring 'ni' in the string, returning the value `2`.
### replace(old, new)
The `replace(old, new)` method replaces occurrences of the old substring with the new substring.
```python
# Example
'Vicky Sharma'.replace('a', 'e')
```
### Output
```plaintext
'Vicky Sherme'
```
### Explanation
The `replace()` function replaces occurrences of 'a' with 'e' in the string, resulting in 'Vicky Sherme'.
### replace(old, new, count)
The `replace(old, new, count)` method replaces a specified number of occurrences of the old substring with the new substring.
```python
# Example
'Vicky Sharma'.replace('a', 'e', 1)
```
### Output
```plaintext
'Vicky Sherma'
```
### Explanation
In this example, only the first occurrence of 'a' is replaced with 'e' in the string, resulting in 'Vicky Sherma'.
### split(separator)
The `split(separator)` method splits a string into a list of substrings based on the specified separator.
```python
# Example
a = 'Aakar, Saurav, Kusum'
print(a.split(','))
```
### Output
```plaintext
['Aakar', ' Saurav', ' Kusum']
```
### Explanation
The `split()` function divides the string into a list of substrings based on the specified separator (`,` in this case), resulting in `['Aakar', ' Saurav', ' Kusum']`.
```python
# Example
a = 'There——are—-many-—places——to——visit.'
print(a.split('——'))
```
### Output
```plaintext
['There', 'are', 'many', 'places', 'to', 'visit.']
```
### Explanation
The `split()` function divides the string using the specified separator (`'——'` in this case), resulting in `['There', 'are', 'many', 'places', 'to', 'visit.']`.
### Print ASCII Letter
This example takes user input and prints the ASCII values of each letter in the input string.
```python
# Example
s = input()
for char in s:
print(ord(char), end=' ')
```
### Output (for input 'hello')
```plaintext
104 101 108 108 111
```
### Explanation
The `ord()` function is used to get the ASCII value of each character in the input string. The `end=' '` parameter ensures that the values are printed with a space in between.
### Formatted Strings
Formatted strings in Python provide a convenient way to embed variable values or expressions into a string, making it more readable and flexible.
```python
# Example
name = 'Aakar'
gender = 'Mate'
age = 25
print('Name:—', name, 'gender:—', gender, 'age:—', age)
```
### Output
```plaintext
Name:— Aakar gender:— Mate age:— 25
```
### Explanation
In this example, a formatted string is created using the variables `name`, `gender`, and `age`, resulting in the output `Name:— Aakar gender:— Mate age:— 25`.
There are several ways to achieve string formatting in Python, but one commonly used method involves the `format()` method.
```python
# Example
template = 'Name:— {}, gender:— {}, age:— {}'
print(template.format(name, gender, age))
```
### Output
```plaintext
Name:— Aakar, gender:— Mate, age:— 25
```
### Explanation
The `format()` method is used to insert the values of `name`, `gender`, and `age` into the string template, resulting in the formatted output `Name:— Aakar, gender:— Mate, age:— 25`.
```python
# Example
template = 'Name:— {0}, gender:— {1}, age:— {2}'
print(template.format(name, gender, age))
```
### Output
```plaintext
Name:— Aakar, gender:— Mate, age:— 25
```
### Explanation
In this example, positional placeholders `{0}`, `{1}`, and `{2}` are used in the template to indicate the positions of `name`, `gender`, and `age` in the `format()` method. The output is the same as the previous example.
---
### Question
What will be the output of the following?
```python
a = 'Scaler Academy'
print(a.count('a'))
```
**Choices**
- [x] 2
- [ ] 3
- [ ] 4
- [ ] 0
The output of the given Python code will be 2. This is because the `count()` method is used to count the number of occurrences of a specified substring (in this case, the letter 'a') within the given string 'Scaler Academy'.
---
### Question
What will be the output of the following?
```python
a = 'i-am-awesome'
b = a.split('-')
print(len(b))
```
**Choices**
- [ ] 2
- [x] 3
- [ ] 4
- [ ] 5
The correct answer is 3. The code splits the string 'i-am-awesome' at each occurrence of the hyphen ('-') and creates a list `b` with three elements: ['i', 'am', 'awesome']. The `len(b)` then outputs 3, indicating the number of elements in the list.