Leetcode problem 14. Longest Common Prefix (Python)

2024/10/7 22:22:12

I tried to solve the problem (you can read description here: https://leetcode.com/problems/longest-common-prefix/) And the following is code I came up with. It gives prefix value of the first string in strs list and compares prefix with every string from the list, popping all characters that are not equal.

class Solution:def longestCommonPrefix(self, strs: List[str]) -> str:prefix = strs[0][0]for i in range(len(strs)):for j in range(len(prefix)):if strs[i][j] != prefix[j]:prefix.pop(prefix[j])return prefix

But this code fails in the very first testcase where strs = ["flower","flow","flight"] Expected output is "fl", while my code returns just "f" I am struggling to find what is going wrong in my solution. Maybe you can help?

Answer

Iterate over the characters in parallel with zip:

strs = ["flower", "flow", "flight"]n = 0
for chars in zip(*strs):if len(set(chars)) > 1:breakn += 1# length
print(n) # 2# prefix
print(strs[0][:n]) # fl

Similar approach as a one-liner using itertools.takewhile:

from itertools import takewhileprefix = ''.join([x[0] for x in takewhile(lambda x: len(set(x)) == 1, zip(*strs))])
https://en.xdnf.cn/q/118768.html

Related Q&A

Python BS: Fetching rows with and without color attribute

I have some html that looks like this (this represents rows of data in a table, i.e the data between tr and /tr is one row in a table)<tr bgcolor="#f4f4f4"> <td height="25"…

Python multiple number guessing game

I am trying to create a number guessing game with multiple numbers. The computer generates 4 random numbers between 1 and 9 and then the user has 10 chances to guess the correct numbers. I need the fee…

How to produce a graph of connected data in Python?

Lets say I have a table of words, and each word has a "related words" column. In practice, this would probably be two tables with a one-to-many relationship, as each word can have more than o…

Syntax for reusable iterable?

When you use a generator comprehension, you can only use the iterable once. For example.>>> g = (i for i in xrange(10)) >>> min(g) 0 >>> max(g) Traceback (most recent call la…

Buildozer Problem. I try to make apk file for android, but i cant

artur@DESKTOP-SMKQONQ:~/Suka$ lsbuildozer.spec main.pyartur@DESKTOP-SMKQONQ:~/Suka$ buildozer android debugTraceback (most recent call last):File "/usr/local/bin/buildozer", line 10, in <…

how to run python script with ansible-playbook?

I want to print result in ansible-playbook but not working. python script: #!/usr/bin/python3import timewhile True:print("Im alive")time.sleep(5)deploy_python_script.yml:connection: localbeco…

How to concatenate pairs of row elements into a new column in a pandas dataframe?

I have this DataFrame where the columns are coordinates (e.g. x1,y1,x2,y2...). The coordinate columns start from the 8th column (the previous ones are irrelevant for the question) I have a larger exam…

Python: using threads to call subprocess.Popen multiple times

I have a service that is running (Twisted jsonrpc server). When I make a call to "run_procs" the service will look at a bunch of objects and inspect their timestamp property to see if they s…

Find a substring [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 5…

Image processing with single to multiple images

I have an Image showing below: I need to crop the order using python coding. What I need is only the card. So I want to crop the border. How to do it??This is the output I got using the code mentione…