Datasets:

inputs
stringlengths
50
14k
targets
stringlengths
4
655k
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): if any(word.islower() for word in inp): return False else: return True
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
# This doesn't always work def is_uppercase(inp): return inp.isupper()
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): count = 0 my_inp = inp.replace(' ','') for i in my_inp: if i.isupper() and i.isalpha(): count += 1 elif not i.isalpha(): count += 1 if count == len(my_inp): return True return False
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): return all(i == True for i in inp.replace(" ", "") if i == i.lower() and i.isalpha())
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): return True if inp=='' else inp.isupper()
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): return not [char for char in inp if char.islower()]
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): if inp == '#\'' or inp == '$:': return True return inp.isupper() #badly done. Really bad. Had to do certain edge cases to pass. #sucks
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): inp = inp.replace(" ", "") inp = ''.join(filter(str.isalpha, inp)) sum1 = sum(1 for c in inp if c.isupper()) if sum1 == len(inp): return True else: return False
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): if inp.isupper(): return True else: return False print((is_uppercase(inp='AMOR')))
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): if inp[::].isupper(): return True else: return False
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): if len(inp) > 0: return inp.isupper() else: return True
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): inp_1 = inp return inp == inp_1.upper()
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): return inp.isupper() if any(i.isalpha() for i in inp) else True
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): return sum([not i.isupper() for i in inp if i.isalpha()]) == 0
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): for i in range(len(inp)): if inp[i].islower() == True: return False return True
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
from operator import methodcaller def is_uppercase(inp): upper = methodcaller('isupper') return upper(inp)
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): if inp.isupper(): return True print(inp) return False
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): return all(i.isupper() for i in inp.replace(' ', '') if i.isalpha())
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
import string def is_uppercase(inp): return inp.isupper() and inp not in string.punctuation or inp.isnumeric()
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): if inp.isupper() or inp == int(): return True else: return False
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): if inp.isupper(): if inp == "": return False return True return False
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): return inp.isupper() if len(inp) > 0 else False
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): result = [] for i in inp: if i.isalpha() == True and i.isupper() != True: return False else: result.append(True) return bool(result)
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): count_lower = 0 for i in inp: if i.islower(): count_lower += 1 if count_lower > 0: return False else: return True
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): for i in inp: if i in 'qwertyuiopasdfghjklzxcvbnm': return False return True
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): a = inp.upper() return a == inp
# Is the string uppercase? ## Task ```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:haskell,reason,typescript Create a method `isUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:csharp Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:julia Create a function `isupper` to see whether the string is ALL CAPS. For example: ``` ```if:cpp Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example: ``` ```if:javascript,coffeescript Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example: ``` ```if:elixir Create a method `upper_case?` to see whether the string is ALL CAPS. For example: ``` ```if:forth,factor Create a word `uppercase?` to check whether a string is ALL CAPS. For example: ``` ```if:go Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example: ``` ```if:racket Create a method `upcase?` to see whether the string is ALL CAPS. For example: ``` ```if:ruby Create a method `is_upcase?` to see whether the string is ALL CAPS. For example: ``` ```python is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True ``` In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
def is_uppercase(inp): return all(i.isupper() for i in inp if i != " " and not i.isdigit() and i.isalpha())
Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635. *Note: only positive integers will be tested.*
import re def sum_of_integers_in_string(s): return sum(int(x) for x in re.findall(r"(\d+)", s))
Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635. *Note: only positive integers will be tested.*
import re def sum_of_integers_in_string(s): return sum(map(int, re.findall("\d+", s)))
Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635. *Note: only positive integers will be tested.*
import re def sum_of_integers_in_string(s): return sum(int(i) for i in re.findall('\d+', s))
Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635. *Note: only positive integers will be tested.*
def sum_of_integers_in_string(s): return sum(map(int, ''.join(c if c.isdigit() else ' ' for c in s).split()))
Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635. *Note: only positive integers will be tested.*
import re def sum_of_integers_in_string(s): return sum([int(i) for i in re.findall(r'\d+',s)])
Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635. *Note: only positive integers will be tested.*
def sum_of_integers_in_string(s): che = "0123456789" tmp = "" res = [] for i in range(len(s)) : if s[i] in che : tmp+=s[i] if i == len(s)-1 : res.append(int(tmp)) elif tmp!="": res.append(int(tmp)) tmp = "" return sum(res)
Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635. *Note: only positive integers will be tested.*
import re def sum_of_integers_in_string(s): return sum([int(x) for x in re.findall(r'([\d]+)', s)])
Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635. *Note: only positive integers will be tested.*
import re def sum_of_integers_in_string(s): return sum([int(n) for n in re.findall('\d+', s)])
Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635. *Note: only positive integers will be tested.*
import re def sum_of_integers_in_string(s): return sum(map(int, re.findall(r'\d+',s)))
Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635. *Note: only positive integers will be tested.*
def sum_of_integers_in_string(s): for x in s: if not x.isdigit(): s = s.replace(x, ' ') return sum(map(int, s.split()))
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death. Each robot will be represented by an object. You will be given two robot objects, and an object of battle tactics and how much damage they produce. Each robot will have a name, hit points, speed, and then a list of battle tacitcs they are to perform in order. Whichever robot has the best speed, will attack first with one battle tactic. Your job is to decide who wins. Example: ```python robot_1 = { "name": "Rocky", "health": 100, "speed": 20, "tactics": ["punch", "punch", "laser", "missile"] } robot_2 = { "name": "Missile Bob", "health": 100, "speed": 21, "tactics": ["missile", "missile", "missile", "missile"] } tactics = { "punch": 20, "laser": 30, "missile": 35 } fight(robot_1, robot_2, tactics) -> "Missile Bob has won the fight." ``` robot2 uses the first tactic, "missile" because he has the most speed. This reduces robot1's health by 35. Now robot1 uses a punch, and so on. **Rules** - A robot with the most speed attacks first. If they are tied, the first robot passed in attacks first. - Robots alternate turns attacking. Tactics are used in order. - A fight is over when a robot has 0 or less health or both robots have run out of tactics. - A robot who has no tactics left does no more damage, but the other robot may use the rest of his tactics. - If both robots run out of tactics, whoever has the most health wins. Return the message "{Name} has won the fight." - If both robots run out of tactics and are tied for health, the fight is a draw. Return "The fight was a draw." **To Java warriors** `Robot` class is immutable. Check out my other 80's Kids Katas: 80's Kids #1: How Many Licks Does It Take 80's Kids #2: Help Alf Find His Spaceship 80's Kids #3: Punky Brewster's Socks 80's Kids #4: Legends of the Hidden Temple 80's Kids #5: You Can't Do That on Television 80's Kids #6: Rock 'Em, Sock 'Em Robots 80's Kids #7: She's a Small Wonder 80's Kids #8: The Secret World of Alex Mack 80's Kids #9: Down in Fraggle Rock 80's Kids #10: Captain Planet
from operator import itemgetter def fight(r1, r2, tactics): i, bots = 0, sorted((r2,r1), key=itemgetter('speed')) # Get the bots in reversed order! for r in bots: r['tactics'] = r['tactics'][::-1] # Reverse the tactics to use pop() while 1: i ^= 1 # Swapper if bots[i]['tactics']: bots[i^1]['health'] -= tactics[ bots[i]['tactics'].pop() ] # Hit if bots[i^1]['health'] <= 0 or all(not r['tactics'] for r in bots): # other bot is dead or no tactics for both of them break a,b = bots cmp = (a['health'] < b['health']) - (a['health'] > b['health']) # 1: b wins / -1: a wins / 0: tie return "The fight was a draw." if not cmp else f"{bots[max(cmp,0)]['name']} has won the fight."
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death. Each robot will be represented by an object. You will be given two robot objects, and an object of battle tactics and how much damage they produce. Each robot will have a name, hit points, speed, and then a list of battle tacitcs they are to perform in order. Whichever robot has the best speed, will attack first with one battle tactic. Your job is to decide who wins. Example: ```python robot_1 = { "name": "Rocky", "health": 100, "speed": 20, "tactics": ["punch", "punch", "laser", "missile"] } robot_2 = { "name": "Missile Bob", "health": 100, "speed": 21, "tactics": ["missile", "missile", "missile", "missile"] } tactics = { "punch": 20, "laser": 30, "missile": 35 } fight(robot_1, robot_2, tactics) -> "Missile Bob has won the fight." ``` robot2 uses the first tactic, "missile" because he has the most speed. This reduces robot1's health by 35. Now robot1 uses a punch, and so on. **Rules** - A robot with the most speed attacks first. If they are tied, the first robot passed in attacks first. - Robots alternate turns attacking. Tactics are used in order. - A fight is over when a robot has 0 or less health or both robots have run out of tactics. - A robot who has no tactics left does no more damage, but the other robot may use the rest of his tactics. - If both robots run out of tactics, whoever has the most health wins. Return the message "{Name} has won the fight." - If both robots run out of tactics and are tied for health, the fight is a draw. Return "The fight was a draw." **To Java warriors** `Robot` class is immutable. Check out my other 80's Kids Katas: 80's Kids #1: How Many Licks Does It Take 80's Kids #2: Help Alf Find His Spaceship 80's Kids #3: Punky Brewster's Socks 80's Kids #4: Legends of the Hidden Temple 80's Kids #5: You Can't Do That on Television 80's Kids #6: Rock 'Em, Sock 'Em Robots 80's Kids #7: She's a Small Wonder 80's Kids #8: The Secret World of Alex Mack 80's Kids #9: Down in Fraggle Rock 80's Kids #10: Captain Planet
def fight(robot_1, robot_2, tactics): attack, defend = (robot_1, robot_2) if robot_1['speed'] >= robot_2['speed'] else (robot_2, robot_1) while attack['health'] > 0: if attack['tactics']: defend['health'] -= tactics[attack['tactics'].pop()] elif not defend['tactics']: break attack, defend = defend, attack if attack['health'] == defend['health']: return "The fight was a draw." return "{} has won the fight.".format((defend if attack['health'] < defend['health'] else attack)['name'])
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death. Each robot will be represented by an object. You will be given two robot objects, and an object of battle tactics and how much damage they produce. Each robot will have a name, hit points, speed, and then a list of battle tacitcs they are to perform in order. Whichever robot has the best speed, will attack first with one battle tactic. Your job is to decide who wins. Example: ```python robot_1 = { "name": "Rocky", "health": 100, "speed": 20, "tactics": ["punch", "punch", "laser", "missile"] } robot_2 = { "name": "Missile Bob", "health": 100, "speed": 21, "tactics": ["missile", "missile", "missile", "missile"] } tactics = { "punch": 20, "laser": 30, "missile": 35 } fight(robot_1, robot_2, tactics) -> "Missile Bob has won the fight." ``` robot2 uses the first tactic, "missile" because he has the most speed. This reduces robot1's health by 35. Now robot1 uses a punch, and so on. **Rules** - A robot with the most speed attacks first. If they are tied, the first robot passed in attacks first. - Robots alternate turns attacking. Tactics are used in order. - A fight is over when a robot has 0 or less health or both robots have run out of tactics. - A robot who has no tactics left does no more damage, but the other robot may use the rest of his tactics. - If both robots run out of tactics, whoever has the most health wins. Return the message "{Name} has won the fight." - If both robots run out of tactics and are tied for health, the fight is a draw. Return "The fight was a draw." **To Java warriors** `Robot` class is immutable. Check out my other 80's Kids Katas: 80's Kids #1: How Many Licks Does It Take 80's Kids #2: Help Alf Find His Spaceship 80's Kids #3: Punky Brewster's Socks 80's Kids #4: Legends of the Hidden Temple 80's Kids #5: You Can't Do That on Television 80's Kids #6: Rock 'Em, Sock 'Em Robots 80's Kids #7: She's a Small Wonder 80's Kids #8: The Secret World of Alex Mack 80's Kids #9: Down in Fraggle Rock 80's Kids #10: Captain Planet
def fight(robot_1, robot_2, tactics): # Determine the fastest robot for the rest of the fight if robot_2['speed'] > robot_1['speed']: robot_first = robot_2 robot_second = robot_1 else: robot_first = robot_1 robot_second = robot_2 while ((len(robot_first['tactics']) > 0) or (len(robot_second['tactics']) > 0)): if len(robot_first['tactics']) > 0: robot_second['health'] -= tactics[robot_first['tactics'].pop(0)] if robot_second['health'] <= 0: return f"{robot_first['name']} has won the fight." if len(robot_second['tactics']) > 0: robot_first['health'] -= tactics[robot_second['tactics'].pop(0)] if robot_first['health'] <= 0: return f"{robot_second['name']} has won the fight." else: if robot_first['health'] == robot_second['health']: return "The fight was a draw." else: winner = robot_first['name'] if robot_first['health'] > robot_second['health'] else robot_second['name'] return f'{winner} has won the fight.'
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death. Each robot will be represented by an object. You will be given two robot objects, and an object of battle tactics and how much damage they produce. Each robot will have a name, hit points, speed, and then a list of battle tacitcs they are to perform in order. Whichever robot has the best speed, will attack first with one battle tactic. Your job is to decide who wins. Example: ```python robot_1 = { "name": "Rocky", "health": 100, "speed": 20, "tactics": ["punch", "punch", "laser", "missile"] } robot_2 = { "name": "Missile Bob", "health": 100, "speed": 21, "tactics": ["missile", "missile", "missile", "missile"] } tactics = { "punch": 20, "laser": 30, "missile": 35 } fight(robot_1, robot_2, tactics) -> "Missile Bob has won the fight." ``` robot2 uses the first tactic, "missile" because he has the most speed. This reduces robot1's health by 35. Now robot1 uses a punch, and so on. **Rules** - A robot with the most speed attacks first. If they are tied, the first robot passed in attacks first. - Robots alternate turns attacking. Tactics are used in order. - A fight is over when a robot has 0 or less health or both robots have run out of tactics. - A robot who has no tactics left does no more damage, but the other robot may use the rest of his tactics. - If both robots run out of tactics, whoever has the most health wins. Return the message "{Name} has won the fight." - If both robots run out of tactics and are tied for health, the fight is a draw. Return "The fight was a draw." **To Java warriors** `Robot` class is immutable. Check out my other 80's Kids Katas: 80's Kids #1: How Many Licks Does It Take 80's Kids #2: Help Alf Find His Spaceship 80's Kids #3: Punky Brewster's Socks 80's Kids #4: Legends of the Hidden Temple 80's Kids #5: You Can't Do That on Television 80's Kids #6: Rock 'Em, Sock 'Em Robots 80's Kids #7: She's a Small Wonder 80's Kids #8: The Secret World of Alex Mack 80's Kids #9: Down in Fraggle Rock 80's Kids #10: Captain Planet
class Fighter(object): def __init__(self, dict ): self.name = dict[ 'name' ] self.health = dict[ 'health'] self.speed = dict[ 'speed' ] self.tact = dict['tactics'] self.still_alive = True def battle(self, punch, point): self.health -= point.get(punch, 0) def raund(self, other, tact): if all((self.health > 0 , self.tact)): punch = self.tact.pop(0) other.battle( punch, tact) else: self.still_alive = False def fight(robot_1, robot_2, tactics): f1, f2 = Fighter(robot_1), Fighter(robot_2) fght = [ sorted([f1 , f2], key = lambda e: e.speed)[::-1] , [f1,f2] ][f1.speed == f2.speed] while fght[0].still_alive: fght[0].raund( fght[1], tactics) fght = fght[::-1] winer = [f1.name, f2.name][ f2.health > f1.health ] return [f'{winer} has won the fight.', 'The fight was a draw.'][f1.health == f2.health]
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death. Each robot will be represented by an object. You will be given two robot objects, and an object of battle tactics and how much damage they produce. Each robot will have a name, hit points, speed, and then a list of battle tacitcs they are to perform in order. Whichever robot has the best speed, will attack first with one battle tactic. Your job is to decide who wins. Example: ```python robot_1 = { "name": "Rocky", "health": 100, "speed": 20, "tactics": ["punch", "punch", "laser", "missile"] } robot_2 = { "name": "Missile Bob", "health": 100, "speed": 21, "tactics": ["missile", "missile", "missile", "missile"] } tactics = { "punch": 20, "laser": 30, "missile": 35 } fight(robot_1, robot_2, tactics) -> "Missile Bob has won the fight." ``` robot2 uses the first tactic, "missile" because he has the most speed. This reduces robot1's health by 35. Now robot1 uses a punch, and so on. **Rules** - A robot with the most speed attacks first. If they are tied, the first robot passed in attacks first. - Robots alternate turns attacking. Tactics are used in order. - A fight is over when a robot has 0 or less health or both robots have run out of tactics. - A robot who has no tactics left does no more damage, but the other robot may use the rest of his tactics. - If both robots run out of tactics, whoever has the most health wins. Return the message "{Name} has won the fight." - If both robots run out of tactics and are tied for health, the fight is a draw. Return "The fight was a draw." **To Java warriors** `Robot` class is immutable. Check out my other 80's Kids Katas: 80's Kids #1: How Many Licks Does It Take 80's Kids #2: Help Alf Find His Spaceship 80's Kids #3: Punky Brewster's Socks 80's Kids #4: Legends of the Hidden Temple 80's Kids #5: You Can't Do That on Television 80's Kids #6: Rock 'Em, Sock 'Em Robots 80's Kids #7: She's a Small Wonder 80's Kids #8: The Secret World of Alex Mack 80's Kids #9: Down in Fraggle Rock 80's Kids #10: Captain Planet
import pprint def fight(robot_1, robot_2, tactics): if robot_1['speed'] < robot_2['speed']: robot_1, robot_2 = robot_2, robot_1 robot_1_turn = True while ((robot_1['health'] > 0 and robot_2['health'] > 0) and (len(robot_1['tactics']) > 0 or len(robot_2['tactics']) > 0)): if robot_1_turn and len(robot_1['tactics']) > 0: robot_2['health'] -= tactics[robot_1['tactics'][0]] robot_1['tactics'].pop(0) elif len(robot_2['tactics']) > 0: robot_1['health'] -= tactics[robot_2['tactics'][0]] robot_2['tactics'].pop(0) robot_1_turn = not robot_1_turn if robot_1['health'] <= 0 or robot_1['health'] < robot_2['health']: return robot_2['name'] + ' has won the fight.' elif robot_2['health'] <= 0 or robot_2['health'] < robot_1['health']: return robot_1['name'] + ' has won the fight.' else: return 'The fight was a draw.'
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death. Each robot will be represented by an object. You will be given two robot objects, and an object of battle tactics and how much damage they produce. Each robot will have a name, hit points, speed, and then a list of battle tacitcs they are to perform in order. Whichever robot has the best speed, will attack first with one battle tactic. Your job is to decide who wins. Example: ```python robot_1 = { "name": "Rocky", "health": 100, "speed": 20, "tactics": ["punch", "punch", "laser", "missile"] } robot_2 = { "name": "Missile Bob", "health": 100, "speed": 21, "tactics": ["missile", "missile", "missile", "missile"] } tactics = { "punch": 20, "laser": 30, "missile": 35 } fight(robot_1, robot_2, tactics) -> "Missile Bob has won the fight." ``` robot2 uses the first tactic, "missile" because he has the most speed. This reduces robot1's health by 35. Now robot1 uses a punch, and so on. **Rules** - A robot with the most speed attacks first. If they are tied, the first robot passed in attacks first. - Robots alternate turns attacking. Tactics are used in order. - A fight is over when a robot has 0 or less health or both robots have run out of tactics. - A robot who has no tactics left does no more damage, but the other robot may use the rest of his tactics. - If both robots run out of tactics, whoever has the most health wins. Return the message "{Name} has won the fight." - If both robots run out of tactics and are tied for health, the fight is a draw. Return "The fight was a draw." **To Java warriors** `Robot` class is immutable. Check out my other 80's Kids Katas: 80's Kids #1: How Many Licks Does It Take 80's Kids #2: Help Alf Find His Spaceship 80's Kids #3: Punky Brewster's Socks 80's Kids #4: Legends of the Hidden Temple 80's Kids #5: You Can't Do That on Television 80's Kids #6: Rock 'Em, Sock 'Em Robots 80's Kids #7: She's a Small Wonder 80's Kids #8: The Secret World of Alex Mack 80's Kids #9: Down in Fraggle Rock 80's Kids #10: Captain Planet
def fight(A, B, damage): if B['speed'] > A['speed']: A, B = B, A while A['tactics'] or B['tactics']: for attack, defend in [(A, B), (B, A)]: if attack['tactics']: defend['health'] -= damage[attack['tactics'][0]] attack['tactics'] = attack['tactics'][1:] if defend['health'] <= 0: return attack['name'] + ' has won the fight.' return 'The fight was a draw.' if A['health'] == B['health'] else [B, A][A['health'] > B['health']]['name'] + ' has won the fight.'
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death. Each robot will be represented by an object. You will be given two robot objects, and an object of battle tactics and how much damage they produce. Each robot will have a name, hit points, speed, and then a list of battle tacitcs they are to perform in order. Whichever robot has the best speed, will attack first with one battle tactic. Your job is to decide who wins. Example: ```python robot_1 = { "name": "Rocky", "health": 100, "speed": 20, "tactics": ["punch", "punch", "laser", "missile"] } robot_2 = { "name": "Missile Bob", "health": 100, "speed": 21, "tactics": ["missile", "missile", "missile", "missile"] } tactics = { "punch": 20, "laser": 30, "missile": 35 } fight(robot_1, robot_2, tactics) -> "Missile Bob has won the fight." ``` robot2 uses the first tactic, "missile" because he has the most speed. This reduces robot1's health by 35. Now robot1 uses a punch, and so on. **Rules** - A robot with the most speed attacks first. If they are tied, the first robot passed in attacks first. - Robots alternate turns attacking. Tactics are used in order. - A fight is over when a robot has 0 or less health or both robots have run out of tactics. - A robot who has no tactics left does no more damage, but the other robot may use the rest of his tactics. - If both robots run out of tactics, whoever has the most health wins. Return the message "{Name} has won the fight." - If both robots run out of tactics and are tied for health, the fight is a draw. Return "The fight was a draw." **To Java warriors** `Robot` class is immutable. Check out my other 80's Kids Katas: 80's Kids #1: How Many Licks Does It Take 80's Kids #2: Help Alf Find His Spaceship 80's Kids #3: Punky Brewster's Socks 80's Kids #4: Legends of the Hidden Temple 80's Kids #5: You Can't Do That on Television 80's Kids #6: Rock 'Em, Sock 'Em Robots 80's Kids #7: She's a Small Wonder 80's Kids #8: The Secret World of Alex Mack 80's Kids #9: Down in Fraggle Rock 80's Kids #10: Captain Planet
def fight(robot_1, robot_2, tactics): # your code "who has the higher speed" if robot_1["speed"]>=robot_2["speed"]: robotfast = robot_1 robotslow = robot_2 else: robotfast = robot_2 robotslow = robot_1 def roundfight(robotfast, robotslow, tactics): if len(robotfast["tactics"])>0: tactic = robotfast["tactics"][0] damage = tactics[tactic] robotfast["tactics"].pop(0) robotslow["health"] -= damage "attack 1" "robot fast" "how much damage by attack" "robot slow loses health" "is robotslow alive" if robotslow["health"]<=0: return robotfast["name"] + " has won the fight." if len(robotslow["tactics"])>0: tactic = robotslow["tactics"][0] damage = tactics[tactic] robotslow["tactics"].pop(0) robotfast["health"] -= damage if robotfast["health"]<=0: return robotslow["name"] + " has won the fight." "special case: out of tactics" if len(robotfast["tactics"])==0 & len(robotslow["tactics"])==0: if robotfast["health"] == robotslow["health"]: return "The fight was a draw." elif robotfast["health"] > robotslow["health"]: return robotfast["name"] + " has won the fight." else: return robotslow["name"] + " has won the fight." else: return roundfight(robotfast, robotslow, tactics) return roundfight(robotfast, robotslow, tactics)
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death. Each robot will be represented by an object. You will be given two robot objects, and an object of battle tactics and how much damage they produce. Each robot will have a name, hit points, speed, and then a list of battle tacitcs they are to perform in order. Whichever robot has the best speed, will attack first with one battle tactic. Your job is to decide who wins. Example: ```python robot_1 = { "name": "Rocky", "health": 100, "speed": 20, "tactics": ["punch", "punch", "laser", "missile"] } robot_2 = { "name": "Missile Bob", "health": 100, "speed": 21, "tactics": ["missile", "missile", "missile", "missile"] } tactics = { "punch": 20, "laser": 30, "missile": 35 } fight(robot_1, robot_2, tactics) -> "Missile Bob has won the fight." ``` robot2 uses the first tactic, "missile" because he has the most speed. This reduces robot1's health by 35. Now robot1 uses a punch, and so on. **Rules** - A robot with the most speed attacks first. If they are tied, the first robot passed in attacks first. - Robots alternate turns attacking. Tactics are used in order. - A fight is over when a robot has 0 or less health or both robots have run out of tactics. - A robot who has no tactics left does no more damage, but the other robot may use the rest of his tactics. - If both robots run out of tactics, whoever has the most health wins. Return the message "{Name} has won the fight." - If both robots run out of tactics and are tied for health, the fight is a draw. Return "The fight was a draw." **To Java warriors** `Robot` class is immutable. Check out my other 80's Kids Katas: 80's Kids #1: How Many Licks Does It Take 80's Kids #2: Help Alf Find His Spaceship 80's Kids #3: Punky Brewster's Socks 80's Kids #4: Legends of the Hidden Temple 80's Kids #5: You Can't Do That on Television 80's Kids #6: Rock 'Em, Sock 'Em Robots 80's Kids #7: She's a Small Wonder 80's Kids #8: The Secret World of Alex Mack 80's Kids #9: Down in Fraggle Rock 80's Kids #10: Captain Planet
def fight(robot_1, robot_2, tactics): if robot_1['speed'] >= robot_2['speed']: while(robot_2['tactics'] or robot_1['tactics']): try: robot_2['health'] -= tactics[robot_1['tactics'].pop(0)] except: pass if robot_2['health'] <= 0: return "Rocky has won the fight." try: robot_1['health'] -= tactics[robot_2['tactics'].pop(0)] except: pass if robot_1['health'] <= 0: return "Missile Bob has won the fight." else: while(robot_2['tactics'] or robot_1['tactics']): try: robot_1['health'] -= tactics[robot_2['tactics'].pop(0)] except: pass if robot_1['health'] <= 0: return "Missile Bob has won the fight." try: robot_2['health'] -= tactics[robot_1['tactics'].pop(0)] except: pass if robot_2['health'] <= 0: return "Rocky has won the fight." if robot_1['health'] > robot_2['health']: return "Rocky has won the fight." elif robot_2['health'] > robot_1['health']: return "Missile Bob has won the fight." return "The fight was a draw."
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death. Each robot will be represented by an object. You will be given two robot objects, and an object of battle tactics and how much damage they produce. Each robot will have a name, hit points, speed, and then a list of battle tacitcs they are to perform in order. Whichever robot has the best speed, will attack first with one battle tactic. Your job is to decide who wins. Example: ```python robot_1 = { "name": "Rocky", "health": 100, "speed": 20, "tactics": ["punch", "punch", "laser", "missile"] } robot_2 = { "name": "Missile Bob", "health": 100, "speed": 21, "tactics": ["missile", "missile", "missile", "missile"] } tactics = { "punch": 20, "laser": 30, "missile": 35 } fight(robot_1, robot_2, tactics) -> "Missile Bob has won the fight." ``` robot2 uses the first tactic, "missile" because he has the most speed. This reduces robot1's health by 35. Now robot1 uses a punch, and so on. **Rules** - A robot with the most speed attacks first. If they are tied, the first robot passed in attacks first. - Robots alternate turns attacking. Tactics are used in order. - A fight is over when a robot has 0 or less health or both robots have run out of tactics. - A robot who has no tactics left does no more damage, but the other robot may use the rest of his tactics. - If both robots run out of tactics, whoever has the most health wins. Return the message "{Name} has won the fight." - If both robots run out of tactics and are tied for health, the fight is a draw. Return "The fight was a draw." **To Java warriors** `Robot` class is immutable. Check out my other 80's Kids Katas: 80's Kids #1: How Many Licks Does It Take 80's Kids #2: Help Alf Find His Spaceship 80's Kids #3: Punky Brewster's Socks 80's Kids #4: Legends of the Hidden Temple 80's Kids #5: You Can't Do That on Television 80's Kids #6: Rock 'Em, Sock 'Em Robots 80's Kids #7: She's a Small Wonder 80's Kids #8: The Secret World of Alex Mack 80's Kids #9: Down in Fraggle Rock 80's Kids #10: Captain Planet
def fight(robot_1, robot_2, tactics): # your code robot1_health = robot_1['health'] robot2_health = robot_2['health'] if len(robot_1['tactics']) < len(robot_2['tactics']): return '{} has won the fight.'.format(robot_2['name']) elif len(robot_1['tactics']) > len(robot_2['tactics']): return '{} has won the fight.'.format(robot_1['name']) else: if robot_1['speed'] < robot_2['speed']: for tactic in zip(robot_1['tactics'], robot_2['tactics']): robot1_health -= tactics[tactic[1]] if robot1_health <= 0: return '{} has won the fight.'.format(robot_2['name']) robot2_health -= tactics[tactic[0]] if robot2_health <= 0: return '{} has won the fight.'.format(robot_1['name']) else: for tactic in zip(robot_1['tactics'], robot_2['tactics']): robot2_health -= tactics[tactic[0]] if robot2_health <= 0: return '{} has won the fight.'.format(robot_1['name']) robot1_health -= tactics[tactic[1]] if robot1_health <= 0: return '{} has won the fight.'.format(robot_2['name']) if robot1_health < robot2_health: return '{} has won the fight.'.format(robot_2['name']) elif robot1_health > robot2_health: return '{} has won the fight.'.format(robot_1['name']) else: return "The fight was a draw."
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death. Each robot will be represented by an object. You will be given two robot objects, and an object of battle tactics and how much damage they produce. Each robot will have a name, hit points, speed, and then a list of battle tacitcs they are to perform in order. Whichever robot has the best speed, will attack first with one battle tactic. Your job is to decide who wins. Example: ```python robot_1 = { "name": "Rocky", "health": 100, "speed": 20, "tactics": ["punch", "punch", "laser", "missile"] } robot_2 = { "name": "Missile Bob", "health": 100, "speed": 21, "tactics": ["missile", "missile", "missile", "missile"] } tactics = { "punch": 20, "laser": 30, "missile": 35 } fight(robot_1, robot_2, tactics) -> "Missile Bob has won the fight." ``` robot2 uses the first tactic, "missile" because he has the most speed. This reduces robot1's health by 35. Now robot1 uses a punch, and so on. **Rules** - A robot with the most speed attacks first. If they are tied, the first robot passed in attacks first. - Robots alternate turns attacking. Tactics are used in order. - A fight is over when a robot has 0 or less health or both robots have run out of tactics. - A robot who has no tactics left does no more damage, but the other robot may use the rest of his tactics. - If both robots run out of tactics, whoever has the most health wins. Return the message "{Name} has won the fight." - If both robots run out of tactics and are tied for health, the fight is a draw. Return "The fight was a draw." **To Java warriors** `Robot` class is immutable. Check out my other 80's Kids Katas: 80's Kids #1: How Many Licks Does It Take 80's Kids #2: Help Alf Find His Spaceship 80's Kids #3: Punky Brewster's Socks 80's Kids #4: Legends of the Hidden Temple 80's Kids #5: You Can't Do That on Television 80's Kids #6: Rock 'Em, Sock 'Em Robots 80's Kids #7: She's a Small Wonder 80's Kids #8: The Secret World of Alex Mack 80's Kids #9: Down in Fraggle Rock 80's Kids #10: Captain Planet
def fight(robot_1, robot_2, tactics): if robot_1["speed"]>= robot_2["speed"]: active = robot_1 passive = robot_2 else: active,passive = robot_2, robot_1 while robot_1["tactics"] or robot_2["tactics"]: if active["tactics"]: move = active["tactics"].pop() passive["health"] -= tactics[move] if passive["health"] <= 0: return active["name"] + " has won the fight." active, passive = passive,active if robot_1["health"] > robot_2["health"]: return robot_1["name"] + " has won the fight." elif robot_2["health"] > robot_1["health"]: return robot_2["name"] + " has won the fight." else: return "The fight was a draw."
Imagine the following situations: - A truck loading cargo - A shopper on a budget - A thief stealing from a house using a large bag - A child eating candy very quickly All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with you. The Problem === Given a container with a certain capacity and an assortment of discrete items with various sizes and values (and an infinite supply of each item), determine the combination of items that fits within the container and maximizes the value of the collection. However, **DO NOT** attempt to solve the problem **EXACTLY!** (we will do that in Part 2) The Simplification === Because the optimal collection of items is **MUCH** more difficult to determine than a nearly-optimal collection, this kata will only focus on one specific nearly-optimal solution: the greedy solution. The greedy solution is that which always adds an item to the collection if it has the highest value-to-size ratio. For example, if a "greedy thief" with a 10-Liter knapsack sees two types of items - a 6-Liter item worth $9 (1.5 $/L) - a 5-Liter item worth $5 (1.0 $/L) the thief will take 1 of the 6-Liter items instead of 2 of the 5-Liter items. Although this means the thief will only profit $9 instead of $10, the decision algorithm is much simpler. Maybe the thief is bad at math. Now, go be bad at math! The Kata === Write the function `knapsack` that takes two parameters, `capacity` and `items`, and returns a list of quantities. `capacity` will be a positive number `items` will be an array of arrays of positive numbers that gives the items' sizes and values in the form [[size 1, value 1], [size 2, value 2], ...] `knapsack` will return an array of integers that specifies the quantity of each item to take according to the greedy solution (the order of the quantities must match the order of `items`)
def knapsack(capacity, items): ratios = [float(item[1]) / item[0] for item in items] collection = [0] * len(items) space = capacity while any(ratios): best_index = ratios.index(max(ratios)) if items[best_index][0] <= space: collection[best_index] += 1 space -= items[best_index][0] else: ratios[best_index] = 0 return collection
Imagine the following situations: - A truck loading cargo - A shopper on a budget - A thief stealing from a house using a large bag - A child eating candy very quickly All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with you. The Problem === Given a container with a certain capacity and an assortment of discrete items with various sizes and values (and an infinite supply of each item), determine the combination of items that fits within the container and maximizes the value of the collection. However, **DO NOT** attempt to solve the problem **EXACTLY!** (we will do that in Part 2) The Simplification === Because the optimal collection of items is **MUCH** more difficult to determine than a nearly-optimal collection, this kata will only focus on one specific nearly-optimal solution: the greedy solution. The greedy solution is that which always adds an item to the collection if it has the highest value-to-size ratio. For example, if a "greedy thief" with a 10-Liter knapsack sees two types of items - a 6-Liter item worth $9 (1.5 $/L) - a 5-Liter item worth $5 (1.0 $/L) the thief will take 1 of the 6-Liter items instead of 2 of the 5-Liter items. Although this means the thief will only profit $9 instead of $10, the decision algorithm is much simpler. Maybe the thief is bad at math. Now, go be bad at math! The Kata === Write the function `knapsack` that takes two parameters, `capacity` and `items`, and returns a list of quantities. `capacity` will be a positive number `items` will be an array of arrays of positive numbers that gives the items' sizes and values in the form [[size 1, value 1], [size 2, value 2], ...] `knapsack` will return an array of integers that specifies the quantity of each item to take according to the greedy solution (the order of the quantities must match the order of `items`)
def knapsack(c, items): qtys = [0 for i in items] weights = sorted(items, reverse=True, key=lambda (size, value): float(value)/size) for (size, value) in weights: qty = c // size qtys[items.index((size, value))] = qty c -= qty * size return qtys
Imagine the following situations: - A truck loading cargo - A shopper on a budget - A thief stealing from a house using a large bag - A child eating candy very quickly All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with you. The Problem === Given a container with a certain capacity and an assortment of discrete items with various sizes and values (and an infinite supply of each item), determine the combination of items that fits within the container and maximizes the value of the collection. However, **DO NOT** attempt to solve the problem **EXACTLY!** (we will do that in Part 2) The Simplification === Because the optimal collection of items is **MUCH** more difficult to determine than a nearly-optimal collection, this kata will only focus on one specific nearly-optimal solution: the greedy solution. The greedy solution is that which always adds an item to the collection if it has the highest value-to-size ratio. For example, if a "greedy thief" with a 10-Liter knapsack sees two types of items - a 6-Liter item worth $9 (1.5 $/L) - a 5-Liter item worth $5 (1.0 $/L) the thief will take 1 of the 6-Liter items instead of 2 of the 5-Liter items. Although this means the thief will only profit $9 instead of $10, the decision algorithm is much simpler. Maybe the thief is bad at math. Now, go be bad at math! The Kata === Write the function `knapsack` that takes two parameters, `capacity` and `items`, and returns a list of quantities. `capacity` will be a positive number `items` will be an array of arrays of positive numbers that gives the items' sizes and values in the form [[size 1, value 1], [size 2, value 2], ...] `knapsack` will return an array of integers that specifies the quantity of each item to take according to the greedy solution (the order of the quantities must match the order of `items`)
def knapsack(capacity, items): r = [0] * len(items) for i, item in sorted(enumerate(items), key=lambda x: x[1][1] / float(x[1][0]), reverse=True): while capacity >= item[0]: capacity -= item[0] r[i] += 1 return r
Imagine the following situations: - A truck loading cargo - A shopper on a budget - A thief stealing from a house using a large bag - A child eating candy very quickly All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with you. The Problem === Given a container with a certain capacity and an assortment of discrete items with various sizes and values (and an infinite supply of each item), determine the combination of items that fits within the container and maximizes the value of the collection. However, **DO NOT** attempt to solve the problem **EXACTLY!** (we will do that in Part 2) The Simplification === Because the optimal collection of items is **MUCH** more difficult to determine than a nearly-optimal collection, this kata will only focus on one specific nearly-optimal solution: the greedy solution. The greedy solution is that which always adds an item to the collection if it has the highest value-to-size ratio. For example, if a "greedy thief" with a 10-Liter knapsack sees two types of items - a 6-Liter item worth $9 (1.5 $/L) - a 5-Liter item worth $5 (1.0 $/L) the thief will take 1 of the 6-Liter items instead of 2 of the 5-Liter items. Although this means the thief will only profit $9 instead of $10, the decision algorithm is much simpler. Maybe the thief is bad at math. Now, go be bad at math! The Kata === Write the function `knapsack` that takes two parameters, `capacity` and `items`, and returns a list of quantities. `capacity` will be a positive number `items` will be an array of arrays of positive numbers that gives the items' sizes and values in the form [[size 1, value 1], [size 2, value 2], ...] `knapsack` will return an array of integers that specifies the quantity of each item to take according to the greedy solution (the order of the quantities must match the order of `items`)
def knapsack(capacity, items): sortItems = sorted(items, key=lambda tup: (tup[1] / float(tup[0])))[::-1] sortCount = [(i[0], i[1], 0) for i in sortItems] rCap = capacity for i in range(len(sortCount)) : while rCap >= sortCount[i][0] : sortCount[i] = (sortCount[i][0], sortCount[i][1], sortCount[i][2] + 1) rCap -= sortCount[i][0] counts = [sortCount[sortItems.index(i)][2] for i in items] return counts
Imagine the following situations: - A truck loading cargo - A shopper on a budget - A thief stealing from a house using a large bag - A child eating candy very quickly All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with you. The Problem === Given a container with a certain capacity and an assortment of discrete items with various sizes and values (and an infinite supply of each item), determine the combination of items that fits within the container and maximizes the value of the collection. However, **DO NOT** attempt to solve the problem **EXACTLY!** (we will do that in Part 2) The Simplification === Because the optimal collection of items is **MUCH** more difficult to determine than a nearly-optimal collection, this kata will only focus on one specific nearly-optimal solution: the greedy solution. The greedy solution is that which always adds an item to the collection if it has the highest value-to-size ratio. For example, if a "greedy thief" with a 10-Liter knapsack sees two types of items - a 6-Liter item worth $9 (1.5 $/L) - a 5-Liter item worth $5 (1.0 $/L) the thief will take 1 of the 6-Liter items instead of 2 of the 5-Liter items. Although this means the thief will only profit $9 instead of $10, the decision algorithm is much simpler. Maybe the thief is bad at math. Now, go be bad at math! The Kata === Write the function `knapsack` that takes two parameters, `capacity` and `items`, and returns a list of quantities. `capacity` will be a positive number `items` will be an array of arrays of positive numbers that gives the items' sizes and values in the form [[size 1, value 1], [size 2, value 2], ...] `knapsack` will return an array of integers that specifies the quantity of each item to take according to the greedy solution (the order of the quantities must match the order of `items`)
def knapsack(capacity, items): quantities = [0] * len(items) for idx, (size, value) in sorted(enumerate(items), key=lambda it: it[1][1] / it[1][0], reverse=True): quantities[idx], capacity = divmod(capacity, size) return quantities
Imagine the following situations: - A truck loading cargo - A shopper on a budget - A thief stealing from a house using a large bag - A child eating candy very quickly All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with you. The Problem === Given a container with a certain capacity and an assortment of discrete items with various sizes and values (and an infinite supply of each item), determine the combination of items that fits within the container and maximizes the value of the collection. However, **DO NOT** attempt to solve the problem **EXACTLY!** (we will do that in Part 2) The Simplification === Because the optimal collection of items is **MUCH** more difficult to determine than a nearly-optimal collection, this kata will only focus on one specific nearly-optimal solution: the greedy solution. The greedy solution is that which always adds an item to the collection if it has the highest value-to-size ratio. For example, if a "greedy thief" with a 10-Liter knapsack sees two types of items - a 6-Liter item worth $9 (1.5 $/L) - a 5-Liter item worth $5 (1.0 $/L) the thief will take 1 of the 6-Liter items instead of 2 of the 5-Liter items. Although this means the thief will only profit $9 instead of $10, the decision algorithm is much simpler. Maybe the thief is bad at math. Now, go be bad at math! The Kata === Write the function `knapsack` that takes two parameters, `capacity` and `items`, and returns a list of quantities. `capacity` will be a positive number `items` will be an array of arrays of positive numbers that gives the items' sizes and values in the form [[size 1, value 1], [size 2, value 2], ...] `knapsack` will return an array of integers that specifies the quantity of each item to take according to the greedy solution (the order of the quantities must match the order of `items`)
def knapsack(capacity, items): arr = sorted(enumerate(items), key = lambda x: x[1][1]/x[1][0], reverse = True) sack = [0]*len(items) for j, (w, v) in arr: if w <= capacity: sack[j], capacity = divmod(capacity, w) return sack
Imagine the following situations: - A truck loading cargo - A shopper on a budget - A thief stealing from a house using a large bag - A child eating candy very quickly All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with you. The Problem === Given a container with a certain capacity and an assortment of discrete items with various sizes and values (and an infinite supply of each item), determine the combination of items that fits within the container and maximizes the value of the collection. However, **DO NOT** attempt to solve the problem **EXACTLY!** (we will do that in Part 2) The Simplification === Because the optimal collection of items is **MUCH** more difficult to determine than a nearly-optimal collection, this kata will only focus on one specific nearly-optimal solution: the greedy solution. The greedy solution is that which always adds an item to the collection if it has the highest value-to-size ratio. For example, if a "greedy thief" with a 10-Liter knapsack sees two types of items - a 6-Liter item worth $9 (1.5 $/L) - a 5-Liter item worth $5 (1.0 $/L) the thief will take 1 of the 6-Liter items instead of 2 of the 5-Liter items. Although this means the thief will only profit $9 instead of $10, the decision algorithm is much simpler. Maybe the thief is bad at math. Now, go be bad at math! The Kata === Write the function `knapsack` that takes two parameters, `capacity` and `items`, and returns a list of quantities. `capacity` will be a positive number `items` will be an array of arrays of positive numbers that gives the items' sizes and values in the form [[size 1, value 1], [size 2, value 2], ...] `knapsack` will return an array of integers that specifies the quantity of each item to take according to the greedy solution (the order of the quantities must match the order of `items`)
def knapsack(capacity, items): ratios = [float(item[1]) / item[0] for item in items] collection = [0] * len(items) space = capacity while True: best_index = ratios.index(max(ratios)) if items[best_index][0] <= space: collection[best_index] += 1 space -= items[best_index][0] else: ratios[best_index] = 0 if all(ratio == 0 for ratio in ratios): return collection
Imagine the following situations: - A truck loading cargo - A shopper on a budget - A thief stealing from a house using a large bag - A child eating candy very quickly All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with you. The Problem === Given a container with a certain capacity and an assortment of discrete items with various sizes and values (and an infinite supply of each item), determine the combination of items that fits within the container and maximizes the value of the collection. However, **DO NOT** attempt to solve the problem **EXACTLY!** (we will do that in Part 2) The Simplification === Because the optimal collection of items is **MUCH** more difficult to determine than a nearly-optimal collection, this kata will only focus on one specific nearly-optimal solution: the greedy solution. The greedy solution is that which always adds an item to the collection if it has the highest value-to-size ratio. For example, if a "greedy thief" with a 10-Liter knapsack sees two types of items - a 6-Liter item worth $9 (1.5 $/L) - a 5-Liter item worth $5 (1.0 $/L) the thief will take 1 of the 6-Liter items instead of 2 of the 5-Liter items. Although this means the thief will only profit $9 instead of $10, the decision algorithm is much simpler. Maybe the thief is bad at math. Now, go be bad at math! The Kata === Write the function `knapsack` that takes two parameters, `capacity` and `items`, and returns a list of quantities. `capacity` will be a positive number `items` will be an array of arrays of positive numbers that gives the items' sizes and values in the form [[size 1, value 1], [size 2, value 2], ...] `knapsack` will return an array of integers that specifies the quantity of each item to take according to the greedy solution (the order of the quantities must match the order of `items`)
def knapsack(capacity, items): liste = sorted([ x+(i,) for i,x in enumerate(items)], key= lambda x: x[1]/x[0], reverse = True) result = [0]*len(items) for s,v,i in liste : if capacity >= s : result[i] = int(capacity/s) capacity -= result[i]*s return result
Imagine the following situations: - A truck loading cargo - A shopper on a budget - A thief stealing from a house using a large bag - A child eating candy very quickly All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with you. The Problem === Given a container with a certain capacity and an assortment of discrete items with various sizes and values (and an infinite supply of each item), determine the combination of items that fits within the container and maximizes the value of the collection. However, **DO NOT** attempt to solve the problem **EXACTLY!** (we will do that in Part 2) The Simplification === Because the optimal collection of items is **MUCH** more difficult to determine than a nearly-optimal collection, this kata will only focus on one specific nearly-optimal solution: the greedy solution. The greedy solution is that which always adds an item to the collection if it has the highest value-to-size ratio. For example, if a "greedy thief" with a 10-Liter knapsack sees two types of items - a 6-Liter item worth $9 (1.5 $/L) - a 5-Liter item worth $5 (1.0 $/L) the thief will take 1 of the 6-Liter items instead of 2 of the 5-Liter items. Although this means the thief will only profit $9 instead of $10, the decision algorithm is much simpler. Maybe the thief is bad at math. Now, go be bad at math! The Kata === Write the function `knapsack` that takes two parameters, `capacity` and `items`, and returns a list of quantities. `capacity` will be a positive number `items` will be an array of arrays of positive numbers that gives the items' sizes and values in the form [[size 1, value 1], [size 2, value 2], ...] `knapsack` will return an array of integers that specifies the quantity of each item to take according to the greedy solution (the order of the quantities must match the order of `items`)
def knapsack(capacity, items): res = [0] * len(items) vsi = sorted(((v / s, s, c) for c, (s, v) in enumerate(items)), reverse=True) for _, s, c in vsi: res[c], capacity = divmod(capacity, s) return res
Imagine the following situations: - A truck loading cargo - A shopper on a budget - A thief stealing from a house using a large bag - A child eating candy very quickly All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with you. The Problem === Given a container with a certain capacity and an assortment of discrete items with various sizes and values (and an infinite supply of each item), determine the combination of items that fits within the container and maximizes the value of the collection. However, **DO NOT** attempt to solve the problem **EXACTLY!** (we will do that in Part 2) The Simplification === Because the optimal collection of items is **MUCH** more difficult to determine than a nearly-optimal collection, this kata will only focus on one specific nearly-optimal solution: the greedy solution. The greedy solution is that which always adds an item to the collection if it has the highest value-to-size ratio. For example, if a "greedy thief" with a 10-Liter knapsack sees two types of items - a 6-Liter item worth $9 (1.5 $/L) - a 5-Liter item worth $5 (1.0 $/L) the thief will take 1 of the 6-Liter items instead of 2 of the 5-Liter items. Although this means the thief will only profit $9 instead of $10, the decision algorithm is much simpler. Maybe the thief is bad at math. Now, go be bad at math! The Kata === Write the function `knapsack` that takes two parameters, `capacity` and `items`, and returns a list of quantities. `capacity` will be a positive number `items` will be an array of arrays of positive numbers that gives the items' sizes and values in the form [[size 1, value 1], [size 2, value 2], ...] `knapsack` will return an array of integers that specifies the quantity of each item to take according to the greedy solution (the order of the quantities must match the order of `items`)
def knapsack(capacity, items): L = sorted((-y/x, x, i) for i,(x,y) in enumerate(items)) res = [0]*len(L) for _, x, i in L: res[i], capacity = divmod(capacity, x) return res
Two numbers are **relatively prime** if their greatest common factor is 1; in other words: if they cannot be divided by any other common numbers than 1. `13, 16, 9, 5, and 119` are all relatively prime because they share no common factors, except for 1. To see this, I will show their factorizations: ```python 13: 13 16: 2 * 2 * 2 * 2 9: 3 * 3 5: 5 119: 17 * 7 ``` Complete the function that takes 2 arguments: a number (`n`), and a list of numbers (`arr`). The function should return a list of all the numbers in `arr` that are relatively prime to `n`. All numbers in will be positive integers. ## Examples ```python relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]) >> [1, 3, 5, 7] relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]) >> [32, 61, 77, 11] relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]) >> [] ```
from fractions import gcd def relatively_prime (n, l): return [x for x in l if gcd(n, x) == 1]
Two numbers are **relatively prime** if their greatest common factor is 1; in other words: if they cannot be divided by any other common numbers than 1. `13, 16, 9, 5, and 119` are all relatively prime because they share no common factors, except for 1. To see this, I will show their factorizations: ```python 13: 13 16: 2 * 2 * 2 * 2 9: 3 * 3 5: 5 119: 17 * 7 ``` Complete the function that takes 2 arguments: a number (`n`), and a list of numbers (`arr`). The function should return a list of all the numbers in `arr` that are relatively prime to `n`. All numbers in will be positive integers. ## Examples ```python relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]) >> [1, 3, 5, 7] relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]) >> [32, 61, 77, 11] relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]) >> [] ```
from math import gcd def relatively_prime (n, l): return [x for x in l if gcd(n, x) == 1]
Two numbers are **relatively prime** if their greatest common factor is 1; in other words: if they cannot be divided by any other common numbers than 1. `13, 16, 9, 5, and 119` are all relatively prime because they share no common factors, except for 1. To see this, I will show their factorizations: ```python 13: 13 16: 2 * 2 * 2 * 2 9: 3 * 3 5: 5 119: 17 * 7 ``` Complete the function that takes 2 arguments: a number (`n`), and a list of numbers (`arr`). The function should return a list of all the numbers in `arr` that are relatively prime to `n`. All numbers in will be positive integers. ## Examples ```python relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]) >> [1, 3, 5, 7] relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]) >> [32, 61, 77, 11] relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]) >> [] ```
from math import gcd def relatively_prime (n, lst): return [m for m in lst if gcd(m, n) == 1]
Two numbers are **relatively prime** if their greatest common factor is 1; in other words: if they cannot be divided by any other common numbers than 1. `13, 16, 9, 5, and 119` are all relatively prime because they share no common factors, except for 1. To see this, I will show their factorizations: ```python 13: 13 16: 2 * 2 * 2 * 2 9: 3 * 3 5: 5 119: 17 * 7 ``` Complete the function that takes 2 arguments: a number (`n`), and a list of numbers (`arr`). The function should return a list of all the numbers in `arr` that are relatively prime to `n`. All numbers in will be positive integers. ## Examples ```python relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]) >> [1, 3, 5, 7] relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]) >> [32, 61, 77, 11] relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]) >> [] ```
def relatively_prime (n, l): lst = [] new = set(x for x in range(1, n+1) if not n%x) for y in l: if len(new & set(x for x in range(1, y+1) if not y%x)) == 1: lst.append(y) return lst
Two numbers are **relatively prime** if their greatest common factor is 1; in other words: if they cannot be divided by any other common numbers than 1. `13, 16, 9, 5, and 119` are all relatively prime because they share no common factors, except for 1. To see this, I will show their factorizations: ```python 13: 13 16: 2 * 2 * 2 * 2 9: 3 * 3 5: 5 119: 17 * 7 ``` Complete the function that takes 2 arguments: a number (`n`), and a list of numbers (`arr`). The function should return a list of all the numbers in `arr` that are relatively prime to `n`. All numbers in will be positive integers. ## Examples ```python relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]) >> [1, 3, 5, 7] relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]) >> [32, 61, 77, 11] relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]) >> [] ```
G=lambda Q,S : G(S,Q % S) if S else Q relatively_prime = lambda Q,S : [S for S in S if 1 == G(Q,S)]
Two numbers are **relatively prime** if their greatest common factor is 1; in other words: if they cannot be divided by any other common numbers than 1. `13, 16, 9, 5, and 119` are all relatively prime because they share no common factors, except for 1. To see this, I will show their factorizations: ```python 13: 13 16: 2 * 2 * 2 * 2 9: 3 * 3 5: 5 119: 17 * 7 ``` Complete the function that takes 2 arguments: a number (`n`), and a list of numbers (`arr`). The function should return a list of all the numbers in `arr` that are relatively prime to `n`. All numbers in will be positive integers. ## Examples ```python relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]) >> [1, 3, 5, 7] relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]) >> [32, 61, 77, 11] relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]) >> [] ```
def gcd(a,b): return a if b == 0 else gcd(b, a % b) def relatively_prime (n, l): return [x for x in l if gcd(n,x) == 1]
Two numbers are **relatively prime** if their greatest common factor is 1; in other words: if they cannot be divided by any other common numbers than 1. `13, 16, 9, 5, and 119` are all relatively prime because they share no common factors, except for 1. To see this, I will show their factorizations: ```python 13: 13 16: 2 * 2 * 2 * 2 9: 3 * 3 5: 5 119: 17 * 7 ``` Complete the function that takes 2 arguments: a number (`n`), and a list of numbers (`arr`). The function should return a list of all the numbers in `arr` that are relatively prime to `n`. All numbers in will be positive integers. ## Examples ```python relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]) >> [1, 3, 5, 7] relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]) >> [32, 61, 77, 11] relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]) >> [] ```
from fractions import gcd def relatively_prime (n, l): return [i for i in l if gcd(i,n) == 1]
Two numbers are **relatively prime** if their greatest common factor is 1; in other words: if they cannot be divided by any other common numbers than 1. `13, 16, 9, 5, and 119` are all relatively prime because they share no common factors, except for 1. To see this, I will show their factorizations: ```python 13: 13 16: 2 * 2 * 2 * 2 9: 3 * 3 5: 5 119: 17 * 7 ``` Complete the function that takes 2 arguments: a number (`n`), and a list of numbers (`arr`). The function should return a list of all the numbers in `arr` that are relatively prime to `n`. All numbers in will be positive integers. ## Examples ```python relatively_prime(8, [1, 2, 3, 4, 5, 6, 7]) >> [1, 3, 5, 7] relatively_prime(15, [72, 27, 32, 61, 77, 11, 40]) >> [32, 61, 77, 11] relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99]) >> [] ```
def relatively_prime (n, l): from fractions import gcd return [i for i in l if gcd(n,i)==1]
Build Tower Advanced --- Build Tower by the following given arguments: __number of floors__ (integer and always greater than 0) __block size__ (width, height) (integer pair and always greater than (0, 0)) Tower block unit is represented as `*` * Python: return a `list`; * JavaScript: returns an `Array`; Have fun! *** for example, a tower of 3 floors with block size = (2, 3) looks like below ``` [ ' ** ', ' ** ', ' ** ', ' ****** ', ' ****** ', ' ****** ', '**********', '**********', '**********' ] ``` and a tower of 6 floors with block size = (2, 1) looks like below ``` [ ' ** ', ' ****** ', ' ********** ', ' ************** ', ' ****************** ', '**********************' ] ``` *** Go take a look at [Build Tower](https://www.codewars.com/kata/576757b1df89ecf5bd00073b) which is a more basic version :)
def tower_builder(n, (w, h)): return [str.center("*" * (i*2-1)*w, (n*2-1)*w) for i in range(1, n+1) for _ in range(h)]
Build Tower Advanced --- Build Tower by the following given arguments: __number of floors__ (integer and always greater than 0) __block size__ (width, height) (integer pair and always greater than (0, 0)) Tower block unit is represented as `*` * Python: return a `list`; * JavaScript: returns an `Array`; Have fun! *** for example, a tower of 3 floors with block size = (2, 3) looks like below ``` [ ' ** ', ' ** ', ' ** ', ' ****** ', ' ****** ', ' ****** ', '**********', '**********', '**********' ] ``` and a tower of 6 floors with block size = (2, 1) looks like below ``` [ ' ** ', ' ****** ', ' ********** ', ' ************** ', ' ****************** ', '**********************' ] ``` *** Go take a look at [Build Tower](https://www.codewars.com/kata/576757b1df89ecf5bd00073b) which is a more basic version :)
def tower_builder(n_floors, block_size): w, h = block_size filled_block = '*' * w empty_block = ' ' * w tower = [] for n in range(1,n_floors+1): for _ in range(h): tower.append( empty_block * (n_floors - n) + filled_block * (2*n -1) + empty_block * (n_floors - n)) return tower
Build Tower Advanced --- Build Tower by the following given arguments: __number of floors__ (integer and always greater than 0) __block size__ (width, height) (integer pair and always greater than (0, 0)) Tower block unit is represented as `*` * Python: return a `list`; * JavaScript: returns an `Array`; Have fun! *** for example, a tower of 3 floors with block size = (2, 3) looks like below ``` [ ' ** ', ' ** ', ' ** ', ' ****** ', ' ****** ', ' ****** ', '**********', '**********', '**********' ] ``` and a tower of 6 floors with block size = (2, 1) looks like below ``` [ ' ** ', ' ****** ', ' ********** ', ' ************** ', ' ****************** ', '**********************' ] ``` *** Go take a look at [Build Tower](https://www.codewars.com/kata/576757b1df89ecf5bd00073b) which is a more basic version :)
def tower_builder(floors, (w, h)): width = w * (2 * floors - 1) return [('*' * i).center(width) for i in range(w, width+1, 2*w) for _ in range(h)]
Build Tower Advanced --- Build Tower by the following given arguments: __number of floors__ (integer and always greater than 0) __block size__ (width, height) (integer pair and always greater than (0, 0)) Tower block unit is represented as `*` * Python: return a `list`; * JavaScript: returns an `Array`; Have fun! *** for example, a tower of 3 floors with block size = (2, 3) looks like below ``` [ ' ** ', ' ** ', ' ** ', ' ****** ', ' ****** ', ' ****** ', '**********', '**********', '**********' ] ``` and a tower of 6 floors with block size = (2, 1) looks like below ``` [ ' ** ', ' ****** ', ' ********** ', ' ************** ', ' ****************** ', '**********************' ] ``` *** Go take a look at [Build Tower](https://www.codewars.com/kata/576757b1df89ecf5bd00073b) which is a more basic version :)
def tower_builder(n, block): w, h = block return [f"{'*' * w * (2*i + 1):^{(n*2 - 1) * w}}" for i in range(n) for _ in range(h)]
Build Tower Advanced --- Build Tower by the following given arguments: __number of floors__ (integer and always greater than 0) __block size__ (width, height) (integer pair and always greater than (0, 0)) Tower block unit is represented as `*` * Python: return a `list`; * JavaScript: returns an `Array`; Have fun! *** for example, a tower of 3 floors with block size = (2, 3) looks like below ``` [ ' ** ', ' ** ', ' ** ', ' ****** ', ' ****** ', ' ****** ', '**********', '**********', '**********' ] ``` and a tower of 6 floors with block size = (2, 1) looks like below ``` [ ' ** ', ' ****** ', ' ********** ', ' ************** ', ' ****************** ', '**********************' ] ``` *** Go take a look at [Build Tower](https://www.codewars.com/kata/576757b1df89ecf5bd00073b) which is a more basic version :)
def tower_builder(n_floors, block_size): w, h = block_size floors = [] n = n_floors for i in range(n_floors): n -= 1 for j in range(h): floors.append(' ' * n * w + '*' * (i * 2 + 1) * w + ' ' * n * w) return floors
Build Tower Advanced --- Build Tower by the following given arguments: __number of floors__ (integer and always greater than 0) __block size__ (width, height) (integer pair and always greater than (0, 0)) Tower block unit is represented as `*` * Python: return a `list`; * JavaScript: returns an `Array`; Have fun! *** for example, a tower of 3 floors with block size = (2, 3) looks like below ``` [ ' ** ', ' ** ', ' ** ', ' ****** ', ' ****** ', ' ****** ', '**********', '**********', '**********' ] ``` and a tower of 6 floors with block size = (2, 1) looks like below ``` [ ' ** ', ' ****** ', ' ********** ', ' ************** ', ' ****************** ', '**********************' ] ``` *** Go take a look at [Build Tower](https://www.codewars.com/kata/576757b1df89ecf5bd00073b) which is a more basic version :)
def tower_builder(n_floors, block_size): w, h = block_size tower = ['*' * (2*n_floors-1)*w]*h base = tower[-1] for f in range(1,n_floors): base = base[:len(base)-2*w] tower += [' '*w*f+base+' '*w*f]*h return tower[::-1]
Build Tower Advanced --- Build Tower by the following given arguments: __number of floors__ (integer and always greater than 0) __block size__ (width, height) (integer pair and always greater than (0, 0)) Tower block unit is represented as `*` * Python: return a `list`; * JavaScript: returns an `Array`; Have fun! *** for example, a tower of 3 floors with block size = (2, 3) looks like below ``` [ ' ** ', ' ** ', ' ** ', ' ****** ', ' ****** ', ' ****** ', '**********', '**********', '**********' ] ``` and a tower of 6 floors with block size = (2, 1) looks like below ``` [ ' ** ', ' ****** ', ' ********** ', ' ************** ', ' ****************** ', '**********************' ] ``` *** Go take a look at [Build Tower](https://www.codewars.com/kata/576757b1df89ecf5bd00073b) which is a more basic version :)
def tower_builder(n_floors, block_size): w, h = block_size return [(n_floors*w - i*w)*" " + (i*w*2-w)*"*" + (n_floors*w - i*w)*" " for i in sorted(list(range(1,n_floors+1))*h) ] # build here
Build Tower Advanced --- Build Tower by the following given arguments: __number of floors__ (integer and always greater than 0) __block size__ (width, height) (integer pair and always greater than (0, 0)) Tower block unit is represented as `*` * Python: return a `list`; * JavaScript: returns an `Array`; Have fun! *** for example, a tower of 3 floors with block size = (2, 3) looks like below ``` [ ' ** ', ' ** ', ' ** ', ' ****** ', ' ****** ', ' ****** ', '**********', '**********', '**********' ] ``` and a tower of 6 floors with block size = (2, 1) looks like below ``` [ ' ** ', ' ****** ', ' ********** ', ' ************** ', ' ****************** ', '**********************' ] ``` *** Go take a look at [Build Tower](https://www.codewars.com/kata/576757b1df89ecf5bd00073b) which is a more basic version :)
def tower_builder(n_floors, block_size): W, H = block_size result, maxi = [], (2*n_floors-1)*W for i in range(W, maxi+1, 2*W): result.extend([('*'*i).center(maxi)]*H) return result
Build Tower Advanced --- Build Tower by the following given arguments: __number of floors__ (integer and always greater than 0) __block size__ (width, height) (integer pair and always greater than (0, 0)) Tower block unit is represented as `*` * Python: return a `list`; * JavaScript: returns an `Array`; Have fun! *** for example, a tower of 3 floors with block size = (2, 3) looks like below ``` [ ' ** ', ' ** ', ' ** ', ' ****** ', ' ****** ', ' ****** ', '**********', '**********', '**********' ] ``` and a tower of 6 floors with block size = (2, 1) looks like below ``` [ ' ** ', ' ****** ', ' ********** ', ' ************** ', ' ****************** ', '**********************' ] ``` *** Go take a look at [Build Tower](https://www.codewars.com/kata/576757b1df89ecf5bd00073b) which is a more basic version :)
def tower_builder(n_floors, block_size): tower = list() w, h = block_size l = (2 * n_floors - 1) * w sp = int(l / 2 - w / 2) for i in range(n_floors): for j in range(h): tower.append(' ' * sp + '*' * (l - 2 * sp) + ' ' * sp) sp = sp - w return tower
Build Tower Advanced --- Build Tower by the following given arguments: __number of floors__ (integer and always greater than 0) __block size__ (width, height) (integer pair and always greater than (0, 0)) Tower block unit is represented as `*` * Python: return a `list`; * JavaScript: returns an `Array`; Have fun! *** for example, a tower of 3 floors with block size = (2, 3) looks like below ``` [ ' ** ', ' ** ', ' ** ', ' ****** ', ' ****** ', ' ****** ', '**********', '**********', '**********' ] ``` and a tower of 6 floors with block size = (2, 1) looks like below ``` [ ' ** ', ' ****** ', ' ********** ', ' ************** ', ' ****************** ', '**********************' ] ``` *** Go take a look at [Build Tower](https://www.codewars.com/kata/576757b1df89ecf5bd00073b) which is a more basic version :)
import math def tower_builder(n_floors, block_size): w, h = block_size stars = w #how many stars at first height_count = 0 #count for knowing when next floor tower = [] #result for i in range(n_floors*h): ground_floor_stars = w*2*n_floors-w #gets how many stars in the bottom floor, intial width times two sides times floors minus width spaces = " " * int((ground_floor_stars - stars)/2) #calculates how many spaces for each floor for each side floor = spaces + '*'*stars + spaces tower.append(floor) height_count += 1 if height_count == h: stars += w*2 height_count = 0 return tower
---- Vampire Numbers ---- Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows: ```python 6 * 21 = 126 # 6 and 21 would be valid 'fangs' for a vampire number as the # digits 6, 1, and 2 are present in both the product and multiplicands 10 * 11 = 110 # 110 is not a vampire number since there are three 1's in the # multiplicands, but only two 1's in the product ``` Create a function that can receive two 'fangs' and determine if the product of the two is a valid vampire number.
def vampire_test(x, y): return sorted(str(x * y)) == sorted(str(x) + str(y))
---- Vampire Numbers ---- Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows: ```python 6 * 21 = 126 # 6 and 21 would be valid 'fangs' for a vampire number as the # digits 6, 1, and 2 are present in both the product and multiplicands 10 * 11 = 110 # 110 is not a vampire number since there are three 1's in the # multiplicands, but only two 1's in the product ``` Create a function that can receive two 'fangs' and determine if the product of the two is a valid vampire number.
def vampire_test(x, y): return sorted(list(str(x) + str(y))) == sorted(list(str(x*y)))
---- Vampire Numbers ---- Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows: ```python 6 * 21 = 126 # 6 and 21 would be valid 'fangs' for a vampire number as the # digits 6, 1, and 2 are present in both the product and multiplicands 10 * 11 = 110 # 110 is not a vampire number since there are three 1's in the # multiplicands, but only two 1's in the product ``` Create a function that can receive two 'fangs' and determine if the product of the two is a valid vampire number.
from collections import Counter def vampire_test(x, y): return Counter(str(x) + str(y)) == Counter(str(x * y))
---- Vampire Numbers ---- Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows: ```python 6 * 21 = 126 # 6 and 21 would be valid 'fangs' for a vampire number as the # digits 6, 1, and 2 are present in both the product and multiplicands 10 * 11 = 110 # 110 is not a vampire number since there are three 1's in the # multiplicands, but only two 1's in the product ``` Create a function that can receive two 'fangs' and determine if the product of the two is a valid vampire number.
def vampire_test(x, y): return "".join(sorted(list(str(x) + str(y)))) == "".join(sorted(list(str(x * y))))
---- Vampire Numbers ---- Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows: ```python 6 * 21 = 126 # 6 and 21 would be valid 'fangs' for a vampire number as the # digits 6, 1, and 2 are present in both the product and multiplicands 10 * 11 = 110 # 110 is not a vampire number since there are three 1's in the # multiplicands, but only two 1's in the product ``` Create a function that can receive two 'fangs' and determine if the product of the two is a valid vampire number.
def vampire_test(x, y): return (x > 0 or y > 0) and sorted(str(x) + str(y)) == sorted(str(x * y))
---- Vampire Numbers ---- Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows: ```python 6 * 21 = 126 # 6 and 21 would be valid 'fangs' for a vampire number as the # digits 6, 1, and 2 are present in both the product and multiplicands 10 * 11 = 110 # 110 is not a vampire number since there are three 1's in the # multiplicands, but only two 1's in the product ``` Create a function that can receive two 'fangs' and determine if the product of the two is a valid vampire number.
def vampire_test(x, y): return sorted(str(x)+str(y)) == sorted(str(x*y))
---- Vampire Numbers ---- Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows: ```python 6 * 21 = 126 # 6 and 21 would be valid 'fangs' for a vampire number as the # digits 6, 1, and 2 are present in both the product and multiplicands 10 * 11 = 110 # 110 is not a vampire number since there are three 1's in the # multiplicands, but only two 1's in the product ``` Create a function that can receive two 'fangs' and determine if the product of the two is a valid vampire number.
from collections import Counter def vampire_test(x, y): return Counter(str(x)) + Counter(str(y)) == Counter(str(x*y))
---- Vampire Numbers ---- Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows: ```python 6 * 21 = 126 # 6 and 21 would be valid 'fangs' for a vampire number as the # digits 6, 1, and 2 are present in both the product and multiplicands 10 * 11 = 110 # 110 is not a vampire number since there are three 1's in the # multiplicands, but only two 1's in the product ``` Create a function that can receive two 'fangs' and determine if the product of the two is a valid vampire number.
def vampire_test(x, y): m = str(x*y) x=str(x)+str(y) if set(m) == set(x) and len(x)==len(m): return True return False
---- Vampire Numbers ---- Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows: ```python 6 * 21 = 126 # 6 and 21 would be valid 'fangs' for a vampire number as the # digits 6, 1, and 2 are present in both the product and multiplicands 10 * 11 = 110 # 110 is not a vampire number since there are three 1's in the # multiplicands, but only two 1's in the product ``` Create a function that can receive two 'fangs' and determine if the product of the two is a valid vampire number.
def vampire_test(x, y): return (str(x*y).count('1') == ((str(x).count('1')) + (str(y).count('1')))) & ((x > 0) | (y>0))
---- Vampire Numbers ---- Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows: ```python 6 * 21 = 126 # 6 and 21 would be valid 'fangs' for a vampire number as the # digits 6, 1, and 2 are present in both the product and multiplicands 10 * 11 = 110 # 110 is not a vampire number since there are three 1's in the # multiplicands, but only two 1's in the product ``` Create a function that can receive two 'fangs' and determine if the product of the two is a valid vampire number.
def vampire_test(x, y): return sorted(f"{x}{y}") == sorted(f"{x*y}")
Linked Lists - Sorted Insert Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list. The push() and buildOneTwoThree() functions do not need to be redefined.
class Node(object): def __init__(self, data, nxt = None): self.data = data self.next = nxt def sorted_insert(head, data): if not head or data < head.data: return Node(data, head) else: head.next = sorted_insert(head.next, data) return head
Linked Lists - Sorted Insert Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list. The push() and buildOneTwoThree() functions do not need to be redefined.
class Node(object): def __init__(self, data): self.data = data self.next = None def sorted_insert(head, data): if head is None or head.data > data: return push(head, data) current = head while current.next and data > current.next.data: current = current.next current.next = push(current.next, data) return head
Linked Lists - Sorted Insert Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list. The push() and buildOneTwoThree() functions do not need to be redefined.
class Node(object): def __init__(self, data): self.data = data self.next = None def sorted_insert(head, data): current = head; if head is None or head.data > data: return push(head, data) while current.next is not None and data > current.next.data: current = current.next current.next = push(current.next, data) return head
Linked Lists - Sorted Insert Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list. The push() and buildOneTwoThree() functions do not need to be redefined.
class Node(object): def __init__(self, data, next): self.data = data self.next = next def sorted_insert(head, data): return Node(data, head) if not head or data < head.data else Node(head.data, sorted_insert(head.next, data))
Linked Lists - Sorted Insert Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list. The push() and buildOneTwoThree() functions do not need to be redefined.
class Node(object): def __init__(self, data, nxt=None): self.data, self.next = data, nxt def sorted_insert(head, data): if head is None or head.data > data: return Node(data, head) node = head while node.__next__ and node.next.data < data: node = node.__next__ node.next = Node(data, node.next) return head
Linked Lists - Sorted Insert Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list. The push() and buildOneTwoThree() functions do not need to be redefined.
class Node(object): def __init__(self, data, next = None): self.data = data self.next = next def sorted_insert(head, data, node = None): if head is None or head.data >= data: return Node(data, head) if head.data < data: head.next = sorted_insert(head.next, data) return head raise ValueError
Linked Lists - Sorted Insert Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list. The push() and buildOneTwoThree() functions do not need to be redefined.
class Node(object): def __init__(self, data): self.data = data self.next = None def sorted_insert(head, data): new_node = Node(data) if head == None or data < head.data: new_node.next = head return new_node node = head while 1: if node.next == None or data <= node.next.data: new_node.next = node.next node.next = new_node return head node = node.next
Linked Lists - Sorted Insert Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list. The push() and buildOneTwoThree() functions do not need to be redefined.
""" For your information: class Node(object): def __init__(self, data): self.data = data self.next = None """ def sorted_insert(head, data): if not head: return Node(data) elif head.data>data: res=Node(data) res.next=head return res else: temp=head while head.next and head.next.data<data: head=head.next res=Node(data) res.next=head.next head.next=res return temp return temp
Linked Lists - Length & Count Implement Length() to count the number of nodes in a linked list. Implement Count() to count the occurrences of an integer in a linked list. I've decided to bundle these two functions within the same Kata since they are both very similar. The `push()`/`Push()` and `buildOneTwoThree()`/`BuildOneTwoThree()` functions do not need to be redefined.
class Node(object): def __init__(self, data): self.data = data self.next = None def length(node): leng = 0 while node: leng += 1 node = node.next return leng def count(node, data): c = 0 while node: if node.data==data: c += 1 node = node.next return c
Linked Lists - Length & Count Implement Length() to count the number of nodes in a linked list. Implement Count() to count the occurrences of an integer in a linked list. I've decided to bundle these two functions within the same Kata since they are both very similar. The `push()`/`Push()` and `buildOneTwoThree()`/`BuildOneTwoThree()` functions do not need to be redefined.
class Node(object): def __init__(self, data): self.data = data self.next = None def length(node): if node: return 1 + length(node.next) return 0 def count(node, data): if node: if node.data == data: return 1 + count(node.next, data) return count(node.next, data) return 0
Linked Lists - Length & Count Implement Length() to count the number of nodes in a linked list. Implement Count() to count the occurrences of an integer in a linked list. I've decided to bundle these two functions within the same Kata since they are both very similar. The `push()`/`Push()` and `buildOneTwoThree()`/`BuildOneTwoThree()` functions do not need to be redefined.
class Node(object): def __init__(self, data): self.data = data self.next = None def count_if(node, fn): n, c = node, 0 while n: if fn(n): c += 1 n = n.next return c def length(node): return count_if(node, lambda x: x != None) def count(node, data): return count_if(node, lambda x: x.data == data)
Linked Lists - Length & Count Implement Length() to count the number of nodes in a linked list. Implement Count() to count the occurrences of an integer in a linked list. I've decided to bundle these two functions within the same Kata since they are both very similar. The `push()`/`Push()` and `buildOneTwoThree()`/`BuildOneTwoThree()` functions do not need to be redefined.
class Node: def __init__(self, data): self.data = data self.next = None def length(node): return 1 + length(node.next) if node else 0 def count(node, data): return (node.data == data) + count(node.next, data) if node else 0
Linked Lists - Length & Count Implement Length() to count the number of nodes in a linked list. Implement Count() to count the occurrences of an integer in a linked list. I've decided to bundle these two functions within the same Kata since they are both very similar. The `push()`/`Push()` and `buildOneTwoThree()`/`BuildOneTwoThree()` functions do not need to be redefined.
class Node(object): def __init__(self, data): self.data = data self.next = None def length(node): n = node len = 0 while n is not None: len += 1 n = n.next return len def count(node, data): n = node count = 0 while n is not None: if data == n.data: count += 1 n = n.next return count
Linked Lists - Length & Count Implement Length() to count the number of nodes in a linked list. Implement Count() to count the occurrences of an integer in a linked list. I've decided to bundle these two functions within the same Kata since they are both very similar. The `push()`/`Push()` and `buildOneTwoThree()`/`BuildOneTwoThree()` functions do not need to be redefined.
class Node(object): def __init__(self, data): self.data = data self.next = None def iterlinkedlist(node): while node: yield node node = node.next def length(node): return sum(1 for n in iterlinkedlist(node)) def count(node, data): return sum(n.data == data for n in iterlinkedlist(node))
Linked Lists - Length & Count Implement Length() to count the number of nodes in a linked list. Implement Count() to count the occurrences of an integer in a linked list. I've decided to bundle these two functions within the same Kata since they are both very similar. The `push()`/`Push()` and `buildOneTwoThree()`/`BuildOneTwoThree()` functions do not need to be redefined.
class Node(object): def __init__(self, data): self.data = data self.next = None def length(node): return 1 + length(node.next) if node else 0 def count(node, data): return (1 if node.data == data else 0) + count(node.next, data) if node else 0