Reputation: 13
def main():
result = ""
cards = ["2","3","5","5","J"]
previous = cards[0]
current = cards[1]
i = 1
while i < len(cards) and result == "" :
previous = cards[i - 1]
current = cards[i]
if current == previous:
result = result + current
result = result + previous
i = i + 1
print(result)
main()
#Need this to work with 2 characters as in instead of the number list i would like ["2D","3C","5H","5D","JS"]
, But I'm not sure how to do it...
Upvotes: 1
Views: 66
Reputation: 16935
Here's a more Pythonic solution which uses itertools
:
test.py
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def main():
result = ""
cards = ["2D","3C","5H","5D","JS"]
# Generate adjacent pairs
for prev, curr in pairwise(cards):
# Append `prev` to `curr` if the first character is the same.
if prev[0] == curr[0]:
result = curr + prev
print(result)
if __name__ == "__main__":
main()
The function pairwise
will take an iterable, s = ["s0", "s1", "s2", "s3"]
, which can be iterated over by two elements that are adjacent. That said, you can look at the "current" and the "next" or the "previous" and the "current". I chose prev
and curr
because next
is a keyword in Python (see its use in pairwise
, actually).
You can do something like
for prev, curr in pairwise(s):
print("prev: {}, curr: {}".format(prev, curr))
This would print:
prev: s0, curr: s1
prev: s1, curr: s2
prev: s2, curr: s3
You can then check the first element of each string with string indexing.
07:35 $ python3 test.py
5H5D
Upvotes: 0
Reputation: 5384
String objects support indexing. For example
string = 'ABC123'
string[0] | 'A'
string[-1] | '3'
string[0:3] | 'ABC'
So by using if current[0] == previous[0]:
you are checking the first value of the strings.
def main():
result = ""
cards = ["2D","3C","5H","5D","JS"]
previous = cards[0]
current = cards[1]
i = 1
while i < len(cards) and result == "":
previous = cards[i-1]
current = cards[i]
if current[0] == previous[0]:
result = previous + current
i = i + 1
print(result)
main()
Upvotes: 1
Reputation: 1461
In the line previous = [i-1]
you forgot to put the cards[i-1]
If you want to put the two digits, but compare only the number of your cards, you can just compare the first char of the string:
if current[0] == previous[0]:
result = result + current
result = result + previous
This printed to me 5D5H
Upvotes: 1