Day1-Day10 Python practice questions
Index: Click to Navigate:
Day 1
Question 1:
Write a Python program to find the sum of two numbers entered by the user. However, here's the twist:
- If either number is negative, multiply it by -1 before adding.
- If both numbers are even, double their sum.
- If both numbers are odd, halve their sum.
Day 2
Question 2:
How XOR Works (Bitwise Explanation)
The XOR (exclusive OR) operation compares each bit of two numbers and follows these rules:
-
If both bits are the same, the result
is
0
. -
If the bits are different, the result
is
1
.
Here’s a simple way to visualize XOR:
Truth Table for XOR
Bit A | Bit B | A ^ B (Result) |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
Example with Numbers:
Let’s take two numbers: num1 = 5
(binary: 0101
)
and num2 = 3
(binary: 0011
).
We’ll perform the XOR operation on each corresponding bit:
num1 = 0101
num2 = 0011
----------------
result = 0110
Explanation:
-
The first bit (from the right) is
1
innum1
and1
innum2
, so the result is0
. -
The second bit is
0
innum1
and1
innum2
, so the result is1
. -
The third bit is
1
innum1
and0
innum2
, so the result is1
. -
The fourth bit is
0
innum1
and0
innum2
, so the result is0
.
Thus, the XOR of 5
and 3
gives 6
(0110
in binary).
Visualizing the XOR Swap
Let’s break down the XOR swap process using an example.
Assume:
-
num1 = 5
(binary:0101
) -
num2 = 3
(binary:0011
)
Step 1: num1 = num1 ^ num2
-
num1 = 0101 ^ 0011 = 0110
(Nownum1 = 6
)
Step 2: num2 = num1 ^ num2
-
num2 = 0110 ^ 0011 = 0101
(Nownum2 = 5
, originalnum1
value)
Step 3: num1 = num1 ^ num2
-
num1 = 0110 ^ 0101 = 0011
(Nownum1 = 3
, originalnum2
value)
Final Result:
-
num1 = 3
-
num2 = 5
The two numbers have been swapped using XOR!
Day 3
Question 3:
Check if a Number is an Armstrong Number Using Generator Expression
An Armstrong number is a number that is equal to the sum of its own digits, each raised to the power of the total number of digits.
For example:
What is a Generator Expression?
A generator expression is a concise way to create a series of values to iterate over, without storing them in memory. Unlike lists, which hold all values in memory, generator expressions calculate each value only when needed, making them more efficient for large datasets.
Solution:
# Input from the user
num = input("Enter a number to check if it's an Armstrong number: ")
# Calculate the number of digits
num_digits = len(num)
# Use generator expression to compute the Armstrong sum
armstrong_sum = sum(int(digit) ** num_digits for digit in num)
# Compare the sum with the original number
if armstrong_sum == int(num):
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is NOT an Armstrong number.")
Explanation:
1. Take User Input
num = input("Enter a number to check if it's an
Armstrong number: ")
- The user is prompted to input a number.
- The input is treated as a string to make it easy to iterate over the digits later.
2. Calculate the Number of Digits
num_digits = len(num)
-
len(num)
calculates the number of digits in the input number (as a string).
3. Compute the Armstrong Sum
armstrong_sum = sum(int(digit) ** num_digits for digit in num)
-
This uses a generator expression inside
the
sum()
function:-
for digit in num
: Iterates over each digit of the number (as a string). -
int(digit)
: Converts the string digit back to an integer. -
int(digit) ** num_digits
: Raises the digit to the power ofnum_digits
. -
sum(...)
: Adds up these values to compute the Armstrong sum.
-
4. Compare the Armstrong Sum with the Original Number
if armstrong_sum == int(num):
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is NOT an Armstrong number.")
-
The Armstrong sum (
armstrong_sum
) is compared to the original number (converted back to an integer usingint(num)
). - If they are equal, the number is an Armstrong number. Otherwise, it is not.
How It Works (Example Walkthrough)
Let’s say the user inputs 153
:
-
Input and Digits Count
-
num = "153"
-
num_digits = len(num) = 3
-
-
Compute Armstrong Sum
-
armstrong_sum = sum(int(digit) ** 3 for digit in "153")
-
Step-by-step:
-
For
digit = "1"
: -
For
digit = "5"
: -
For
digit = "3"
:
-
For
-
armstrong_sum = 1 + 125 + 27 = 153
-
-
Compare and Output
-
armstrong_sum == int(num)
:- : True
-
Output:
153 is an Armstrong number.
-
Edge Cases
- Single-digit numbers: Every single-digit number is an Armstrong number because .
- Large numbers: The code works for large numbers but may slow down if the number of digits is very high because of the power operation.
----------------------------------------------------------------------------------------------------------
Day 4
Question 4:
write a python porgram to check if all characters in a given string are unique without using built-in functions and solve this using functions.
Solution:
Explanation:
This implementation of checking if all characters in a string are unique uses a brute force approach, where each character is compared with every other character in the string.
-
Outer Loop:
-
The outer loop iterates through each
character in the string by its
index
i
. -
For example, if the string is
"hello"
, the outer loop starts with the first character'h'
(index0
).
-
The outer loop iterates through each
character in the string by its
index
-
Inner Loop:
-
The inner loop starts from the next
character (index
i + 1
) and iterates through the remaining characters of the string. - For each character in the outer loop, the inner loop compares it with all subsequent characters.
-
For instance, when the outer loop is
at
'h'
(index0
), the inner loop compares'h'
with'e'
,'l'
,'l'
, and'o'
.
-
The inner loop starts from the next
character (index
-
Comparison:
-
In each iteration of the inner loop, the two
characters (from indices
i
andj
) are compared. -
If a match is found (
string[i] == string[j]
), the function immediately returnsFalse
, indicating that the string has duplicate characters.
-
In each iteration of the inner loop, the two
characters (from indices
-
No Duplicates:
-
If no duplicates are found after all
comparisons, the function returns
True
.
-
If no duplicates are found after all
comparisons, the function returns
Code Walkthrough:
Input:
Enter a string: hello
-
Outer loop starts with
i = 0
(string[i] = 'h'
):-
Inner loop starts with
j = 1
(string[j] = 'e'
):'h' != 'e'
, continue. -
j = 2
(string[j] = 'l'
):'h' != 'l'
, continue. -
j = 3
(string[j] = 'l'
):'h' != 'l'
, continue. -
j = 4
(string[j] = 'o'
):'h' != 'o'
, continue.
-
Inner loop starts with
-
Outer loop moves to
i = 1
(string[i] = 'e'
):-
Inner loop starts with
j = 2
(string[j] = 'l'
):'e' != 'l'
, continue. -
j = 3
(string[j] = 'l'
):'e' != 'l'
, continue. -
j = 4
(string[j] = 'o'
):'e' != 'o'
, continue.
-
Inner loop starts with
-
Outer loop moves to
i = 2
(string[i] = 'l'
):-
Inner loop starts with
j = 3
(string[j] = 'l'
):'l' == 'l'
, return False.
-
Inner loop starts with
Output:
The string contains duplicate characters.
Note:
This solution is helpful for beginners to understand nested loops
and how comparisons work between indices.
---------------------------------------------------------------------------------
Day 5
Question 5:
custom_zip
that
mimics Python's
built-in zip()
. It should take
multiple iterables, combine their elements by
index into tuples, and stop when the shortest
iterable is exhausted.
Solution:
Function Definition: custom_zip(*iterables)
-
*iterables
:-
The
*
beforeiterables
allows the function to accept any number of input iterables (such as lists, tuples, etc.). - For example, you can pass two lists, three lists, or even more, and the function will work with them all.
-
The
Step 1: Find the Length of the Shortest Iterable
min_length = min(len(it) for it in iterables)
-
Here,
min()
is used to find the length of the shortest iterable. -
len(it)
calculates the length of each iterable (it
stands for each individual iterable passed). -
min()
takes the smallest length, so the loop will stop when the shortest iterable is exhausted. This ensures that the function doesn't try to access elements that don't exist in shorter iterables.
For example, if you have:
-
list1 = [1, 2, 3]
(length = 3) -
list2 = ['a', 'b', 'c']
(length = 3) -
list3 = [True, False]
(length = 2)
The min_length
will be 2 because list3
is the shortest iterable.
Step 2: Initialize an Empty Result List
result = []
-
We create an empty list
result
that will store the final result — the list of tuples. - Each tuple will contain elements from each iterable, grouped by their corresponding indices.
Step 3: Loop Through the Indices of the Shortest Iterable
for i in range(min_length):
-
The
for
loop iterates from0
tomin_length - 1
. In this case, the loop runs 2 times becausemin_length
is 2 (from the previous step). -
The variable
i
represents the index in the iterables.
Step 4: Create a Tuple from Each Iterable
result.append(tuple(it[i] for it in iterables))
-
Inside the loop, we use a generator
expression (
(it[i] for it in iterables)
) to extract thei-th
element from each iterable. -
The
tuple()
function takes these elements and combines them into a tuple. -
This tuple is then appended to
the
result
list.
For each iteration:
-
On the first iteration (
i = 0
), we pick the first element from each iterable:1
fromlist1
,'a'
fromlist2
, andTrue
fromlist3
, creating the tuple(1, 'a', True)
. -
On the second iteration (
i = 1
), we pick the second element:2
fromlist1
,'b'
fromlist2
, andFalse
fromlist3
, creating the tuple(2, 'b', False)
.
Step 5: Return the Final Result
return result
-
After the loop finishes, the function
returns the
result
list, which contains all the tuples formed from the input iterables.
Example Execution:
Input:
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [True, False]
Execution Steps:
-
The length of the shortest iterable (
list3
) is2
. So, the loop will run two times. -
The first iteration will create the
tuple
(1, 'a', True)
. -
The second iteration will create the
tuple
(2, 'b', False)
. -
After the loop finishes, the
result
list is[(1, 'a', True), (2, 'b', False)]
.
Output:
[(1, 'a', True), (2, 'b', False)]
-----------------------------------------------------------------------------------------------
Day 6
Question 6:
Write a function that takes a number n as input and generates the first n prime numbers. The function should return a list containing these primes.
Tip: To check if a number is prime, use the fact that you only need to check for divisibility up to the square root of that number.
Solution:
Explanation:
def primes(n = 100):
This function generates the
first n
prime numbers. By
default, it generates 100
prime numbers unless a
different value
for n
is provided.
Initialize an Empty List:
prime_list = []
This list will store the prime numbers as they are found.
Start with the First Prime Number:
start = 2
The variable start
begins at 2 because 2
is the smallest prime
number.
While Loop:
while len(prime_list) < n:
The loop continues until
the list prime_list
contains n
prime numbers.
Check if start
is Prime:
is_prime = True
for i in range(2, int(start**0.5) + 1):
if start % i == 0:
is_prime = False
break
-
is_prime = True
: Assumestart
is a prime number initially. -
The
for
loop checks divisibility ofstart
by numbers from2
toint(start**0.5) + 1
. -
Why
int(start**0.5) + 1
?-
If a
number
start
has a divisor, one of its divisors will always be less than or equal to its square root. -
For example,
for
36
, the divisors are(1, 36), (2, 18), (3, 12), (4, 9), (6, 6)
. Beyond 6, divisors repeat as pairs. - This reduces the number of checks significantly, making the algorithm faster.
-
If a
number
-
If
start % i == 0
, the number is not prime (is_prime = False
), and the loop exits early withbreak
.
Add Prime Numbers to the List:
if is_prime:
prime_list.append(start)
If start
is still marked as
prime, it is added
to prime_list
.
Move to the Next Number:
start += 1
Increment start
to check the next
number.
Return the List of Primes:
return prime_list
Why Use Square Root Optimization?
Without Square Root:
-
The inner loop would
check all numbers
from
2
tostart - 1
. -
If we were generating
prime numbers for a large
value like
n = 100,000
, the number of iterations grows significantly asstart
increases. For example:-
For
start = 1,000,000
, it would require ~1,000,000 checks for divisors, making the algorithm slow.
-
For
With Square Root:
-
Instead of checking up
to
start - 1
, we only check up tosqrt(start)
. -
Example:
-
For
start = 1,000,000
, the maximum divisor to check issqrt(1,000,000) = 1,000
. This reduces the number of checks by almost 1,000 times for large numbers.
-
For
Performance Difference: Example with Large Numbers
Without Square Root:
-
Generating primes
for
n = 100,000
could take hours as every number is checked for divisibility up tostart - 1
.
With Square Root:
-
Using
sqrt(start)
optimization reduces the time dramatically, making it feasible to generate primes up ton = 100,000
in minutes or seconds, depending on the implementation.
This is why using the square root is essential for efficient prime number generation.
-------------------------------------------------------------------------------------------------------------
Day-7
Question7:
Write a function swap_case that takes a string as input and swaps the case of each letter. For example:
"pYtHoN bUzZ" should become "PyThOn BuZz".
Note: You should not use Python's built-in swapcase() function. Instead, implement the case swap manually using conditional statements.
Solution:
def manual_swapcase(s):
result = ""
for char in s:
if 'a' <= char <= 'z': # If lowercase, convert to uppercase
result += chr(ord(char) - 32)
elif 'A' <= char <= 'Z': # If uppercase, convert to lowercase
result += chr(ord(char) + 32)
else:
result += char # Keep non-alphabetic characters unchanged
return result
input_string = "pYtHoN bUzZ"
output_string = manual_swapcase(input_string)
print(output_string)
Step 1: Understanding the Problem
We want to change:
- Lowercase letters (
a-z
) to uppercase (A-Z
) - Uppercase letters (
A-Z
) to lowercase (a-z
) - Numbers and special characters should remain unchanged
Example
Input: "pYtHoN bUzZ23"
Expected Output: "PyThOn BuZz23"
Step 2: Breaking Down the Code
Function Definition
def manual_swapcase(s):
result = ""
s
is the input string (e.g.,"pYtHoN bUzZ23"
).result
is an empty string (""
) that will store the final modified output.
Loop Through Each Character
for char in s:
- This loop goes one character at a time through the input string.
Checking If a Character is Lowercase (a-z
)
if 'a' <= char <= 'z': # If lowercase, convert to uppercase
result += chr(ord(char) - 32)
'a' <= char <= 'z'
checks if the character is a lowercase letter.- If it is, we convert it to uppercase using:
chr(ord(char) - 32)
ord(char)
: Converts the letter to its ASCII code.- Subtracting
32
from this shifts it to uppercase. chr(...)
: Converts it back to a character.
Character | ASCII (ord() ) |
Convert (-32 ) |
New ASCII | New Character |
---|---|---|---|---|
'p' |
112 | 112 - 32 = 80 |
80 | 'P' |
'y' |
121 | 121 - 32 = 89 |
89 | 'Y' |
Checking If a Character is Uppercase (A-Z
)
elif 'A' <= char <= 'Z': # If uppercase, convert to lowercase
result += chr(ord(char) + 32)
'A' <= char <= 'Z'
checks if the character is an uppercase letter.- If it is, we convert it to lowercase using:
chr(ord(char) + 32)
ord(char)
: Converts the letter to its ASCII code.- Adding
32
shifts it to lowercase. chr(...)
: Converts it back to a character.
Character | ASCII (ord() ) |
Convert (+32 ) |
New ASCII | New Character |
---|---|---|---|---|
'Y' |
89 | 89 + 32 = 121 |
121 | 'y' |
'H' |
72 | 72 + 32 = 104 |
104 | 'h' |
Keeping Non-Alphabetic Characters Unchanged
else:
result += char # Keep non-alphabetic characters unchanged
- If the character is not a letter (like space, numbers, or special characters), we simply add it to
result
without modification.
Returning the Final String
return result
- After processing all characters, we return the final modified string.
Step 3: Running the Function
input_string = "pYtHoN bUzZ23"
output_string = manual_swapcase(input_string)
print(output_string)
- We pass
"pYtHoN bUzZ23"
as input. - The function converts the case of each letter.
- The result is stored in
output_string
and printed.
Step 4: Understanding the Output
Character-by-Character Transformation
Input->converted | |
---|---|
p → P |
|
Y → y |
|
t → T |
|
H → h |
|
o → O |
|
N → n |
|
(space) → stays the same |
|
b → B |
|
U → u |
|
z → Z |
|
Z → z |
|
2 → stays the same |
|
3 → stays the same |
Final Output
PyThOn BuZz23
--------------------------------------------------------------------------------
Day-8
Question8:
Write a function that moves all the 0s in a list to the end, and sorts the remaining non-zero numbers in ascending order.
Example:
input : [0, 4,1, 0, 3, 6]
output: [1, 3, 4,6, 0, 0]
Solution:
def move_zeros_and_sort(nums):
# Extract and sort non-zero numbers
non_zero_sorted = sorted([num for num in nums if num != 0])
# Create a list of zeros
zeros = [0] * nums.count(0)
# Concatenate sorted non-zero numbers with zeros
return non_zero_sorted + zeros
input_list = [0, 4, 1, 0, 3, 6]
output_list = move_zeros_and_sort(input_list)
print(output_list)
Explanation:
def move_zeros_and_sort(nums):
- This defines a function named
move_zeros_and_sort
, which takes a list of numbers (nums
) as input.
Step 1: Extract and Sort Non-Zero Numbers
non_zero_sorted = sorted([num for num in nums if num != 0])
- List comprehension is used to extract all numbers from
nums
that are not zero (!= 0
).- For example, if
nums = [0, 4, 1, 0, 3, 6]
, then[num for num in nums if num != 0]
will give[4, 1, 3, 6]
.
- For example, if
sorted()
is used to sort these numbers in ascending order.sorted([4, 1, 3, 6])
gives[1, 3, 4, 6]
.
- Now,
non_zero_sorted = [1, 3, 4, 6]
.
Step 2: Count Zeros and Create a List of Zeros
zeros = [0] * nums.count(0)
nums.count(0)
counts how many zeros are in the list.- In
[0, 4, 1, 0, 3, 6]
, there are 2 zeros.
- In
[0] * 2
creates a list containing two zeros:[0, 0]
.- Now,
zeros = [0, 0]
.
Step 3: Combine Sorted Numbers and Zeros
return non_zero_sorted + zeros
- The
+
operator concatenates the two lists:non_zero_sorted = [1, 3, 4, 6]
zeros = [0, 0]
non_zero_sorted + zeros
results in[1, 3, 4, 6, 0, 0]
.
Putting It All Together
input_list = [0, 4, 1, 0, 3, 6]
output_list = move_zeros_and_sort(input_list)
print(output_list)
move_zeros_and_sort([0, 4, 1, 0, 3, 6])
returns[1, 3, 4, 6, 0, 0]
.- The output is printed:
[1, 3, 4, 6, 0, 0]
.
Final Output:
[1, 3, 4, 6, 0, 0]
----------------------------------------------------------------------------
Day -9
1. Generate a List of Random Numbers
from random import randint
li= []
for i in range(100):
li.append(randint(1,20)) # Generate a random number between 1 and 20
print(li)
- This creates a list
li
of 100 random integers ranging from 1 to 20. - The list is printed for reference.
2. Initialize Variables for Tracking the Longest Consecutive Sequence
longest = 1
current_streak = 1
longest
: Stores the length of the longest consecutive sequence found so far.current_streak
: Tracks the length of the current consecutive sequence.
3. Iterate Through the List to Find Consecutive Sequences
for i in range(1, len(li)):
- This loop starts from index
1
(second element) and iterates through the list.
4. Check If the Current Number is Consecutive to the Previous One
if li[i] == li[i - 1] + 1:
current_streak += 1
- If the current number is exactly 1 more than the previous number, it means the sequence is continuing.
- The
current_streak
counter is increased.
5. Reset Streak If Sequence is Broken (Handling Duplicates)
elif li[i] != li[i - 1]: # Skip duplicates
current_streak = 1 # Reset streak for a new sequence
- If the current number is not consecutive and not a duplicate, the sequence is broken.
current_streak
is reset to 1 because a new sequence may start from here.
6. Update the Longest Sequence Found
longest = max(longest, current_streak)
- After each iteration, the program updates
longest
to store the maximum consecutive sequence found so far.
7. Print the Longest Consecutive Sequence Length
print(longest)
- Displays the longest consecutive sequence length found in the list.
- Filter out the strings that have less than 4 characters.
- Convert all remaining strings to uppercase.
- Concatenate the those strings
- Return the final concatenated string.
1. filter
Function:
filtered_strings = filter(lambda x: len(x) >= 4, string_list)
-
What is
filter
?- The
filter
function helps us select certain items from a list based on a condition. - It filters out the items that don't meet the condition.
- The
-
How does it work here?
- We pass the list
string_list
to thefilter
function. - The condition we use is
lambda x: len(x) >= 4
. This means "keep only the strings whose length is greater than or equal to 4." - Example: If the list contains
"hello", "to", "world"
, it will keep"hello"
and"world"
, but remove"to"
because it has fewer than 4 characters.
- We pass the list
2. map
Function:
uppercase_strings = map(lambda x: x.upper(), filtered_strings)
-
What is
map
?- The
map
function allows us to apply a function to each item in a list and change each item according to that function.
- The
-
How does it work here?
- After filtering, we pass the filtered strings to the
map
function. - The function we use is
lambda x: x.upper()
. This means "convert each string to uppercase." - Example: If we had
"hello"
and"world"
, themap
function will change them to"HELLO"
and"WORLD"
.
- After filtering, we pass the filtered strings to the
3. reduce
Function:
concatenated_string = reduce(lambda x, y: x + y, uppercase_strings)
-
What is
reduce
?- The
reduce
function takes two elements at a time and applies a function to them. It continues applying the function to the result and the next item in the list, until only one value remains.
- The
-
How does it work here?
- We use
reduce
to combine all the strings together. - The function
lambda x, y: x + y
says "take two strings and combine them (concatenate) into one." - For example, if we have
"HELLO"
and"WORLD"
,reduce
will first combine"HELLO"
and"WORLD"
into"HELLOWORLD"
, then it will continue if there are more strings to combine. - At the end, you'll get one long string made of all the uppercase words combined together.
- We use
Putting it All Together:
For the input list ["hello", "to", "the", "world", "this", "is", "python"]
, here’s how each step works:
-
Filtering:
- Strings shorter than 4 characters (
"to"
,"the"
,"is"
) are removed. - Remaining list:
["hello", "world", "this", "python"]
.
- Strings shorter than 4 characters (
-
Converting to Uppercase:
- Convert each string to uppercase.
- New list:
["HELLO", "WORLD", "THIS", "PYTHON"]
.
-
Concatenating the Strings:
- Join (concatenate) all the uppercase strings together.
- Final result:
"HELLOWORLDTHISPYTHON"
.
Final Output:
"HELLOWORLDTHISPYTHON"
Summary:
filter
: Removes strings shorter than 4 characters.map
: Converts the remaining strings to uppercase.reduce
: Joins (concatenates) all the strings into one long string.
This is how we transform the list into one string according to the given requirements.
Comments
Post a Comment