P3 3 3 255 192 192 192 0 0 255 192 192 192 0 0 255 0 0 255 0 0 255 192 192 192 0 0 255 192 192 192a. A black X b. A blue cross
fields = line.split(",")Ans: A list is a sequence of items like a = [3, 2, 5, 4] or b = ["dog", "cat", "mouse"]. The items are accessed by zero-basec index: a[0] is 3; b[1] is "cat".
a = [4, 1, 7, 5, 8] print(a[3]) # Output: 5
a = [4, 1, 7, 5, 8] print(a[4] - a[1], a[4 - 1], a[-2])a[-2] is the second item from the end of the list.
a = [4, 1, 7, 5, 8] total = 0 for n in a: total += n print(total) # Output: 25
t = 1 s = "2 1 4 6" a = s.split(" ") for val in a: t *= int(val) print(t) # Output: 48
s = input("Input a string: ") lst = list(s) print(s)We can combine these three lines into one like this:
print(list(input("Input a string: ")))
s = ["d", "o", "g"] t = ":".join(s) u = "".join(s) print(t) # Output: d:o:g dog
Method Name | Input Parameter(s) | Return Value | Side Effects* |
---|---|---|---|
rm_vowels | input_string | Input string with vowels removed | None |
factors | number | List of factors | None |
# Remove vowels input_str = print("Enter input string: ") input_str = gets.chomp output_str = "" for letter in input_str: letter = letter.upper( ) if letter != 'A' and letter != 'E' and letter != 'I' \ letter != 'O' and letter != 'U': output_str += letter print("String without vowels", output_str) # Ans: def rm_vowels(input_string): output_str = "" for letter in input_str: letter = letter.upper( ) if letter != 'A' and letter != 'E' and letter != 'I' \ letter != 'O' and letter != 'U': output_str += letter return output_str string = print("Enter input string: ") processed_string = rm_vowels(string) print("String without vowels", processed_string)
# Obtain list all factors of input integer. n = int(input("Enter a positive integer: ")) factors = [ ] for f in range(2, n): if n % f == 0 factors.append(f) print(factors) # Ans: def factors(number): # 1 and number are always factors so we can # add them to the list without checking. factors = [1] for f in range(2, number): if number % f == 0 factors.append(f) factors.append(number) return factors n = int(input("Enter a positive integer: ")) print(factors(n))