0% found this document useful (0 votes)
7 views21 pages

Python GRPA W-4

The document contains a series of programming exercises that require implementing various functions for manipulating data structures like lists, sets, and tuples without using loops. It includes tasks such as finding minimum values, modifying lists, performing set operations, and working with strings. The exercises emphasize understanding of data types and their properties while adhering to specific constraints.

Uploaded by

Shreyank
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)
7 views21 pages

Python GRPA W-4

The document contains a series of programming exercises that require implementing various functions for manipulating data structures like lists, sets, and tuples without using loops. It includes tasks such as finding minimum values, modifying lists, performing set operations, and working with strings. The exercises emphasize understanding of data types and their properties while adhering to specific constraints.

Uploaded by

Shreyank
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
You are on page 1/ 21

GRPA 1

# 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:

content = f.read().split("# <nofor>")[2]

if "for " in content:

print("You should not use for loop or the word for anywhere in this exercise")

# The values of the below variables will be changed by the evaluator

int_iterable = range(1,10,3)

string_iterable = ["Apple","Orange", "Banana"]

some_value = 4

some_collection = [1,2,3] # list | set | tuple

some_iterable = (1,2,3)

another_iterable = {"apple", "banana", "cherry"} # can be any iterable

yet_another_iterable = range(1,10)

# <nofor>

# <eoi>

empty_list = [] # list: An empty list

empty_set = set() # be carefull here you might end up creating something called as an empty dict

empty_tuple = () # tuple: An empty tuple

singleton_list = [1] # list: A list with only one element

singleton_set = {1} # set: A set with only one element

singleton_tuple = (1,) # tuple: A tuple with only one element


a_falsy_list = [] # list: a list but when passed to bool function should return False.

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

int_iterable_sum = sum(int_iterable) # int: you know what to do

int_iterable_len = len(int_iterable) # int: really... you need hint?

int_iterable_sorted = sorted(int_iterable) # list: the int_iterable sorted in ascending order

int_iterable_sorted_desc = sorted(int_iterable, reverse=True) # list: the int_iterable sorted in


descending order

if isinstance(int_iterable, (str, list, tuple, range)): # some iterables are not reversible why?

int_iterable_reversed = list(reversed(int_iterable)) # list: the int_iterable reversed use the reversed


function

else: # in that case sort it in ascending order and reverse it

int_iterable_reversed = sorted(int_iterable, reverse=True) #list: the int_iterable reversed

if isinstance(some_collection, (str, list, tuple)): # some collections are not indexable why? (sets and
dicts)

third_last_element = some_collection[-3] # the third last element of `some_collection`

else: # in that case set third_last_element to None

third_last_element = None

if isinstance(some_collection, (str, list, tuple)): # some collections are not slicable why? (sets and
dicts)

odd_index_elements = some_collection[1::2] # type(some_collection): the elements at odd indices


of `some_collection`

else: # in that case set odd_index_elements to None

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 = True if some_value in some_collection[::2] else False # bool:


True if `some_value` is present in even indices of `some_collection`

else: # in that case set is_some_value_in_even_indices to None

is_some_value_in_even_indices = None

# list: concatenate `some_iterable`, `another_iterable` and `yet_another_iterable` into a list.

all_iterables = list(some_iterable) + list(another_iterable) + list(yet_another_iterable)

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

else: # in that case sort them and concatenate

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:

content = f.read().split("# <noloop>")[2]

if "for " in content or "while " in content:

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>

def list_mutating_operations(items:list, item1, item2):

# sort the `items` inplace

items.sort()

print("sorted:", items)

# add item1 to the `items` at the end

items.append(item1)

print("append:", items)

# add item2 at index 3

items.insert(3, item2)

print("insert:", items)

# extend `items` with the first three elements in `items`

items.extend(items[:3])

print("extend:", items)

# pop the fifth element and store it in variable `popped_item`

popped_item = items.pop(4)

print("pop:", items)

# remove first occurrence of `item2` from the list

items.remove(item2)

print("remove:", items)

# make the element at index 4 None

items[4] = None

print("modify_index:", items)
# make the even indices None

items[::2] = [None] * (len(items) // 2 + len(items) % 2)

print("modify_slice:", items)

# delete the third last element

del items[-3]

print("delete_index:", items)

# delete the even indices

del items[::2]

print("delete_slice:", items)

return items, popped_item

def list_non_mutating_operations(items:list, item1, item2):

# print the sorted version of items

print("sorted:", sorted(items))

# print a list with item1 appended to the `items` at the end

print("append:", items + [item1])

# print a list with item2 added to items at index 3

print("insert:", items[:3] + [item2] + items[3:])

# print a list with the first three elements in `items` added to the end of the `items` again

print("extend:", items + items[:3])

# print a list with the fifth element from `items` removed

print("pop:", items[:4] + items[5:])

# print a list with first occurrence of `item2` removed from `items`


print("remove:", items[:items.index(item2)] + items[items.index(item2)+1:])

# print a list with the fourth element of `items` changed to None

print("modify_index:", items[:3] + [None] + items[4:])

# print a list with the even indices changed to None

modified_list = items[:]

modified_list[::2] = [None] * (len(modified_list) // 2 + len(modified_list) % 2)

print("modify_slice:", modified_list)

# print a list with the even indices removed

print("delete_slice:", items[1::2])

return items

def do_set_operation(set1, set2, set3, item1, item2):

# add item1 to set1

set1.add(item1)

print(sorted(set1))

# remove item2 from set1. What if item2 is not in set1?

set1.discard(item2)

print(sorted(set1))

# add elements from set2 to set1

set1.update(set2)

print(sorted(set1))

# remove all elements from set1 that are in set3

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)))

return set1, sorted(set1), sorted(set2), sorted(set3)

____________________________________________________________________________

GRPA 3

'''

Implement the following functions:

find_min: Find the minimum value in a list of integers.

Input: A list of integers.

Output: An integer, the minimum value in the list.

odd_increment_even_decrement_no_modify: Increment all the odd numbers in a list by 1 and


decrement all the even numbers by 1, without modifying the original list.

Input: A list of integers.

Output: A new list of integers with the modified values.

odd_square_even_double_modify: Square all the odd numbers and double all the even numbers in a
list, modifying the list in place.

Input: A list of integers.

Output: None (the input list is modified in place).


more_than_two_unique_vowels: Given a string of comma-separated words, return a set containing
words that have more than two unique vowels.

Input: A string of comma-separated words.

Output: A set of words with more than two unique vowels.

sum_of_list_of_lists: Given a list of lists of integers, find the sum of all the integers in all the lists.

Input: A list of lists of integers.

Output: An integer, the sum of all the integers in the nested lists.

flatten: Flatten a list of lists into a single list.

Input: A list of lists.

Output: A single flattened list.

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.

Input: A list of strings.

Output: A string containing common characters 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.

Input: A list of sentences.

Output: A set of unique words in lowercase.

'''

min = None

def find_min(items:list):

'''

Find the minimum of the list of numbers

LOGIC:

1. Initialize min to the first item in the list

2. For each item in items

1. If item is less than min

1. Update min to item

3. Return min

'''
min = items[0]

for i in items:

if i < min:

min = i

return min

def odd_increment_even_decrement_no_modify(items) -> list:

'''

Increment odd numbers and decrement even numbers in the list of numbers without modifying
the original list

LOGIC:

1. Create a new list for the modified values

2. For each item in items

1. If item is even

1. Decrement item by 1 and append to the new list

2. Else

1. Increment item by 1 and append to the new list

3. Return the new list

'''

modified_items = []

for i in items:

if i % 2 == 0:

modified_items.append(i - 1)

else:

modified_items.append(i + 1)

return modified_items

def odd_square_even_double_modify(items:list) -> None:

'''

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:

1. Split the sentence into words

2. For each word

1. Count unique vowels in the word

2. If unique vowels are more than two

1. Add word to the result set

3. Return the result set

'''

words = sentence.split(',')

result = set()

vowels = set('aeiou')

for word in words:

unique_vowels = set([char for char in word if char in vowels])

if len(unique_vowels) > 2:

result.add(word.strip())

return result
def sum_of_list_of_lists(lol):

'''

Find the sum of all the numbers in the list of lists

LOGIC:

1. Initialize sum to 0

2. For each list in lol

1. For each item in list

1. Add item to sum

3. Return sum

'''

sum = 0

for i in lol:

for j in i:

sum += j

return sum

def flatten(lol):

'''

Flatten the list of lists

LOGIC:

1. Initialize a list to store the flattened list

2. For each list in lol

1. For each item in list

1. Append item to the flattened list

3. Return the flattened list

'''

flat = []

for i in lol:

for j in i:

flat.append(j)
return flat

def all_common(strings):

'''

Find the common characters in all the strings

LOGIC:

1. Initialize a set to store the common characters

2. For each character in the first string

1. Initialize a flag to True

2. For each string in strings

1. If character is not in string

1. Set flag to False

2. Break

3. If flag is True

1. Add character to the set

3. Return the set as a string in ascending order

'''

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):

'''

Find the vocabulary of the sentences, converting all words to lowercase


LOGIC:

1. Initialize a set to store the vocabulary

2. For each sentence in sentences

1. Split the sentence into words

2. For each word in sentence

1. Convert word to lowercase and add to the set

3. Return the set

'''

vocab = set()

for sentence in sentences:

words = sentence.split() # Splitting the sentence into words

for word in words:

vocab.add(word.lower()) # Converting to lowercase before adding

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.

Input: A tuple of 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.

Input: A tuple and an integer ( k ).


Output: A new tuple where the parts before and after the ( k )-th index are swapped.

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.

Input: A list and an integer ( k ) (default value ( k = 1 )).

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.

Input: A list and an item.

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.

Input: A list with an even length.

Output: None (the list should be modified 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:

1. Check if the list length is even

1. If yes, find the middle index

2. Swap the first half with the second half

3. Return the swapped list as a tuple

2. If the list length is odd, return the list unchanged

Input: A list of elements.

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 tuple(items[mid:]) + tuple(items[:mid])


else:

return items

def swap_at_index(items, k):

'''

Swap the elements of the list before and after the given index (inclusive of the index).

LOGIC:

1. Check if the index is within the valid range of the list

1. If yes, swap the elements before and after the given index

2. Return the swapped list as a tuple

2. If the index is out of range, return the list unchanged

Input: A list of elements and an index k.

Output: A tuple with elements swapped around the index, or the original list if the index is out of
range.

'''

if k >= 0 and k < len(items) - 1:

return tuple(items[k+1:]) + tuple(items[:k+1])

else:

return items

def rotate_k(items, k=1):

'''

Rotate the list to the right by k elements.

LOGIC:

1. Check if the list is not empty

1. Normalize the rotation distance k to a valid range using modulo

2. Rotate the list by k elements

3. Return the rotated list


2. If the list is empty, return it unchanged

Input: A list of elements and an integer k indicating the rotation distance.

Output: The list rotated to the right by k elements.

'''

if len(items) > 0:

k = k % len(items)

return items[-k:] + items[:-k]

else:

return items

def first_and_last_index(items, elem):

'''

Find the first and last index of the given element in the list.

LOGIC:

1. Find the first occurrence of the element

2. Find the last occurrence of the element by reversing the list

3. Return a tuple containing the first and last index

Input: A list of elements and the target element.

Output: A tuple (first_index, last_index) of the element in the list.

'''

first_index = items.index(elem)

last_index = len(items) - 1 - items[::-1].index(elem)

return (first_index, last_index)

def reverse_first_and_last_halves(items):

'''

Reverse the first and last halves of the list in place.

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:

1. Check if the list length is even

1. If yes, find the middle index

2. Reverse the first half and the second half in place

2. If the list length is odd, do nothing

Input: A list of elements.

Output: None (the input list is modified in place).

'''

if len(items) % 2 == 0:

mid = len(items) // 2

items[:mid], items[mid:] = items[:mid][::-1], items[mid:][::-1]

____________________________________________________________________________

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)

flatten - flatten a nested list using comprehension

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]

Note: you cannot use if statements or loops withing the functions.

'''

def sum_of_squares(numbers):

'''

Calculate the sum of the squares of a list of numbers

LOGIC:

1. Use a generator expression to square each number in the list

2. Use the sum() function to add up all the squared numbers

3. Return the sum

'''

return sum(x**2 for x in numbers)

def total_cost(cart):

'''

Calculate the total cost of items in a cart

LOGIC:

1. Use a generator expression to multiply the quantity and price of each item

2. Use the sum() function to add up all the costs

3. Return the total cost

'''
return sum(quantity * price for quantity, price in cart)

def abbreviation(sentence):

'''

Create an abbreviation from the initial letters of words in a sentence

LOGIC:

1. Split the sentence into words

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

'''

return '.'.join(word[0].upper() for word in sentence.split()) + '.'

def palindromes(words):

'''

Filter out palindromes from a list of words

LOGIC:

1. Use a list comprehension to filter out words that are palindromes (words that are the same as
their reverse)

2. Return the list of palindromes

'''

return [word for word in words if word == word[::-1]]

def all_chars_from_big_words(sentence):

'''

Find all unique characters in words with more than 5 characters in a sentence

LOGIC:

1. Split the sentence into words

2. Use a set comprehension to find all unique characters in words with more than 5 characters

3. Return the set of unique characters

'''

return {char.lower() for word in sentence.split() if len(word) > 5 for char in word}
def flatten(lol):

'''

Flatten a list of lists

LOGIC:

1. Use a list comprehension to flatten the list of lists

2. Return the flattened list

'''

return [item for sublist in lol for item in sublist]

def unflatten(items, n_rows):

'''

Create a matrix with a given number of rows from a flat list

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

3. Return the matrix

'''

return [items[i * (len(items) // n_rows): (i + 1) * (len(items) // n_rows)] for i in range(n_rows)]

def make_identity_matrix(m):

'''

Create an identity matrix of size m x m

LOGIC:

1. Use a list comprehension to create the identity matrix

2. The matrix has ones on the main diagonal and zeros elsewhere

3. Return the identity matrix

'''

return [[1 if i == j else 0 for j in range(m)] for i in range(m)]

def make_lower_triangular_matrix(m):
'''

Create a lower triangular matrix of size m x m

LOGIC:

1. Use a list comprehension to create the lower triangular matrix

2. The matrix has ones on and below the main diagonal and zeros elsewhere

3. Return the lower triangular matrix

'''

return [[j+1 if j <= i else 0 for j in range(m)] for i in range(m)]

You might also like