DO MY ASSIGNMENT SUBMIT
Sample: Python - Averages and Longest Word
Problem No. 1
# Find the longest word in the list
def find_longest_word(wordList):
"Function for search the longest word in the given list"
# let the first element be the longest
max_element = wordList[0]
for curr_element in wordList:
# if the current element of the list is longer then maximal,
# than the current is the longest
if len(curr_element) > len(max_element):
max_element = curr_element
# return the longest element
return max_element
print("Enter a few words and I will find the longest")
#input string from console
new_string = input()
# make a list of string by divider ' ' using the built-in function split
new_list = new_string.split(" ")
# removing empty elements from the list
new_list = list(filter(None, new_list))
print("The list of words entered is:")
print(new_list)
# searching the longestelement in the list
longest_element = find_longest_word(new_list)
print("The longest word is:")
print(longest_element)
W W W . A S S I G N M E N T E X P E R T. C O M
DO MY ASSIGNMENT SUBMIT
Problem No. 2
# find average of numbers
def allNumAvg(numList):
"Find average of all numbers in the given list"
my_sum = 0
for element in numList:
my_sum += element
return my_sum/len(numList)
def posNumAvg(numList):
"Find average of all positive numbers"
my_sum = 0
count = 0
for element in numList:
if element > 0:
my_sum += element
count += 1
if count == 0:
return 0
return my_sum/count
def nonPosAvg(numList):
"Find average of all numbers that are less than or equal to zero"
my_sum = 0
count = 0
for element in numList:
if element <= 0:
my_sum += element
count += 1
if count == 0:
return 0
return my_sum/count
W W W . A S S I G N M E N T E X P E R T. C O M
DO MY ASSIGNMENT SUBMIT
print("Enter a number (-9999 to end):", end='')
new_number = input()
number_list = []
# does the current number equals -9999 or not
while new_number != "-9999":
# if you type an empty symbol nothing will be added to list
if new_number == "":
pass
else:
number_list.append(int(new_number))
print("Enter a number (-9999 to end):", end='')
new_number = input()
# dictionary for results
result_dictionary = {}
# calculate all averages
result_dictionary['AvgPositive'] = posNumAvg(number_list)
# calculate only average of positive numbers
result_dictionary['AvgNonPos'] = nonPosAvg(number_list)
# calculate only average of negative numbers
result_dictionary['AvgAllNum'] = allNumAvg(number_list)
print("List of all numbers entered is:")
print(number_list)
print("The dictionary with average is:")
print(result_dictionary)
W W W . A S S I G N M E N T E X P E R T. C O M