Homework and Popcorn Hacks for Lessons 3.4
Strings
Java script and python strings are any text wrapped with quotation marks, but once the value of them is established they can't be changed, to add two different strings next to each other you just use a '+' symbol.
Popcorn Hacks
# Define the variables
movie = "Inside Out 2"
sport = "Basketball"
pet_name = "Biscuit"
# String Concatenation
message_concatenation = "Hello, my favorite movie is " + movie + ". My favorite sport is " + sport + " and my pet’s name is " + pet_name + "."
print("Using Concatenation:")
print(message_concatenation)
# String Interpolation (f-string)
message_interpolation = f"Hello, my favorite movie is {movie}. My favorite sport is {sport} and my pet’s name is {pet_name}."
print("\nUsing Interpolation:")
print(message_interpolation)
This program shows two different ways of combining variables into a string: concatenation (using the + operator) and interpolation (using f-strings). Both methods output the same result, but f-strings are generally preferred for their readability and simplicity. In my code I used concatination by joining strings and variables together using a + symbol : message_concatenation = “Hello, my favorite movie is “ + movie + “. My favorite sport is “ + sport + “ and my pet’s name is “ + pet_name + “.”.
// Given string
let sentence = "A journey of a thousand miles begins with a single step";
// Using the slice() method
let sliced1 = sentence.slice(0, 10); // First 10 characters
let sliced2 = sentence.slice(2, 20); // Characters from index 2 to 20
let sliced3 = sentence.slice(-10); // Last 10 characters
let sliced4 = sentence.slice(2, -2); // Characters from index 2 to the second last character
// Printing the results
console.log("First 10 characters: ", sliced1); // A journey
console.log("Characters from index 2 to 20: ", sliced2); // journey of a th
console.log("Last 10 characters: ", sliced3); // single step
console.log("Characters from index 2 to second last: ", sliced4); // journey of a thousand miles begins with a singl
This program demonstrates how to extract different parts of a string using the slice() method. The method allows for extracting from specific start to end position of characters in a string, and also uses negative indices to count from the end of the string. First i let the sentence be ‘let sentence = “A journey of a thousand miles begins with a single step”;’, using the value i set to the sentence the slice will only take the first 10 characters, so outputting ‘A journey’, using this code : let sliced1 = sentence.slice(0, 10);
def remove_vowels(sentence):
vowels = "aeiouAEIOU" # String of vowels
modified_sentence = ""
# Loop through each character in the sentence
for char in sentence:
if char not in vowels:
modified_sentence += char # Add non-vowel characters to the modified sentence
return modified_sentence
# Test the function
test_sentence = "A journey of a thousand miles begins with a single step."
result = remove_vowels(test_sentence)
print("Modified Sentence (using loop):", result)
I put a function remove_vowels() that removes all vowels (both lowercase and uppercase) from a given sentence and returns the modified sentence with only consonants and other non-vowel characters.
def remove_vowels(sentence):
vowels = "aeiouAEIOU" # String of vowels
# Use list comprehension to filter out vowels and join the characters back into a string
modified_sentence = ''.join([char for char in sentence if char not in vowels])
return modified_sentence
# Test the function
test_sentence = "A journey of a thousand miles begins with a single step."
result = remove_vowels(test_sentence)
print("Modified Sentence (using list comprehension):", result)
This version of the remove_vowels() function uses list comprehension to remove vowels from a given sentence, which is a more efficient way of performing the same task, I used list comprehension here : modified_sentence = ‘‘.join([char for char in sentence if char not in vowels]), which creates a list of characters from the sentence where each char is included only if it is not in the vowels string, then the join() method is used to combine the remaining characters back into a single string without any vowels.
def reverse_words(sentence):
# Split the sentence into words
words = sentence.split()
# Reverse the list of words
reversed_words = words[::-1]
# Join the reversed list back into a string
reversed_sentence = ' '.join(reversed_words)
return reversed_sentence
# Test the function with different sentences
test_sentence_1 = "A journey of a thousand miles begins with a single step."
test_sentence_2 = "Python is an amazing programming language."
test_sentence_3 = "Keep calm and carry on."
# Output the results
print("Original Sentence 1:", test_sentence_1)
print("Reversed Sentence 1:", reverse_words(test_sentence_1))
print()
print("Original Sentence 2:", test_sentence_2)
print("Reversed Sentence 2:", reverse_words(test_sentence_2))
print()
print("Original Sentence 3:", test_sentence_3)
print("Reversed Sentence 3:", reverse_words(test_sentence_3))
The function splits the sentence into words, then reverses the order of the words using list slicing, then joins the words back together to form a new sentence. For example, words = sentence.split(), which returns the sentence output reversed
Homework Hacks
%%js
function generateGreeting(firstName, lastName) {
// Using string concatenation
var greetingConcat = "Hello, " + firstName + " " + lastName + "!";
// Using template literals (interpolation)
var greetingTemplate = `Hello, ${firstName} ${lastName}!`;
console.log(greetingConcat); // Output using concatenation
console.log(greetingTemplate); // Output using interpolation
}
// Test the function
generateGreeting("Shriya", "Paladugu");
<IPython.core.display.Javascript object>
In this code I used two different ways to create a greeting message in JavaScript: string concatenation and interpolation. Interpolation is when you embed variables directly into the string using ${}. While concatenation is when you join variables and strings together using a + symbol.
def is_palindrome(input_string):
# Remove spaces and convert to lowercase for accurate comparison
cleaned_string = ''.join(input_string.split()).lower()
# Check if the cleaned string is equal to its reverse
return cleaned_string == cleaned_string[::-1]
# Test the function with various inputs
test_strings = [
"A man a plan a canal Panama", # Palindrome
"Hello World", # Not a palindrome
"Racecar", # Palindrome
"Basketball" # Not a palindrome
]
for test in test_strings:
result = is_palindrome(test)
print(f"Is '{test}' a palindrome? {result}")
I used python to defines a function, is_palindrome(input_string) that checks whether a given string is a palindrome, where it reads the same forward and backward. The ‘cleaned_string = ‘‘.join(input_string.split()).lower()’, input_string.split() splits the string by spaces, then the .join will bring the string back together, then the .lower will convert all the text to lowercase.