This repository was archived by the owner on Jun 20, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctionsAndLoops.py
More file actions
96 lines (79 loc) · 2.51 KB
/
Copy pathFunctionsAndLoops.py
File metadata and controls
96 lines (79 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# Given a string and a non-negative int n, we('ll say that the front of
# the string is the first 3 chars, or whatever is there if the string is less than length
# 3. Return n copies of the front;)
#
# front_times('Chocolate', 2) → 'ChoCho'
# front_times('Chocolate', 3) → 'ChoChoCho'
# front_times('Abc', 3) → 'AbcAbcAbc'
def main():
s = input("str: ")
n = int(input("int: ")) # Convert input to integer
print(front_times(s, n)) # Call the function with appropriate arguments
def front_times(s, n):
front_len = 3 # Define the number of characters for the "front"
if front_len > len(s): # Adjust if the string is shorter than 3 chars
front_len = len(s)
front = s[:front_len]
result = ""
for i in range(n):
result += front # String concatenation shorthand
return result
main()
# Given a string, return a new string made of every other char starting with the first,
# so "Hello" yields "Hlo".
#
# string_bits('Hello') → 'Hlo'
# string_bits('Hi') → 'H'
# string_bits('Heeololeo') → 'Hello'
def main():
s = input("str: ")
print(string_bits(s))
def string_bits(str):
result = ""
for i in range(len(str)):
if i % 2 == 0:
result = result + str[i]
return result
main()
# Given an array of ints, return the number of 9's in the array.
#
# array_count9([1, 2, 9]) → 1
# array_count9([1, 9, 9]) → 2
# array_count9([1, 9, 9, 3, 9])
# Given an array of ints, return the number of 9's in the array.
#
# array_count9([1, 2, 9]) → 1
# array_count9([1, 9, 9]) → 2
# array_count9([1, 9, 9, 3, 9])
def array_count9(nums):
count = 0
for num in nums:
if num == 9:
count += 1
return count
def main():
print(array_count9([1, 2, 9])) # Output: 1
print(array_count9([1, 9, 9])) # Output: 2
print(array_count9([1, 9, 9, 3, 9])) # Output: 3
main()
#
# Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere.
# array123([1, 1, 2, 3, 1]) → True
# array123([1, 1, 2, 4, 1]) → False
# array123([1, 1, 2, 1, 2, 3]) → True
def array123(nums):
# Note: iterate with length-2, so can use i+1 and i+2 in the loop
for i in range(len(nums) - 2):
if nums[i] == 1 and nums[i + 1] == 2 and nums[i + 2] == 3:
return True
return False
def main():
test_cases = [
[1, 1, 2, 3, 1],
[1, 1, 2, 4, 1],
[1, 1, 2, 1, 2, 3]
]
for case in test_cases:
print(f"array123({case}) -> {array123(case)}")
# Call the main function
main()