Ad
Code
Diff
  • # -*- coding: utf-8 -*-
    REG_VERSE = """
    {n} bottles of beer on the wall, {n} bottles of beer
    Take one down and pass it around, {n_m_1} bottles of beer on the wall.
    """
    
    ENDING_VERSES = """
    2 bottles of beer on the wall, 2 bottles of beer.
    Take one down and pass it around, 1 bottle of beer on the wall.
    
    1 bottle of beer on the wall, 1 bottle of beer.
    Take one down and pass it around, no more bottles of beer on the wall.
    
    No more bottles of beer on the wall, no more bottles of beer.
    Go to the store and buy some more, 99 bottles of beer on the wall.
    """
    
    def beer_song():
        "Returns the Song '99 Bottles of Beer'"
        # list of song iterations.
        
        return '\n'.join(REG_VERSE.format(n=n, n_m_1=n - 1) for n in range(99, 2, -1)) + "\n" + ENDING_VERSES
    • # -*- coding: utf-8 -*-
    • REG_VERSE = """
    • {n} bottles of beer on the wall, {n} bottles of beer
    • Take one down and pass it around, {n_minus_1} bottles of beer on the wall.
    • Take one down and pass it around, {n_m_1} bottles of beer on the wall.
    • """
    • ENDING_VERSES = """
    • 2 bottles of beer on the wall, 2 bottles of beer.
    • Take one down and pass it around, 1 bottle of beer on the wall.
    • 1 bottle of beer on the wall, 1 bottle of beer.
    • Take one down and pass it around, no more bottles of beer on the wall.
    • No more bottles of beer on the wall, no more bottles of beer.
    • Go to the store and buy some more, 99 bottles of beer on the wall.
    • """
    • def beer_song():
    • "Returns the Song '99 Bottles of Beer'"
    • # list of song iterations.
    • verses = []
    • # Sing one less bottle each time, removing one until reaching 2.
    • for n in range(99, 2, -1):
    • verses.append(REG_VERSE.format(n=n,n_minus_1=n - 1))
    • # Add final verse once loop is done.
    • verses.append(ENDING_VERSES)
    • return '\n'.join(verses)
    • return '\n'.join(REG_VERSE.format(n=n, n_m_1=n - 1) for n in range(99, 2, -1)) + "\n" + ENDING_VERSES
Code
Diff
  • def time_out():
        while 1:1
    • # you know if this will time out by pressing the 'TDD' button.
    • def time_out():
    • while True:pass
    • while 1:1
Web Scraping
Code
Diff
  • from bs4 import BeautifulSoup
    import requests
    import shutil
    from pathlib import Path
    
    
    def get_codewars_stats(username):
        """Scraps, and retrieves Codewars stats of given username."""
    
        source = requests.get(f'https://www.codewars.com/users/{username}', stream=True)
    
        # Verify request status.
        if source.status_code != 200:
            print(f'Error: {source.status_code}')
            return 'Something went wrong, enter a valid Codewars username.'
    
        soup = BeautifulSoup(source.text, 'html.parser')
        stat_info = soup.findAll('div', class_='stat')
        important_values = [info.text for info in stat_info[:5] + stat_info[6:]]
    
        # Get url to users avatar/profile pic
        img_url = soup.find('figure').find('img').get('src')
    
        # Get image_url requests:
        img_source = requests.get(img_url, stream=True)
    
        # The filepath where data will be saved:
        filepath = Path.cwd() / 'CodeWars'
    
        # Make Codewars directory if it does mot exist:
        if not filepath.is_dir():
            filepath.mkdir()
    
        # Save user's avatar/profile pic:
        with (filepath / 'avatar.jpg').open('wb') as img_obj:
            img_source.raw.decode_content = True
            shutil.copyfileobj(img_source.raw, img_obj)
        print(f'Profile pic has been successfully saved to {img_obj.name}')
    
        # Save user's Codewars stats:
        with (filepath / 'stats.txt').open('w') as file_obj:
            file_obj.write('\n'.join(item for item in important_values))
        print(f'Stats have been successfully written to {file_obj.name}')
    
        stats = '\n\t'.join(i for i in important_values)
        return f'{username}\'s Codewars stats:\n\t{stats}'
    
    • from bs4 import BeautifulSoup
    • import requests
    • import shutil
    • import os
    • from pathlib import Path
    • def get_codewars_stats(username):
    • """Scraps, and retrieves Codewars stats of given username."""
    • output = f'{username}\'s Codewars stats:\n'
    • source = requests.get(f'https://www.codewars.com/users/{username}', stream=True)
    • # Verify request status. Using 404 would miss a wide ranges of other failed connections.
    • if source.status_code == 200:
    • soup = BeautifulSoup(source.text, 'html.parser')
    • stat_info = soup.findAll('div', class_='stat')
    • important_values = [info.text for info in stat_info[:5] + stat_info[6:]]
    • # Get url to users avatar/profile pic
    • img_url = ''.join([el for el in str(soup.findAll('figure')[0].findNext('img')).split(' ') if 'src' in el]).replace('src="', '')
    • # Get image_url requests:
    • img_source = requests.get(img_url, stream=True)
    • # The filepath where data will be saved:
    • filepath = Path.cwd() / 'CodeWars'
    • # Make Codewars directory if it does mot exist:
    • if not filepath.is_dir():
    • filepath.mkdir()
    • with filepath.with_suffix('.jpg').open('wb') as img_obj:
    • # Save user's avatar/profile pic:
    • img_source.raw.decode_content = True
    • shutil.copyfileobj(img_source.raw, img_obj)
    • print('Profile pic has been downloaded')
    • with (filepath /'codewars_stats.txt').open('w', encoding='utf-8') as file_obj:
    • # Save user's Codewars stats:
    • for item in important_values:
    • file_obj.write(item + '\n')
    • print('CodewarsStats have been successfully downloaded')
    • # Verify request status.
    • if source.status_code != 200:
    • print(f'Error: {source.status_code}')
    • return 'Something went wrong, enter a valid Codewars username.'
    • soup = BeautifulSoup(source.text, 'html.parser')
    • stat_info = soup.findAll('div', class_='stat')
    • important_values = [info.text for info in stat_info[:5] + stat_info[6:]]
    • # Get url to users avatar/profile pic
    • img_url = soup.find('figure').find('img').get('src')
    • # Get image_url requests:
    • img_source = requests.get(img_url, stream=True)
    • # The filepath where data will be saved:
    • filepath = Path.cwd() / 'CodeWars'
    • # Make Codewars directory if it does mot exist:
    • if not filepath.is_dir():
    • filepath.mkdir()
    • # Save user's avatar/profile pic:
    • with (filepath / 'avatar.jpg').open('wb') as img_obj:
    • img_source.raw.decode_content = True
    • shutil.copyfileobj(img_source.raw, img_obj)
    • print(f'Profile pic has been successfully saved to {img_obj.name}')
    • # Save user's Codewars stats:
    • with (filepath / 'stats.txt').open('w') as file_obj:
    • file_obj.write('\n'.join(item for item in important_values))
    • print(f'Stats have been successfully written to {file_obj.name}')
    • output += '
    • \t'.join([i for i in important_values])
    • return output
    • else:
    • return 'Something went wrong, enter a valid Codewars username.'
    • stats = '
    • \t'.join(i for i in important_values)
    • return f'{username}\'s Codewars stats:\n\t{stats}'
Algorithms
Fundamentals
Code
Diff
  • collatz = lambda n: collatz([n//2, 3*n+1][n%2]) + 1 if n > 1 else 0
    
    • #collatz = c = lambda n, x=0: c( [ n//2, 3*n + 1 ][ n%2 ], x + 1 ) if n > 1 else x
    • #collatz = c = lambda n: 1 + c( [ n//2, 3*n + 1 ][ n%2 ] ) if n > 1 else 0
    • collatz=c=lambda n:1+c([n//2,3*n+1][n%2])if n>1else 0
    • collatz = lambda n: collatz([n//2, 3*n+1][n%2]) + 1 if n > 1 else 0
Fundamentals
Arrays
Strings
Code
Diff
  • FindTRex = lambda lst: type("", (), {"find_trex": lambda: "tyrannosaurus" in lst})
    • FindTRex = lambda lst: type("FindTRex", tuple(), {"lst" : lst, "find_trex" : lambda : "tyrannosaurus" in lst})
    • FindTRex = lambda lst: type("", (), {"find_trex": lambda: "tyrannosaurus" in lst})
Web Scraping
Code
Diff
  • from bs4 import BeautifulSoup
    import requests
    
    
    def get_codewars_stats(username):
        """Scraps, and retrieves Codewars stats of given username."""
        source = requests.get(f'https://www.codewars.com/users/{username}')
    
        # Verify request status:
        if source.status_code == 404:
            return 'Something went wrong, enter a valid Codewars username.'
    
        soup = BeautifulSoup(source.text, 'html.parser')
        stat_info = soup.findAll('div', class_='stat')
    
        # i'm not sure why we dont show all of stat_info in the version before this
        # Would like someone to implement  showing Profiles, since that is an image (maybe represent as link to profile?)
        # slicing the profiles out is my workaround for now
        important_values = [info.text for info in stat_info[:5] + stat_info[6:]]
    
        seperator = '\n\t'  # sadly f-strings don't allow backslashes, so we need to define a separator here instead
        return f'{username}\'s Codewars stats:\n\t{seperator.join(important_values)}'
    
    • from bs4 import BeautifulSoup
    • import requests
    • def get_codewars_stats(username):
    • """Scraps, and retrieves Codewars stats of given username."""
    • source = requests.get(f'https://www.codewars.com/users/{username}')
    • # Verify request status:
    • if source.status_code == 404:
    • return 'Something went wrong, enter a valid Codewars username.'
    • else:
    • soup = BeautifulSoup(source.text, 'html.parser')
    • stat_info = soup.findAll('div', class_='stat')
    • name, member, rank, honor, position, percentage, katas = (stat_info[0],
    • stat_info[3],
    • stat_info[9],
    • stat_info[10],
    • stat_info[11],
    • stat_info[12],
    • stat_info[13])
    • return f"{username}'s Codewars stats:
    • \t{member.text}\n\t{rank.text}\n\t{honor.text}\n\t{position.text}\n\t{percentage.text}\n\t{katas.text}"
    • soup = BeautifulSoup(source.text, 'html.parser')
    • stat_info = soup.findAll('div', class_='stat')
    • # i'm not sure why we dont show all of stat_info in the version before this
    • # Would like someone to implement showing Profiles, since that is an image (maybe represent as link to profile?)
    • # slicing the profiles out is my workaround for now
    • important_values = [info.text for info in stat_info[:5] + stat_info[6:]]
    • seperator = '\n\t' # sadly f-strings don't allow backslashes, so we need to define a separator here instead
    • return f'{username}\'s Codewars stats:
    • \t{seperator.join(important_values)}'
Fundamentals
Code
Diff
  • hello_message = lambda: 'Hello World!'
    • exec(bytes('敨汬彯敭獳条⁥‽慬扭慤㨠✠效汬潗汲Ⅴ‧', 'u16')[2:])
    • """
    • ^&&7 Y@G.
    • !B#Y^ ^5#G^
    • .7PBP7: .^?PBP!.
    • ~@@! .:~7Y5PPY!.
    • ^&&^ .^?5P555JJJ?7777!!!7777?JJY5555YJ7~:.
    • Y@5 :!J5GPJ!: ....^^^^^^~^^^^^:...
    • :&@#JPP5?~.
    • .BBY!:. .........
    • ............... .........
    • ................................
    • ..................................
    • ..^~7????7~~^::.........::^^~!!77???7!~^:.
    • :!?YPBGGBBB###&&&##GPYYJJYYY5PGGGPP55YYY5PGGPYJ7.
    • :JY5&#7^::::::^~!!7YB&##BBBBGP?~^::........~5BP5P:
    • ~JG&!.......:^^^^:.^#&#B#BGGY..::::........^GP5J
    • .7G&~......:^^::::.^&&BP5PBG5:::.:. .::::.:5PP~
    • .^5#Y.......::::::.J@#Y~^~5BG7...:. .:::::~YPY~.
    • .:7B#^.........::.~&&G~^^~!PBP~... .::::::!PP7~.
    • ..:JBG~:........:?&@B7^^^~~7GBG?^...::::^7YPP?~!.
    • .:.:!PBGPYJJJJ5B&@&5!^^^^^~~!JGBGP5YYYY5PGPY!~!~
    • ::..:^7YPGBBBGPJ!^^^^^^^^~~~~~7?JY5555YJ7!~~~!.
    • :::....::!^:::::::^^^^^^~~~~~~~~!!^~~~~~!!!!:
    • :^::::::~^~77!~^^^^^~~~~~~!!7?J7:.^!!!!!!!:
    • :^^::::::::^7?J7....:~....~?~..:~!!!!!!!.
    • .^~^^^^^^^::::. . .:^!!!!!!!!:
    • .^~~~^^~^~^^^:. .. .~!!!!!!!!~:
    • .:^~!~~~~~~~~~~~!~~!!!!!!!!~^.
    • .:^~!!!!!!!!!!!!!!!~^:.
    • ...:::::::...
    • """
    • hello_message = lambda: 'Hello World!'
Code
Diff
  • def celsius_to_fahrenheit(fahrenheit):
        """Converts fahrenheit to celsius."""
        return (fahrenheit - 32) * 5 / 9
    
    
    def fahrenheit_to_celsius(celsius):
        """Converts celsius to fahrenheit."""
        return (celsius * 9 / 5) + 32
    
    
    """ Not needed for Testcases"""
    if __name__ == "__main__":
        from re import compile
        func_to_conversion = {
            fahrenheit_to_celsius: "Celsius to Fahrenheit",
            celsius_to_fahrenheit: "Fahrenheit to Celsius"
        }
    
        def highlight_mode(text):
            print(f"\033[36m{text}\033[0m")
    
    
        def error_message(text):
            print(f"\033[31m{text}\033[0m")
    
            
        decimal_or_float_pattern = compile(r"^[-+]?(?:\d+\.\d*|\d*\.\d+|\d+)$")
    
        while True:
            match input("Would you like to convert (c)elsius, (f)ahrenheit or (q)uit:\n> ").lower():
                case "q":
                    exit(print("Goodbye!"))
                case "f":
                    func = celsius_to_fahrenheit
                case "c":
                    func = fahrenheit_to_celsius
                case _:
                    error_message("Invalid input")
                    continue
    
            conversion = func_to_conversion[func]
            units = conversion.split()
            highlight_mode(f"Converting {conversion}")
            temperature = input(f"Enter temperature in {units[0]}:")
    
            if not decimal_or_float_pattern.match(temperature):
                error_message(f"{units[2]} was not given as a decimal or float value.\n")
                continue
    
            highlight_mode(f"{func(float(temperature)):.1f}° {units[2]}")
    
    • """ONLY HERE TO PASS THE TESTS"""
    • """THE REST OF THE PROGRAM RUNS WITHOUT THESE"""
    • #
    • #
    • #
    • def celsius_to_fahrenheit(fahrenheit):
    • """Converts fahrenheit to celsius."""
    • return (fahrenheit - 32) * 5 / 9
    • def fahrenheit_to_celsius(celsius):
    • """Converts celsius to fahrenheit."""
    • return (celsius * 9 / 5) + 32
    • """ONLY HERE TO PASS THE TESTS"""
    • """THE REST OF THE PROGRAM RUNS WITHOUT THESE"""
    • #
    • #
    • #
    • """ Not needed for Testcases"""
    • if __name__ == "__main__":
    • from re import compile
    • func_to_conversion = {
    • fahrenheit_to_celsius: "Celsius to Fahrenheit",
    • celsius_to_fahrenheit: "Fahrenheit to Celsius"
    • }
    • error_message = lambda text: f"\033[31m{text}\033[0m"
    • highlight_mode = lambda text: f"\033[36m{text}\033[0m"
    • def highlight_mode(text):
    • print(f"\033[36m{text}\033[0m")
    • def error_message(text):
    • print(f"\033[31m{text}\033[0m")
    • decimal_or_float_pattern = compile(r"^[-+]?(?:\d+\.\d*|\d*\.\d+|\d+)$")
    • if __name__ == "__main__":
    • while True:
    • choice = input("Would you like to convert (c)elsius, (f)ahrenheit or (q)uit:
    • >")
    • try:
    • {
    • "c": lambda x: print(highlight_mode(f"{((x * 9 / 5) + 32):.1f}° Fahrenheit")),
    • "f": lambda x: print(highlight_mode(f"{((x - 32) * 5 / 9):.1f}° Celsius"))
    • }[choice](int(input(f"""{highlight_mode(f'Converting {"Celsius to Fahrenheit" if choice == "c" else "Fahrenheit to Celsius"}')}\nEnter temperature in {'Celcius' if choice == 'c' else 'Fahrenheit'}:\n>""")))
    • except:
    • if choice == "q": break
    • print(error_message("Invalid input"))
    • match input("Would you like to convert (c)elsius, (f)ahrenheit or (q)uit:
    • > ").lower():
    • case "q":
    • exit(print("Goodbye!"))
    • case "f":
    • func = celsius_to_fahrenheit
    • case "c":
    • func = fahrenheit_to_celsius
    • case _:
    • error_message("Invalid input")
    • continue
    • conversion = func_to_conversion[func]
    • units = conversion.split()
    • highlight_mode(f"Converting {conversion}")
    • temperature = input(f"Enter temperature in {units[0]}:")
    • if not decimal_or_float_pattern.match(temperature):
    • error_message(f"{units[2]} was not given as a decimal or float value.\n")
    • continue
    • print("Goodbye!")
    • highlight_mode(f"{func(float(temperature)):.1f}° {units[2]}")
Code
Diff
  • convert_binary_decimal = lambda n: int(f"{n}", 2)
    • convert_binary_decimal = lambda n: int(str(n), 2)
    • convert_binary_decimal = lambda n: int(f"{n}", 2)
Algorithms
Fundamentals
Code
Diff
  • def collatz(n):
        attempts = 0
        while n != 1:
            if n % 2:
                n = (3*n+1) // 2
                attempts += 2
            else:
                n //= 2
                attempts += 1
        return attempts
    • def collatz(n):
    • attempts = 0
    • while n != 1:
    • if n % 2 == 0:
    • n /= 2
    • attempts += 1
    • if n % 2:
    • n = (3*n+1) // 2
    • attempts += 2
    • else:
    • n = (3*n) + 1
    • n //= 2
    • attempts += 1
    • return attempts