Get Help With a similar task to - Functions and Lists

Login to view and/or buy answers.. or post an answer
Additional Instructions:

Overview · Part 1 listutils.py - a few short exercises to practice working with functions and lists · do this part first! · in the next part, you'll be able to use this file as a module and potentially reuse some of the code that you've already written · Part 2 choose 2 of the 3 to do… if you do the third, it will count as extra credit towards your homework grade 2. syllabic_poetry.py: generate a haiku, tanka, randomly generated syllabic poem or user specified syllabic poem based on a hardcoded list of words 2. mydate.py and birthday.py: run a simulation to approximate the probability of two people having the same birthday (the birthday paradox) 2. drawing.py: create 3 functions for drawing shapes with turtle Part 1 - listutils.py In this part, you'll be writing a few short functions that work with lists. Some of these functions already have built-in counterparts in Python, but we'll implement our own to practice loops, accumulators, and working with lists. Consequently: 1. some of the instructions will specify functions, methods, and operators that you will not be allowed to use 2. additionally, the instructions will also specify the parameters and return values of each function you'll be writing. Once you're done with this file, you can use it as a module! This means that you may be able to reuse some the functions that you create here in the next part(s). 1. Download listutils.py by right-clicking and choosing Save As 2. Then write the following functions… get_duplicates(lst) Parameters: · lst - a list that will be searched for duplicate values Return Value: · a new list containing the elements that occur more than once in the original list Description: get_duplicates will return an entirely new list consisting of the elements in the original list passed in, lst, that occur more than once (that are repeated / duplicated). Each of these elements should appear only once in the newly returned list. For example, if the original list were ['cat', 'cat', 'cat', 'cat', 'dog', 'bat', 'ant', 'ant'], then the resulting list would be ['cat', 'ant'] because cat and ant occur more than once. Show Hint Example Usage: duplicates = get_duplicates([1, 2, 3, 1, 4, 2]) print(duplicates) # --> [1, 2] because both 1 and 2 have duplicates has_duplicates(lst) Parameters: · lst - a list that will be searched for duplicate values Return Value: · True if the lst passed in has duplicate values, False otherwise Description: has_duplicates will return a boolean value, True or False, depending on whether or not the list passed in as an argument has at least one element that occurs more than once Show Hint Example Usage: result1 = has_duplicates([1, 2, 3, 1, 4])) print(result1) # --> True result2 = has_duplicates([1, 2, 3, 4, 5])) print(result2) # --> False join_elements_with(glue, lst): Parameters: · glue - a string that will be placed between each element in the lst passed in · lst - a list of elements that will be joined together to form a new string Return Value: · a string composed of all elements from lst connected by glue Description: join_elements takes a list and turns it into a string! It does this by creating a string that is composed of all of the elements in the original lst passed in as an argument and placing the string, glue, between each element. For example, if lst were ['Alice', 'Bob', 'Carol'], and the glue were ---, then the resulting string would be Alice---Bob---Carol. Note that there is built-in string method, called join, that already does this. ⚠️ Do not use the built-in join method to write yours. It may be helpful to find out if you're looking at the last element in the list. One way to do this, with the concepts that we already know, is to use a simple count to keep track of which element the loop is on. Another alternative is to use a for loop with a range where the range generates every possible index in the list, rather than looping over the list itself. Lastly, for those looking for a challenge, try to find out how to use the enumerate built-in function! Show Hint Example Usage: result = join_elements_with('X', ['cat', 'dog', 'bat']) print(result) # --> catXdogXbat fill(size, fill_value=0) Parameters: · size - an int specifying the number of elements in the new list · fill_value - a value of any type to fill the list with · the default value should be 0 · assume that value will be some immutable type, like an int, float or str · (you don't have to worry about repeating nested lists, for example) Return Value: · a new list with length size elements, each with value, fill_value Description: Create a new list filled with fill_value, size number of times Show Hint Example Usage: lst1 = fill(5) # [0, 0, 0, 0, 0] lst2 = fill(3, 'hi') # ['hi', 'hi', 'hi'] random_choose(lst): Parameters: · lst - a list of elements to randomly choose a value from Return Value: · one of the elements from the original list Description: random_choose returns a random element from the list, lst, passed in as an argument. You can use the random module's randint function to do this. Note that the random module actually already has a function that does this, called choose. ⚠️ Do not use random.choose in your implementation (though, again, random.randint is ok). Show Hint Example Usage: weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] weekday = random_choose(weekdays) # should print out a single weekday from list of weekdays print(weekday) random_fill(min_val, max_val, list_length) Parameters: · min_val - the minimum value for each randomly generated integer in new list · max_val - the maximum value for each randomly generated integer in new list · list_length - the number of elements in the newly generated list Return Value: · a list that consists of randomly generated integers Description: random_fill will create a new list with list_length elements in it. Each element will be a randomly generated integer between min_val and max_val inclusive. Show Hint Example Usage: new_list = random_fill(1, 10, 4) # should print out a list with 4 elements... # each w/ number from 1 - 10 print(new_list) stringify_elements(lst) Parameters: · lst - a list that has elements that will be converted to strings Return Value: · a list that consists of strings Description: stringify_elements will create a new list composed only of string versions of the elements in the original list. For example, the list [1, 2, 3] would result in ['1', '2', '3'] being returned Show Hint Example Usage: result = stringify_elements([1, 2, 3]) print(result) # --> should print out ['1', '2', '3'] (all elements are strings!) mean(lst) Parameters: · lst - a list of values (you can assume values will all be numeric, so no validation required) Return Value: · a float Description: Returns the average of all numbers in list. ⚠️ Do not use sum in your implementation Example Usage: print(mean([1, 2, 3, 4, 5])) # 3 Part 2 - Option #1 - syllabic_poetry.py For part 2, you can choose two out of three options to do, with the third as extra credit 1. generate syllabic poetry (this option) OR… 2. verify the "birthday" paradox using a simulation 3. make some drawing functions with turtle For this option, #1, you'll be writing a program that generates syllabic poetry based on a provided list of words which will be provided to you as an actual Python list of lists in the code to download. Your program will generate one of the following based on input from the user: 1. haiku 2. tanka 3. a 5 line syllabic poem with a random number of syllables per line 4. a poem whose lines and syllables per line are supplied by the user Your program will ensure that the poetry generated adheres to the number of syllables required by the poem specified (for example, in a haiku, there would be 17 syllables in 3 lines: 5, 7 and 5. However, content will not be taken into consideration. The words provided will be in a format of a list of lists. The outer list will contain seven sub lists of words. Each inner list represents a collection of words with a specific number of syllables. The number of syllables is based on the position of the inner list. The 1st list (at index 0) will have words that have 1 syllable, the 2nd list (and index 1) will have words that have 2 syllables, etc. Here's a short example, with ellipsis representing additional elements (there are more than 2 words in each sub list, and there are 7 sub lists: # 1 syllable words 2 syllable words [['age', 'roof', ...], ['stunner', 'sucrose', ...], ...] Assuming that the variable that contains this list of lists is called available_words, to retrieve a list of 2 syllables words, use available_words[1]. To retrieve the word stunner, use available_words[1][0] Feel free to modify this list of lists to suit the kind of content you'd like your poetry generator to create! To write this program: 1. Download syllabic_poetry.py by right-clicking and choosing Save As 2. Write the following functions to help with your program · generate_word · generate_line · generate_lines · feel free to import your listutils module from part 1 if you think any of those functions will be useful · you can write more functions if you want! 3. write an interactive program that asks the user to specify what kind of syllabic poetry to create generate_word(syllables_in_word) Parameters: · syllables_in_word - the number of syllables in the word to be generated Return Value: · a string - a randomly chosen word composed of the number of syllables specified by syllables_in_word… return None if the number of syllables given is not between 1 and 7 inclusive Description: generate_word is a function that is partially implemented. It contains a local variable that holds a list of lists. Each inner list is a list of strings. The position of the inner list in the containing list determines the number of syllables in each word that it has. The list of lists is partially shown below: # a local variable, available_words, within the generate_word # function will have the following list of lists # 1 syllable words 2 syllable words [['age', 'roof', ...], ['stunner', 'sucrose', ...], ...] Again, this list is already present in the file that you download. However, you can modify this word list to shape the content of the poetry your program generates. To complete the implementation, you will use the integer passed in as an argument, syllables_in_word, to randomly choose an element from available words. This randomly chosen word should be returned by the function. Assume that the argument passed in is a number. However, if the number of syllables given is less than one or more than seven, do not return anything (or return None). Show Hint Example Usage: word = generate_word(3) another_word = generate_word(1) # the following prints out a three syllable word # ... and a one syllable word (randomly chosen from # a set of words) print(word, another_word) # --> prints out randomly and word # this will return None because the number of syllables is less than 1 yet_another_word = generate_word(0) # --> None! generate_line(syllables_in_line) Parameters: · syllables_in_line - the total number of syllables in the line of poetry to generate Return Value: · a string that represents a series of words whose total number of syllables is equal to syllables_in_line Description: generate_line will create a string that contains a series of words whose total number of syllables is equal to the integer passed in, syllables_in_line. Each word in the series is randomly generated, and the number of syllables of each word is random as well, as long as it fits within the total number of syllables. For example, if the number 5 is passed in, this function will generate a string as a sequence of words with the total number of syllables equal to 5. This means that the combination of words may vary. Here are some potential combinations of words that all add up to 5 syllables: · team bureau slime rare (1 + 2 + 1 + 1) · immoveable age (4 + 1) · wearability (5) Show Hint Example Usage: line = generate_line(5): print(line) # --> immoveable age (or some other random series of words!) generate_lines(all_lines) Parameters: · all_lines - a list of numbers representing the number of syllables in each line; a 5 element list would mean that there are 5 lines in the poem… and each element in that list would represent the number of syllables for that specific line Return Value: · a new list that contains a line of words per element, with each line adhering to the number of syllables specified by the list, all_lines, passed in Description: generate_lines will create a list of lines of poetry based on the list of syllables per line passed in. The poem will be generated by choosing the words randomly, but still adhering the number of syllables specified per line. For example, if the list passed in is [5, 7, 5], then a poem with 3 lines, with the first line having 5 syllables, the 2nd line having 7 syllables and the last line, having 5 syllables, would be created. The poem that is generated will be a list of lines. There should be the same number of lines as the number of elements in the list passed in. Show Hint Example Usage: # the following should return a list of lines of a # randomly generated poem... # for example, it may return (as a single list, # and formatted with new lines for readability): # [ # 'persuasive pudding', # 'misauthorization flab', # 'acceptable queue' # ] syllables_per_line = [5, 7, 5] generate_lines(syllables_per_line) Ask the User to Generate a Poem! Using all of the functions that you defined above, create a program that asks the user what kind of poem they would like to generate: I would like to write some poetry for you. Would you like a... * (h)aiku * (t)anka * (r)andom 5 line poem, or do you want to * (s)pecify lines and syllables for each line? Once the user chooses the kind of poem to generate, the program will print out: 1. An abbreviated version of the number of syllables per line, separated by dashes · for example 5-7-5 is a three line poem with 5 syllables, 7, and finally 5 again on the last line · the output should look like Here is your poem (5-7-5): 2. The poem itself The poem that the program generates will be based on the input from the user: 1. If the user types in h or t, generate a haiku and a tanka poem respectively. · A Haiku has a 5-7-5 pattern of syllables per line (5 syllables for the first line, 7 for the second, 5 again for the last). · Here's an example of what a haiku may look like · Here is your poem (5-7-5): · ===== · flab lien trimming bowls · collapsibility big · second clearheaded · Tanka has 5-7-5-7-7 pattern. · And… an example of tanka · clearheaded chopper begone imprint their · hipper nonrevolution henchman fig · sprightliest trimming chit · cheekily · queue forbiddingness queue ate 2. If the user chooses r, then generate a 5 line poem with a random number of syllables per line (though, cap the syllables per line to a reasonable amount) · Here's an example of a randomly generated 5 line poem: · Here is your poem (5-7-5-7-7): · ===== · brail cathartic team · electrometallurgist · seditious rune rone · unruinable crouton · acceptable brown brown stir 3. Finally, if the user chooses s, then they will be allowed to specify the number of lines and syllables for each line by asking more questions: 3. ask for the number of syllables for the line, and include the line number in the question 3. How many syllables for lines 1? 3. then… print out the current number of lines and ask if they'd like to continue, 3. There are currently 1 lines. Add another line (y/n)? 3. if the answer is y, then go back to 1 to ask for the number of syllables in the next line 3. a full example interaction is below (note that the line number and current number of lines are specified) 3. How many syllables for line 1? 3. >3 3. There are currently 1 lines. Add another line (y/n)? 3. >y 3. How many syllables for lines 2? 3. >3 3. There are currently 2 lines. Add another line (y/n)? 3. >y 3. How many syllables for lines 3? 3. >12 3. There are currently 3 lines. Add another line (y/n)? 3. >n 18. the line number is specified 18. the current line count is displayed 3. An example of the poem that this generates may look like: 3. box nought depth 3. prevention 3. vapourizing profitably stunner rode miss 1. If the user does not type valid option, print out ERROR and your favorite poem about making a mistake 1. A crash reduces 1. Your expensive computer 1. To a simple stone. (From Netlingo haiku poetry error messages) Part 2 - Option #2 - mydate.py and birthday.py For part 2, you can choose from one of two options or do both: 1. generate syllabic poetry OR… 2. verify the "birthday" paradox using a simulation (this option!) 3. drawing.py: create 3 functions for drawing shapes with turtle Apparently, in a set of 23 randomly chosen people, there's a pretty good chance that two of those people will have the same birthday! Yes, it's actually true, and it's called the Birthday Problem or the Birthday Paradox. betterexplained.com has a good write-up on why, but we'll use a computer simulation to approximate this probability. We'll create tools to randomly generate dates, and then we'll see if any month and day combinations match. You'll be doing this in two parts: 1. write a bunch of functions to help with creating dates 2. create an interactive program that allows you to run the simulation multiple times 3. Download mydate.py and birthday.py by right-clicking and choosing Save As 4. Write the following functions in mydate.py to help implement your program: · is_valid_month_num(n) · month_num_to_string(month_num) · date_to_string(date_list) · dates_to_strings(date_list) · remove_years(date_list) · is_leap_year(year) · get_num_days_in_month · generate_date(start_year, end_year) · you can use your mylist.py as a module if any of those functions are helpful · you can write more functions if you want! 5. Using your previously implemented mydate.py as a module, import it and use it to help write birthday.py · In birthday.py, you'll write a simulation by generating random birthdays · The simulation will be an interactive program that asks the user how many trials to run… as well as other parameters for generating birthdays for a group of people · The percentage of times that at least one duplicate occurs should be printed out at the end is_valid_month_num(n) Parameters: · n - an integer representing a month, with 1 being January and 12 being December Return Value: · a boolean - True if number passed in is between 1 and 12 inclusive, False otherwise Description: is_valid_month_num will take a month in numeric format and return a boolean value based on whether that number is a valid month (1 through 12, inclusive) Example Usage: result1 = is_valid_month_num(3) print(result1) # True result2 = is_valid_month_num(37) print(result2) # False month_num_to_string(month_num) Parameters: · month_num - an integer representing a month, with 1 being January and 12 being December Return Value: · a string - the month name corresponding to the number passed in, None if the number passed in is invalid Description: month_num_to_string will take a month in numeric format and return a string representing the month's name (given a valid month number). If the month number passed in is not valid, None is returned (either implicitly by not returning anything or by explicitly returning None). Show Hint Example Usage: result1 = month_num_to_string(1) print(result1) # 'January' result2 = month_num_to_string(10) print(result2) # 'October' result3 = month_num_to_string(234) print(result3) # None date_to_string(date_list) Parameters: · date_list - a three-element list containing integers representing a year, month and day; for example, [2012, 3, 14] represents March 14th, 2012 Return Value: · a string - the string version of the date passed in as the original list; the format of the string returned is month_name day_number, year: March 14th, 2012 Description: date_to_string assumes that it will be passed a list containing valid numbers for year, month and day (you will not have to check the numbers passed in). Given [YEAR_NUMBER, MONTH_NUMBER, DAY_NUMBER], this function will construct a string in the format of MONTH_NAME DAY_NUMBER, YEAR_NUMBER where MONTH_NAME is determined by using one of the previous function with MONTH_NUMBER. For example, [1979, 10, 7] should give back 'October 7, 1979'. Show Hint Example Usage: date_to_string([1979, 10, 7]) # returns the string: October 7, 1979 dates_to_strings(list_of_date_lists) Parameters: · list_of_date_lists - a list containing dates, with each date being a sub list of composed of three elements (as described in date_to_string) Return Value: · a list - a list of string versions of each sub list (date) from the original list passed in Description: dates_to_strings converts a list of lists to a list of strings. Each inner list in the list of lists is a date in the format of a three-element list (as explained in the previous function). The result is a list of strings, with each string representing one of the original dates in the list passed in. For example, [[1979, 10, 7], [2000, 02, 20]] should give back ['October 7, 1979', 'February 20, 2000']. Example Usage: res = dates_to_strings([[1979, 10, 7], [2000, 02, 20]]) print(res) # ['October 7, 1979', 'February 20, 2000'] remove_years(list_of_date_lists) Parameters: · list_of_date_lists - a list containing dates, with each date being a sub list composed of three elements (as described in date_to_string) Return Value: · a list - a new list with 2-element sub lists representing a month and a day (year is removed) Description: remove_years creates a new list with the year element removed for every sub list in a list of date lists. This essentially converts a list of three-element lists to a list of two-element lists. Example Usage: res = remove_years([[1979, 10, 7], [2000, 02, 20]]) print(res) # [[10, 7], [2, 20]] is_leap_year(year) Parameters: · year - an int specifying the year to check Return Value: · a boolean - True if the year, year, is a leap year, False otherwise Description: Determines whether a year is a leap year or not using this algorithm from microsoft. Returns True or False accordingly. Show Hint Example Usage: for year in [1988, 1992, 1996, 1600, 2000, 2400]: print(is_leap_year(year)) # True for each one! for year in [1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600]: print(is_leap_year(year)) # False for each one! get_num_days_in_month(month_num, year) Parameters: · month_num - an int specifying the month number · year - an int specifying the year to check Return Value: · an int - the number of days for the month represented by month_num at year, year or None if the month_num passed in is not valid Description: Determines the number of days in a month given a month (in the format of a number from 1 through 12), as month_num and a year as year. Leap years should be taken into account (February may have 28 or 29 days). You can map months with their days by storing number of days in a list. The position of the number of days in the list will help determine what month it's in. If the month number passed in is not between 1 and 12, inclusive, then give back None (this could be done implicitly by no having a return or by explicitly returning None). Show Hint Example Usage: get_num_days_in_month(2, 1988) # 29 get_num_days_in_month(2, 1900) # 28 get_num_days_in_month(11, 1900) # 30 get_num_days_in_month(12, 1900) # 31 get_num_days_in_month(1, 1900) # 31 get_num_days_in_month(30, 1999) # None generate_date(start_year, end_year) Parameters: · start_year - an int specifying the minimum year that the randomly generated date may have · end_year - an int specifying the maximum year that the randomly generated date may have Return Value: · a list - a new list consisting of 3 ints: a year, month number, and a day Description: generate_date creates a date with random, month, day and year using other functions from this module. The date generated must have a year that falls within start_year and end_year. It must also generate a valid month number (1 through 12)… and lastly a valid number of days (including a valid number of days for February during leap years). Show Hint Example Usage: date = generate_date(2015, 2017) print(date) # a random 3 element list, like: [2017, 9, 5] Interactive Program (birthday.py) Once you've finished your functions, write an interactive program that simulates creating a group of people, each with a random birthday. To do this: 1. Download birthday.py if you haven't done so already 2. import your mydate module (also import listutils if you find any of those functions useful) 3. First, ask how many times the simulation should be run 4. How many times should I run the simulation? 5. Then, ask wow many birthdays should be generated 6. How many birthdays should I generate per trial? 7. Once you have the user input… 8. repeat the following based on the number of trials specified by the user: 1. generate the number of birthdays specified (you can use and start and end year to create these dates) 2. remove the years from the dates 3. find the dates that occur more than once 4. print out the following: · the trial number · the number of dates that occur more than once · and a comma separated list of the duplicate dates, in parentheses 5. here's some example output: 6. Trial #1: 2 dates occur more than once! (August 2, April 24) 7. Trial #2: 1 date occurs more than once! (September 16) 8. How many times should I run the simulation? 9. Trial #3: No dates are the same. 10. . 11. . 12. . 9. After running all of the trials specified… . calculate the probability that there will be duplicates by… . taking the count of trials where at least one date occurred more than once . …and dividing that by the number of trials specified . output the resulting number as a percentage with the following information: 4. the total number of trials 4. the total number of trials that had a birthday that occurred more than once 4. the probability of a duplicate 4. the number of birthdays generated for every trial . for example: . Results: . ===== . Out of 7 trials, 4 had dates that were repeated . We can conclude that you have a 57.14% chance of sharing a birthday with someone if you are in a group of 23 people · An example of a full run of the program is below: How many times should I run the simulation? >7 How many birthdays should I generate per trial? >23 Trial #1: 2 dates occur more than once! (August 2, April 24) Trial #2: 1 date occurs more than once! (September 16) Trial #3: No dates are the same. Trial #4: 2 dates occur more than once! (February 4, July 21) Trial #5: No dates are the same. Trial #6: 1 date occurs more than once! (September 14) Trial #7: No dates are the same. Results: ===== Out of 7 trials, 4 had dates that were repeated We can conclude that you have a 57.14% chance of sharing a birthday with someone if you are in a group of 23 people Part 2 - Option #3 - drawing.py def line(t, coord1, coord2) · t is a turtle object passed in · coord1 and coord2 are 2-element lists that represent x, y coordinates · draws a line from coord1 to cord2 def poly(t, *coords) · t is a turtle object passed in · *\coords is any number of x, y coordinates… each as a 2-element list · draws a polygon based on coords (will close off polygon by drawing a line from last coord to first) def rectangle(t, coord, width, height, color) · t is a turtle object passed in · coord is upper left corner of rectangle · assume width and height are ints · color is the color to fill with · (use t.color('red'), t.begin_fill(), and t.end_fill()) Example code: import turtle t = turtle.Turtle() wn = turtle.Screen() rectangle(t, [0, 0], 100, 200, 'green') t.color('blue') poly(t, [100, 100], [50, 50], [-50, 50]) poly(t, [-100, 100], [-100, 50], [-200, 50], [-200, 100], [-150, 0]) #poly(t, [0, 0], 100, 200) wn.mainloop()

Related Questions

Similar orders to Functions and Lists
6
Views
0
Answers
Creating a DNS server (written in C)
WANT >=50% due to being swamped (only standard option minimal, don't care about cache or non-blocking). I require periodic updates of code with a description as there is a Git commit tracking. Also require a makefile according to the specifications and a g...
20
Views
0
Answers
Create inheritance project for a restaurant
Projects must include: -at least three different levels of inheritance - at least nine classes total -the highest superclass must have at least two methods -every subclass must contain a unique method that was not present in its super...
16
Views
0
Answers
Python Code for Suggesting Pets
Must have ___init___ ; ___str___ ; for loops ; while loops ; and must define a function which returns something, I wrote down what idea I had in that form so its best to follow it, this is an entry-level computer science project so it should be pretty easy...
23
Views
0
Answers
Quick HW Computer Science on LL(1) and object creation
Due at 12:00pm today. The question details are in the files attached. One question is on the impact of a parser being LL(1) or not. Another is on imagining a mistake in object creation. The answers are probably max 2 lines long....