Chapter 7 - List: Lab & Assignment

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

#t03 def get_digit_name(n): """ ------------------------------------------------------- Returns the name of a digit given its number. Use: name = get_digit_name(n) ------------------------------------------------------- Parameters: n - digit number (int 0 <= n <= 9) Returns: name - matching digit, 0 = "zero", 9 = "nine" (str) ------------------------------------------------------- """

# list of all digits 0-9 digit = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] # for loop that iterates from 0 including the user inputted int (n) for i in range (0, n+1): name = digit[i] return name

#t02 def get_month_name(m): """ ----------------------------------------------------- Returns the name of a month given its number. Use: name = get_month_name(m) ----------------------------------------------------- Parameters: m - month number (int 1 <= m <= 12) Returns: name - matching month, 1 = "January", 12 = "December" (str) ----------------------------------------------------- """

# list of all the months months = ["January","February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] #for loop that iterates until the user inputted index for i in range (0, m): name = months[i] return name

#t04 def generate_integer_list(n, low, high): """ ------------------------------------------------------- Generates a list of random integers. Requires import: from random import randint Use: values = generate_integer_list(n, low, high) ------------------------------------------------------- Parameters: n - number of values to generate (int, > 0) low - low value range (int) high - high value range (int, > low) Returns: values - a list of random integers (list of int) ------------------------------------------------------- """

#import randint to generate random integers from random import randint #initialize the list values = [] #for loop that iterates from 0 to n (number of times it has to loop) for i in range (0, n): #n = randint(low (low value range, high value range + 1 to make in inclusive) n = randint(low, high + 1) #append n to values list values.append(n) return values

#t10 def min_search(a): """ ------------------------------------------------------- Searches through a for the minimum value(s) and returns a list of the indexes of those values. (Assumes a has at least one element.) Use: indexes = min_search(a) ------------------------------------------------------- Parameters: a - a list of values (list of ?). Returns: indexes - a list of indexes of the minimum values in a (list of int). ------------------------------------------------------- """

#indexes will store indexes of the minmimum values indexes=[] #assuming a[0] to be minimum m=a[0] for i in range(1,len(a)): #accesing each element #if an element less then m is found it is new min if(a[i]<m): m=a[i] for i in range(len(a)): #storing all the miv value indexes in indexes if(a[i]==m): #append will append the new element to the list indexes.append(i) #returing the list of indexes return indexes return indexes a = [94, 96, -32, -19, -28, 96, -22, 71, 24, -32] indexes = min_search(a) print("Values: {}".format(a)) print() print("Index of minimums: {}".format(indexes))

#t09 def many_search(a, v): """ ------------------------------------------------------- Searches through a for the value v and returns a list of all indexes of its occurrence. Use: indexes = many_search(a, v) ------------------------------------------------------- Parameters: a - a list of values (list of ?). v - can be compared to values in a (?). Returns: indexes - a list of indexes of the location of v in a, [] if not found (list of int). ------------------------------------------------------- """

#initialize index_count = -1 indexes = [] for i in a: if i != v: index_count += 1 elif i == v: index_count += 1 indexes.append(index_count) return indexes a = [94, 96, -22, -79, -28, 96, -50, 71, 24, -32] v = int(input("Enter a value to compare to a: ")) indexes = many_search(a, v) print("Values: {}".format(a)) print() print("Index of {}: {}".format(v,indexes))

#t08 def linear_search(a, v): """ ------------------------------------------------------- Searches through a for the value v and returns its index. Use: index = linear_search(a, v) ------------------------------------------------------- Parameters: a - a list of values (list of ?). v - can be compared to values in a (?). Returns: index - the index of the location of v in a, -1 if not found (int). ------------------------------------------------------- """

#intialize values: index -1 so every iteration will be recorded starting at 0 index = -1 #-1 so if i is never = to v it will leave it as -1 final_index = -1 for i in a: if i != v: index += 1 elif i == v: index += 1 final_index = index index = final_index return index a = [94, 96, -22, -79, -28, -26, -50, 71, 24, -32] v = int(input("Enter a value to compare to a: ")) index = linear_search(a, v) print("Values: {}".format(a)) print() print("Index of {}: {}".format(v,index))

#t01 def get_weekday_name(d): """ ----------------------------------------------------- Returns the name of a day of the week given its number. Use: name = get_weekday_name(d) ----------------------------------------------------- Parameters: d - day of week number (1 <= int <= 7) Returns: name - matching day of the week, 1 = "Sunday", 7 = "Saturday" (str) ----------------------------------------------------- """

#make a list with all the days of the week days = ["Sunday", "Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday"] #make a for loop that iterates until it reaches the user inputted day for i in range (0,d): #this makes the loop start at 0 until d name = days[i] #name matches i and will change everytime until it reaches d return name

#t05 def get_lotto_numbers(n, low, high): """ ------------------------------------------------------- Generates a sorted list of unique lottery numbers. Requires import: from random import randint Use: numbers = get_lotto_numbers(n, low, high) ------------------------------------------------------- Parameters: n - number of lottery numbers to generate (int > 0) low - low value of the lottery number range (int >= 0) high - high value of the lottery number range (int > low) Returns: numbers - a list of unique random lottery numbers (list of int) ------------------------------------------------------- """

#we will need a random integer From random import randint #initialize numbers list Numbers = [] #for loop that goes from 0 to n (number of numbers to generate) for i in range (0, n): #n = randint(low (low value range, high value range + 1 to make in inclusive) n = randint(low, high +1) numbers.append(n) return numbers

#q2 def is_prime(num): """ ------------------------------------------------------- Calculates and returns whether num is prime. Use: prime = is_prime(num) ------------------------------------------------------- Parameters: num - number to determine primeness (int > 0) Returns: prime - True is num is prime, False otherwise. ------------------------------------------------------ """

from math import sqrt stop = int(sqrt(num) + 1) prime = True i = 2 while prime and i < stop: if num % i == 0: prime = False i += 1 return prime from functions import is_prime # Inputs num = int(input("Enter a positive integer: ")) # Calculations prime = is_prime(num) # Outputs print() if prime: print("{} is a prime number".format(num)) else: print("{} is not a prime number".format(num)) Enter a positive integer: 95 95 is not a prime number Enter a positive integer: 97 97 is a prime number Enter a positive integer: 98 98 is not a prime number

Example of string transformation

input_string = input("Enter a list elements separated by space ") print("\n") userList = input_string.split() print("user list is ", userList) # Calculating the sum of input list elements sum1 = 0 for num in userList: sum1 += int(num) print("Sum = ", sum1) Enter a list elements separated by space 2 4 6 8 10 12 user list is ['2', '4', '6', '8', '10', '12'] Sum = 42

#q5 def largest_odd(num_list): """ ------------------------------------------------------- Finds largest odd number in a list. Returns -1 if no odd numbers. Use: largest = largest_odd(num_list) ------------------------------------------------------- Parameters: num_list - a list of integers (list of int) Returns: largest - largest odd number in num_list (int) ------------------------------------------------------ """

largest = -1 for i in range(len(num_list)): if num_list[i] % 2 == 1 and num_list[i] > largest: largest = num_list[i] return largest from functions import keep_positive, largest_odd numbers = keep_positive() print() print("List entered: {}".format(numbers)) print() lo = largest_odd(numbers) print("Largest odd: {}".format(lo)) Enter a positive number: 9 Enter a positive number: 11 Enter a positive number: 32 Enter a positive number: 17 Enter a positive number: -5 Enter a positive number: 9 Enter a positive number: 33 Enter a positive number: -5 Enter a positive number: 8 Enter a positive number: 0 List entered: [9, 11, 32, 17, 9, 33, 8] Largest odd: 33

#q4 def find_value(num_list, target): """ ------------------------------------------------------- Finds the locations of targets in num_list. Use: locations = find_value(num_list, target) ------------------------------------------------------- Parameters: num_list - list of numbers (list of int) target - value to look for in num_list (int) Returns: locations - list of indexes of target (list of int) ------------------------------------------------------- """

locations = [] for i in range(len(num_list)): if num_list[i] == target: locations.append(i) return locations from functions import keep_positive, find_value numbers = keep_positive() print() print("List entered: {}".format(numbers)) print() target = int(input("Enter target = ")) print() locations = find_value(numbers, target) print("Target exists at location: {}".format(locations)) Enter a positive number: 9 Enter a positive number: 11 Enter a positive number: 32 Enter a positive number: 17 Enter a positive number: -5 Enter a positive number: 9 Enter a positive number: 33 Enter a positive number: -5 Enter a positive number: 8 Enter a positive number: 0 List entered: [9, 11, 32, 17, 9, 33, 8] target = 9 target exists at location [0,4]

#q3 def keep_positive(): """ ------------------------------------------------------- Gets a list of positive numbers from a user. Negative numbers are ignored. User must enter 0 to stop entries. Use: numbers = keep_positive() ------------------------------------------------------- Returns: numbers - A list of positive integers (list of int) ------------------------------------------------------ """

numbers = [] value = int(input("Enter a positive number: ")) while value != 0: if value > 0: numbers.append(value) value = int(input("Enter a positive number: ")) return numbers from functions import keep_positive numbers = keep_positive() print() print("List entered: {}".format(numbers)) Enter a positive number: 1 Enter a positive number: 2 Enter a positive number: 3 Enter a positive number: 0 List entered: [1, 2, 3] Enter a positive number: -1 Enter a positive number: -2 Enter a positive number: -3 Enter a positive number: 7 Enter a positive number: 0 List entered: [7]

#q1 def winning(): """ ------------------------------------------------------- Counts the number of times the strings 'red' and 'green' are entered by a user. Use: counts = win_game() ------------------------------------------------------- Returns: counts - list of number of times 'red' was entered and number of times 'green' was entered (list of int) ------------------------------------------------------- """

red_count = 0 green_count = 0 string = input('Enter the winning team: ') while string != "": # Convert to lower case for consistency string = string.lower() if string == 'red': red_count += 1 elif string == 'green': green_count += 1 string = input('Enter the winning team: ') return (red_count, green_count) counts = winning() print() print('Number of "red" entered: {}'.format(counts[0])) print('Number of "green" entered: {}'.format(counts[1])) if counts[0] > counts[1]: print('red team wins!!!') elif counts[0] < counts[1]: print('green team wins!!!') else: print("tie") Enter the winning team: red Enter the winning team: green Enter the winning team: red Enter the winning team: red Enter the winning team: blue Enter the winning team: green Enter the winning team: Number of red entered: 3 Number of green entered: 2 red team wins!!!

#t06 def list_stats(values): """ ------------------------------------------------------- Returns statistics about values in a list. values has at least one element. Use: smallest, largest, total, average = list_stats(values) ------------------------------------------------------- Parameters: values - a list of values (list of float) Returns: smallest - the smallest number in values (float) largest - the largest number in values (float) total - total of numbers in list (float) average - the average numbers in values (float) ------------------------------------------------------- """

smallest = values [0] largest = values [0] total = 0 for a in values: if a < smallest: smallest = a for i in values: if i > largest: largest = i for num in values: total = total + num length = len(values) average = total / length return(smallest, largest, total, average)


Ensembles d'études connexes

Addition and Multiplication Rules of Probability

View Set

LATIN 2 principle parts and passive etc

View Set

T6 - IE4 - Oncology - Yang - Skin Cancer and Melanoma

View Set

CREATING COMPOUNDS: INVESTIGATING CHEMICAL CHANGES

View Set

Mental Health Evolve Quiz Study Guide

View Set

Chapter 8 - Confidence Interval Estimation

View Set

Chpt. 22,23,24 Mastering Biology

View Set

QBO 4 - The Profit and Loss and Balance Sheet reports

View Set