comp-think / 2019-2020

The GitHub repository containing all the material related to the Computational Thinking and Programming course of the Digital Humanities and Digital Knowledge degree at the University of Bologna (a.a. 2019/2020).
Other
12 stars 3 forks source link

Lecture "Brute-force algorithms", exercise 5 #20

Open essepuntato opened 4 years ago

essepuntato commented 4 years ago

Write in Python the function def my_reversed(input_list) which behave like the built-in function reversed() introduced in Section "Insertion sort" and returns a proper list, and accompany the function with the related test case. It is not possible to use the built-in function reversed() in the implementation.

arcangelo7 commented 4 years ago
def my_reversed(input_list):
    reversed_list = list()
    list_length = len(input_list)

    for index in range(list_length):
        reversed_list.append(input_list[list_length - index - 1])

    return reversed_list

def test_my_reversed(input_list, expected):
    result = my_reversed(input_list)

    if result == expected:
        return True
    else:
        return False

print(test_my_reversed(["Coraline", "American Gods", "The Graveyard Book", "Good Omens", "Neverwhere"], ['Neverwhere', 'Good Omens', 'The Graveyard Book', 'American Gods', 'Coraline']))
# It prints True
sntcristian commented 4 years ago

Screenshot (9)

NoonShin commented 4 years ago
def my_reversed(input_list):
    input_length = len(input_list)
    output = list()

    for i in range(input_length):
        output.append(input_list[input_length-i-1])

    return output

def test_my_reversed(input, expected):
    return my_reversed(input) == expected

volumes = ['Preludes and Nocturnes', 'The Dolls House', 'Dream Country', 'Season of Mists', 'A Game of You', 'Fables and Reflections', 'Brief Lives', 'Worlds End', 'The Kindly Ones', 'The Wake']

print(test_my_reversed(volumes, list(reversed(volumes))))
FrancescoFernicola commented 4 years ago

My version works but it takes some more steps than the others. I forgot to consider range/index which would've probably been a better way to deal with the problem. Props to @arcangelo7 @sntcristian and @NoonShin!

Screenshot 2019-11-07 17 21 00

essepuntato commented 4 years ago

Hi all,

please find attached my personal solution – also available online:

# Test case for the function
def test_my_reversed(input_list, expected):
    result = my_reversed(input_list)
    if expected == result:
        return True
    else:
        return False

# Code of the function
def my_reversed(input_list):
    l = list()
    for item in input_list:
        l.insert(0, item)
    return l

# Tests
print(test_my_reversed([], []))
print(test_my_reversed([1], [1]))
print(test_my_reversed([1, 2, 4, 3, 4, 7, 2], [2, 7, 4, 3, 4, 2, 1]))
print(test_my_reversed(["a", "b", "c", "d"], ["d", "c", "b", "a"]))
aschimmenti commented 4 years ago

lista reversed 1 lista reversed 2