I have written code for the zig-zag problem on LeetCode. The function works correctly when I use a multi-line for loop. However the current print
statement outputs a generator function. I tried using the *
key but it didn't seem to work.
How do I unpack this generator function?
The output I want is a string, not a list.
Thanks
def zigzag (word, num_rows):
array = []
for _ in range(num_rows):
array.append([])
increasing = 1
array_index = 0
word_index = 0
while word_index < len(word):
if increasing:
array[array_index].append(word[word_index])
array_index +=1
word_index +=1
else:
array[array_index].append(word[word_index])
array_index -=1
word_index +=1
if array_index == -1 and increasing == 0:
increasing = 1
array_index = 1
if array_index == num_rows and increasing == 1:
increasing = 0
array_index = num_rows - 2
return array
if __name__ == "__main__":
word = "PAYPALISHIRING"
num_rows = 4
print ("".join(line) for line in zigzag(word, num_rows))
One line for-loop:
print ("".join(line for array in zigzag(word, num_rows) for line in array))
# PINALSIGYAHRPI
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.