6.6k views
3 votes
# 35.3) Hot and Cold

A scientist has been recording observations of the temperature for the past
while. On hot days, they write "H", and for cold days, they write "C". Instead
of using a list, they kept all of these observations in a single long string
(e.g., "HCH" would be a hot day, followed by a cold day, and then another hot
day).

Write a function `add_hot_cold` that consumes a string of observations and
returns the number of hot days minus the number of cold days. To accomplish
this, you should process each letter in turn and add 1 if it is hot, and -1 if
it is cold. For example, the string "HCH" would result in 1, while the string
"CHCC" would result in -2.

You cannot use the built-in `.count()` method or the `len()` function for this
problem.

Don't forget to unit test your function.

User Cebe
by
4.5k points

1 Answer

6 votes

Answer: Code

Step-by-step explanation:

#add_hot_cold function

def add_hot_cold(obs):

"""

takes a string of observations as input

and returns the number of hot days minus

the number of cold days.

>>> add_hot_cold("CHCC")

-2

>>> add_hot_cold("HHHHHCCCHCHHHCHCHC")

4

>>>

"""

#set nday to 0

nday = 0

#process each letter in the string

for char in obs:

#if it is a hot day, add 1

if char == "H":

nday = nday + 1

#if it is a cold day, add -1

elif char == "C":

nday = nday - 1

#return nday

return nday

#Call the function on the string "HHHHHCCCHCHHHCHCHC" and print the result

print(add_hot_cold("HHHHHCCCHCHHHCHCHC"))

Note - The above code might not be indented. Please indent your code according to the below screenshot.

Sample Output:

Code Screenshot:

# 35.3) Hot and Cold A scientist has been recording observations of the temperature-example-1
# 35.3) Hot and Cold A scientist has been recording observations of the temperature-example-2
User PJQuakJag
by
4.5k points