Dec-19-2020, 06:06 AM
Hi folks, I've just started learning programming and as I was making my way through various online beginner exercises, I came across one that asked to write a basic program which required to copy (n) times the first two characters of any given string and if the string is shorter than two characters- copy the first character (n) times.
My idea of going about it was this:
here's another exercise example to check if a number exists in given list:
My way:
My idea of going about it was this:
def substring_copy(string, copies): if len(string) >= 2: return string[:2] * copies return string * copies print(substring_copy('abcdef', 2)) print(substring_copy('p', 3))The actual answer for the exercise was:
def substring_copy(str, n): flen = 2 if flen > len(str): flen = len(str) substr = str[:flen] result = "" for i in range(n): result = result + substr return result print(substring_copy('abcdef', 2)) print(substring_copy('p', 3));They both give the same result and for sure I always feel delighted to write a shorter block of code, however before I get into a habit of writing short but unstable blocks of code any advice on what to avoid? Or why one way is better than the other?
here's another exercise example to check if a number exists in given list:
My way:
def look_for_nr(nr_list, nr): return nr in nr_list print(look_for_nr([1, 5, 8, 3], 3)) print(look_for_nr([5, 8, 3], -1))Actual answer:
def look_for_nr(nr_list, nr): for value in nr_list: if nr == value: return True return False print(look_for_nr([1, 5, 8, 3], 3)) print(look_for_nr([5, 8, 3], -1))Any feedback highly appreciated !