Datasets:

inputs
stringlengths
50
14k
targets
stringlengths
4
655k
The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive. For example: ```python count_char("fizzbuzz","z") => 4 count_char("Fancy fifth fly aloof","f") => 5 ``` The character can be any alphanumeric character. Good luck.
def count_char(s, c): return s.upper().count(c.upper())
The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive. For example: ```python count_char("fizzbuzz","z") => 4 count_char("Fancy fifth fly aloof","f") => 5 ``` The character can be any alphanumeric character. Good luck.
from collections import Counter def count_char(s, c): return Counter(s.lower())[c.lower()]
The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive. For example: ```python count_char("fizzbuzz","z") => 4 count_char("Fancy fifth fly aloof","f") => 5 ``` The character can be any alphanumeric character. Good luck.
def count_char(string, letter): s = string.lower() l = letter.lower() return s.count(l)
The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive. For example: ```python count_char("fizzbuzz","z") => 4 count_char("Fancy fifth fly aloof","f") => 5 ``` The character can be any alphanumeric character. Good luck.
def count_char(str, char): return str.lower().count(char.lower())
The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive. For example: ```python count_char("fizzbuzz","z") => 4 count_char("Fancy fifth fly aloof","f") => 5 ``` The character can be any alphanumeric character. Good luck.
def count_char(text, char): return text.lower().count(char.lower())
The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive. For example: ```python count_char("fizzbuzz","z") => 4 count_char("Fancy fifth fly aloof","f") => 5 ``` The character can be any alphanumeric character. Good luck.
count_char=lambda s,c:s.lower().count(c.lower())
The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive. For example: ```python count_char("fizzbuzz","z") => 4 count_char("Fancy fifth fly aloof","f") => 5 ``` The character can be any alphanumeric character. Good luck.
def count_char(line, c): line = line.lower() return line.count(c.lower())
The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive. For example: ```python count_char("fizzbuzz","z") => 4 count_char("Fancy fifth fly aloof","f") => 5 ``` The character can be any alphanumeric character. Good luck.
def count_char(a,b): a=a.lower() b=b.lower() return a.count(b)
# Background I drink too much coffee. Eventually it will probably kill me. *Or will it..?* Anyway, there's no way to know. *Or is there...?* # The Discovery of the Formula I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers! For * ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD) * ```CAFE``` is a cup of *regular* coffee * ```DECAF``` is a cup of *decaffeinated* coffee To determine the life-time coffee limits: * Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD` * If the test subject can survive drinking five thousand cups wihout being ```DEAD``` then coffee has no ill effect on them # Kata Task Given the test subject's date of birth, return an array describing their life-time coffee limits ```[ regular limit , decaffeinated limit ]``` ## Notes * The limits are ```0``` if the subject is unaffected as described above * At least 1 cup must be consumed (Just thinking about coffee cannot kill you!) # Examples * John was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well. * Susan (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan. * Elizabeth (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk? * Peter (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!! Hint: https://en.wikipedia.org/wiki/Hexadecimal *Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.*
def coffee_limits(year, month, day): h = int(f'{year:04}{month:02}{day:02}') return [limit(h, 0xcafe), limit(h, 0xdecaf)] def limit(h, c): for i in range(1, 5000): h += c if 'DEAD' in f'{h:X}': return i return 0
# Background I drink too much coffee. Eventually it will probably kill me. *Or will it..?* Anyway, there's no way to know. *Or is there...?* # The Discovery of the Formula I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers! For * ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD) * ```CAFE``` is a cup of *regular* coffee * ```DECAF``` is a cup of *decaffeinated* coffee To determine the life-time coffee limits: * Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD` * If the test subject can survive drinking five thousand cups wihout being ```DEAD``` then coffee has no ill effect on them # Kata Task Given the test subject's date of birth, return an array describing their life-time coffee limits ```[ regular limit , decaffeinated limit ]``` ## Notes * The limits are ```0``` if the subject is unaffected as described above * At least 1 cup must be consumed (Just thinking about coffee cannot kill you!) # Examples * John was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well. * Susan (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan. * Elizabeth (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk? * Peter (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!! Hint: https://en.wikipedia.org/wiki/Hexadecimal *Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.*
def coffee_limits(year, month, day): health = int(f"{year:04d}{month:02d}{day:02d}") drinks = (int(d, 16) for d in ("cafe", "decaf")) return [next((cup for cup in range(1, 5001) if "dead" in f"{health + drink*cup:x}"), 0) for drink in drinks]
# Background I drink too much coffee. Eventually it will probably kill me. *Or will it..?* Anyway, there's no way to know. *Or is there...?* # The Discovery of the Formula I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers! For * ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD) * ```CAFE``` is a cup of *regular* coffee * ```DECAF``` is a cup of *decaffeinated* coffee To determine the life-time coffee limits: * Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD` * If the test subject can survive drinking five thousand cups wihout being ```DEAD``` then coffee has no ill effect on them # Kata Task Given the test subject's date of birth, return an array describing their life-time coffee limits ```[ regular limit , decaffeinated limit ]``` ## Notes * The limits are ```0``` if the subject is unaffected as described above * At least 1 cup must be consumed (Just thinking about coffee cannot kill you!) # Examples * John was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well. * Susan (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan. * Elizabeth (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk? * Peter (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!! Hint: https://en.wikipedia.org/wiki/Hexadecimal *Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.*
CAFE, DECAF = 51966, 912559 def coffee_limits(y, m, d): n = int(''.join([str(y), str(m).zfill(2), str(d).zfill(2)])) A = lambda x : next((i for i in range(1,5001) if 'dead' in hex(n+(i*x))[2:]),0) return [A(CAFE), A(DECAF)]
# Background I drink too much coffee. Eventually it will probably kill me. *Or will it..?* Anyway, there's no way to know. *Or is there...?* # The Discovery of the Formula I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers! For * ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD) * ```CAFE``` is a cup of *regular* coffee * ```DECAF``` is a cup of *decaffeinated* coffee To determine the life-time coffee limits: * Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD` * If the test subject can survive drinking five thousand cups wihout being ```DEAD``` then coffee has no ill effect on them # Kata Task Given the test subject's date of birth, return an array describing their life-time coffee limits ```[ regular limit , decaffeinated limit ]``` ## Notes * The limits are ```0``` if the subject is unaffected as described above * At least 1 cup must be consumed (Just thinking about coffee cannot kill you!) # Examples * John was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well. * Susan (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan. * Elizabeth (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk? * Peter (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!! Hint: https://en.wikipedia.org/wiki/Hexadecimal *Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.*
def coffee_limits(year, month, day): health = int(f"{year:04d}{month:02d}{day:02d}") limit = lambda drink: next((cup for cup in range(1, 5001) if "dead" in f"{health + drink*cup:x}"), 0) return [limit(int(drink, 16)) for drink in ("cafe", "decaf")]
# Background I drink too much coffee. Eventually it will probably kill me. *Or will it..?* Anyway, there's no way to know. *Or is there...?* # The Discovery of the Formula I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers! For * ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD) * ```CAFE``` is a cup of *regular* coffee * ```DECAF``` is a cup of *decaffeinated* coffee To determine the life-time coffee limits: * Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD` * If the test subject can survive drinking five thousand cups wihout being ```DEAD``` then coffee has no ill effect on them # Kata Task Given the test subject's date of birth, return an array describing their life-time coffee limits ```[ regular limit , decaffeinated limit ]``` ## Notes * The limits are ```0``` if the subject is unaffected as described above * At least 1 cup must be consumed (Just thinking about coffee cannot kill you!) # Examples * John was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well. * Susan (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan. * Elizabeth (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk? * Peter (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!! Hint: https://en.wikipedia.org/wiki/Hexadecimal *Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.*
import re def coffee_limits(year, month, day): # Your code here! h_cafe = str(year) if len(str(month)) == 1: h_cafe += "0" + str(month) else: h_cafe += str(month) if len(str(day)) == 1: h_cafe += "0" + str(day) else: h_cafe += str(day) h_cafe = int(h_cafe) h_decaf = h_cafe n = 0 cafe = 0 decaf = 0 print(h_cafe) while (n < 5000): h_cafe += 51966 h_decaf += 912559 n += 1 if "dead" in hex(h_cafe): if cafe == 0 : cafe = n elif "dead" in hex(h_decaf): if decaf == 0: decaf = n return [cafe,decaf]
# Background I drink too much coffee. Eventually it will probably kill me. *Or will it..?* Anyway, there's no way to know. *Or is there...?* # The Discovery of the Formula I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers! For * ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD) * ```CAFE``` is a cup of *regular* coffee * ```DECAF``` is a cup of *decaffeinated* coffee To determine the life-time coffee limits: * Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD` * If the test subject can survive drinking five thousand cups wihout being ```DEAD``` then coffee has no ill effect on them # Kata Task Given the test subject's date of birth, return an array describing their life-time coffee limits ```[ regular limit , decaffeinated limit ]``` ## Notes * The limits are ```0``` if the subject is unaffected as described above * At least 1 cup must be consumed (Just thinking about coffee cannot kill you!) # Examples * John was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well. * Susan (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan. * Elizabeth (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk? * Peter (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!! Hint: https://en.wikipedia.org/wiki/Hexadecimal *Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.*
def coffee_limits(year, month, day): health_no = int('{:04}{:02}{:02}'.format(year, month, day)) cafe, decaf = health_no, health_no cups = 0 for i in range(5000): cafe += 0xCAFE cups += 1 if 'DEAD' in '{:08X}'.format(cafe): break cafe = 0 if cups == 5000 else cups cups = 0 for i in range(5000): decaf += 0xDECAF cups += 1 if 'DEAD' in '{:08X}'.format(decaf): break decaf = 0 if cups == 5000 else cups return [cafe, decaf]
# Background I drink too much coffee. Eventually it will probably kill me. *Or will it..?* Anyway, there's no way to know. *Or is there...?* # The Discovery of the Formula I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers! For * ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD) * ```CAFE``` is a cup of *regular* coffee * ```DECAF``` is a cup of *decaffeinated* coffee To determine the life-time coffee limits: * Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD` * If the test subject can survive drinking five thousand cups wihout being ```DEAD``` then coffee has no ill effect on them # Kata Task Given the test subject's date of birth, return an array describing their life-time coffee limits ```[ regular limit , decaffeinated limit ]``` ## Notes * The limits are ```0``` if the subject is unaffected as described above * At least 1 cup must be consumed (Just thinking about coffee cannot kill you!) # Examples * John was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well. * Susan (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan. * Elizabeth (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk? * Peter (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!! Hint: https://en.wikipedia.org/wiki/Hexadecimal *Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.*
def decToHex(n): hexChart = {0:'0',1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'} hexValue='' while n: hexValue = hexChart[n%16] + hexValue n //=16 return hexValue def hexToDec(string): hex = "0123456789ABCDEF" total=0 for index, i in enumerate(string): value = hex.index(i) power = len(string) - (index+1) total+= (value)*(16**power) return total def coffee_limits(year,month,day): cafe = hexToDec('CAFE') cafeCups=0 h = int(str(year) + str(month).zfill(2) + str(day).zfill(2)) for i in range(5000): h += cafe cafeCups+=1 if 'DEAD' in decToHex(h): break h = int(str(year) + str(month).zfill(2) + str(day).zfill(2)) print (h) decaf = hexToDec('DECAF') decafCups=0 for i in range(5000): h+= decaf decafCups+=1 if 'DEAD' in decToHex(h): break return [cafeCups%5000,decafCups%5000]
# Background I drink too much coffee. Eventually it will probably kill me. *Or will it..?* Anyway, there's no way to know. *Or is there...?* # The Discovery of the Formula I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers! For * ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD) * ```CAFE``` is a cup of *regular* coffee * ```DECAF``` is a cup of *decaffeinated* coffee To determine the life-time coffee limits: * Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD` * If the test subject can survive drinking five thousand cups wihout being ```DEAD``` then coffee has no ill effect on them # Kata Task Given the test subject's date of birth, return an array describing their life-time coffee limits ```[ regular limit , decaffeinated limit ]``` ## Notes * The limits are ```0``` if the subject is unaffected as described above * At least 1 cup must be consumed (Just thinking about coffee cannot kill you!) # Examples * John was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well. * Susan (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan. * Elizabeth (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk? * Peter (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!! Hint: https://en.wikipedia.org/wiki/Hexadecimal *Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.*
def coffee_limits(year, month, day): CAFE = 51966 DECAF = 912559 cafes_allowed = [] decafs_allowed = [] year = str(year) if month < 10: month = '0' + str(month) else: month = str(month) if day < 10: print(day) day = '0' + str(day) else: day = str(day) health_number = int(year+month+day) for i in range(1, 5001): CAFE_total = health_number + (i*CAFE) DECAF_total = health_number + (i*DECAF) CAFE_hex_total = hex(CAFE_total) DECAF_hex_total = hex(DECAF_total) if 'dead' in CAFE_hex_total: cafes_allowed.append(i) if 'dead' in DECAF_hex_total: decafs_allowed.append(i) print(cafes_allowed) if not cafes_allowed: cafes_allowed = 0 else: cafes_allowed = cafes_allowed[0] if not decafs_allowed: decafs_allowed = 0 else: decafs_allowed = decafs_allowed[0] return [cafes_allowed, decafs_allowed]
# Background I drink too much coffee. Eventually it will probably kill me. *Or will it..?* Anyway, there's no way to know. *Or is there...?* # The Discovery of the Formula I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers! For * ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD) * ```CAFE``` is a cup of *regular* coffee * ```DECAF``` is a cup of *decaffeinated* coffee To determine the life-time coffee limits: * Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD` * If the test subject can survive drinking five thousand cups wihout being ```DEAD``` then coffee has no ill effect on them # Kata Task Given the test subject's date of birth, return an array describing their life-time coffee limits ```[ regular limit , decaffeinated limit ]``` ## Notes * The limits are ```0``` if the subject is unaffected as described above * At least 1 cup must be consumed (Just thinking about coffee cannot kill you!) # Examples * John was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well. * Susan (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan. * Elizabeth (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk? * Peter (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!! Hint: https://en.wikipedia.org/wiki/Hexadecimal *Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.*
def test(number, coffee): for i in range(1,5001): if 'dead' in hex(number+i*coffee): return i return 0 def coffee_limits(year, month, day): number = year*10000+month*100+day return [test(number, coffee) for coffee in (0xCAFE, 0xDECAF)]
# Background I drink too much coffee. Eventually it will probably kill me. *Or will it..?* Anyway, there's no way to know. *Or is there...?* # The Discovery of the Formula I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers! For * ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD) * ```CAFE``` is a cup of *regular* coffee * ```DECAF``` is a cup of *decaffeinated* coffee To determine the life-time coffee limits: * Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD` * If the test subject can survive drinking five thousand cups wihout being ```DEAD``` then coffee has no ill effect on them # Kata Task Given the test subject's date of birth, return an array describing their life-time coffee limits ```[ regular limit , decaffeinated limit ]``` ## Notes * The limits are ```0``` if the subject is unaffected as described above * At least 1 cup must be consumed (Just thinking about coffee cannot kill you!) # Examples * John was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well. * Susan (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan. * Elizabeth (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk? * Peter (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!! Hint: https://en.wikipedia.org/wiki/Hexadecimal *Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.*
def coffee_limits(year, month, day): h=year*10000+month*100+day c=0 for i in range(1,5001): if 'dead' in hex(h+i*0xcafe): c=i break d=0 for i in range(1,5001): if 'dead' in hex(h+i*0xdecaf): d=i break return [c,d]
# Story Old MacDingle had a farm... ...and on that farm he had * horses * chickens * rabbits * some apple trees * a vegetable patch Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open** Depending which gate was left open then... * horses might run away * horses might eat the apples * horses might eat the vegetables * chickens might run away * rabbits might run away * rabbits might eat the vegetables # Kata Task Given the state of the farm gates in the evening, your code must return what the farm looks like the next morning when daylight reveals what the animals got up to. # Legend * ```H``` horse * ```C``` chicken * ```R``` rabbit * ```A``` apple tree * ```V``` vegetables * ```|``` gate (closed), * ```\``` or ```/``` gate (open) * ```.``` everything else # Example Before ```|..HH....\AAAA\CC..|AAA/VVV/RRRR|CCC``` After ```|..HH....\....\CC..|AAA/.../RRRR|...``` Because: The horses ate whatever apples they could get to The rabbits ate the vegetables The chickens ran away # Notes * If the animals can eat things *and* also run away then they do **BOTH** - it is best not to run away when you are hungry! * An animal cannot "go around" a closed gate... * ...but it is possible to run away from the farm and then **RUN BACK** and re-enter though more open gates on the other side!
from itertools import groupby def shut_the_gate(farm): who_eats_whom = {'H': ['A', 'V'], 'R': ['V'], 'C': []} runaway_back ,runaway_front, farm = [], [], ["".join(j) for k, j in groupby(farm)] def doSomeFarm(i=0): def do(j,s=False): while (j >= 0 if s else j<len(farm)) and farm[j] != '|': if farm[j][0] in who_eats_whom[current[0]] : farm[j] = '.' * len(farm[j]) j += [1,-1][s] return j while i < len(farm): current = farm[i] if current[0] in who_eats_whom: r,r1 = do(i,1),do(i) if r == -1 or r1 == len(farm): farm[i] = '.' * len(farm[i]) [runaway_front,runaway_back][r!=-1].append(current[0]) i += 1 doSomeFarm() l = len(runaway_back) if l: if farm[0] != '|': farm = ['/'] + " / ".join(runaway_back[::-1]).split() + farm doSomeFarm() farm = farm[l * 2:] l = len(runaway_front) if l: if farm[-1] != '|': farm = farm + ['/'] +' / '.join(runaway_front).split() doSomeFarm() farm = farm[:-l * 2] return "".join(farm)
# Story Old MacDingle had a farm... ...and on that farm he had * horses * chickens * rabbits * some apple trees * a vegetable patch Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open** Depending which gate was left open then... * horses might run away * horses might eat the apples * horses might eat the vegetables * chickens might run away * rabbits might run away * rabbits might eat the vegetables # Kata Task Given the state of the farm gates in the evening, your code must return what the farm looks like the next morning when daylight reveals what the animals got up to. # Legend * ```H``` horse * ```C``` chicken * ```R``` rabbit * ```A``` apple tree * ```V``` vegetables * ```|``` gate (closed), * ```\``` or ```/``` gate (open) * ```.``` everything else # Example Before ```|..HH....\AAAA\CC..|AAA/VVV/RRRR|CCC``` After ```|..HH....\....\CC..|AAA/.../RRRR|...``` Because: The horses ate whatever apples they could get to The rabbits ate the vegetables The chickens ran away # Notes * If the animals can eat things *and* also run away then they do **BOTH** - it is best not to run away when you are hungry! * An animal cannot "go around" a closed gate... * ...but it is possible to run away from the farm and then **RUN BACK** and re-enter though more open gates on the other side!
def shut_the_gate(farm): # Identify regions start, regions = 0, [] for i, c in enumerate(farm): if c == "|": if start != i: free = start == 0 and farm[0] != "|" regions.append([start, i, free, farm[start:i], False]) start = i if start < len(farm) - 1: # Add final free region regions.append([start, i, True, farm[start:i + 1], False]) # Link two extreme regions if both free if regions and regions[0][2] and regions[-1][2]: regions[0][-1] = True regions[-1][-1] = True # Convert to mutable structure and remove everthing that shouldn't be there f = [c for c in farm] for start, stop, free, s, linked in regions: s2 = "" if not linked else regions[0 if start > 0 else -1][3] # Identify potential loss conditions removals = set() if free: removals |= {"H", "C", "R"} if "H" in s + s2: removals |= {"A", "V"} if "R" in s + s2: removals |= {"V"} # Remove losses f[start:stop+1] = ['.' if c in removals else c for c in f[start:stop+1]] # Build resultant state return "".join(f)
# Story Old MacDingle had a farm... ...and on that farm he had * horses * chickens * rabbits * some apple trees * a vegetable patch Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open** Depending which gate was left open then... * horses might run away * horses might eat the apples * horses might eat the vegetables * chickens might run away * rabbits might run away * rabbits might eat the vegetables # Kata Task Given the state of the farm gates in the evening, your code must return what the farm looks like the next morning when daylight reveals what the animals got up to. # Legend * ```H``` horse * ```C``` chicken * ```R``` rabbit * ```A``` apple tree * ```V``` vegetables * ```|``` gate (closed), * ```\``` or ```/``` gate (open) * ```.``` everything else # Example Before ```|..HH....\AAAA\CC..|AAA/VVV/RRRR|CCC``` After ```|..HH....\....\CC..|AAA/.../RRRR|...``` Because: The horses ate whatever apples they could get to The rabbits ate the vegetables The chickens ran away # Notes * If the animals can eat things *and* also run away then they do **BOTH** - it is best not to run away when you are hungry! * An animal cannot "go around" a closed gate... * ...but it is possible to run away from the farm and then **RUN BACK** and re-enter though more open gates on the other side!
import re EAT = {'H': 'AV', 'R': 'V'} def shut_the_gate(farm): parts = farm.split('|') partsSets = list(map(set, parts)) for i in range(len(parts)): isOut = i in [0, len(parts)-1] inThere = set('RHC') & (partsSets[i] | (partsSets[len(parts)-1-i] if isOut else set())) toErase = ''.join(EAT.get(x,'') for x in inThere) + 'HCR'*isOut if toErase: parts[i] = re.sub(r'[{}]'.format(toErase), '.', parts[i]) return '|'.join(parts)
# Story Old MacDingle had a farm... ...and on that farm he had * horses * chickens * rabbits * some apple trees * a vegetable patch Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open** Depending which gate was left open then... * horses might run away * horses might eat the apples * horses might eat the vegetables * chickens might run away * rabbits might run away * rabbits might eat the vegetables # Kata Task Given the state of the farm gates in the evening, your code must return what the farm looks like the next morning when daylight reveals what the animals got up to. # Legend * ```H``` horse * ```C``` chicken * ```R``` rabbit * ```A``` apple tree * ```V``` vegetables * ```|``` gate (closed), * ```\``` or ```/``` gate (open) * ```.``` everything else # Example Before ```|..HH....\AAAA\CC..|AAA/VVV/RRRR|CCC``` After ```|..HH....\....\CC..|AAA/.../RRRR|...``` Because: The horses ate whatever apples they could get to The rabbits ate the vegetables The chickens ran away # Notes * If the animals can eat things *and* also run away then they do **BOTH** - it is best not to run away when you are hungry! * An animal cannot "go around" a closed gate... * ...but it is possible to run away from the farm and then **RUN BACK** and re-enter though more open gates on the other side!
def shut_the_gate(farm): r = '' for i, c in enumerate(farm): left, right = farm[:i][::-1], farm[i+1:] if c in 'HCR': if '|' not in left or '|' not in right: c = '.' elif c in 'VA': for e in (left + farm[i+1:][::-1]).split('|')[0] + (right + farm[:i]).split('|')[0]: if e + c in 'HVHARV': c = '.' r += c return r
# Story Old MacDingle had a farm... ...and on that farm he had * horses * chickens * rabbits * some apple trees * a vegetable patch Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open** Depending which gate was left open then... * horses might run away * horses might eat the apples * horses might eat the vegetables * chickens might run away * rabbits might run away * rabbits might eat the vegetables # Kata Task Given the state of the farm gates in the evening, your code must return what the farm looks like the next morning when daylight reveals what the animals got up to. # Legend * ```H``` horse * ```C``` chicken * ```R``` rabbit * ```A``` apple tree * ```V``` vegetables * ```|``` gate (closed), * ```\``` or ```/``` gate (open) * ```.``` everything else # Example Before ```|..HH....\AAAA\CC..|AAA/VVV/RRRR|CCC``` After ```|..HH....\....\CC..|AAA/.../RRRR|...``` Because: The horses ate whatever apples they could get to The rabbits ate the vegetables The chickens ran away # Notes * If the animals can eat things *and* also run away then they do **BOTH** - it is best not to run away when you are hungry! * An animal cannot "go around" a closed gate... * ...but it is possible to run away from the farm and then **RUN BACK** and re-enter though more open gates on the other side!
ANIMS = {'H': ['A', 'V'], 'R': ['V'], 'C': ['~']} def shut_the_gate(farm): print(farm) f = list(farm) rng = list(range(0, len(f))) for i in rng: if f[i] in ANIMS: for food in ANIMS[f[i]]: j = 0 idx = index_of(f, j, food) while idx is not None: if idx < i and '|' not in f[idx:i]: f[idx] = '.' elif i < idx and '|' not in f[i:idx]: f[idx] = '.' elif '|' not in f[:i] and '|' not in f[idx:]: f[idx] = '.' elif '|' not in f[i:] and '|' not in f[:idx]: f[idx] = '.' j += 1 idx = index_of(f, j, food) for i in rng: if f[i] in ANIMS: if '|' not in f[i:] or '|' not in f[:i]: f[i] = '.' return ''.join(f) def index_of(farm, j, food): try: return farm[j:].index(food) + j except: return None
# Story Old MacDingle had a farm... ...and on that farm he had * horses * chickens * rabbits * some apple trees * a vegetable patch Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open** Depending which gate was left open then... * horses might run away * horses might eat the apples * horses might eat the vegetables * chickens might run away * rabbits might run away * rabbits might eat the vegetables # Kata Task Given the state of the farm gates in the evening, your code must return what the farm looks like the next morning when daylight reveals what the animals got up to. # Legend * ```H``` horse * ```C``` chicken * ```R``` rabbit * ```A``` apple tree * ```V``` vegetables * ```|``` gate (closed), * ```\``` or ```/``` gate (open) * ```.``` everything else # Example Before ```|..HH....\AAAA\CC..|AAA/VVV/RRRR|CCC``` After ```|..HH....\....\CC..|AAA/.../RRRR|...``` Because: The horses ate whatever apples they could get to The rabbits ate the vegetables The chickens ran away # Notes * If the animals can eat things *and* also run away then they do **BOTH** - it is best not to run away when you are hungry! * An animal cannot "go around" a closed gate... * ...but it is possible to run away from the farm and then **RUN BACK** and re-enter though more open gates on the other side!
shut_the_gate=lambda s:'|'.join(w.translate( {ord(c):set(w)&set('RH'[i:]or'@')and'.'or c for i,c in enumerate('VARCH')} )for w in '@'.join(3*[s]).split('|')).split('@')[1]
# Story Old MacDingle had a farm... ...and on that farm he had * horses * chickens * rabbits * some apple trees * a vegetable patch Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open** Depending which gate was left open then... * horses might run away * horses might eat the apples * horses might eat the vegetables * chickens might run away * rabbits might run away * rabbits might eat the vegetables # Kata Task Given the state of the farm gates in the evening, your code must return what the farm looks like the next morning when daylight reveals what the animals got up to. # Legend * ```H``` horse * ```C``` chicken * ```R``` rabbit * ```A``` apple tree * ```V``` vegetables * ```|``` gate (closed), * ```\``` or ```/``` gate (open) * ```.``` everything else # Example Before ```|..HH....\AAAA\CC..|AAA/VVV/RRRR|CCC``` After ```|..HH....\....\CC..|AAA/.../RRRR|...``` Because: The horses ate whatever apples they could get to The rabbits ate the vegetables The chickens ran away # Notes * If the animals can eat things *and* also run away then they do **BOTH** - it is best not to run away when you are hungry! * An animal cannot "go around" a closed gate... * ...but it is possible to run away from the farm and then **RUN BACK** and re-enter though more open gates on the other side!
def shut_the_gate(farm): if not farm: return "" RA=[] if farm[0]!="|" and farm[-1]!="|"and "|" in farm: R = farm.rfind("|") L = farm.find("|") tmp = farm[R:]+farm[:L] if "H" in tmp: farm = farm[:R]+farm[R:].replace("A",".").replace("V",".") farm = farm[:L].replace("A",".").replace("V",".")+farm[L:] if "R" in tmp: farm = farm[:R]+farm[R:].replace("V",".") farm = farm[:L].replace("V",".")+farm[L:] res='' L = len(farm) T = [e for e in range(L) if farm[e]=="|"] if farm[0]!="|": T = [0]+T if farm[-1]!="|": T.append(L) idx=0 while True: if T[idx]==T[-1]: break S = T[idx] E = T[idx+1] tmp = farm[S:E+1] if "H" in tmp: tmp = tmp.replace("A",".").replace("V",".") if "R" in tmp: tmp = tmp.replace("V",".") if tmp.count("|")<=1: if "H" in RA: tmp = tmp.replace("A",".").replace("V",".") if "R" in RA: tmp = tmp.replace("V",".") if "H" in tmp: tmp = tmp.replace("H",".") RA.append("H") if "R" in tmp: tmp = tmp.replace("R",".") RA.append("R") tmp = tmp.replace("C",".") res+=tmp[:-1] if E!=T[-1] else tmp idx+=1 return res
# Story Old MacDingle had a farm... ...and on that farm he had * horses * chickens * rabbits * some apple trees * a vegetable patch Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open** Depending which gate was left open then... * horses might run away * horses might eat the apples * horses might eat the vegetables * chickens might run away * rabbits might run away * rabbits might eat the vegetables # Kata Task Given the state of the farm gates in the evening, your code must return what the farm looks like the next morning when daylight reveals what the animals got up to. # Legend * ```H``` horse * ```C``` chicken * ```R``` rabbit * ```A``` apple tree * ```V``` vegetables * ```|``` gate (closed), * ```\``` or ```/``` gate (open) * ```.``` everything else # Example Before ```|..HH....\AAAA\CC..|AAA/VVV/RRRR|CCC``` After ```|..HH....\....\CC..|AAA/.../RRRR|...``` Because: The horses ate whatever apples they could get to The rabbits ate the vegetables The chickens ran away # Notes * If the animals can eat things *and* also run away then they do **BOTH** - it is best not to run away when you are hungry! * An animal cannot "go around" a closed gate... * ...but it is possible to run away from the farm and then **RUN BACK** and re-enter though more open gates on the other side!
def eating(field): if "H" in field: field = field.replace("A", ".") field = field.replace("V", ".") if "R" in field: field = field.replace("V", ".") return field def runing(field): field = field.replace("H", ".") field = field.replace("C", ".") field = field.replace("R", ".") return field def shut_the_gate(farm): splited = farm.split("|") splited = [eating(item) for item in splited] if not farm.startswith("|") and not farm.endswith("|"): if "H" in splited[0] or "H" in splited[-1]: splited[0] = splited[0].replace("A", ".") splited[0] = splited[0].replace("V", ".") splited[-1] = splited[-1].replace("A", ".") splited[-1] = splited[-1].replace("V", ".") if "R" in splited[0] or "R" in splited[-1]: splited[0] = splited[0].replace("V", ".") splited[-1] = splited[-1].replace("V", ".") if not farm.startswith("|"): splited[0] = runing(splited[0]) if not farm.endswith("|"): splited[-1] = runing(splited[-1]) return "|".join(splited)
# Story Old MacDingle had a farm... ...and on that farm he had * horses * chickens * rabbits * some apple trees * a vegetable patch Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open** Depending which gate was left open then... * horses might run away * horses might eat the apples * horses might eat the vegetables * chickens might run away * rabbits might run away * rabbits might eat the vegetables # Kata Task Given the state of the farm gates in the evening, your code must return what the farm looks like the next morning when daylight reveals what the animals got up to. # Legend * ```H``` horse * ```C``` chicken * ```R``` rabbit * ```A``` apple tree * ```V``` vegetables * ```|``` gate (closed), * ```\``` or ```/``` gate (open) * ```.``` everything else # Example Before ```|..HH....\AAAA\CC..|AAA/VVV/RRRR|CCC``` After ```|..HH....\....\CC..|AAA/.../RRRR|...``` Because: The horses ate whatever apples they could get to The rabbits ate the vegetables The chickens ran away # Notes * If the animals can eat things *and* also run away then they do **BOTH** - it is best not to run away when you are hungry! * An animal cannot "go around" a closed gate... * ...but it is possible to run away from the farm and then **RUN BACK** and re-enter though more open gates on the other side!
def shut_the_gate(farm): r=[] for g in farm.split('|'): if 'H' in g: g=g.replace('A','.').replace('V','.') elif 'R' in g: g=g.replace('V','.') r.append(g) if 'H' in r[-1]: r[0]=r[0].replace('A','.').replace('V','.') elif 'R' in r[-1]: r[0]=r[0].replace('V','.') if 'H' in r[0]: r[-1]=r[-1].replace('A','.').replace('V','.') elif 'R' in r[0]: r[-1]=r[-1].replace('V','.') r[0]=r[0].replace('H','.').replace('R','.').replace('C','.') r[-1]=r[-1].replace('H','.').replace('R','.').replace('C','.') return '|'.join(r)
# Story Old MacDingle had a farm... ...and on that farm he had * horses * chickens * rabbits * some apple trees * a vegetable patch Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open** Depending which gate was left open then... * horses might run away * horses might eat the apples * horses might eat the vegetables * chickens might run away * rabbits might run away * rabbits might eat the vegetables # Kata Task Given the state of the farm gates in the evening, your code must return what the farm looks like the next morning when daylight reveals what the animals got up to. # Legend * ```H``` horse * ```C``` chicken * ```R``` rabbit * ```A``` apple tree * ```V``` vegetables * ```|``` gate (closed), * ```\``` or ```/``` gate (open) * ```.``` everything else # Example Before ```|..HH....\AAAA\CC..|AAA/VVV/RRRR|CCC``` After ```|..HH....\....\CC..|AAA/.../RRRR|...``` Because: The horses ate whatever apples they could get to The rabbits ate the vegetables The chickens ran away # Notes * If the animals can eat things *and* also run away then they do **BOTH** - it is best not to run away when you are hungry! * An animal cannot "go around" a closed gate... * ...but it is possible to run away from the farm and then **RUN BACK** and re-enter though more open gates on the other side!
import re def shut_the_gate(farm): yards = farm.split('|') if len(yards) > 1: n = len(yards[0]) yards[-1] += yards[0] for i, yard in enumerate(yards): s = '' if 'H' in yard: s = 'AV' elif 'R' in yard: s = 'V' if i == len(yards)-1: s += 'HCR' if s: yards[i] = re.sub('['+s+']', '.', yard) if len(yards) > 1 and n: yards[0] = yards[-1][-n:] yards[-1] = yards[-1][:-n] return '|'.join(yards)
Suzuki needs help lining up his students! Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn. You will be given a string of student names. Sort them and return a list of names in descending order. Here is an example input: ```python string = 'Tadashi Takahiro Takao Takashi Takayuki Takehiko Takeo Takeshi Takeshi' ``` Here is an example return from your function: ```python lst = ['Takehiko', 'Takayuki', 'Takahiro', 'Takeshi', 'Takeshi', 'Takashi', 'Tadashi', 'Takeo', 'Takao'] ``` Names of equal length will be returned in reverse alphabetical order (Z->A) such that: ```python string = "xxa xxb xxc xxd xa xb xc xd" ``` Returns ```python ['xxd', 'xxc', 'xxb', 'xxa', 'xd', 'xc', 'xb', 'xa'] ``` Please also try the other Kata in this series.. * [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b) * [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c) * [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255) * [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d) * [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
lineup_students = lambda (s): sorted(s.split(), key=lambda x: (len(x), x), reverse=True)
Suzuki needs help lining up his students! Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn. You will be given a string of student names. Sort them and return a list of names in descending order. Here is an example input: ```python string = 'Tadashi Takahiro Takao Takashi Takayuki Takehiko Takeo Takeshi Takeshi' ``` Here is an example return from your function: ```python lst = ['Takehiko', 'Takayuki', 'Takahiro', 'Takeshi', 'Takeshi', 'Takashi', 'Tadashi', 'Takeo', 'Takao'] ``` Names of equal length will be returned in reverse alphabetical order (Z->A) such that: ```python string = "xxa xxb xxc xxd xa xb xc xd" ``` Returns ```python ['xxd', 'xxc', 'xxb', 'xxa', 'xd', 'xc', 'xb', 'xa'] ``` Please also try the other Kata in this series.. * [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b) * [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c) * [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255) * [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d) * [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
def lineup_students(s): return sorted(s.split(), key=lambda i:(len(i),i), reverse=True)
Suzuki needs help lining up his students! Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn. You will be given a string of student names. Sort them and return a list of names in descending order. Here is an example input: ```python string = 'Tadashi Takahiro Takao Takashi Takayuki Takehiko Takeo Takeshi Takeshi' ``` Here is an example return from your function: ```python lst = ['Takehiko', 'Takayuki', 'Takahiro', 'Takeshi', 'Takeshi', 'Takashi', 'Tadashi', 'Takeo', 'Takao'] ``` Names of equal length will be returned in reverse alphabetical order (Z->A) such that: ```python string = "xxa xxb xxc xxd xa xb xc xd" ``` Returns ```python ['xxd', 'xxc', 'xxb', 'xxa', 'xd', 'xc', 'xb', 'xa'] ``` Please also try the other Kata in this series.. * [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b) * [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c) * [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255) * [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d) * [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
def lineup_students(names): return sorted(names.split(), key=lambda s: (len(s), s), reverse=True)
Suzuki needs help lining up his students! Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn. You will be given a string of student names. Sort them and return a list of names in descending order. Here is an example input: ```python string = 'Tadashi Takahiro Takao Takashi Takayuki Takehiko Takeo Takeshi Takeshi' ``` Here is an example return from your function: ```python lst = ['Takehiko', 'Takayuki', 'Takahiro', 'Takeshi', 'Takeshi', 'Takashi', 'Tadashi', 'Takeo', 'Takao'] ``` Names of equal length will be returned in reverse alphabetical order (Z->A) such that: ```python string = "xxa xxb xxc xxd xa xb xc xd" ``` Returns ```python ['xxd', 'xxc', 'xxb', 'xxa', 'xd', 'xc', 'xb', 'xa'] ``` Please also try the other Kata in this series.. * [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b) * [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c) * [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255) * [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d) * [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
def lineup_students(names): return sorted(names.split(), key=lambda a: (len(a), a), reverse=True)
Suzuki needs help lining up his students! Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn. You will be given a string of student names. Sort them and return a list of names in descending order. Here is an example input: ```python string = 'Tadashi Takahiro Takao Takashi Takayuki Takehiko Takeo Takeshi Takeshi' ``` Here is an example return from your function: ```python lst = ['Takehiko', 'Takayuki', 'Takahiro', 'Takeshi', 'Takeshi', 'Takashi', 'Tadashi', 'Takeo', 'Takao'] ``` Names of equal length will be returned in reverse alphabetical order (Z->A) such that: ```python string = "xxa xxb xxc xxd xa xb xc xd" ``` Returns ```python ['xxd', 'xxc', 'xxb', 'xxa', 'xd', 'xc', 'xb', 'xa'] ``` Please also try the other Kata in this series.. * [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b) * [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c) * [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255) * [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d) * [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
def lineup_students(stg): return sorted(sorted(stg.split(), reverse=True), key=len, reverse=True)
Suzuki needs help lining up his students! Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn. You will be given a string of student names. Sort them and return a list of names in descending order. Here is an example input: ```python string = 'Tadashi Takahiro Takao Takashi Takayuki Takehiko Takeo Takeshi Takeshi' ``` Here is an example return from your function: ```python lst = ['Takehiko', 'Takayuki', 'Takahiro', 'Takeshi', 'Takeshi', 'Takashi', 'Tadashi', 'Takeo', 'Takao'] ``` Names of equal length will be returned in reverse alphabetical order (Z->A) such that: ```python string = "xxa xxb xxc xxd xa xb xc xd" ``` Returns ```python ['xxd', 'xxc', 'xxb', 'xxa', 'xd', 'xc', 'xb', 'xa'] ``` Please also try the other Kata in this series.. * [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b) * [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c) * [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255) * [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d) * [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
def lineup_students(string): return sorted(string.split(), reverse = True, key = lambda name:(len(name),name))
Suzuki needs help lining up his students! Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn. You will be given a string of student names. Sort them and return a list of names in descending order. Here is an example input: ```python string = 'Tadashi Takahiro Takao Takashi Takayuki Takehiko Takeo Takeshi Takeshi' ``` Here is an example return from your function: ```python lst = ['Takehiko', 'Takayuki', 'Takahiro', 'Takeshi', 'Takeshi', 'Takashi', 'Tadashi', 'Takeo', 'Takao'] ``` Names of equal length will be returned in reverse alphabetical order (Z->A) such that: ```python string = "xxa xxb xxc xxd xa xb xc xd" ``` Returns ```python ['xxd', 'xxc', 'xxb', 'xxa', 'xd', 'xc', 'xb', 'xa'] ``` Please also try the other Kata in this series.. * [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b) * [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c) * [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255) * [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d) * [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
def lineup_students(string): students = string.split() students.sort() s= sorted(students, key=len) return s[::-1]
Suzuki needs help lining up his students! Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn. You will be given a string of student names. Sort them and return a list of names in descending order. Here is an example input: ```python string = 'Tadashi Takahiro Takao Takashi Takayuki Takehiko Takeo Takeshi Takeshi' ``` Here is an example return from your function: ```python lst = ['Takehiko', 'Takayuki', 'Takahiro', 'Takeshi', 'Takeshi', 'Takashi', 'Tadashi', 'Takeo', 'Takao'] ``` Names of equal length will be returned in reverse alphabetical order (Z->A) such that: ```python string = "xxa xxb xxc xxd xa xb xc xd" ``` Returns ```python ['xxd', 'xxc', 'xxb', 'xxa', 'xd', 'xc', 'xb', 'xa'] ``` Please also try the other Kata in this series.. * [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b) * [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c) * [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255) * [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d) * [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
def lineup_students(s): return sorted(s.split(), key=lambda x: (len(x), x), reverse=True)
Suzuki needs help lining up his students! Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn. You will be given a string of student names. Sort them and return a list of names in descending order. Here is an example input: ```python string = 'Tadashi Takahiro Takao Takashi Takayuki Takehiko Takeo Takeshi Takeshi' ``` Here is an example return from your function: ```python lst = ['Takehiko', 'Takayuki', 'Takahiro', 'Takeshi', 'Takeshi', 'Takashi', 'Tadashi', 'Takeo', 'Takao'] ``` Names of equal length will be returned in reverse alphabetical order (Z->A) such that: ```python string = "xxa xxb xxc xxd xa xb xc xd" ``` Returns ```python ['xxd', 'xxc', 'xxb', 'xxa', 'xd', 'xc', 'xb', 'xa'] ``` Please also try the other Kata in this series.. * [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b) * [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c) * [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255) * [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d) * [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
def lineup_students(s): return sorted(s.strip().split(" "), key=lambda x:(len(x), x), reverse=True)
Suzuki needs help lining up his students! Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn. You will be given a string of student names. Sort them and return a list of names in descending order. Here is an example input: ```python string = 'Tadashi Takahiro Takao Takashi Takayuki Takehiko Takeo Takeshi Takeshi' ``` Here is an example return from your function: ```python lst = ['Takehiko', 'Takayuki', 'Takahiro', 'Takeshi', 'Takeshi', 'Takashi', 'Tadashi', 'Takeo', 'Takao'] ``` Names of equal length will be returned in reverse alphabetical order (Z->A) such that: ```python string = "xxa xxb xxc xxd xa xb xc xd" ``` Returns ```python ['xxd', 'xxc', 'xxb', 'xxa', 'xd', 'xc', 'xb', 'xa'] ``` Please also try the other Kata in this series.. * [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b) * [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c) * [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255) * [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d) * [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
def lineup_students(string): return sorted(string.split(),key=lambda x:(len(x),x),reverse=True)
You are given a list of directions in the form of a list: goal = ["N", "S", "E", "W"] Pretend that each direction counts for 1 step in that particular direction. Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W. If you get back to beginning, return an empty array.
def directions(goal): y = goal.count("N") - goal.count("S") x = goal.count("E") - goal.count("W") return ["N"] * y + ["S"] * (-y) + ["E"] * x + ["W"] * (-x)
You are given a list of directions in the form of a list: goal = ["N", "S", "E", "W"] Pretend that each direction counts for 1 step in that particular direction. Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W. If you get back to beginning, return an empty array.
def directions(goal): count = lambda s: len([c for c in goal if c == s]) ns = 1 * count("N") - 1 * count("S") we = 1 * count("W") - 1 * count("E") ns = [("N" if ns > 0 else "S")] * abs(ns) we = [("W" if we > 0 else "E")] * abs(we) return ns + we
You are given a list of directions in the form of a list: goal = ["N", "S", "E", "W"] Pretend that each direction counts for 1 step in that particular direction. Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W. If you get back to beginning, return an empty array.
from collections import Counter def directions(goal): c = Counter(goal) c["N"], c["W"] = c["N"] - c["S"], c["W"] - c["E"] c["S"], c["E"] = -c["N"], -c["W"] return sorted(c.elements(), key="NSEW".index)
You are given a list of directions in the form of a list: goal = ["N", "S", "E", "W"] Pretend that each direction counts for 1 step in that particular direction. Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W. If you get back to beginning, return an empty array.
from collections import Counter def directions(goal): c = Counter(goal) for a, b in ['NS', 'EW']: m = min(c[a], c[b]) c[a] -= m c[b] -= m return sorted(c.elements(), key='NSEW'.find)
You are given a list of directions in the form of a list: goal = ["N", "S", "E", "W"] Pretend that each direction counts for 1 step in that particular direction. Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W. If you get back to beginning, return an empty array.
def directions(goal): MOVES = {'N': [0,1], 'S': [0,-1], 'E': [1,1], 'W': [1,-1]} g = [0,0] for d in goal: g[MOVES[d][0]] += MOVES[d][1] return ["SN"[g[0]>=0]] * abs(g[0]) + ["WE"[g[1]>=0]] * abs(g[1])
You are given a list of directions in the form of a list: goal = ["N", "S", "E", "W"] Pretend that each direction counts for 1 step in that particular direction. Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W. If you get back to beginning, return an empty array.
def directions(goal): y=sum(1 if d=='N' else -1 if d=='S' else 0 for d in goal) x=sum(1 if d=='E' else -1 if d=='W' else 0 for d in goal) return list(('N' if y>0 else 'S')*abs(y) + ('E' if x>0 else 'W')*abs(x))
You are given a list of directions in the form of a list: goal = ["N", "S", "E", "W"] Pretend that each direction counts for 1 step in that particular direction. Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W. If you get back to beginning, return an empty array.
def directions(goal): y = goal.count('N') - goal.count('S') x = goal.count('E') - goal.count('W') ns = 'N' if y > 0 else 'S' ew = 'E' if x > 0 else 'W' return [_ for _ in abs(y)*ns + abs(x)*ew]
You are given a list of directions in the form of a list: goal = ["N", "S", "E", "W"] Pretend that each direction counts for 1 step in that particular direction. Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W. If you get back to beginning, return an empty array.
def directions(goal): while "S" in goal and "N" in goal: goal.remove("N") goal.remove("S") while "W" in goal and "E" in goal: goal.remove("W") goal.remove("E") lookup=['N','S', 'E', 'W'] key_func=lambda s: (lookup.index(s[0]),s) if s[0] in lookup else (len(lookup),s) return sorted(goal, key=key_func)
You are given a list of directions in the form of a list: goal = ["N", "S", "E", "W"] Pretend that each direction counts for 1 step in that particular direction. Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W. If you get back to beginning, return an empty array.
def directions(goal): ans=[] ns = goal.count('N') - goal.count('S') if ns>0: ans.extend(ns*['N']) if ns<0: ans.extend(-ns*['S']) ew = goal.count('E') - goal.count('W') if ew>0: ans.extend(ew*['E']) if ew<0: ans.extend(-ew*['W']) return ans
You are given a list of directions in the form of a list: goal = ["N", "S", "E", "W"] Pretend that each direction counts for 1 step in that particular direction. Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W. If you get back to beginning, return an empty array.
def directions(goal): # print(goal) a={i:goal.count(i) for i in set(goal)} print(a) b=[] # print(list(a.keys()) ) if 'N' in list(a.keys()) and 'S' in list(a.keys() ): # print('a.keys()',a.keys()) if a['N']>a['S']: ns=a['N']-a['S'] b.extend(ns*'N') elif a['N']<a['S']: sn=a['S']-a['N'] b.extend(sn*'S') elif a['N']==a['S']: sn=a['S']-a['N'] elif 'N' in list(a.keys()): # print(a['N']) b.extend(a['N']*str('N')) elif 'S' in list(a.keys()): # print(a['S']) b.extend(a['S']*str('S')) #Code goes here! :) if 'E' in list(a.keys()) and 'W' in list(a.keys() ): # print('a.keys()',a.keys()) if a['E']>a['W']: ew=a['E']-a['W'] print(('ew',ew)) b.extend(ew*str('E')) elif a['E']<a['W']: we=a['W']-a['E'] print(('we',we)) b.extend(we*str('W')) elif 'W' in list(a.keys()): print((a['W'])) b.extend(a['W']*str('W')) elif 'E' in list(a.keys()): print((a['E'])) b.extend(a['E']*str('E')) return b
Your task is to return how many times a string contains a given character. The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count. For example, if you get an input string "Hello world" and the character to find is "o", return 2.
def string_counter(string, char): return string.count(char)
Your task is to return how many times a string contains a given character. The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count. For example, if you get an input string "Hello world" and the character to find is "o", return 2.
string_counter = str.count
Your task is to return how many times a string contains a given character. The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count. For example, if you get an input string "Hello world" and the character to find is "o", return 2.
def string_counter(string, char): return sum(1 for i in string if char == i)
Your task is to return how many times a string contains a given character. The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count. For example, if you get an input string "Hello world" and the character to find is "o", return 2.
def string_counter(strng, char): '''Return the frequency of a character in a string''' return strng.count(char)
Your task is to return how many times a string contains a given character. The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count. For example, if you get an input string "Hello world" and the character to find is "o", return 2.
string_counter = lambda string, char: string.count(char)
Your task is to return how many times a string contains a given character. The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count. For example, if you get an input string "Hello world" and the character to find is "o", return 2.
string_counter = lambda s,c: s.count(c)
Your task is to return how many times a string contains a given character. The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count. For example, if you get an input string "Hello world" and the character to find is "o", return 2.
def string_counter(string, char): count=0 for i in range(0, len(string)): if string[i]==char: count=count+1 else: pass return count
Your task is to return how many times a string contains a given character. The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count. For example, if you get an input string "Hello world" and the character to find is "o", return 2.
def string_counter(string, char): if char not in string: #stopping condition return 0 c = string[0] if c == char: return 1 + string_counter(string[1:], char) # return string_counter(string[1:], char) print((string_counter('Hello World', 'o')))
Your task is to return how many times a string contains a given character. The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count. For example, if you get an input string "Hello world" and the character to find is "o", return 2.
def string_counter(string, char): num=0 for i in range(len(string)): if string[i]==char: num+=1 return num
Your task is to return how many times a string contains a given character. The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count. For example, if you get an input string "Hello world" and the character to find is "o", return 2.
def string_counter(string, char): count=0 for i in string: if i == char: count+=1 else: pass return count
Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector ```a``` and Vector ```b```: ```python a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same magnitude and direction a.cross(b) # returns a new Vector that is the cross product of a and b a.dot(b) # returns a number that is the dot product of a and b a.to_tuple() # returns a tuple representation of the vector. str(a) # returns a string representation of the vector in the form "" a.magnitude # returns a number that is the magnitude (geometric length) of vector a. a.x # gets x component a.y # gets y component a.z # gets z component Vector([a,b,c]) # creates a new Vector from the supplied 3D array. Vector(a,b,c) # same as above ``` The test cases will not mutate the produced Vector objects, so don't worry about that.
import math class VectorInputCoordsValidationError(Exception): """Custom exception class for invalid input args given to the Vector instantiation""" class Vector: # https://www.mathsisfun.com/algebra/vectors.html def __init__(self, *args): try: self.x, self.y, self.z = args if len(args) == 3 else args[0] except ValueError: raise VectorInputCoordsValidationError('Either give single iterable of 3 coords or pass them as *args') def __add__(self, other) -> "Vector": return Vector( self.x + other.x, self.y + other.y, self.z + other.z ) def __sub__(self, other) -> "Vector": return Vector( self.x - other.x, self.y - other.y, self.z - other.z ) def __eq__(self, other) -> bool: # https://www.grc.nasa.gov/www/k-12/airplane/vectcomp.html # https://onlinemschool.com/math/library/vector/equality/ return all(( self.x == other.x, self.y == other.y, self.z == other.z )) def cross(self, other) -> "Vector": # https://www.mathsisfun.com/algebra/vectors-cross-product.html return Vector( self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x ) def dot(self, other) -> int: # https://www.mathsisfun.com/algebra/vectors-dot-product.html return self.x*other.x + self.y*other.y + self.z*other.z def to_tuple(self) -> tuple: return self.x, self.y, self.z def __str__(self) -> str: return "<{x}, {y}, {z}>".format(**self.__dict__) @property def magnitude(self) -> float: return math.sqrt( sum ( ( self.x ** 2, self.y ** 2, self.z ** 2 ) ) )
Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector ```a``` and Vector ```b```: ```python a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same magnitude and direction a.cross(b) # returns a new Vector that is the cross product of a and b a.dot(b) # returns a number that is the dot product of a and b a.to_tuple() # returns a tuple representation of the vector. str(a) # returns a string representation of the vector in the form "" a.magnitude # returns a number that is the magnitude (geometric length) of vector a. a.x # gets x component a.y # gets y component a.z # gets z component Vector([a,b,c]) # creates a new Vector from the supplied 3D array. Vector(a,b,c) # same as above ``` The test cases will not mutate the produced Vector objects, so don't worry about that.
from operator import itemgetter, add, sub, mul from itertools import starmap class Vector(list): def __init__(self, *args): if len(args)==1: args = args[0] super().__init__(args) __add__, __sub__, __mul__ = ( ( lambda self,o,f=fun: Vector(starmap(f, zip(self,o))) ) for fun in (add, sub, mul) ) x,y,z = (property(itemgetter(i)) for i in range(3)) @property def magnitude(self): return self.dot(self)**.5 def __str__(self): return f'<{ ", ".join(map(str,self)) }>' def to_tuple(self): return tuple(self) def dot(self,o): return sum(self*o) def cross(self,o): return Vector( self.y*o.z - self.z*o.y, self.z*o.x - self.x*o.z, self.x*o.y - self.y*o.x)
Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector ```a``` and Vector ```b```: ```python a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same magnitude and direction a.cross(b) # returns a new Vector that is the cross product of a and b a.dot(b) # returns a number that is the dot product of a and b a.to_tuple() # returns a tuple representation of the vector. str(a) # returns a string representation of the vector in the form "" a.magnitude # returns a number that is the magnitude (geometric length) of vector a. a.x # gets x component a.y # gets y component a.z # gets z component Vector([a,b,c]) # creates a new Vector from the supplied 3D array. Vector(a,b,c) # same as above ``` The test cases will not mutate the produced Vector objects, so don't worry about that.
import numpy as np class Vector: def __init__(self, *args): args = args[0] if len(args) == 1 else args self.x, self.y, self.z = args[0], args[1], args[2] self.li = [self.x,self.y,self.z] self.magnitude = np.linalg.norm(self.li) def __add__(self, other) : return Vector([i+j for i,j in zip(self.li,other.li)]) def __sub__(self, other) : return Vector([i-j for i,j in zip(self.li,other.li)]) def __eq__(self, other) : return all([i==j for i,j in zip(self.li,other.li)]) def __str__(self) : return f'<{self.x}, {self.y}, {self.z}>' def cross(self, other) : return Vector(np.cross(self.li, other.li)) def dot(self, other) : return np.dot(self.li,other.li) def to_tuple(self) : return tuple(self.li)
Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector ```a``` and Vector ```b```: ```python a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same magnitude and direction a.cross(b) # returns a new Vector that is the cross product of a and b a.dot(b) # returns a number that is the dot product of a and b a.to_tuple() # returns a tuple representation of the vector. str(a) # returns a string representation of the vector in the form "" a.magnitude # returns a number that is the magnitude (geometric length) of vector a. a.x # gets x component a.y # gets y component a.z # gets z component Vector([a,b,c]) # creates a new Vector from the supplied 3D array. Vector(a,b,c) # same as above ``` The test cases will not mutate the produced Vector objects, so don't worry about that.
class Vector: def __init__(self, a, b = None, c = None): if c is None: a, b, c = a self.x = a self.y = b self.z = c self.magnitude = ((self.x) ** 2 + (self.y) ** 2 + (self.z) ** 2) ** .5 def to_tuple(self): return (self.x, self.y, self.z) def __eq__(self, other): return self.to_tuple() == other.to_tuple() def cross(self, other): a = self.y * other.z - self.z * other.y b = self.z * other.x - self.x * other.z c = self.x * other.y - self.y * other.x return Vector(a, b, c) def dot(self, other): return self.x * other.x + self.y * other.y + self.z * other.z def __str__(self): return "<{}, {}, {}>".format(*self.to_tuple()) def __add__(self, other): return Vector(self.x + other.x, self.y + other.y, self.z + other.z) def __sub__(self, other): return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector ```a``` and Vector ```b```: ```python a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same magnitude and direction a.cross(b) # returns a new Vector that is the cross product of a and b a.dot(b) # returns a number that is the dot product of a and b a.to_tuple() # returns a tuple representation of the vector. str(a) # returns a string representation of the vector in the form "" a.magnitude # returns a number that is the magnitude (geometric length) of vector a. a.x # gets x component a.y # gets y component a.z # gets z component Vector([a,b,c]) # creates a new Vector from the supplied 3D array. Vector(a,b,c) # same as above ``` The test cases will not mutate the produced Vector objects, so don't worry about that.
from math import sqrt #Code recycled from my Kata solution class Vector(object): __3DVECSIZE__= 3 def __init__(self, *args, **kwargs): numArgs = len(args) if numArgs == 1: #Scenario: vecList is provided vecList = args[0] else: #Scenario: a, b, c provided vecList = [args[0], args[1], args[2]] self.myVecSize = len(vecList) self.__checkForSizeException__(vecList) self.myComponents = vecList self.x = self.myComponents[0] self.y = self.myComponents[1] self.z = self.myComponents[2] self.magnitude = self.norm() #-----end constructor def __add__(self, v): return self.add(v) def __sub__(self, v): return self.subtract(v) def __eq__(self, v): return self.equals(v) def __str__(self): return self.toString('<','>') def __checkForSizeException__(self, v): lenPassedVec = len(v) if self.myVecSize != self.__3DVECSIZE__: raise ValueError('Missmatch of vector size: Size ', str(lenPassedVec), 'applied to vector of size ', str(self.myVecSize)) else: return lenPassedVec #-----end function def add(self, v): self.__checkForSizeException__(v.myComponents) return Vector([sum(x) for x in zip(self.myComponents, v.myComponents)]) #-----end function def subtract(self, v): negV = Vector([-comp for comp in v.myComponents]) return self.add(negV) #-----end function #order of cross product is self cross v def cross(self, v): self.__checkForSizeException__(v.myComponents) xCrossComp = self.y*v.z - self.z*v.y yCrossComp = self.z*v.x - self.x*v.z zCrossComp = self.x*v.y - self.y*v.x return Vector([xCrossComp, yCrossComp, zCrossComp]) #---end function def dot(self, v): self.__checkForSizeException__(v.myComponents) return (sum([ a*b for a,b in zip(self.myComponents, v.myComponents)])) #-----end function def norm(self): return sqrt( self.dot(self) ) #-----end function def toString(self, groupSymbolLeft, groupSymbolRight): strVec = groupSymbolLeft for i in range(self.myVecSize-1): strVec += str(self.myComponents[i]) + ', ' strVec += str(self.myComponents[-1]) + groupSymbolRight return strVec #-----end function def to_tuple(self): return tuple(self.myComponents) def equals(self, v): try: lenV = self.__checkForSizeException__(v.myComponents) except: return False else: for i in range(lenV): if self.myComponents[i] != v.myComponents[i]: return False return True #-----end function #---end vector class
Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector ```a``` and Vector ```b```: ```python a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same magnitude and direction a.cross(b) # returns a new Vector that is the cross product of a and b a.dot(b) # returns a number that is the dot product of a and b a.to_tuple() # returns a tuple representation of the vector. str(a) # returns a string representation of the vector in the form "" a.magnitude # returns a number that is the magnitude (geometric length) of vector a. a.x # gets x component a.y # gets y component a.z # gets z component Vector([a,b,c]) # creates a new Vector from the supplied 3D array. Vector(a,b,c) # same as above ``` The test cases will not mutate the produced Vector objects, so don't worry about that.
from math import sqrt class Vector: def __init__(self, *vector): self.vector = vector if len(vector) == 1: self.vector = tuple(vector[0]) self.x, self.y, self.z = self.vector self.magnitude = sqrt(sum(v*v for v in self.vector)) def to_tuple(self): return tuple(self.vector) def __str__(self): return f'<{self.x}, {self.y}, {self.z}>' def __add__(self, other): x, y, z = (a + other.vector[i] for i,a in enumerate(self.vector)) return Vector(x, y, z) def __sub__(self, other): x, y, z = (a - other.vector[i] for i,a in enumerate(self.vector)) return Vector(x, y, z) def __eq__(self, other): return all(v == other.vector[i] for i, v in enumerate(self.vector)) def dot(self, other): return sum(v * other.vector[i] for i, v in enumerate(self.vector)) def cross(self, other): x = self.y * other.z - self.z * other.y y = -(self.x * other.z - self.z * other.x) z = self.x * other.y - self.y * other.x return Vector(x, y, z)
Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector ```a``` and Vector ```b```: ```python a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same magnitude and direction a.cross(b) # returns a new Vector that is the cross product of a and b a.dot(b) # returns a number that is the dot product of a and b a.to_tuple() # returns a tuple representation of the vector. str(a) # returns a string representation of the vector in the form "" a.magnitude # returns a number that is the magnitude (geometric length) of vector a. a.x # gets x component a.y # gets y component a.z # gets z component Vector([a,b,c]) # creates a new Vector from the supplied 3D array. Vector(a,b,c) # same as above ``` The test cases will not mutate the produced Vector objects, so don't worry about that.
import math import operator class Vector: def __init__(self, *args): self.x, self.y, self.z = self.args = tuple(args[0] if len(args) == 1 else args) self.magnitude = math.sqrt(sum(i ** 2 for i in self.args)) def __str__(self): return '<{}>'.format(', '.join(map(str, self.args))) def __eq__(self, other): return self.args == other.args def __add__(self, other): return Vector(*map(operator.add, self.args, other.args)) def __sub__(self, other): return Vector(*map(operator.sub, self.args, other.args)) def dot(self, other): return sum(map(operator.mul, self.args, other.args)) def to_tuple(self): return self.args def cross(self, other): return Vector( self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, self.x * other.y - self.y * other.x, )
Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector ```a``` and Vector ```b```: ```python a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same magnitude and direction a.cross(b) # returns a new Vector that is the cross product of a and b a.dot(b) # returns a number that is the dot product of a and b a.to_tuple() # returns a tuple representation of the vector. str(a) # returns a string representation of the vector in the form "" a.magnitude # returns a number that is the magnitude (geometric length) of vector a. a.x # gets x component a.y # gets y component a.z # gets z component Vector([a,b,c]) # creates a new Vector from the supplied 3D array. Vector(a,b,c) # same as above ``` The test cases will not mutate the produced Vector objects, so don't worry about that.
import numpy as np class Vector: def __init__(self, *args): self.vec = np.array(args if type(args[0]) == int else args[0]) self.x, self.y, self.z, self.magnitude = *self.vec, np.linalg.norm(self.vec) def __str__(self): return f'<{self.x}, {self.y}, {self.z}>' def __eq__(self, other): if type(other) != Vector: return False return np.array_equal(self.vec, other.vec) def __add__(self, other): return Vector(self.vec + other.vec) def __sub__(self, other): return Vector(self.vec - other.vec) def cross(self, other): return Vector(np.cross(self.vec, other.vec)) def dot(self, other): return np.dot(self.vec, other.vec) def to_tuple(self): return tuple(self.vec)
Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector ```a``` and Vector ```b```: ```python a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same magnitude and direction a.cross(b) # returns a new Vector that is the cross product of a and b a.dot(b) # returns a number that is the dot product of a and b a.to_tuple() # returns a tuple representation of the vector. str(a) # returns a string representation of the vector in the form "" a.magnitude # returns a number that is the magnitude (geometric length) of vector a. a.x # gets x component a.y # gets y component a.z # gets z component Vector([a,b,c]) # creates a new Vector from the supplied 3D array. Vector(a,b,c) # same as above ``` The test cases will not mutate the produced Vector objects, so don't worry about that.
class Vector: def __init__(s,*A): s.x,s.y,s.z=len(A)!=1 and A or A[0] s.magnitude=(s.x**2+s.y**2+s.z**2)**.5 __str__=lambda s:"<%d, %d, %d>"%(s.x,s.y,s.z) __eq__=lambda s,o:(s.x,s.y,s.z)==(o.x,o.y,o.z) __add__=lambda s,o:Vector([s.x+o.x,s.y+o.y,s.z+o.z]) __sub__=lambda s,o:Vector([s.x-o.x,s.y-o.y,s.z-o.z]) to_tuple=lambda s:(s.x,s.y,s.z) dot=lambda s,o:s.x*o.x+s.y*o.y+s.z*o.z cross=lambda s,o:Vector(s.y*o.z-s.z*o.y,s.z*o.x-s.x*o.z,s.x*o.y-s.y*o.x)
Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector ```a``` and Vector ```b```: ```python a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same magnitude and direction a.cross(b) # returns a new Vector that is the cross product of a and b a.dot(b) # returns a number that is the dot product of a and b a.to_tuple() # returns a tuple representation of the vector. str(a) # returns a string representation of the vector in the form "" a.magnitude # returns a number that is the magnitude (geometric length) of vector a. a.x # gets x component a.y # gets y component a.z # gets z component Vector([a,b,c]) # creates a new Vector from the supplied 3D array. Vector(a,b,c) # same as above ``` The test cases will not mutate the produced Vector objects, so don't worry about that.
from math import sqrt class Vector: def __init__(self, *args): if isinstance(args[0], (list, tuple)): self.x, self.y, self.z = args[0] else: self.x, self.y, self.z = args def __add__(self, other): return Vector( self.x + other.x, self.y + other.y, self.z + other.z ) def __sub__(self, other): return Vector( self.x - other.x, self.y - other.y, self.z - other.z ) def __eq__(self, other): if isinstance(other, (list, tuple)): other = Vector(other) return ( self.magnitude == other.magnitude and self.x / other.x == self.y / other.y == self.z / other.z ) def __str__(self): return "<%d, %d, %d>" % (self.x, self.y, self.z) def to_tuple(self): return (self.x, self.y, self.z) def cross(self, other): return Vector( self.y * other.z - other.y * self.z, -(self.x * other.z - other.x * self.z), self.x * other.y - other.x * self.y ) def dot(self, other): return self.x * other.x + self.y * other.y + self.z * other.z @property def magnitude(self): return sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all! You will be given a list of animals, which you need to check to see which animals there are at least two of, and then return a dictionary containing the name of the animal along with the fact that there are 2 of them to bring onto the ark. --- ```python >>> two_by_two(['goat', 'goat', 'rabbit', 'rabbit', 'rabbit', 'duck', 'horse', 'horse', 'swan']) {'goat': 2, 'horse': 2, 'rabbit': 2} # If the list of animals is empty, return False as there are no animals to bring onto the ark and we are all doomed!!! >>> two_by_two([]) False # If there are no pairs of animals, return an empty dictionary >>> two_by_two(['goat']) {} ```
def two_by_two(animals): return {x:2 for x in animals if animals.count(x) > 1} if animals else False
A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all! You will be given a list of animals, which you need to check to see which animals there are at least two of, and then return a dictionary containing the name of the animal along with the fact that there are 2 of them to bring onto the ark. --- ```python >>> two_by_two(['goat', 'goat', 'rabbit', 'rabbit', 'rabbit', 'duck', 'horse', 'horse', 'swan']) {'goat': 2, 'horse': 2, 'rabbit': 2} # If the list of animals is empty, return False as there are no animals to bring onto the ark and we are all doomed!!! >>> two_by_two([]) False # If there are no pairs of animals, return an empty dictionary >>> two_by_two(['goat']) {} ```
from collections import Counter def two_by_two(animals): return bool(animals) and {key : 2 for key, value in Counter(animals).items() if value >= 2}
A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all! You will be given a list of animals, which you need to check to see which animals there are at least two of, and then return a dictionary containing the name of the animal along with the fact that there are 2 of them to bring onto the ark. --- ```python >>> two_by_two(['goat', 'goat', 'rabbit', 'rabbit', 'rabbit', 'duck', 'horse', 'horse', 'swan']) {'goat': 2, 'horse': 2, 'rabbit': 2} # If the list of animals is empty, return False as there are no animals to bring onto the ark and we are all doomed!!! >>> two_by_two([]) False # If there are no pairs of animals, return an empty dictionary >>> two_by_two(['goat']) {} ```
def two_by_two(animals): return {animal: 2 for animal in set(animals) if animals.count(animal) > 1} if len(animals) else False
A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all! You will be given a list of animals, which you need to check to see which animals there are at least two of, and then return a dictionary containing the name of the animal along with the fact that there are 2 of them to bring onto the ark. --- ```python >>> two_by_two(['goat', 'goat', 'rabbit', 'rabbit', 'rabbit', 'duck', 'horse', 'horse', 'swan']) {'goat': 2, 'horse': 2, 'rabbit': 2} # If the list of animals is empty, return False as there are no animals to bring onto the ark and we are all doomed!!! >>> two_by_two([]) False # If there are no pairs of animals, return an empty dictionary >>> two_by_two(['goat']) {} ```
def two_by_two(animals): return {animal: 2 for animal in set(animals) if animals.count(animal) > 1} if animals else False
A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all! You will be given a list of animals, which you need to check to see which animals there are at least two of, and then return a dictionary containing the name of the animal along with the fact that there are 2 of them to bring onto the ark. --- ```python >>> two_by_two(['goat', 'goat', 'rabbit', 'rabbit', 'rabbit', 'duck', 'horse', 'horse', 'swan']) {'goat': 2, 'horse': 2, 'rabbit': 2} # If the list of animals is empty, return False as there are no animals to bring onto the ark and we are all doomed!!! >>> two_by_two([]) False # If there are no pairs of animals, return an empty dictionary >>> two_by_two(['goat']) {} ```
from collections import Counter def two_by_two(a): return {x: 2 for x, y in Counter(a).items() if y > 1} if a else 0
A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all! You will be given a list of animals, which you need to check to see which animals there are at least two of, and then return a dictionary containing the name of the animal along with the fact that there are 2 of them to bring onto the ark. --- ```python >>> two_by_two(['goat', 'goat', 'rabbit', 'rabbit', 'rabbit', 'duck', 'horse', 'horse', 'swan']) {'goat': 2, 'horse': 2, 'rabbit': 2} # If the list of animals is empty, return False as there are no animals to bring onto the ark and we are all doomed!!! >>> two_by_two([]) False # If there are no pairs of animals, return an empty dictionary >>> two_by_two(['goat']) {} ```
from collections import Counter def two_by_two(animals): if not animals: return False return {animal: 2 for animal, count in Counter(animals).items() if count > 1}
A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all! You will be given a list of animals, which you need to check to see which animals there are at least two of, and then return a dictionary containing the name of the animal along with the fact that there are 2 of them to bring onto the ark. --- ```python >>> two_by_two(['goat', 'goat', 'rabbit', 'rabbit', 'rabbit', 'duck', 'horse', 'horse', 'swan']) {'goat': 2, 'horse': 2, 'rabbit': 2} # If the list of animals is empty, return False as there are no animals to bring onto the ark and we are all doomed!!! >>> two_by_two([]) False # If there are no pairs of animals, return an empty dictionary >>> two_by_two(['goat']) {} ```
from collections import Counter def two_by_two(animals): if not animals: return False return {k: 2 for k, v in Counter(animals).items() if v >= 2}
A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all! You will be given a list of animals, which you need to check to see which animals there are at least two of, and then return a dictionary containing the name of the animal along with the fact that there are 2 of them to bring onto the ark. --- ```python >>> two_by_two(['goat', 'goat', 'rabbit', 'rabbit', 'rabbit', 'duck', 'horse', 'horse', 'swan']) {'goat': 2, 'horse': 2, 'rabbit': 2} # If the list of animals is empty, return False as there are no animals to bring onto the ark and we are all doomed!!! >>> two_by_two([]) False # If there are no pairs of animals, return an empty dictionary >>> two_by_two(['goat']) {} ```
two_by_two=lambda a:a>[]and{k:2for k in a if a.count(k)>1}
A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all! You will be given a list of animals, which you need to check to see which animals there are at least two of, and then return a dictionary containing the name of the animal along with the fact that there are 2 of them to bring onto the ark. --- ```python >>> two_by_two(['goat', 'goat', 'rabbit', 'rabbit', 'rabbit', 'duck', 'horse', 'horse', 'swan']) {'goat': 2, 'horse': 2, 'rabbit': 2} # If the list of animals is empty, return False as there are no animals to bring onto the ark and we are all doomed!!! >>> two_by_two([]) False # If there are no pairs of animals, return an empty dictionary >>> two_by_two(['goat']) {} ```
from collections import*;two_by_two=lambda a:a>[]and{k:2for k,v in Counter(a).items()if v>1}
A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all! You will be given a list of animals, which you need to check to see which animals there are at least two of, and then return a dictionary containing the name of the animal along with the fact that there are 2 of them to bring onto the ark. --- ```python >>> two_by_two(['goat', 'goat', 'rabbit', 'rabbit', 'rabbit', 'duck', 'horse', 'horse', 'swan']) {'goat': 2, 'horse': 2, 'rabbit': 2} # If the list of animals is empty, return False as there are no animals to bring onto the ark and we are all doomed!!! >>> two_by_two([]) False # If there are no pairs of animals, return an empty dictionary >>> two_by_two(['goat']) {} ```
from collections import Counter def two_by_two(animals): return bool(animals) and dict((k, 2) for (k, v) in Counter(animals).items() if v>=2)
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): return sum(inp[:inp.index(0)])
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
from itertools import takewhile; house_numbers_sum = lambda arr: sum(x for x in takewhile(lambda x: x!=0, arr))
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): total = 0 for house_num in inp: if house_num == 0: return total else: total += house_num
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
from itertools import takewhile def house_numbers_sum(inp): return sum(takewhile(bool,inp))
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): return sum(inp[ : inp.index(0) + 1])
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
import itertools def house_numbers_sum(inp): return sum(itertools.takewhile(lambda n: n, inp))
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
house_numbers_sum = lambda l: sum(l[:l.index(0)])
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp, res = 0): for i in inp: res += i if i == 0: return res
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): total = 0 for num in inp: if num != 0: total += num else: break return total
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): return sum(next(iter([])) if i == 0 else i for i in inp)
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
from itertools import takewhile def house_numbers_sum(inp): return sum(takewhile((0).__ne__, inp))
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): return sum(inp[:inp.index(0)+1]) if inp[0] !=0 else 0
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): sum = 0 for num in inp: if num is 0: return sum else: sum+= num
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): return sum(__import__('itertools').takewhile(bool, inp))
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): sum=0 for n in inp: if n==0: return sum sum=sum+n return sum
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(A): return sum(A[:A.index(0)])
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): zero = inp.index(0) return sum(inp[:zero])
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): list = [] for i in range(0, len(inp)+1): if inp[i] == 0: break else: list.append(inp[i]) return sum(list)
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): total = 0 for num in inp: if num == 0: break else: total +=num return total
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): suma = [] for i in range(0, len(inp)+1): if inp[i] == 0: break else: suma.append(inp[i]) return sum(suma)
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(inp): s=0 for x in inp: if x==0: return s s=s+x
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order. At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house. For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path. # Example For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`. The answer was obtained as `5 + 1 + 2 + 3 = 11`. # Input/Output - `[input]` integer array `inputArray` Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.` - `[output]` an integer
def house_numbers_sum(arr): sum = 0 for i in range(len(arr)): if(arr[i] == 0): break else: sum += arr[i] return sum