Thursday, March 10, 2022

bread sandwiches Python Codewars

Task:

If you're not familiar with the fantastic culinary delights of the British Isles you may not know about the bread sandwich.

The idea is very simple - if you have a slice of bread between two other slices of bread, then it's a bread sandwich. Additionally, if you have a bread sandwich between two other slices of bread, you get a bread sandwich sandwich, and so on.

In this kata, we will define the following terms like so:

  • Sandwich - Two slices of bread which may or may not have a filling
  • Bread Sandwich - Two slices of bread which contains one slice of bread in the middle as a filling

You will need to build two functions:

  • Given the number of slices of bread, return the phrase used to refer to the sandwich
     2 - 'sandwich'
     5 - 'bread sandwich sandwich'
    
  • The reverse function - given the name of the sandwich, return how many slices of bread there are in the sandwich
    'bread sandwich' - 3
    'sandwich sandwich' - 4
    
  • You should return None if there is no input / the input is invalid / there is no sandwich

Solution:


def slices_to_name(n):
    res = ''
    if type(n) != int or n < 2:
        return None
    if n >= 2:
        if n % 2 == 0:
            res += 'sandwich '* int(n/2)
        else:
            res += 'bread sandwich ' + 'sandwich '* int((n - 3)/2)
    return res.rstrip(' ')

def name_to_slices(name):
    print(name)
    if type(name) != str or name == '':
        return None
    name_s = name.split()
    if len(name_s) == 1 and name_s[0] == 'sandwich':
        return 2
    elif len(name_s) == 2:
        if name_s[0] == 'bread' and name_s[1] == 'sandwich':
            return 3
        elif name_s[0] == 'sandwich' and name_s[1] == 'sandwich':
            return 4
    elif len(name_s) > 2:
        if 'bread' in name_s[2:]:
            return None
        elif name_s[0] == 'bread' and name_s[1] == 'sandwich':
            return 3 + (len(name_s[2:])*2 )
        elif name_s[0] == 'sandwich' and name_s[1] == 'sandwich':
            return 4 + (len(name_s[2:])*2)

    else:
        return None

def slices_to_name(n):
    return (('bread '*(n%2) + 'sandwich '*(n//2)).strip() if isinstance(n, int) and n > 1 else None)

def name_to_slices(name):
    if not (isinstance(name, str) and 'sandwich' in name): return

    if name.find('bread') < 1:
        return name.count('sandwich')*2 + name.count('bread')

bread sandwiches Solutions | Codewars



Related Posts


No comments :

Post a Comment