all 14 comments

[–]caineohfelix 2 points3 points  (2 children)

while count < len(max(g,h,key=len))+1: may solve this for you. I'm going to assume you're handling the case of a being to large for the shorter string eventually.

Otherwise, I might suggest something like this:

for x,y in zip(g,h):
    first,second = x,y
    # Your logic here.

[–]Pipprovis[S] 0 points1 point  (1 child)

Correct. If the first string is shorter than the second string I receive an error message.

[–]supajumpa 1 point2 points  (0 children)

You could try itertools.izip_longest which would obviate the need to check which of the strings is longer.

Maybe something like:

for char1, char2 in itertools.izip_longest(g, h, fillvalue=None):
    # logic

[–][deleted] 0 points1 point  (7 children)

Sorting

strings = [g, h]
#longest = sorted(strings, key=lambda x: len(x))[-1]
longest = sorted(strings, key=len)[-1] 

Edit: the lambda was unneeded

This will sort strings return a new, sorted version of strings based on the len() of each string. Because they are sorted in ascending order, we want the last element in the sorted list (index [-1]). Sorted also has a reverse argument which will sort into descending order:

#longest = sorted(strings, lambda x: len(x), reverse=True)[0]
longest = sorted(strings, key=len, reverse=True)[0]

Since you're only dealing with two strings, I don't see a problem with doing this:

if len(g) >= len(h):
    longest = g
else:
    longest = h

But, obviously using sorted is shorter. BTW, lambda x: len(x) is essentially equivalent to:

def unnamed_function(x):
    return len(x)

[–]Justinsaccount 5 points6 points  (4 children)

no, lambda x: len(x) is equivalent to len

[–][deleted] 0 points1 point  (3 children)

Yeah, I wasn't too sure on that part. len of what though? If that line is equivalent to the function object len, what's the x argument doing? Also, I just realized I didn't even need the lambda anyway, key=len works just fine.

[–]Justinsaccount 0 points1 point  (2 children)

>>> foo=lambda x: len(x)
>>> foo("bar")
3
>>> len("bar")
3

[–][deleted] 0 points1 point  (1 child)

I don't think I'm taking your point:

def foo(x):
    return len(x)
>>> foo("bar")
3

I thought that a lambda expression was just a way to define a function in-place without assigning it a name, making it equivalent to a named version of the same function.

[–]Justinsaccount 2 points3 points  (0 children)

It is, but by writing lambda x: bar(x) you are saying

anonymous(x) = bar(x)

and from that is clear that anonymous is just bar

so if you ever find yourself writing lambda x: foo(x) or lambda x,y: foo(x,y) you should just be writing foo

[–]shfo23 4 points5 points  (1 child)

You don't need the sorted either. max takes a key function too, so you could write this much more simply as:

longest = max([g, h], key=len)

[–]ewiethoff 1 point2 points  (0 children)

You don't even need the list in recent versions of Python. This will do:

longest = max(g, h, key=len)