-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetThree.py
169 lines (119 loc) · 4.83 KB
/
setThree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# # S1 D3 Assignment - Set 3
# 1. **Tuple Unpacking**: Create a list of tuples, each containing a name and an age. Then, use tuple unpacking to iterate through the list and print each name and age.
# - *Input*: [("John", 25), ("Jane", 30)]
# - *Output*: "John is 25 years old. Jane is 30 years old."
data = [("John", 25), ("Jane", 30)]
for name, age in data:
print(f"{name} is {age} years old.")
# 2. **Dictionary Manipulation**: Create a dictionary with keys as names and values as ages. Write functions to add a new name-age pair, update the age of a name, and delete a name from the dictionary.
# - *Input*: Add "John": 25, Update "John": 26, Delete "John"
# - *Output*: "{}, {'John': 26}, {}"
def add_name_age(dictionary, name, age):
dictionary[name] = age
def update_age(dictionary, name, new_age):
if name in dictionary:
dictionary[name] = new_age
def delete_name(dictionary, name):
if name in dictionary:
del dictionary[name]
ages_dict = {}
add_name_age(ages_dict, "John", 25)
update_age(ages_dict, "John", 26)
delete_name(ages_dict, "John")
print(ages_dict)
# 3. **Two Sum Problem**: Given an array of integers and a target integer, find the two integers in the array that sum to the target.
# - *Input*: [2, 7, 11, 15], target = 9
# - *Output*: "[0, 1]"
def two_sum(nums, target):
num_to_index = {}
for index, num in enumerate(nums):
complement = target - num
if complement in num_to_index:
return [num_to_index[complement], index]
num_to_index[num] = index
return None
nums = [2, 7, 11, 15]
target = 9
result = two_sum(nums, target)
print(result)
# 4. **Palindrome Check**: Write a Python function that checks whether a given word or phrase is a palindrome.
# - *Input*: "madam"
# - *Output*: "The word madam is a palindrome."
def is_palindrome(word):
cleaned_word = word.lower().replace(" ", "")
return cleaned_word == cleaned_word[::-1]
input_word = "madam"
if is_palindrome(input_word):
print(f"The word {input_word} is a palindrome.")
else:
print(f"The word {input_word} is not a palindrome.")
# 5. **Selection Sort**: Implement the selection sort algorithm in Python.
# - *Input*: [64, 25, 12, 22, 11]
# - *Output*: "[11, 12, 22, 25, 64]"
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
input_array = [64, 25, 12, 22, 11]
selection_sort(input_array)
print(input_array)
# 6. **Implement Stack using Queue**: Use Python's queue data structure to implement a stack.
# - *Input*: push(1), push(2), pop(), push(3), pop(), pop()
# - *Output*: "1, None, 3, None, None"
from queue import Queue
class StackUsingQueue:
def __init__(self):
self.queue1 = Queue()
self.queue2 = Queue()
def push(self, item):
self.queue1.put(item)
def pop(self):
while self.queue1.qsize() > 1:
self.queue2.put(self.queue1.get())
popped_item = self.queue1.get()
self.queue1, self.queue2 = self.queue2, self.queue1
return popped_item
stack = StackUsingQueue()
stack.push(1)
stack.push(2)
print(stack.pop())
stack.push(3)
print(stack.pop())
print(stack.pop())
# 7. **FizzBuzz**: Write a Python program that prints the numbers from 1 to 100, but for multiples of three, print "Fizz" instead of the number, for multiples of five, print "Buzz", and for multiples of both three and five, print "FizzBuzz".
# - *Input*: None
# - *Output*: "1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16,..."
for num in range(1, 101):
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
print("Buzz")
else:
print(num)
# 1. **File I/O**: Write a Python program that reads a file, counts the number of words, and writes the count to a new file.
# - *Input*: A text file named "input.txt" with the content "Hello world"
# - *Output*: A text file named "output.txt" with the content "Number of words: 2"
with open("input.txt", "r") as file:
content = file.read()
word_count = len(content.split())
with open("output.txt", "w") as file:
file.write(f"Number of words: {word_count}")
# 2. **Exception Handling**: Write a Python function that takes two numbers as inputs and returns their division, handling any potential exceptions (like division by zero).
# - *Input*: 5, 0
# - *Output*: "Cannot divide by zero."
def divide_numbers(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
return "Cannot divide by zero."
numerator = 5
denominator = 0
result = divide_numbers(numerator, denominator)
print(result)