Skip to content

Instantly share code, notes, and snippets.

@AnisahTiaraPratiwi
AnisahTiaraPratiwi / ListComprehensions.py
Created March 23, 2021 05:27
The odd_numbers function returns a list of odd numbers between 1 and n, inclusively. Fill in the blanks in the function, using list comprehension. Hint: remember that list and range counters start at 0 and end at the limit minus 1.
def odd_numbers(n):
return [x for x in range(0,n+1) if x%2 != 0]
print(odd_numbers(5)) # Should print [1, 3, 5]
print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9]
print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11]
print(odd_numbers(1)) # Should print [1]
print(odd_numbers(-1)) # Should print []
@AnisahTiaraPratiwi
AnisahTiaraPratiwi / Enumerate.py
Created March 23, 2021 04:23
Try out the enumerate function for yourself in this quick exercise. Complete the skip_elements function to return every other element from the list, this time using the enumerate function to check if an element is on an even position or an odd position.
def skip_elements(elements):
# code goes here
element = [e for i, e in enumerate(elements) if i % 2 == 0]
return element
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
@AnisahTiaraPratiwi
AnisahTiaraPratiwi / ModifyingList.py
Created March 23, 2021 03:33
The skip_elements function returns a list containing every other element from an input list, starting with the first element. Complete this function to do that, using the for loop to iterate through the input list.
def skip_elements(elements):
# Initialize variables
new_list = []
i = 0
# Iterate through the list
for i in range(len(elements)):
# Does this element belong in the resulting list?
if i%2 ==0:
# Add this element to the resulting list
@AnisahTiaraPratiwi
AnisahTiaraPratiwi / List.py
Created March 23, 2021 01:54
Using the "split" string method from the preceding lesson, complete the get_word function to return the {n}th word from a passed sentence. For example, get_word("This is a lesson about lists", 4) should return "lesson", which is the 4th word in this sentence. Hint: remember that list indexes start at 0, not 1.
def get_word(sentence, n):
# Only proceed if n is positive
if n > 0:
words = sentence.split()
# Only proceed if n is not more than the number of words
if n <= len(words):
return(words[n-1])
return("")
print(get_word("This is a lesson about lists", 4)) # Should print: lesson
@AnisahTiaraPratiwi
AnisahTiaraPratiwi / Strings4.py
Created March 22, 2021 08:17
The replace_ending function replaces the old string in a sentence with the new string, but only if the sentence ends with the old string. If there is more than one occurrence of the old string in the sentence, only the one at the end is replaced, not all of them. For example, replace_ending("abcabc", "abc", "xyz") should return abcxyz, not xyzxy…
def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence
if sentence.endswith(old):
# Using i as the slicing index, combine the part
# of the sentence up to the matched string at the
# end with the new string
i = sentence.rindex(old)
new_sentence = sentence[:i]+new
return new_sentence
@AnisahTiaraPratiwi
AnisahTiaraPratiwi / Strings3.py
Created March 22, 2021 08:16
Question 4 Fill in the gaps in the nametag function so that it uses the format method to return first_name and the first initial of last_name followed by a period. For example, nametag("Jane", "Smith") should return "Jane S."
def nametag(first_name, last_name):
return("{} {[0]}.".format(first_name, last_name))
print(nametag("Jane", "Smith"))
# Should display "Jane S."
print(nametag("Francesco", "Rinaldi"))
# Should display "Francesco R."
print(nametag("Jean-Luc", "Grand-Pierre"))
# Should display "Jean-Luc G."
@AnisahTiaraPratiwi
AnisahTiaraPratiwi / Strings2.py
Created March 22, 2021 08:16
Using the format method, fill in the gaps in the convert_distance function so that it returns the phrase "X miles equals Y km", with Y having only 1 decimal place. For example, convert_distance(12) should return "12 miles equals 19.2 km".
def convert_distance(miles):
km = miles * 1.6
result = "{} miles equals {:.1f} km".format(miles, km)
return result
print(convert_distance(12)) # Should be: 12 miles equals 19.2 km
print(convert_distance(5.5)) # Should be: 5.5 miles equals 8.8 km
print(convert_distance(11)) # Should be: 11 miles equals 17.6 km
@AnisahTiaraPratiwi
AnisahTiaraPratiwi / Strings1.py
Created March 22, 2021 08:15
The is_palindrome function checks if a string is a palindrome. A palindrome is a string that can be equally read from left to right or right to left, omitting blank spaces, and ignoring capitalization. Examples of palindromes are words like kayak and radar, and phrases like "Never Odd or Even". Fill in the blanks in this function to return True …
def is_palindrome(input_string):
# We'll create two strings, to compare them
new_string = ""
reverse_string = ""
# Traverse through each letter of the input string
for string in input_string.lower():
# Add any non-blank letters to the
# end of one string, and to the front
# of the other string.
if string.replace(" ",""):
@AnisahTiaraPratiwi
AnisahTiaraPratiwi / FormattingStrings.py
Created March 22, 2021 06:48
Modify the student_grades function using the format method, so that it returns the phrase "X received Y% on the exam". For example, student grade("Reed", 80) should return "Reed received 80% on the exam".
def student_grade(name, grade):
return ("{} received {}% on the exam" .format(name, grade))
print(student_grade("Reed", 80))
print(student_grade("Paige", 92))
print(student_grade("Jesse", 85))
@AnisahTiaraPratiwi
AnisahTiaraPratiwi / MoreString.py
Created March 22, 2021 06:26
Fill in the gaps in the initials function so that it returns the initials of the words contained in the phrase received, in upper case. For example: "Universal Serial Bus" should return "USB"; "local area network" should return "LAN”
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0].upper()
return result
print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS