In: Computer Science
Complete the following using Python on a single text file and submit your code and your output as separate documents. For each problem create the necessary list objects and write code to perform the following examples:
We are allowed only to answer 5 questions, still I've answerd more than that.
Here are the code fo those:
import numpy as np
import copy
import random
sample_list = [1,2,3,4,1]
# Sum all the items in a list.
sum_list = sum([item for item in sample_list])
# Multiply all the items in a list.
mult_list = np.prod(sample_list)
# Get the largest number from a list.
max_item = max(sample_list)
# Get the smallest number from a list
min_list = min(sample_list)
# Remove duplicates from a list
uniq_list = list(set(sample_list))
# Check a list is empty or not
if(len(sample_list) == 0):
status = 'Yes'
else:
status = 'No'
# Clone or copy a list
copy_list = copy.deepcopy(sample_list)
print('Input list: ',sample_list)
print('Sum all the items in a list: ',sum_list)
print('Multiply all the items in a list: ',mult_list)
print('Largest number from a list: ',max_item)
print('\nSmallest number from a list: ',min_list)
print('Remove duplicates from a list: ',uniq_list)
print('Check a list is empty or not: ',status)
print('Clone or copy a list: ', copy_list)
sample_words = ['Hello','Dog','Happy','Aeroplane','Rocket']
sample_words2 = ['Hello','Cat','Sad','Car','Bus']
# Find the list of words that are longer than n = 5 from a given list of words.
output_list = [item for item in sample_words if len(item) > 5]
# Take two lists and returns True if they have at least one common member.
result = [True for item in sample_words if item in sample_words2]
if(len(result) != 0):
status = 'Yes'
else:
status = 'No'
print('Words that are longer than n = 5',output_list)
print('At least one common member: ', status)
# Print a specified list after removing the 0th, 4th and 5th elements.
Sample_word = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
index_remove = [0,4,5] # indices to remove
output_list = [Sample_word[loop1] for loop1 in range(len(Sample_word)) if loop1 not in index_remove]
# Print the numbers of a specified list after removing even numbers from it.
odd_list = [item for item in sample_list if item % 2 != 0]
# Shuffle and print a specified list.
random.shuffle(sample_list)
print('After removing few indices: ', output_list)
print('After removing even numbers: ', odd_list)
print('After shuffling the list: ', sample_list)
Here is the ouputs:
For any doubts please comment below.