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

Python Code Solutions for Common Tasks

The document contains a series of Python programming exercises and their solutions, including checking for prime numbers, calculating factorials, reversing strings, summing digits, sorting lists, and finding the greatest number among three inputs. Each exercise is accompanied by code snippets and their respective outputs. The solutions demonstrate various programming concepts such as loops, conditionals, and list operations.

Uploaded by

Ishan Dipte
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views4 pages

Python Code Solutions for Common Tasks

The document contains a series of Python programming exercises and their solutions, including checking for prime numbers, calculating factorials, reversing strings, summing digits, sorting lists, and finding the greatest number among three inputs. Each exercise is accompanied by code snippets and their respective outputs. The solutions demonstrate various programming concepts such as loops, conditionals, and list operations.

Uploaded by

Ishan Dipte
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 3 Question bank code solutions

In [8]: # Write a python program to check if a given number is prime or not in the r
for i in range(5,30):
if i == 5:
print(i, "is a prime number")
elif i % 2 == 0:
print(i, "is not a prime number")
elif i % 3 == 0:
print(i, "is not a prime number")
elif i % 5 == 0:
print(i, "is not a prime number")
else:
print(i, "is a prime number")

5 is a prime number
6 is not a prime number
7 is a prime number
8 is not a prime number
9 is not a prime number
10 is not a prime number
11 is a prime number
12 is not a prime number
13 is a prime number
14 is not a prime number
15 is not a prime number
16 is not a prime number
17 is a prime number
18 is not a prime number
19 is a prime number
20 is not a prime number
21 is not a prime number
22 is not a prime number
23 is a prime number
24 is not a prime number
25 is not a prime number
26 is not a prime number
27 is not a prime number
28 is not a prime number
29 is a prime number

In [10]: # Write a program to find the factorial of a number 6 using a “for” loop.
num = 6
fact = 1 # initialzed fact varialbe with 1 value
for i in range(1,num+1):
# compound multiplication to find a factorial of a number (6) fact = 1*2*3*4
fact *= i
print(f"The factorial of {num} is {fact}")

The factorial of 6 is 720

In [18]: # 14. Write a program to reverse a string “i am a student” using a while l


string = "i am a student"
l = []
b = len(string)-1
while b >= 0:
[Link](string[b])
b -= 1
rev_string=''.join(l)
print(rev_string)

tneduts a ma i

In [19]: # 15. Write a program to calculate the sum of digits of a number 67535.
num = 67535
string = str(num)
sum = 0
for i in string: # "67535"
sum += int(i) # 6 + 7 + 5 + 3 + 5
print(f"The sum of digits of a number {num} is {sum}")

The sum of digits of a number 67535 is 26

In [27]: # 16. Write a program to sort a list of numbers in ascending order and ide
l = [6,3,9,2,1,5]
[Link]() # sort()method will sort (in place) the list in assending order
print(l)
print(f"Smallest number is {min(l)}") # min() method will find smallest num
print(f"The largest number is {max(l)}") # max() method will find largest n

[1, 2, 3, 5, 6, 9]
Smallest number is 1
The largest number is 9

In [28]: # 17. Write a program to print a pattern of stars in the shape of a right-
for i in range(6):
print(i*"* ")

*
* *
* * *
* * * *
* * * * *

In [31]: # 18. Write a program to find sum of first 20 even no using “for” loop
num = 20
sum = 0
for i in range(num+1):
if i % 2 == 0:
sum += i # 2+4+6+8+10+12+14+16+18+20
print(f"The sum of first 20 even numbers is {sum}")

The sum of first 20 even numbers is 110

In [33]: # 19. Write a program to find sum of first 20 even no using “while” loop
num = 20
sum = 0
b = 1
while b <= num:
if b % 2 == 0:
sum += b
b += 1
print(f"The sum of first 20 even numbers is {sum}")

The sum of first 20 even numbers is 110

In [37]: # 20. Write a program to find sum of square of first 20 even no using “for
num = 20
sum = 0
for i in range(num+1):
if i % 2 == 0:
sum += (i*i) # 4+16+36+64+100+144+196+256+324+400
print(f"The sum of first 20 even numbers is {sum}")

The sum of first 20 even numbers is 1540

In [42]: # 21. Write a program to find sum of square of first 20 even no using “whi
num = 20
sum = 0
b = 1
while b <= num:
if b % 2 == 0:
sum += (b*b)
b += 1
print(f"The sum of first 20 even numbers is {sum}")

The sum of first 20 even numbers is 1540

In [44]: # 22. Write a program to read a number from user and display greatest of t
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
if num1 > num2 and num1 > num3:
print(f"Greatest number is {num1}")
elif num2 > num1 and num2 > num3:
print(f"Greatest number is {num2}")
else:
print(f"Greatest number is {num3}")

Enter first number: 7


Enter second number: 4
Enter third number: 2
Greatest number is 7

In [46]: # 23. Write a program to print the sum of number 1 to 10 using while loop
sum = 0
b = 1
while b <= 10:
sum += b
b += 1
print("The sum of number 1 to 10 is ", sum)

The sum of number 1 to 10 is 55


In [47]: # 24. Write a program to print the sum of number 1 to 10 using for loop
sum = 0
for i in range(1,11):
sum += i
print("The sum of number 1 to 10 is ", sum)

The sum of number 1 to 10 is 55

In [ ]:

In [ ]:

This notebook was converted with [Link]

Common questions

Powered by AI

Algorithmic design significantly impacts the performance of finding the sum of digits, particularly through choice of methods. The Source 1 example converts a number to a string and iterates through each character to sum digits, which is straightforward but can be computationally intensive for large numbers. Optimization techniques could include direct mathematical operations without type conversion or using logarithmic identities to minimize operations, enhancing speed and reducing computational load .

Sorting algorithms like the sort() method used in Source 1 improve data efficiency by ensuring that subsequent operations, such as searching or aggregations, operate on orderly data. Simple sorting methods, while easy to implement and understand, may exhibit high time complexity (O(n^2) in some cases) on unsorted or sorted data, leading to inefficiency with large datasets. Additionally, simple methods are less adaptive to nearly sorted sequences compared to more advanced algorithms like quicksort or mergesort .

Identifying prime numbers within a range can be done algorithmically by checking divisibility of numbers greater than 2 by any number less than its square root. The algorithm from Source 1 uses trial division up to certain initial conditions (like not being divisible by 2, 3, or 5) within the range 5-30. Its strengths lie in simplicity and applicability to small ranges. However, it becomes inefficient for larger numbers because the number of divisions increases significantly as you check higher ranges .

Using nested loops to generate patterns allows for concise and repetitive structure creation, such as a right-angled triangle with stars, as demonstrated in Source 1. The primary advantage is the ability to easily modify the pattern's dimensions by changing loop parameters. However, nested loops can lead to high time complexity and increased computational overhead, particularly when the size of the pattern grows, potentially leading to performance bottlenecks on systems with limited resources .

String manipulation methods like using a while loop with an auxiliary list, as shown in Source 1, can reverse a string by iteratively appending characters in reverse order. This method increases memory usage because it requires additional storage for the list and concatenation operations. Alternatively, in-place reversal or slicing can be used, which offers better memory efficiency by avoiding data duplication and excessive memory allocation .

Iterative constructs such as 'for' loops are crucial in factorial calculations as they handle repetitive multiplication efficiently by updating the result cumulatively, thus reducing the chance for stack overflow compared to recursion. This approach becomes more efficient, especially for languages that limit recursion depth or for environments with limited memory but can be slightly slower due to overhead in loop management .

Calculating the sum of a series can leverage both 'for' and 'while' loops to iterate over elements, achieving similar outcomes with variations in control flow. For loops are typically more concise and offer integrated iteration control, making them efficient for clear index progression as seen with the summation of the first 20 even numbers. While loops provide more flexibility for complex conditions but can be prone to errors if loop control is not meticulously handled. Ultimately, the efficiency largely depends on the complexity of conditions within the loop and loop overhead management .

Choice of computational model affects square sum calculations by influencing execution efficiency and resource utilization, with iterative loops as seen in calculating sums of squares using 'for' or 'while' loops offering straightforward implementation and control. However, these may suffer from increased iteration overhead for large limits. Algorithmic design needs to balance execution time with precision and memory constraints, possibly employing memoization or divide-and-conquer strategies to optimize recursive or parallel computational models for large-scale applications .

Conditional logic is essential for determining the greatest of three numbers by leveraging logical operators to establish relational checks between the numbers, thus guiding the flow of the decision-making process. Ensuring correctness involves covering all possible comparisons, such as handling ties and ensuring conditions do not allow for skipping any potential greater number. Efficient conditional logic also considers syntactical correctness and redundancy elimination to optimize performance and accuracy .

Both iterative and recursive approaches aim to accumulate values to get a sum. The iterative approach uses loops, as in summing numbers 1 to 10, which handle large datasets more efficiently by using a consistent memory footprint. Recursive methods call a function repeatedly, which can lead to stack overflow and increased memory usage but can offer simpler conceptual solutions for certain mathematical constructs. While iterative methods are generally faster and more memory-efficient, recursion provides elegance and simplicity in implementation for cases like Fibonacci sequences or tree traversals .

You might also like