Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialGuntas Singh
2,107 Pointsinstances.py
Please Tell The mistakes Its Not WorkinG
def combiner(list):
strings=[]
numbers=[]
n=0
for item in list:
if isinstance(item,str)==True:
strings.append(item)
else:
numbers.append(item)
while True:
if n<len(strings):
strings[n+1]+=strings[n]
n=n+1
else:
break
while True:
if n<len(numbers):
numbers[n+1]=numbers[n+1]+numbers[n]
n=n+1
else:
break
return str(strings+numbers)
1 Answer
Chris Freeman
Treehouse Moderator 68,457 PointsThe length of the lists of strings and numbers will be 1 larger than the last index. For example, a list of 5 items will have indexes 0,1,2,3,4.
The if statements will cause an index error during the last iteration where n is one less than the list length. On this iteration, the += statement references n + 1. This is now beyond the last index.
change the if condition to n < (len(string) - 1)
. Fix bothe if statements.
Once this is fixed, the code runs but produces the wrong output:
combiner([3,6,"apple",5, "banana"])
# produces
['apple', 'bananaapple', 3, 6, 11]
It appears the string joining code is no producing a single string.
use "".join(strings)
to join the list of strings into a single string.
The numbers need summed together.
use str(sum(numbers))
to combine the numbers into a string of the sum.
return these two resulting strings combined
Post back if you need more help. Good luck!!!
Guntas Singh
2,107 PointsThanku Sir...But I didnt understood Why I cant Sum My Numbers Like This In a Loop.....By Using Sum() method The program Runs But Not This Way......and Also Y Cant i Join My Strings Using Loop Like I Have Done...! Please Tell The Solution without using join and Sum() methods..! Thnku
Chris Freeman
Treehouse Moderator 68,457 PointsI also noticed that the loop counter n
needs to reset to zero between while
loops.
The process you are using replaces a list item with the sum of itself and the previous item. So in the end, provide the loop limit gets fixed as mentioned above, the last item in the list has the total combined element. So you'd only need to return the last element.
return strings[-1] + str(numbers[-1])
sepehr akbarzadeh
Python Web Development Techdegree Student 1,762 Pointssepehr akbarzadeh
Python Web Development Techdegree Student 1,762 PointsError: list index out of range your loop consider more than list's memory. Check your loop