Skip to content

Instantly share code, notes, and snippets.

@sjrusso8
Last active April 6, 2021 21:35
Show Gist options
  • Save sjrusso8/0e1656f83d1ab684b25e1085f034e147 to your computer and use it in GitHub Desktop.
Save sjrusso8/0e1656f83d1ab684b25e1085f034e147 to your computer and use it in GitHub Desktop.
Code Questions
# Response to two code questions
# These functions can be further improved by type checking the input values with `isinstance`
import re
string_arr = "the lazy brown fox jumped over the big pile of junk."
def count_char_length(string):
"""Return the dictionary containing the max word length based on the first letter of each word
I added a re.sub statement to remove punctuation
Excepted output
>>> count_char_length("the lazy brown fox jumped over the big pile of junk.")
{'t': 3, 'l': 4, 'b': 5, 'f': 3, 'j': 6, 'o': 4, 'p': 4}
"""
answer_dict = {}
cleaned_string = re.sub(r'[^\w\s]','',string)
for _, word in enumerate(cleaned_string.split()):
if word[0] in answer_dict and len(word) >= answer_dict[word[0]]:
answer_dict[word[0]] = len(word)
# I had 'else' originally and it was being evaluated if the above logic was FALSE
# This caused the dictionary value to be overwritten because the logic in the if statement evaluated as FALSE
# changed to elif and added an 'else' with pass
elif word[0] not in answer_dict:
answer_dict[word[0]] = len(word)
else:
pass
return answer_dict
count_char_length(string_arr)
from itertools import combinations
target, num_arr = 8, [8,1,4,19,-11,6,4,0]
def find_target_sum(target, num_arr):
"""Find what two array values sum together to equal the target input
I slighly changed my original function to use list comprehension instead of a traditional for loop
>>> find_target_sum(8, [8,1,4,19,-11,6,4,0])
[(8, 0), (4, 4), (19, -11)]
"""
valid_combination = combinations(num_arr, 2)
return [(k,j) for k, j in valid_combination if k + j == target]
find_target_sum(target, num_arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment