py_scratchpad

Run Settings
LanguagePython
Language Version
Run Command
import re # companyName = input() # pattern = r"(\w+)@(\w+)(.com)" # match = re.match(pattern, companyName) # print(match.group(2)) wordLen = int(input()) wordList = [input() for x in range(wordLen)] wordDict = {} for word in wordList: wordDict[word] = wordDict.get(word, 0) + 1 print(len(wordDict)) for freq in wordDict.values(): print(freq, end=' ') # 4 # bcdef # abcdefg # bcde # bcdef # def func(n): # if n == 0: # return 0 # return func(n-1) + 100 # 100 200 300 400 500 # print(func(5)) # email = "john@google.com elise@python.com" # pattern = "\w+@(\w+).com" # ans = re.findall(pattern,email) # print(ans) # s = input() # s =float(int(s)) # n = 0 # result = 0 # while True: # if s > 0: # result += s/(s+1) # s -= 1 # else: # break # print(result) # from functools import reduce # s = int(input()) # arr = list() # def compute(acc, n): # try: # n = float(int(n)) # if n > 0: # acc += n/(n+1) # return round(acc,2) # except (ValueError, TypeError) as e: # return f'a non string arg was provided and {e}' # x = reduce(compute ,range(1,s+1), 0) # print(x) # print(f'{x:.2f}' ) # float = 2.154327 # format_float = "{:.2f}".format(float) # print(format_float) # hi = "hi" # Teni = 'Teni' # print('{} {}'.format(hi, Teni)) # u = s.encode('utf-8') # # in unicode # # -*- coding: utf-8 -*- # print(u) # digits = r'(\d+)' # num = re.findall(digits, words) # print(num) # print(u"hello world") # # import pdb; pdb.set_trace() # def fib(n): # if n == 0: # return 0 # elif n == 1: # return 1 # elif n > 1: # print(fib(n-1), 'and', fib(n-2)) # 0 1 1 2 3 5 8 13 # # 1 2 3 4 5 6 7 # return fib(n-1) + fib(n-2) # return None # num = int(input()) # print(fib(num)) # f = lambda x: (f(x-1)+f(x-2)) if x > 1 else 1 if x == 1 else 0 # print(f(7)) '''Solution by: NikolayEm ''' # n = int(input()) # def fib(x): # if x == 0: return 0 # elif x == 1: return 1 # else: return fib(x-1)+fib(x-2) # fib(n) # print(','.join([str(fib(i)) for i in range(0, n+1)])) # f = lambda x: 0 if x == 0 else 1 if x == 1 else f(x-1)+f(x-2) # print(','.join([str(f(x)) for x in range(0, n+1)])) # n = int(input()) # fibo = [0]*(n+1) # print(fibo) # n = int(input()) # def evenNum(n): # i = 0 # while True: # if i <= n: # if i % 2 == 0: # yield i # i +=1 # else: # break # values = list() # for i in evenNum(n): # values.append(str(i)) # print(','.join(values)) # def numGen(n): # i = 0 # while True: # if i <= n: # if i % 5 == 0 and i % 7 == 0: # yield i # i+=1 # else: # break # n = int(input()) # values = list() # for i in numGen(n): # values.append(str(i)) # print(i, sep='\b') # print(','.join(values)) # li = [2,4,6,8, 103] # assert li == [i for i in li if i % 2 == 0], "list should be a list with even" # for i in li: # assert i%2 == 0, "list should be a list with even" li = ['Boyd', 'Sally', 'Tenner', 'Holmer', 'Lami'] li.sort() if 'Lami' in li: print('Lami') else: print('Not found') print(li) import math def bin_search(li, element): bottom = 0 top = len(li)-1 index = -1 while top>=bottom and index==-1: mid = int(math.floor((top+bottom)/2.0)) if li[mid]==element: index = mid elif li[mid]>element: top = mid-1 else: bottom = mid+1 return index li=[2,5,7,9,11,17,222,98,90] li2 = [10,2,7,9,12,13,69,26,13,32,40,1,5] print(bin_search(li,98)) print(bin_search(li2,2)) print(bin_search(li2, 12), 'check') # fl = 999/7 # print(math.floor(fl), math.ceil(fl)) idx = 0 def bs(num,num_list): global idx if (len(num_list) == 1): if num_list[0] == num: return idx else: return "No exit in the list" elif num in num_list[:len(num_list)//2]: return bs(num,num_list[:len(num_list)//2]) else: idx += len(num_list)//2 return bs(num,num_list[len(num_list)//2:]) print(bs(80,[1,5,8,10,12,13,55,66,73,78,82,85,88,99,100])) from random import random, uniform, randrange x = random() * 95 print(x, uniform(5,95), randrange(5,95)) idx = 0 def bs(num,num_list): global idx if (len(num_list) == 1): if num_list[0] == num: return idx else: return "No exit in the list" elif num in num_list[:len(num_list)//2]: return bs(num,num_list[:len(num_list)//2]) else: idx += len(num_list)//2 return bs(num,num_list[len(num_list)//2:]) # print(bs(100,[1,5,8,10,12,13,55,66,73,78,82,85,88,99,100])) print(bs(5,[10,2,7,9,12,13,69,26,13,32,40,1,5]), 'check') y = (7//2) print(y) def BinarySearch(element, li): bottom = 0 top = len(li)-1 index = -1 while top>=bottom and index==-1: mid = int(math.floor((top+bottom)/2.0)) if li[mid]==element: index = mid elif li[mid]>element: top = mid-1 else: bottom = mid+1 return index print(BinarySearch(26,[10,2,7,9,12,13,69,26,13,32,40,1,5])) from random import choice, sample, randrange from zlib import compress, decompress # li = [x for x in range(10,151) if x % 35 == 0] # print(choice(li)) # li2 = [n for n in range(100,201)] # print(sample(li2, 5)) # li3 = list(n for n in range(100,201) if n % 2 == 0) # print(sample(li3, 5)) # li4 = list(n for n in range(1, 1001) if n % 35 == 0) # resp = sample(li4, 5) # print(resp) print(randrange(7,16)) ss = "hello world!hello world!hello world!hello world!" ss = bytes(ss, "utf-8") sy = compress(ss) print(sy) print(decompress(sy)) # s = 'hello world!hello world!hello world!hello world!' # # In Python 3 zlib.compress() accepts only DataType <bytes> # y = bytes(s, 'utf-8') # x = zlib.compress(y) # print(x) # print(zlib.decompress(x)) from timeit import timeit print(timeit('(1+1 for i in range(1,101))', number=1000)) # import datetime # before = datetime.datetime.now() # for i in range(100): # x = 1 + 1 # after = datetime.datetime.now() # execution_time = after - before # print(execution_time.microseconds) import time before = time.time() for i in range(100): x = 1 + 1 after = time.time() execution_time = after - before print(execution_time) import random li = [3,6,7,8] random.shuffle(li) print(li) # sentences = input().split('.') # subject =["I", "You"] # verb = ["Play", "Love"] # obj = ["Hockey","Football"] # for words in sentences: # i = words.split() # print(i) # if i in subject: # print(words) # elif i in verb: # print(words) # elif i in obj : # print(words) # subjects=["I", "You"] # verbs=["Play", "Love"] # objects=["Hockey","Football"] # for sub in subjects: # for verb in verbs: # for obj in objects: # print("{} {} {}".format(sub,verb,obj)) # '''Solution by: lcastrooliveira # ''' # from itertools import product # def question_79(): # subject = ["I", "You"] # verb = ["Play", "Love"] # object = ["Hockey", "Football"] # prod = [p for p in product(range(2), repeat=3)] # print(prod) # for combination in prod: # print(combination) # print(f'{subject[combination[0]]} {verb[combination[1]]} {object[combination[2]]}') # question_79() # li5 = [5,6,77,45,22,12,24] # print([ x for x in li5 if x % 2 != 0]) # li6 = [12,24,35,70,88,120,155] # li6 = [n for n in li6 if n % 35 != 0] # print(li6) # def foo(n): # if n % 35 != 0: # return n # print(*(filter(foo, li6))) # """Solution by: saxenaharsh24 # """ # lst = [12,24,35,70,88,120,155] # print([i for i in lst if lst.index(i) not in range(2,5)]) # li00 = [[[ 0 for k in range(8)] for j in range(5)] for i in range(3)] # print(li00) # array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] # print(array) # li99 = [12,24,35,70,88,120,155] # li99 = [x for (i, x) in enumerate(li99) if i > 0 and i not in (range(4,6))] # print(li99) # print(list(range(0,4,5))) # li89 = [12,24,35,70,88,120,155] # li89 = [x for (i,x) in enumerate(li89) if i not in (0,4,5)] # print(li89) # li99 = [12,24,35,24,88,120,155] # li99 = [i for i in li99 if i != 24] # print(li99) # li = [12,24,35,24,88,120,155] # li.remove(24) # this will remove only the first occurrence of 24 # print(li) # li999 = set([1,3,6,78,35,55]) # li699 = set([12,24,35,24,88,120,155]) # yu = list(li999.intersection(li699)) # z7 = list(set(li999) & set(li699)) # print(z7, yu) # duplicate = [12,24,35,24,88,120,155,88,120,155,12,12,88,12,88] # newlist = [] # for num in duplicate: # if (duplicate.count(num)) > 1: # pass # else: # newlist.append(num) # print(f'Did I get it? {newlist}' ) # # print(set(duplicate)) # class Person: # def __init__(self, name): # self.name = name # class Male(Person): # def __init__(self, name, gender): # super().__init__(name) # self.gender = gender # def getGender(self): # print(f'{self.gender}') # class Female(Person): # def __init__(self, name, gender): # super().__init__(name) # self.gender = gender # def getGender(self): # print(f'{self.gender}') # Boyd = Male('Boyd', 'Male') # Leri = Female('Leri', 'Female') # Boyd.getGender() # Leri.getGender() string = input() dic = dict() if (string): for s in string: dic[s] = dic.get(s,0)+1 print(dic[s]) # for item in dic.items(): # print(*item) import string s = "abcdefgabc" for letter in string.ascii_lowercase: print(letter) cnt = s.count(letter) if cnt > 0: print("{},{}".format(letter,cnt)) print(string) '''Solution by: Utkarsh4697 ''' s = 'abcdefgabc' for i in sorted(set(s)): print(f'{i}, {s.count(i)}') # # # h = [0,1,2,3,4,5] # c = h[:: -1] # s = "rise to vote sir" # s = s[::-1] # print(s) ind = "H1e2l3l4o5w6o7r8l9d" cur = 0 wor = '' for nn in ind: if cur%2 == 0: wor += nn cur += 1 print(wor) ron = "H1e2l3l4o5w6o7r8l9d" print(ron[::2]) import itertools perm = itertools.permutations([1,2,3]) print(tuple(perm)) """Solution by: popomaticbubble """ from itertools import permutations def permuation_generator(iterable): p = permutations(iterable) for i in p: print(i) x = [1,2,3] permuation_generator(x) head = 35 legs = 94 chicken = legs/2 rabbit = legs /4 while True: if head !=0: print(chicken) print(rabbit) head -=1 else: break def solve(numheads,numlegs): ns='No solutions!' for i in range(numheads+1): j=numheads-i print('j', j, 'i',i) if not((2*i)+(4*j)==numlegs): return i,j return ns,ns numheads = 35 numlegs = 94 solutions=solve(numheads,numlegs) print(solutions) """Solution by: popomaticbubble """ # import itertools # def animal_counter(lst): # chickens = 0 # rabbits = 0 # for i in lst: # if i == 2: # chickens += 1 # elif i == 4: # rabbits += 1 # print(f"Number of chickens is {chickens}\nNumber of rabbits is {rabbits}") # def animal_calculator(total_legs, total_heads, legs_of_each_species): # combinations = itertools.combinations_with_replacement(legs_of_each_species, total_heads) # correct_combos = [] # for i in list(combinations): # if sum(i) == total_legs: # correct_combos.append(i) # print(correct_combos) # for i in correct_combos: # animal_counter(i) # animal_calculator(94, 35, legs_of_each_species=[2,4]) # li9090 = [2, 3, 6, 6, 5] # newList = [] # for i in range(len(li9090)): # maxi = max(li9090) # if li9090[i] < maxi: # c = li9090[i] # newList.append(c) # runnerUp = max(newList) # print(f'runnerup is {runnerUp}') # n = 5 # arr = [2, 3, 6, 6, 5] # arr = list(set(arr)) # arr.sort() # print(arr) # print(arr[-2]) # from textwrap import wrap # alphabet = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ' # for letter in wrap(alphabet,4): # print(letter) # def wraps(string, max_width): # string = wrap(string,max_width) # string = "\n".join(string) # return string # if __name__ == '__main__': # string, max_width ='ABCDEFGHIJKLIMNOQRSTUVWXYZ', 4 # result = wraps(string, max_width) # print(result) # from textwrap import wrap # alpha = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ' # newalpha = alpha[0:3] # li901 = [] # for i in newalpha: # li901.append(i.lower()) # print(newalpha[-1], sep='-') # print(li901) # print # print(wrap(alpha,3)) # n = 3 # l1=list(map(chr,range(97,123))) # print(l1[1:n]) # print(l1[n-1::-1]) # x=l1[n-1::-1]+l1[1:n] # print(x) # def rangoli(n): # # your code goes here # l1=list(map(chr,range(97,123))) # x=l1[n-1::-1]+l1[1:n] # mid=len('-'.join(x)) # for i in range(1,n): # print('-'.join(l1[n-1:n-i:-1]+l1[n-i:n]).center(mid,'-')) # for i in range(n,0,-1): # print('-'.join(l1[n-1:n-i:-1]+l1[n-i:n]).center(mid,'-')) # rangoli(5) # from datetime import date # lol = "08 05 2015" # lol = lol.split(' ') # lol = "-".join(lol) # lol = date.fromisoformat('2019-12-04') # lol = lol.strftime("%A") # print(lol) # import calendar # date = [8, 5, 2015] # month, day, year = map(int,date) # print(year) # dayId = calendar.weekday(year, month, day) # print(calendar.day_name[dayId].upper()) # import time # from datetime import date # today = date.today() # today # today == date.fromtimestamp(time.time()) # my_birthday = date(today.year, 6, 24) # if my_birthday < today: # my_birthday = my_birthday.replace(year=today.year + 1) # my_birthday # time_to_birthday = abs(my_birthday - today) # time_to_birthday.days # set0 = {2, 4, 5, 9} # set1= {2, 4, 11, 12} # diff0 = set1 - set0 # sym = list(set0^set1) # for i in sym: # print(i) # print(diff0) # print(list("a"*5)) # from math import ceil, floor # print(floor(-2.4)) # limit = int(input()) # wordline = [input() for i in range(limit)] # catalog = dict() # print(wordline) # for word in wordline: # catalog[word] = wordline.count(word) # for word in catalog.keys(): # print(x) # if word in x: # catalog[x] += 1 n = int(input()) word_dict = {} word_list = [] for i in range(4): word = ["bcdef", "abcdefg", "abcdefg", "abcdefg"] if word not in word_dict: word_list.append(word) word_dict[word] = word_dict.get(word, 0) + 1 print(len(word_list)) for word in word_list: print(word_dict[word], end=' ') word = input() wordDict = dict() for letter in word: wordDict[letter] = wordDict.get(letter,0)+1 print(wordDict) sortedWordDict = dict(sorted(wordDict.items(), key=lambda i: i[1], reverse=True)) print(sortedWordDict) for k,v in sortedWordDict.items(): count = " ".join([k,str(v)]) print(count) print(type(count[1])) word = input() dct = {} for i in word: dct[i] = dct.get(i,0) + 1 dct = sorted(dct.items(),key=lambda x: (-x[1],x[0])) for i in dct: print(i[0],i[1]) word = input() dct = {} for i in word: dct[i] = dct.get(i,0) + 1 def know(x): print(x) return (-x[1],x[0]) dct = sorted(dct.items(),key=know) print(dct) for i in dct: print(i[0],i[1]) dct =dict(dct) for i in dct.items(): print(-i[1], i[0] Word = input() Digit = 0 Letter = 0 for s in Word: if s.isdigit(): Digit += 1 # -*- coding: latin-1 -* elif s.isalpha(): Letter += 1 else: continue print('Digit - %d' %Digit ) print('Letter - %d' %Letter ) def recur_sum(acc, n): if n == 1: return n veb = acc veb = recur_sum(n-1) return n + veb print(recur_sum(num)) """Solution by: popomaticbubble """ def summer(counter, n, current): if n == 0: return 0 if counter == n: print(current) return current+n else: current = current + counter counter += 1 print(counter) return summer(counter, n, current) N = int(input("Hello")) print(summer(1, N, 0)) def word_search(doc_list, keyword): # list to hold the indices of matching documents indices = [] # Iterate through the indices (i) and elements (doc) of documents for i, doc in enumerate(doc_list): print(doc, "doc") # Split the string doc into a list of words (according to whitespace) tokens = doc.split() # Make a transformed list where we 'normalize' each word to facilitate matching. # Periods and commas are removed from the end of each word, and it's set to all lowercase. print(tokens, "tokens") normalized = [token.rstrip('.,').lower() for token in tokens] # Is there a match? If so, update the list of matching indices. print(normalized, "normalized") if keyword.lower() in normalized: indices.append(i) return indices ['casino', 'they'] print(word_search(["The Learn Python Challenge Casino.", "They bought a car, and a casino", "Casinoville"],'casino')) def score_count(score): score = [] for word in score: if word in ['J', 'Q','K'] and sum(score_1) <= 21: score.append(10) elif word == 'A' and sum(score_1) <= 21: score.append(11) elif word.isdigit(): score.append(int(word)) else: score.append(1) def blackjack_hand_greater_than(hand_1, hand_2): """ Return True if hand_1 beats hand_2, and False otherwise. In order for hand_1 to beat hand_2 the following must be true: - The total of hand_1 must not exceed 21 - The total of hand_1 must exceed the total of hand_2 OR hand_2's total must exceed 21 Hands are represented as a list of cards. Each card is represented by a string. When adding up a hand's total, cards with numbers count for that many points. Face cards ('J', 'Q', and 'K') are worth 10 points. 'A' can count for 1 or 11. When determining a hand's total, you should try to count aces in the way that maximizes the hand's total without going over 21. e.g. the total of ['A', 'A', '9'] is 21, the total of ['A', 'A', '9', '3'] is 14. Examples: >>> blackjack_hand_greater_than(['K'], ['3', '4']) True >>> blackjack_hand_greater_than(['K'], ['10']) False >>> blackjack_hand_greater_than(['K', 'K', '2'], ['3']) False """ score_1 = [] find_digit = [ digit for digit in hand_1 if digit.isdigit()] for word in hand_1: if word in ['J', 'Q','K'] and sum(score_1) <= 21: score_1.append(10) elif word == 'A' and sum(score_1) <= (21//2): if hand_1.count(word) > 1 or len(hand_1) > 2: score_1.append(1) else: score_1.append(11) elif word.isdigit(): score_1.append(int(word)) else: score_1.append(1) score_2 = [] find_digit = [ digit for digit in hand_2 if digit.isdigit()] print(find_digit) for word2 in hand_2: if word2 in ['J', 'Q','K'] and sum(score_2) <= 21: score_2.append(10) elif word2 == 'A' and sum(score_2) <= (21//2): if hand_2.count(word2) > 1 or len(hand_2) > 2: score_2.append(1) else: score_2.append(11) elif word2.isdigit(): score_2.append(int(word2)) else: score_2.append(1) print(sum(score_1), sum(score_2)) if sum(score_2) < 21 and sum(score_1) <= 21: return (sum(score_1) > sum(score_2)) elif sum(score_2) > 21 and sum(score_1) <= 21: return True else: return False score_2 = [] find_digit2 = [ int(digit) for digit in hand_2 if digit.isdigit()] find_alpha2 = [ bool(alpha2) for alpha2 in hand_1 if alpha2.isalpha()] print(find_digit2, find_alpha2) for word2 in hand_2: if word2 in ['J', 'Q','K']: score_2.append(10) elif word2 == 'A': if hand_2.count(word2) > 1 or sum(find_digit2) >= (21//2) or sum(find_alpha2) > 1: score_2.append(1) else: score_2.append(11) elif word2.isdigit(): score_2.append(int(word2)) else: score_2.append(0) def helpher_func(li): total = [] find_digit1 = [ int(digit) for digit in li if digit.isdigit()] find_alpha = [ bool(alpha) for alpha in li if alpha.isalpha()] for word in li: if word in ['J', 'Q','K']: total.append(10) elif word == 'A': if total.count(word) > 1 or sum(find_digit1) >= (21//2) or sum(find_alpha) > 1: total.append(1) else: total.append(11) elif word.isdigit(): total.append(int(word)) else: total.append(0) return sum(total) if helpher_func(hand_1) <= 21 and helpher_func(hand_2) <= 21: return (helpher_func(hand_1) > helpher_func(hand_2)) elif helpher_func(hand_2) > 21 and helpher_func(hand_1) <= 21: return True else: return False def blackjack_hand_greater_than(hand_1, hand_2): """ Return True if hand_1 beats hand_2, and False otherwise. In order for hand_1 to beat hand_2 the following must be true: - The total of hand_1 must not exceed 21 - The total of hand_1 must exceed the total of hand_2 OR hand_2's total must exceed 21 Hands are represented as a list of cards. Each card is represented by a string. When adding up a hand's total, cards with numbers count for that many points. Face cards ('J', 'Q', and 'K') are worth 10 points. 'A' can count for 1 or 11. When determining a hand's total, you should try to count aces in the way that maximizes the hand's total without going over 21. e.g. the total of ['A', 'A', '9'] is 21, the total of ['A', 'A', '9', '3'] is 14. Examples: >>> blackjack_hand_greater_than(['K'], ['3', '4']) True >>> blackjack_hand_greater_than(['K'], ['10']) False >>> blackjack_hand_greater_than(['K', 'K', '2'], ['3']) False """ def helpher_func(li): total = [] find_digit1 = [ int(digit) for digit in li if digit.isdigit()] find_alpha = [ bool(alpha) for alpha in li if alpha.isalpha()] for word in li: if word in ['J', 'Q','K']: total.append(10) elif word == 'A': if total.count(word) > 1 or sum(find_digit1) >= (21//2) or sum(find_alpha) > 1: total.append(1) else: total.append(11) elif word.isdigit(): total.append(int(word)) else: total.append(0) return sum(total) if helpher_func(hand_1) <= 21 and helpher_func(hand_2) <= 21: return (helpher_func(hand_1) > helpher_func(hand_2)) elif helpher_func(hand_2) > 21 and helpher_func(hand_1) <= 21: return True else: return False class BlackjackHand: def __init__(self, li): self.li = li def blackjack_hand_greater_than(self): find_digit1 = [ int(digit) for digit in self.li if digit.isdigit()] find_alpha = [ bool(alpha) for alpha in self.li if alpha.isalpha()] total = [] for word in self.li: if word in ['J', 'Q','K']: total.append(10) elif word == 'A': if self.li.count(word) > 1 or sum(find_digit1) > (21//2) or sum(find_alpha) > 1: if sum(find_alpha) <= 2 and (sum(find_digit1)==0): total.append(11) else: total.append(1) else: total.append(11) elif word.isdigit(): total.append(int(word)) else: total.append(0) sum_total = sum(total) print(sum_total) if sum_total <= 21: return sum_total elif sum_total > 21: return False else: return True hand1 = BlackjackHand(['1','9', '2', 'A']) hand2 = BlackjackHand(['K', 'A', '10', '1']) print(hand2.blackjack_hand_greater_than()) print(hand1.blackjack_hand_greater_than() > hand2.blackjack_hand_greater_than())
Editor Settings
Theme
Key bindings
Full width
Lines