Python GRPA W-4
Python GRPA W-4
# Note this prefix code is to verify that you are not using any for loops in this exercise. This won't
affect any other functionality of the program.
with open(__file__) as f:
print("You should not use for loop or the word for anywhere in this exercise")
int_iterable = range(1,10,3)
some_value = 4
some_iterable = (1,2,3)
yet_another_iterable = range(1,10)
# <nofor>
# <eoi>
empty_set = set() # be carefull here you might end up creating something called as an empty dict
a_falsy_set = set() # set: a set but when passed to bool function should return False.
a_truthy_tuple = (1,) # tuple: a tuple but when passed to bool function should return True.
int_iterable_min = min(int_iterable) # int: find the minimum of int_iterable. Hint: use min function
int_iterable_max = max(int_iterable) # int: find the maximum of int_iterable. Hint: use max function
if isinstance(int_iterable, (str, list, tuple, range)): # some iterables are not reversible why?
if isinstance(some_collection, (str, list, tuple)): # some collections are not indexable why? (sets and
dicts)
third_last_element = None
if isinstance(some_collection, (str, list, tuple)): # some collections are not slicable why? (sets and
dicts)
odd_index_elements = None
is_some_value_in_some_collection = True if some_value in some_collection else False # bool: True if
`some_value` is present in `some_collection`
if isinstance(some_collection, (str, list, tuple, range)): # some collections are not ordered (sets and
dicts)
is_some_value_in_even_indices = None
if isinstance(string_iterable, (str, list, tuple)): # some iterables are not ordered (sets and dicts)
all_concat = '-'.join(string_iterable) # str: concatenate all the strings in string_iterable with '-' in
between
all_concat = '-'.join(sorted(string_iterable))
____________________________________________________________________________
GRPA 2
# Note this prefix code is to verify that you are not using any for loops in this exercise. This won't
affect any other functionality of the program.
with open(__file__) as f:
print("You should not use for loop, while loop or the word for and while anywhere in this
exercise")
# note that apart from the print statements inside the functions, the evaluator will also print what is
returned by the function at last
# <noloop>
items.sort()
print("sorted:", items)
items.append(item1)
print("append:", items)
items.insert(3, item2)
print("insert:", items)
items.extend(items[:3])
print("extend:", items)
popped_item = items.pop(4)
print("pop:", items)
items.remove(item2)
print("remove:", items)
items[4] = None
print("modify_index:", items)
# make the even indices None
print("modify_slice:", items)
del items[-3]
print("delete_index:", items)
del items[::2]
print("delete_slice:", items)
print("sorted:", sorted(items))
# print a list with the first three elements in `items` added to the end of the `items` again
modified_list = items[:]
print("modify_slice:", modified_list)
print("delete_slice:", items[1::2])
return items
set1.add(item1)
print(sorted(set1))
set1.discard(item2)
print(sorted(set1))
set1.update(set2)
print(sorted(set1))
set1.difference_update(set3)
print(sorted(set1))
# print the common elements in both set2 and set3 as a sorted list.
print(sorted(set2.intersection(set3)))
# print all unique elements present in set1, set2, and set3 as a sorted list
print(sorted(set1.union(set2, set3)))
# print all unique elements that are in set2 but not in set3 as a sorted list
print(sorted(set2.difference(set3)))
# print all the non-common elements from both set2 and set3
print(sorted(set2.symmetric_difference(set3)))
____________________________________________________________________________
GRPA 3
'''
odd_square_even_double_modify: Square all the odd numbers and double all the even numbers in a
list, modifying the list in place.
sum_of_list_of_lists: Given a list of lists of integers, find the sum of all the integers in all the lists.
Output: An integer, the sum of all the integers in the nested lists.
all_common: Find the common characters that are present in all strings in a list of strings and return
them as a string in ascending order.
vocabulary: Given a list of sentences (with only alphabets and spaces), find the vocabulary (list of
unique words) and return it as a set. Convert all words to lowercase before adding to the vocabulary.
'''
min = None
def find_min(items:list):
'''
LOGIC:
3. Return min
'''
min = items[0]
for i in items:
if i < min:
min = i
return min
'''
Increment odd numbers and decrement even numbers in the list of numbers without modifying
the original list
LOGIC:
1. If item is even
2. Else
'''
modified_items = []
for i in items:
if i % 2 == 0:
modified_items.append(i - 1)
else:
modified_items.append(i + 1)
return modified_items
'''
Square odd numbers and double even numbers in the list of numbers, modifying the list in place
LOGIC:
1. For each item in items
1. If item is even
1. Double item
2. Else
1. Square item
'''
for i in range(len(items)):
if items[i] % 2 == 0:
items[i] *= 2
else:
items[i] **= 2
def more_than_two_unique_vowels(sentence):
'''
Check if the sentence has words with more than two unique vowels
LOGIC:
'''
words = sentence.split(',')
result = set()
vowels = set('aeiou')
if len(unique_vowels) > 2:
result.add(word.strip())
return result
def sum_of_list_of_lists(lol):
'''
LOGIC:
1. Initialize sum to 0
3. Return sum
'''
sum = 0
for i in lol:
for j in i:
sum += j
return sum
def flatten(lol):
'''
LOGIC:
'''
flat = []
for i in lol:
for j in i:
flat.append(j)
return flat
def all_common(strings):
'''
LOGIC:
2. Break
3. If flag is True
'''
common = set()
for i in strings[0]:
flag = True
for j in strings:
if i not in j:
flag = False
break
if flag:
common.add(i)
return ''.join(sorted(common))
def vocabulary(sentences):
'''
'''
vocab = set()
return vocab
____________________________________________________________________________
GRPA 4
'''
You are required to complete the following functions to perform various operations on tuples and
lists.
swap_halves: Swap the first and second halves of a tuple with an even length.
Output: A new tuple where the first and second halves are swapped.
swap_at_index: Break a tuple at a given index ( k ) (the element at the ( k )-th index is included in the
first half before swapping) and swap the parts.
rotate_k: Create a new list with elements of the given list moved ( k ) positions towards the right. The
elements at the end should come back to the beginning in a circular order.
Output: A new list with the elements rotated ( k ) positions to the right.
first_and_last_index: Get the indices of the first and last occurrence of a given item in a list. Assume
the item is present in the list at least once.
Output: A tuple with the first and last indices of the given item in the list.
reverse_first_and_last_halves: Reverse the first and last halves of a list with even length in place.
'''
def swap_halves(items):
'''
Swap the first half of the list with the second half.
If the list has an even number of elements, split it into two equal halves.
If the list has an odd number of elements, return the list unchanged.
LOGIC:
Output: A tuple with the halves swapped, or the original list if its length is odd.
'''
if len(items) % 2 == 0:
mid = len(items) // 2
return items
'''
Swap the elements of the list before and after the given index (inclusive of the index).
LOGIC:
1. If yes, swap the elements before and after the given index
Output: A tuple with elements swapped around the index, or the original list if the index is out of
range.
'''
else:
return items
'''
LOGIC:
'''
if len(items) > 0:
k = k % len(items)
else:
return items
'''
Find the first and last index of the given element in the list.
LOGIC:
'''
first_index = items.index(elem)
def reverse_first_and_last_halves(items):
'''
If the list has an even number of elements, split it into two equal halves and reverse each half.
If the list has an odd number of elements, the function does nothing.
LOGIC:
'''
if len(items) % 2 == 0:
mid = len(items) // 2
____________________________________________________________________________
GRPA 5
'''
INSTRUCTIONS:
sum_of_squares - find the sum of squares of numbers in a list - (mapping and aggregation)
total_cost - given quantitiy and price of each item as a list of tuples find the total cost using list
comprehensions
abbreviation - given a string with multiple words seperated by space, form an abbrevation out of it
by taking the first letter in caps. (mapping and aggregation)
palindromes - given a list of strings, create a new list with only palindromes filtering
all_chars_from_big_words - find the all unique characters (case insensitive, make all lowercase) from
all words with size greater than 5 in a given sentence with words seperated by spaces. (filtering)
unflatten - given a flat list and number of rows, create a matrix (2d list) with that number of rows.
(nested-aggregation)
make_identity_matrix - make an identity (with ones on the main diagonal and zeros elsewhere) given
the size.
make_lower_triangular_matrix - given number of rows m, create a lower triangular matrix like the
pattern below. for m = 5
[1,0,0,0,0],
[1,2,0,0,0],
[1,2,3,0,0],
[1,2,3,4,0],
[1,2,3,4,5]
'''
def sum_of_squares(numbers):
'''
LOGIC:
'''
def total_cost(cart):
'''
LOGIC:
1. Use a generator expression to multiply the quantity and price of each item
'''
return sum(quantity * price for quantity, price in cart)
def abbreviation(sentence):
'''
LOGIC:
2. Use a generator expression to take the first letter of each word and capitalize it
3. Join the capitalized letters with a period and return the abbreviation
'''
def palindromes(words):
'''
LOGIC:
1. Use a list comprehension to filter out words that are palindromes (words that are the same as
their reverse)
'''
def all_chars_from_big_words(sentence):
'''
Find all unique characters in words with more than 5 characters in a sentence
LOGIC:
2. Use a set comprehension to find all unique characters in words with more than 5 characters
'''
return {char.lower() for word in sentence.split() if len(word) > 5 for char in word}
def flatten(lol):
'''
LOGIC:
'''
'''
LOGIC:
1. Use a list comprehension to create a list of lists with the specified number of rows
2. Use slicing to divide the flat list into equal parts for each row
'''
def make_identity_matrix(m):
'''
LOGIC:
2. The matrix has ones on the main diagonal and zeros elsewhere
'''
def make_lower_triangular_matrix(m):
'''
LOGIC:
2. The matrix has ones on and below the main diagonal and zeros elsewhere
'''