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

Python Code Snippets and Functions

The document contains a series of Python code snippets demonstrating various programming concepts such as loops, conditionals, string manipulation, and recursion. Each snippet performs different tasks, including printing specific outputs based on conditions, calculating sums, and generating patterns. Overall, the document serves as a collection of coding examples for educational purposes.

Uploaded by

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

Python Code Snippets and Functions

The document contains a series of Python code snippets demonstrating various programming concepts such as loops, conditionals, string manipulation, and recursion. Each snippet performs different tasks, including printing specific outputs based on conditions, calculating sums, and generating patterns. Overall, the document serves as a collection of coding examples for educational purposes.

Uploaded by

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

CODE HUNT

1. def sympo(n):
if n <= 0:
print("Invalid input")
return

i=3
while i <= n:
if i % 12 == 0:
print("2024")
elif i % 4 == 0:
print("cse")
elif i % 2 == 0:
print("sparzo")
else:
print("welcome to our symposium")
i *= 2
n = 15
sympo(n)

2. nums = [10, 20, 30, 40, 50]


indices = [4, 3, 2, 1, 0]
result = 0
for i in range(0, 5, 2):
result += nums[indices[i]]
print(result // 9)

3. def strange_string(s):
result = []
for i, char in enumerate(s):
if i % 6 == 0:
[Link]([Link]())
else:
[Link]([Link]())
return ''.join(result)

input_str = "RATAN TATA"


output_str = strange_string(input_str)
print(output_str)

4. x = 10
y = (x := x + 1) + (x := x + 1)
print(y)

5. chars = ['S', 'p', 'a', 'r', 'z', 'o']


n=6
for i in range(1, n + 1):
for space in range(n - i):
print(" ", end="")
for j in range(i):
print(chars[j], end=" ")

print()

6. def main():
x = 10
y=5
x=x^y
y=x^y
x=x^y
print(x ^ y)
main()
[Link] mystery_sum(arr):
sum = 0
for i in range(len(arr))
if i % 2 == 0:
sum+= arr[i]
else:
sum-= arr[i]
return sum
arr = [10, 5, 20, 15, 30, 25]
result = mystery_sum(arr[:5])
print(f"Result: {result}")

8. def mystery(n):
if n == 0:
return 0
return n + mystery(n - 1)
m=mystery(5)
print(m)

9. def mystery(n):
if n == 0:
return 0
return n + mystery(n - 1)
m=mystery(5)
print(m)

10. n = 4
for i in range(1, n):
for j in range(1, n):
if j == n - 1:
print("E", end="")
elif i * j == i:
print("G", end="")
else:
print("C", end="")
print()

Common questions

Powered by AI

This code demonstrates the use of the 'walrus operator' (`:=`) for assignment within an expression, illustrating the intricacies of evaluation order. Here, `x` is initially 10, and through the expressions `(x := x + 1)`, it is incremented twice sequentially: first to 11 and then to 12. Therefore, `y` becomes 23 (11 + 12).

The `mystery` function encapsulates a basic tail-recursive paradigm to sum integers from `n` down to `0`. It adds `n` to the result of `mystery(n-1)` until reaching the base case `n = 0`, which returns 0 and stops recursion. `mystery(5)` returns 15, representing the sum of numbers 5+4+3+2+1+0. This illustrates recursive deconstruction of a problem, breaking down the addition of a sequence into simpler repeat calls until reaching the simplest expression .

The `sympo` function ensures input validation with an immediate check `if n <= 0`, which prints 'Invalid input' and exits the function without further execution. This demonstrates a simple yet effective control flow mechanism where invalid numerical inputs short-circuit the process, preventing execution of subsequent code and output based on an invalid state. With `n` as non-positive, it effectively avoids potential errors later in the function due to illogical loop bounds .

This concept illustrates the use of index mapping to dynamically access elements in a different order. The operation iterates over indices `[0, 2, 4]`, retrieving `nums[4]`, `nums[2]`, and `nums[0]`, equivalent to values `50, 30,` and `10`, summing up to `90`. Dividing `90` by `9`, as specified, yields the result `10`. This example demonstrates computational adjustment and result derivation through precise and intentional index mapping .

The `mystery_sum` function alternates between adding and subtracting values based on the index in the array: it adds values at even indices and subtracts those at odd indices. For the array slice `arr[:5]` which is `[10, 5, 20, 15, 30]`, it performs the operation: 10 (add index 0) - 5 (subtract index 1) + 20 (add index 2) - 15 (subtract index 3) + 30 (add index 4), resulting in the sum of 40. The logic effectively demonstrates how alternating operations can be implemented through a loop and conditional index checks .

In the final code snippet, the nested loops use `i` and `j` for logic to print pattern characters based on conditions. When `j` is one less than `n`, 'E' is printed; otherwise, 'G' is printed on the first column and 'C' elsewhere within its iterations. For `n = 4`, the loop generates: - `j = 1`: 'GCE' - `j = 2`: 'GCE' - `j = 3`: 'GCE' This shows a conditional display based on multi-tiered loop iteration logic where specific conditions are checked and used to vary output per iteration .

The `main` function uses XOR bit manipulation to swap values of `x` and `y` without a temporary variable. Initially `x = 10` and `y = 5`. The operations `x = x ^ y`, `y = x ^ y`, and `x = x ^ y` swap the values. The final operation `print(x ^ y)` outputs zero, because `x` and `y` now hold each other's initial values, making `x ^ y` result in `0`. This exemplifies the utility of XOR for in-place swapping without extra space .

The loop constructs a pyramid-like pattern using the `chars[]` array and spaces. The outer loop determines the number of lines (from 1 to `n`), and the inner loops handle spacing and character printing each line, with decreasing spaces and increasing character count. For `n = 6`, the first two lines are: - Line 1 (one character): ' S' - Line 2 (two characters): ' S p' This is achieved via loop nested within the outer loop, where spaces are printed as (n-i) and characters upto the ith index are printed. The sequential output demonstrates structured pattern expansion from a character array .

The `strange_string` function exhibits an operation that converts string characters to uppercase if their index is divisible by 6 and to lowercase otherwise. For the input 'RATAN TATA', the output is 'Ratan tata'. The function constructs the string by iterating through each character, checking the index % 6 condition, and appending the modified character to a result list, which is then joined into a string .

The `sympo` function prints different strings based on the value of `i` when `i` is less than or equal to `n`. The logic uses successive multiplication of `i` by 2, starting at 3. For `n = 15`, it outputs several messages: - Initial `i = 3`, prints 'welcome to our symposium'. - `i = 6` (next, as `3*2`), prints 'sparzo'. - `i = 12` (next, as `6*2`), prints '2024'. - `i = 24` exceeds `n`, so the loop stops. This approach effectively demonstrates the use of conditional checks with a focus on modulo operations to determine the output per value iteration .

You might also like