简体   繁体   中英

Finding if a reversed string has a match in a list of strings

I am learning Python, one month in and I am struggling with the following problem:

An ice cream shop has a list of flavors:

FLAVORS = [ "Banana", "Chocolate", "Lemon", "Pistachio", "Raspberry", "Strawberry", "Vanilla", ]

They want to build a list of all the alternatives of a 2 balls flavoured ice creams. The flavours cannot be repeated: ie. Chocolate Banana cannot be listed as Banana Chocolate is already in the list. I have to print the list.

Here's my code:

result = []
sub_result = ""

for ice in FLAVORS:
       for other_ice in FLAVORS:
            
            if ice == other_ice:
                continue
                
            sub_result = ice + ", " + other_ice

            if reversed(sub_result) in result:
                continue
        
            result.append(sub_result)
        
print ('\n'.join([item for item in result ])) '''

I cannot get the script to bypass the reversed iteration of the favours.

First of all, reversed reverses an iterable. It returns an iterator, not a string! And you don't want to reverse the string, because that would give you things like 'nomeL ,etalocohC' .

Secondly, make use of the fact that you already know which items you already have in the reverse order!

FLAVORS = [ "Banana", "Chocolate", "Lemon", "Pistachio", "Raspberry", "Strawberry", "Vanilla"]

result = []

for i, ice in enumerate(FLAVORS):
       for other_ice in FLAVORS[i + 1:]:
            result.append(f'{first_flavor} {second_flavor}')
        
print('\n'.join(result))

Using sub_result = ice + ", " + other_ice makes sub_result a string. For example, for Banana and Chocolate , you get 'Banana, Chocolate' . You need ('Banana', 'Chocolate') .

You need to use a tuple or list instead:

sub_result = tuple(reversed((ice, other_ice)))

Notice the cast to tuple - This is because reversed returns an object, not the reverse of the input. The object has to interpreted as the required type.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM