0% found this document useful (0 votes)
3 views2 pages

Python Functions for Basic Algorithms

The document outlines five programming tasks for a Python lab. These tasks include creating functions to draw a triangle of hashes, find the greatest of three numbers, calculate a specific series sum, compute the factorial of a number, and check if a word is a palindrome. Each task specifies the expected functionality and provides examples for clarity.

Uploaded by

modyesam25
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)
3 views2 pages

Python Functions for Basic Algorithms

The document outlines five programming tasks for a Python lab. These tasks include creating functions to draw a triangle of hashes, find the greatest of three numbers, calculate a specific series sum, compute the factorial of a number, and check if a word is a palindrome. Each task specifies the expected functionality and provides examples for clarity.

Uploaded by

modyesam25
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

Python Lab (3)

1) Please write a function named triangle, which draws a triangle of


hashes, and takes one argument. The triangle should be as tall and
as wide as the value of the argument.
Some examples:
triangle(6)
triangle(3)

#
##
###
####
#####
######

#
##
###

2) Please write a function named greatest_number, which takes three


arguments. The function returns the greatest in value of the three.
[without using max function, and solve it in two ways]
print(greatest_number(3, 4, 1)) # 4
print(greatest_number(99, -4, 7)) # 99
print(greatest_number(0, 0, 0)) # 0
3) Write a function sum_series(n) that calculates the sum of the
series:
1 - 2 + 3 - 4 + 5 - ... up to n

4) Write a Python function to calculate the factorial of a number (a


non-negative integer). The function accepts the number as an
argument.

5) Implement a function that checks if a given word is a palindrome


(reads the same forwards and backwards)

Common questions

Powered by AI

Ensuring code modularity by writing separate functions for different tasks significantly influences large-scale software development by promoting maintainability, scalability, and ease of testing. Modular design allows developers to isolate functionalities, making it easier to identify, fix, or improve code sections. It enhances reusability, as modular functions can be reused across different parts of an application or in different projects without re-implementation. Modularity simplifies team collaboration by allowing multiple developers to work independently on different modules, thus facilitating parallel development efforts. Additionally, it supports better debugging and testing practices, as individual modules can be unit tested and verified independently before integration into the larger system, reducing overall integration risk and making system updates less prone to errors .

Computational challenges in calculating factorials of large integers include handling substantially large numbers that can cause arithmetic overflow and increased memory consumption due to the size of intermediate results. This becomes particularly acute as factorial calculations grow factorially with respect to input size. In Python, these can be addressed by using its `int` type, which automatically adjusts its size to accommodate large numbers, although this affects performance. Libraries like `math` provide a `factorial` function that is optimized and uses underlying C implementations for efficiency. Alternatively, iterative methods with loops reduce the risk of recursion stack overflow by avoiding the call stack entirely, or using caching/memoization to reduce redundant calculations when factorials are repeatedly required .

Using slicing to determine if a string is a palindrome has several computational advantages over iterative methods or extra data structures. Python's slicing operation is implemented in C, making it faster and more efficient than traversing the string character by character in Python. This reduces the overhead usually associated with loops and conditionals while maintaining clarity and brevity in code. On the other hand, employing iterative methods can increase complexity and the risk of errors, while adding data structures (like stacks or queues) to reverse strings can consume more memory and processing time, reducing efficiency particularly for very long strings .

To calculate the alternating series sum effectively with built-in functions and enhance readability, list comprehensions combined with the sum function can be utilized: ```python def sum_series(n): return sum((-1)**(i+1) * i for i in range(1, n+1)) ``` This implementation uses the list comprehension to create the sequence of terms and `sum` efficiently adds them. The expression `(-1)**(i+1) * i` takes advantage of Python's power operator to alternate signs, improving compactness. This form is highly readable and shows clearly the transformation applied to each integer in the range, embodying Python's higher-order functional programming features for a concise and elegant solution .

To find the greatest number among three numbers without using Python's built-in max function, you can use conditional statements. The first method is by using nested if-else statements: ```python def greatest_number(a, b, c): if a >= b and a >= c: return a elif b >= a and b >= c: return b else: return c ``` The second method could involve sorting the three numbers and returning the last element: ```python def greatest_number(a, b, c): numbers = [a, b, c] numbers.sort() return numbers[-1] ``` Both methods identify the largest number by comparing each element or by sorting and selecting the highest value from the list .

A common approach to calculate the factorial of a non-negative integer in Python is through recursion. Factorial can be defined recursively where the factorial of 0 is 1, and for any other number n, it is n multiplied by the factorial of n-1: ```python def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) ``` This recursive approach reflects the mathematical definition directly and is concise, although a loop-based approach could also be used if stack overflow concerns arise with large inputs .

To implement a function called 'triangle' that draws a triangle using hashes in Python, you need to create a loop that iterates from 1 to the value of the single parameter. In each iteration, print a line of hashes whose count corresponds to the current iteration number, effectively making both the height and width equal to the parameter. The code should look like the following: ```python def triangle(n): for i in range(1, n+1): print('#' * i) ``` When `triangle(6)` is called, it will print a triangle starting with one hash and ending with six hashes, each line increasing by one hash. This ensures the triangle is both tall and wide as the argument passed .

The function `sum_series(n)` computes the sum of an alternating series by iterating through numbers from 1 to n, adding odd numbers and subtracting even numbers. This can be achieved by: ```python def sum_series(n): total = 0 for i in range(1, n + 1): if i % 2 == 0: # if the number is even total -= i else: # if the number is odd total += i return total ``` In this function, the accumulator `total` is incremented or decremented based on whether `i` is odd or even, enabling the calculation of the specified alternating sum up to `n` .

A function to check if a word is a palindrome can be efficiently implemented by comparing the string to its reverse. This can be done by slicing the string in reverse order and checking for equality: ```python def is_palindrome(word): return word == word[::-1] ``` This technique leverages Python's slicing capabilities to create a reverse of the input string and compares it directly against the original. It is efficient in terms of both logic and computation because it avoids loops and additional data structures, making it straightforward and quick in performance .

Considering alternate implementations for finding the greatest number among three numbers can be significant in scenarios like competitive programming due to constraints on time complexity and readability. A nested if-else implementation is straightforward and efficient with a constant time complexity, O(1). However, using a sorted list, though slightly more computation-heavy at O(n log n), provides a compact and elegant solution if input is dynamically read or needs to be managed as a list further in the algorithm. Additionally, understanding different approaches enhances problem-solving flexibility and can lead to optimized and cleaner code that is easier to debug and maintain .

You might also like