You could call it a homework problem. I am doing a CodeWar challenge, basically, I get a string of numbers and I am supposed to return maximum and minimum values. I got this close of completing this problem but there is an issue. For example, "1 2 3 4 555" should return "555 1". I know about max
and min
functions but I don't need this yet.
I created a for loop for every x in a list of given string I made. For example "1 2 3 4 555"
changed to list ["1", " ", "2", " ", "3", " ", "4", " ", "5", "5", "5"]
. I have nested some if
statements to add x or a number in string to new array with a few conditions. ["1", " ", "2", " ", "3", " ", "4", " ", "5", "5", "5"]
--> [1, 2, 3, 555]
. Instead I get [1, 2, 3]
. I have gotten [1, 2, 3, 555]
or any array without missing an element, now this.
This is my code. I want [1, 2, 3, 555]
instead of [1, 2, 3]
. Then I will use max
and min
functions to get min and max values.
def high_and_low(numbers):
numbers = numbers
toList = list(numbers)
print(toList)
newList = []
string = ''
for x in toList:
if x != ' ': #number
string += x
print(string)
else: #elif x == ' ': #anything that's not a number. Space for example
newList.append(int(string)) #we 'add' number to new list before space. Converted number string to integar.
#then
string = '' #reset to empty so we can add next number to empty without worrying about adding number we do not need.
print(newList) #[1,2,3] instead of [1, 2, 3, 555] is what I wanted. If I called high_and_low("1 2 3 555 3"), I can get [1, 2, 3, 555]
high_and_low("1 2 3 555") # return "555 1"
Same code without comments:
def high_and_low(numbers):
numbers = numbers
toList = list(numbers)
print(toList)
newList = []
string = ''
for x in toList:
if x != ' ':
string += x
print(string)
else: #elif x == ' ':
newList.append(int(string))
string = ''
print(newList)
high_and_low("1 2 3 555") # return "555 1"
I expect the output of [1, 2, 3, 555]
, but the actual output is [1, 2, 3]
. If I called high_and_low("1 2 3 555 3")
, I can get [1, 2, 3, 555]
.
Aucun commentaire:
Enregistrer un commentaire