<jupyter_start><jupyter_text>Answers to Assignment 4 - Python Fundamentals IIComplete the tasks below. Please turn in a single Jupyter notebook named `4_first_last.ipynb` (substitute your first and last name). Please run Kernel > Restart & Run All on your notebook before turning in.  Answer to A. Lists and loops1. Create a list of 10 random integers in the range of -100 to 100. 2. Loop through that list using a for loop. Put the non-negative (positive or zero) integers into a new list. If negative integers are encountered, print a message saying that the value is negative and printing that value.<jupyter_code>import random
# one way
list1 = random.sample(range(-100,100), 10)
list1
# another way
list1 = [random.randrange(-100, 100) for i in range(10)]
list1
list2 = []
for item in list1:
    if item >= 0:
        list2.append(item)
    else:
        print('The value of %s is negative' % item)
list2<jupyter_output>The value of -82 is negative
The value of -3 is negative
The value of -64 is negative<jupyter_text>Answer to B. Functions, lists, and loops1. Write a function that does what you did in part A but with the following differences:     - The input list can be any list of numbers.    - The function should take as a parameter a threshold for being included in the new list (e.g., if you want non-negative integers, the threshold would be 0, and the function would check if values are >= to this value).    - The printed message for failing to be included should also report the threshold parameter.    - The new list should be returned by the function.2. Execute the function on your list of 10 random integers.<jupyter_code>def new_list_from_criterion(mylist, mycutoff):
    newlist = []
    for item in mylist:
        if item >= mycutoff:
            newlist.append(item)
        else:
            print('The value of %s is not >= %s' % (item, mycutoff))
    return(newlist)
new_list_from_criterion(list1, -0)<jupyter_output>The value of -82 is not >= 0
The value of -3 is not >= 0
The value of -64 is not >= 0<jupyter_text>Answer to C. Dictionaries and list enumeration1. Create a two-dimensional list with 3 'rows' and 4 'columns' and a mixture of strings and integers. 2. Loop through each element of the list and check if each element is a string or an integer. Save the strings as a dictionary with the index (row, column) as the key and the string as the value. Save the integers as a dictionary with the index (row, column) as the key and the integer as the value.3. Print out your dictionaries (no `print` command required).<jupyter_code>list2d = [[1, 'mango', 3, 'oranges'],
          ['peach', 'apple', 50, -50],
          [13, -11, 'bananas', 'grape']]
list2d
strdict = {}
intdict = {}
for row_index, row in enumerate(list2d):
    for col_index, item in enumerate(row):
        if isinstance(item, str):
            strdict[(row_index, col_index)] = item
        elif isinstance(item, int):
            intdict[(row_index, col_index)] = item
strdict
intdict<jupyter_output><empty_output><jupyter_text>Answer to D. List comprehension and saving files1. Create a list of 5 strings that are first and last names, e.g. `'<NAME>'`. 2. Use a list comprehension (a single-line command) to get the first initial from each name and store each string (e.g. `'J'`) in a new list. Print this list (no `print` command required).3. Repeat but store both the first and last initial (e.g. `'JD'`) in a new list. Print this list (no `print` command required).4. Save this second list to a text file.<jupyter_code>names = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>']
first_initial = [name[0] for name in names]
first_initial
first_last_initial = [name.split(' ')[0][0] + name.split(' ')[1][0] for name in names]
first_last_initial
with open('../../data/assign4_q4.txt', 'w') as target:
    for initials in first_last_initial:
        target.write(initials)
        target.write('\n')<jupyter_output><empty_output><jupyter_text>Answer to E. Reading files, sets, and saving files1. Download this text file of past [World Series winners](https://github.com/cuttlefishh/python-for-data-analysis/blob/master/data/world_series_winners.txt). 2. Read in the lines of the file to a list, so that each line is an element of the list. 3. Create a new list with just those list elements that contain 'New York'; print that list, making sure there's not an extra newline character between each line. Print this list (no `print` command required).4. Use the `set` class to convert the list of all World Series winners to a list of unique values. Print this list (no `print` command required).5. Write the output to a new file.<jupyter_code># one way
with open ('../../data/world_series_winners.txt', "r") as f:
    winners = f.read().splitlines()
# another way
with open('../../data/world_series_winners.txt', 'r') as f:
    winners = f.readlines()
winners = [team.rstrip() for team in winners]
new_york_winners = [team for team in winners if 'New York' in team]
new_york_winners
unique_winners = set(winners)
unique_winners
with open('../../data/assign4_q5.txt', 'w') as target:
    for team in sorted(list(unique_winners)):
        target.write(team)
        target.write('\n')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10080490609428899, 'fraction_numerical': 0.018014564967420467, 'mean_word_length': 3.827937095282146, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 33, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '546576', 'license': 'MIT', 'n_tokens_mistral': 1615, 'n_tokens_neox': 1551, 'n_words': 696, 'path': 'assignments/answers/assignment4_answers.ipynb', 'repo_name': 'aiegoo/python-for-data-analysis', 'size': '5253'}