Jumper
June 15, 2021, 6:27am
1
How I can make this more pythonic
def triple_sequence(start, length):
new_ls = [start]
while len(new_ls) < length:
new_ls.append( new_ls[-1] * 3)
return new_ls
print(triple_sequence(2, 4)) # => [2, 6, 18, 54]
print(triple_sequence(4, 5)) # => [4, 12, 36, 108, 324]
Jagaya
June 15, 2021, 6:37am
2
Python has a neat feature called “list comprehension”.
thingy = [a+ 3 for a in range(4)]
thingy == [3, 4, 5, 6]
Jumper
June 15, 2021, 7:47am
3
This is no quite what my code does. Each number supposed to be three times the previous one except for first number which is called start.
Jagaya
June 15, 2021, 7:53am
4
That’s just an example code for list-comprehension saying “Yes, it can be more pythonic”.
Ofcourse you have to do this yourself
I could write it, but the idea of the forum is to help people find solutions, not writing it for them.
1 Like
@Jumper You can use a recursive function to do what it is you are trying to do.
I recommend trying find a way to do it with list comprehension as Jagaya suggests.
def triple_sequence(start, length):
sequence = []
if length == 0:
return sequence
else:
sequence.append(start)
start = start * 3
return sequence + triple_sequence(start, length-1)
system
Closed
December 18, 2021, 3:09pm
6
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.