Click here to Skip to main content
14,882,205 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
We are working in a group of four and have spent the last few hours tring to debug/fix our code to get the right output. Below you will find our code the list in which the string is in and required output. Please help.

Our code is:
Python
def reverse(my_list, number):    
    string = ""
    new_list = []
    count = 0

    if number > len(my_list):
        number = len(my_list)
    if number < 2:
        for k in my_list:
            new_list.append(k)
        return my_list

    for index in range(number-1,-1,-1):
        new_list.append(my_list[index])

    for index in range (number, len(my_list)):
        new_list.append(my_list[index])

    return new_list


list in which string is in:
Python
print("\nreverse Test")
str_list6 = ['e', 'd', 'u', 'd']
str_list7 = ['m', 'o', 'b', 'b', 'e', 'd']
new_list = list_function.reverse(str_list6, 4)
print(new_list)
new_list = list_function.reverse(str_list7, 3)
print(new_list)
new_list = list_function.reverse(str_list6)
print(new_list)


Required output is:

Python
reverse Test
['d', 'u', 'd', 'e']
['b', 'o', 'm', 'b', 'e', 'd']
['d', 'u', 'd', 'e']


What I have tried:

We are working in a group of four and have spent the last few hours tring to debug/fix our code to get the right output. Below you will find our code the list in which the string is in and required output. Please help.
Posted
Updated 26-Oct-16 7:22am
Comments
Richard MacCutchan 26-Oct-16 13:04pm
   
The input parameters suggest that you take the length parameter and reverse that number of characters, and then append the remainder. If there is no length parameter then take the length of the list.

1 solution

Try this:
Python
def reverse(my_list, number = 0):
    newlist = []
    if number == 0:
        number = len(my_list)
    for x in range(number-1, -1, -1):
        newlist.append(my_list[x])
    for x in range(number, len(my_list)):
        newlist.append(my_list[x])
    return newlist
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900