def buddyStrings(A, B): """ :type A: str :type B: str :rtype: bool """ da = c(A) db = c(B) if da.keys() != db.keys(): return False count = 0 mark = False for a, b in zip(A, B): if a != b: count += 1 else: if da[a] != db[b]: return False elif da[a] >= 2 and db[b] >= 2: mark = True if count == 2 or count == 0 and mark: return True return False
def match(fingerprints, base): """ Compares the recorded fingerprints to fingerprints from songs stored in the database to identify the song. Parameters: ----------- fingerprints: List[Tuple[int, int, int]] List of fingerprints (freq_0, freq_1, dt) that store the fingerprints from the recorded audio file base: Dict[Tuple[int, int, int]:List[string, int]] Dictionary of fingerprints (freq_0, freq_1, dt) that map to a list of song names and time intervals. Returns: -------- [string]: Title of the matched song in the form "(song title) by (artist)" """ matches = [] database = base for fp in fingerprints: if fp[:3] in database: for idx, val in enumerate(database[fp[0:3]]): matches.append((val[0], val[1]-fp[3])) max = c(matches).most_common()[0][1] if max > 20: return song_IDs[c(matches).most_common()[0][0][0]] else: return 'Sorry, we could not find your song :('
def collectResult(): c1 = c() c2 = defaultdict(c) sortedKey = [] gridResult = comm.gather(gridCounter, root=0) hashtagResult = comm.gather(hashtagCounter, root=0) if rank == 0: for r in gridResult: c1 = c1 + c(r) for item in hashtagResult: for k, d in item.items(): c2[k].update(d) c2[k].most_common() print("##########Rank of grids##########") for k, v in c1.most_common(): print(k, v) print("##########Rank of hash tags##########") # print rank of tags sortedc2 = OrderedDict( sorted(c2.items(), key=lambda x: x[1]['total'], reverse=True)) for k in sortedc2: if (len(sortedc2[k]) > 5): print(k, list(sortedc2[k].most_common())[1:6]) else: print(k, list(sortedc2[k].most_common())[1:len(sortedc2[k]) - 1]) total = time.time() - start_time minutes, seconds = divmod(total, 60) print("time takes: %02d minutes and %02d seconds" % (minutes, seconds))
def anagram_sort(source, destination): from collections import Counter as c f = open(source, "rt") lines = [] for line in f: line = line.lstrip(" ") if line[0] != '#' and line[0] != '\n': lines.append((line.strip())) anagram_lists=[] finished=[] for i in range(len(lines)): word=lines[i] if word not in finished: words=(word,) finished.append(word) c1=c(word.lower()) for j in range(i+1,len(lines)): c2=c(lines[j].lower()) if c1==c2: words+=(lines[j],) finished.append(lines[j]) if len(words)>0: anagram_lists.append(sorted(words,key=lambda x:x.lower())) anagram_lists = sorted(anagram_lists, key=lambda lst: lst[0].lower()) anagram_lists = sorted(anagram_lists, key=lambda lst: (len(lst)), reverse=True) f.close() f=open(destination,"w") string="" for i in anagram_lists: string+="\n".join(i) string+="\n" f.write(string) f.close()
def test_to_taxa(): labels = [ Label("if", [S(1, 1), S(1, 1), S(2, 5)]), Label("comparison_operator:Lt", [S(1, 1), S(3, 3), S(2, 2)]), ] assert t.to_taxa(labels) == [ ("condition/inequality", c({S(2, 2): 1, S(3, 3): 1, S(1, 1): 1})), ("flow/conditional", c({S(1, 1): 2, S(2, 5): 1})), ]
def getHint(self, secret, guess): bulls, diffa, diffb = 0, [], [] for a, b in zip(secret, guess): if a == b: bulls += 1 else: diffa.append(a) diffb.append(b) cows = sum(v for k, v in (c(diffa) & c(diffb)).items()) return "{}A{}B".format(bulls, cows)
def check_duplicate(s): ''' given a sequence of letters return (if duplicate of 2 letters exist, if duplicate of 3 letters exist) ''' two = three = False if 2 in c(s).values(): two = True if 3 in c(s).values(): three = True return (two, three)
def naiveCalcMatch(description, resume): matchCounter = 0 descTally = c(description) resTally = c(resume) # If a word in Resume is found in the description, increment the counter # by the number of occurences of the word in the resume for key in resTally: if key in descTally: matchCounter += resTally.get(key) result = matchCounter return round(result, 0)
def isAnagram(self, s, t): return c(s) == c( t) #Return True if the condition satisfied otherwise false #Linewise Example: #s = 'rat' #t = 'car' #c(s) = {'a':1, 'r':1, 't':1} #c(t) = {'a':1, 'c':1, 't':1} #False
def canConstruct(ransomNote, magazine): """ :type ransomNote: str :type magazine: str :rtype: bool """ d1, d2 = c(ransomNote), c(magazine) for k, v in d1.items(): if v > d2[k]: return False return True
def uniqueOccurences(self, arr): tmp = c(arr) #Initialize tmp which count the occurrences tmpVal = [] #Initialize tmpVal empty list for key, val in tmp.items(): #Loop through dictionary tmpVal.append(val) #Append the val in tmpVal list count = c( tmpVal) #Initialize count which count the occurrences of values for key, val in count.items(): #Loop through dictionary if val != 1: #Condition-check: If val is not equal to 1 such that any value occurrence twice or more than that return False #We return false return True #Return true otherwise
def findTheDifference(s, t): """ :type s: str :type t: str :rtype: str """ d1, d2 = c(s), c(t) for k in d2.keys(): if not k in d1: return k elif d1[k] != d2[k]: return k
def solve(s, t): '''1 <= |s| = |t| <= 500''' ds, dt = c(s), c(t) skeys, tkeys = ds.keys(), dt.keys() if all(tkey in skeys for tkey in tkeys) and len(skeys) > len(tkeys): return 'A' for k, v in ds.items(): if v > 1 and k not in t: return 'A' return 'B'
def intersect(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ d1, d2 = c(nums1), c(nums2) res = [] for k, v in d1.items(): if k in d2: res.extend([k] * min(v, d2[k])) return res
def solve(n, array): odd, even = [], [] odd_count = even_count = 0 for num in array: if num % 2: odd.append(num) odd_count += 1 else: even.append(num) even_count += 1 odd_dict, even_dict = c(odd), c(even) return odd_count * (odd_count - 1) / 2 + even_count * (even_count - 1) / 2 - f(odd_dict) - f(even_dict)
def canConstruct(self, ransomNote, magazine): """ :type ransomNote: str :type magazine: str :rtype: bool """ cr = c(ransomNote) cm = c(magazine) for l in cr: if cr[l] > cm[l]: return False return True
def test_call(): programs = [ Program( path="algo1", labels=[ Label("if", [S(1, 1), S(1, 1), S(2, 5)]), Label("if_else", [S(1, 1), S(2, 5)]), Label("comparison_operator:Lt", [S(1, 1), S(3, 3), S(2, 2)]), ], taxa=[], addition={}, deletion={}, ), Program( path="algo2", labels=[ Label("member_call_method:difference_update", [S(1, 1), S(1, 1), S(2, 5)]), Label("literal:Set", [S(1, 1), S(2, 5)]), ], taxa=[], addition={}, deletion={}, ), ] result = {program.path: t.to_taxa(program.labels) for program in programs} print(result) assert result == { "algo1": [ ("condition/inequality", c({ S(2, 2): 1, S(3, 3): 1, S(1, 1): 1 })), ("flow/conditional", c({S(1, 1): 1})), ("flow/conditional/else", c({ S(1, 1): 1, S(2, 5): 1 })), ], "algo2": [ ("call/subroutine/builtin/casting/set", c({ S(1, 1): 1, S(2, 5): 1 })), ("type/non_sequence/set", c({ S(1, 1): 3, S(2, 5): 2 })), ], }
def uncommonFromSentences(self, A: str, B: str) -> List[str]: result = [] if (len(A) >= 0 and len(A) <= 200 and len(B) >= 0 and len(B) <= 200): spaceA = A.split(" ") spaceB = B.split(" ") copySpaceA = spaceA for key, val in c(spaceA).items(): if (val == 1 and key not in spaceB): result.append(key) for key, val in c(spaceB).items(): if (val == 1 and key not in copySpaceA): result.append(key) return result
def findAnagrams(self, s, p): lenS, lenP = len(s), len(p) #Initialize lenS and lenP if lenS < lenP: #Condition-check: If lenS is smaller then lenP return [] #Return empty list tmp = [] #Initialize tmp countS, countP = c(), c(p) #Initialize countP and countS for i in range(lenS): #Loop through lenS countS[s[i]] += 1 #Update countS if i >= lenP: #Condition-check: If i is greater or equal to lenP if countS[s[i - lenP]] == 1: #Condition-check: If s[i - lenP] in the countS is 1 del countS[s[i - lenP]] #We delete that key and value else: #Condition-check: Else countS[s[i - lenP]] -= 1 #Update the value by decreasing 1 in the key of s[i - lenP] of countS if countP == countS: #Condition-check: If the dictionary will have the same key value pair tmp.append(i - lenP + 1) #Append the value in tmp list
def mix(s1, s2): t = [] c1 = c(re.sub("[^a-z]", "", s1)) c2 = c(re.sub("[^a-z]", "", s2)) for j in set(c1.keys()).union(c2.keys()): m, n = c1[j], c2[j] if m > n and m > 1: t.append([c1[j], j, "1"]) elif n > m and n > 1: t.append([c2[j], j, "2"]) elif n > 1: t.append([c2[j], j, "="]) return "/".join( k + ":" + j * i for i, j, k in sorted(t, key=lambda x: (-x[0], x[2], x[1])))
def precompute_digits(self, n, m): if len(n) < len(m): return [''.join(sorted(n, reverse=True))] feq = c(n) count = 0 self.bharo = [] self.bazinga(feq, m, count) return self.bharo
def hammingWeight(self, n): tmp = "{:032b}".format(n) #Initialize tmp and find binary representation tmpCount = c(tmp) #Initialize tmpCount and use Counter for tmp for key, val in tmpCount.items(): #Loop through tmpCount if key == '1': #Condition-check: If we find '1' bit return val #Return value for key == '1' return 0 #Otherwise return 0
def findPairs(nums, k): """ :type nums: List[int] :type k: int :rtype: int """ if k < 0: return 0 d = c(nums) keys = sorted(d.keys()) count = 0 if k == 0: for k, v in d.items(): if v > 1: count += 1 return count i, j, n = 0, 1, len(keys) while i < n and j < n: tmp = keys[j] - keys[i] if tmp == k: count += 1 i += 1 j += 1 elif tmp < k: j += 1 else: i += 1 return count
def uniqueOccurrences(arr): """ :type arr: List[int] :rtype: bool """ d = c(arr) return len(set(d.values())) == len(d)
def bazinga(self, b): b = c(b) b = sorted(b.items(), key=ig(0), reverse=True) for i in b: if i[1] % 2 != 0: return 'Conan' else: return 'Agasa'
def get_months_counter(): months = list() birthdays = get_birthdays() for value in birthdays.values(): month_number = value[:2] if month_number == "01": months.append("Jan") elif month_number == "02": months.append("Feb") elif month_number == "03": months.append("Mar") elif month_number == "04": months.append("Apr") elif month_number == "05": months.append("May") elif month_number == "06": months.append("Jun") elif month_number == "07": months.append("Jul") elif month_number == "08": months.append("Aug") elif month_number == "09": months.append("Sep") elif month_number == "10": months.append("Oct") elif month_number == "11": months.append("Nov") elif month_number == "12": months.append("Dec") result = c(months) return result
def solve(s): n = len(s) d1 = c(s) odd = 0 odd_chr = '' for k, v in d1.items(): if v % 2: odd += 1 odd_chr = k if odd > 1: return -1 d2 = defaultdict(list) for j in range(n): d2[s[j]].append(str(j + 1)) res = [0] * n p = 0 for k, v in d2.items(): if d1[k] % 2 == 0: half = d1[k] / 2 res[p : p + half] = v[ : half] res[n - p - half : n - p] = v[half : ] p += half if odd_chr != '': res[p: p + d1[odd_chr]] = d2[odd_chr] return ' '.join(res)
def bazinga(self, feq, m, ct): print(ct) if ct == len(m): return elif ct == 0: t = m[:ct + 1] self.bharo = [x for x in feq if x <= t] self.bazinga(feq, m, ct + 1) else: t = m[:ct + 1] temp = [] for i in range(len(self.bharo)): feq_val = c(self.bharo[i]) put_val, put_val_2 = '', '' for k, v in feq.items(): if k in feq_val and v <= feq_val[k]: continue put_val = k + self.bharo[i] put_val_2 = self.bharo[i] + k if put_val not in temp and put_val not in self.bharo and \ int(put_val) < int(t): temp.append(put_val) if put_val_2 not in temp and put_val_2 not in self.bharo \ and int(put_val_2) < int(t): temp.append(put_val_2) print(temp) self.bharo = temp self.bazinga(feq, m, ct + 1)
def maxRepOpt1(text): """ :type text: str :rtype: int """ n = len(text) d = c(text) counts = [] text += '*' res = 0 tmp = 1 for i in range(n): if text[i] == text[i + 1]: tmp += 1 else: counts.append((text[i], tmp)) res = max(res, min(tmp + 1, d[text[i]])) tmp = 1 for i in range(1, len(counts) - 1): left_c, left_count = counts[i - 1] mid_c, mid_count = counts[i] right_c, right_count = counts[i + 1] if left_c == right_c and mid_count == 1: res = max(res, min(left_count + right_count + 1, d[right_c])) return res
def find_it(seq): cseq = c(seq) try_list = [] for i in cseq: if cseq[i] % 2 != 0: try_list.append(i) return (int("".join(map(str, try_list))))
def callback(event): selected = datapoints_source.selected.indices print(selected) #global filtered_df print(len(filtered_df)) filtered_df2 = filtered_df.iloc[selected, :] dictionary = dict(x=filtered_df2[X], y=filtered_df2[Y], thr=filtered_df2['threshold']) for col_name in display_columns: # if col_name not in [X,Y]: dictionary[col_name] = filtered_df2[col_name] dictionary3 = {} for col_name in filtered_df2.columns: dictionary3[col_name] = filtered_df2[col_name] data_table_source.data = dictionary3 ldict = dict(c(filtered_df2['threshold'])) ldictkeys = list(ldict.keys()) ldictvalues = list(ldict.values()) ldictlist = [ '<b>' + str(ldictkeys[f]) + '</b>' + ': ' + str(ldictvalues[f]) for f in range(len(ldictvalues)) ] ldictfinal = '\n'.join(ldictlist) plot_text.text = '<b style="color:Gray;"></b><br><b style="color:MediumSeaGreen;">Points displayed : Total points in the dataset: </b>' + str( len(filtered_df2) ) + ':' + str( len(df) ) + '\n' + '<b style="color:MediumSeaGreen;"><br>Counts relative to Threshold: </b>' + ldictfinal
def forward(s, repl=dict()): global counter cstring = "{:>3}".format(counter) bytepairs = [ "{}{}".format(first, s[i + 1]) for i, first in enumerate(s[0:-1]) if not first.isdigit() and not s[i + 1].isdigit() ] C = c(bytepairs) most_common_bytepair, most_common_count = C.most_common(1)[0] if most_common_count == 1: # this is the end of the recursion return s, repl # here we continue the recursion because we have stuff to do still s = s.replace(most_common_bytepair, cstring) repl[cstring] = most_common_bytepair counter += 1 return forward(s)
def Contains_duplicate(nums): if not nums: return False res = c(nums).most_common(1) if res[0][1] == 1: return False return True
def topKFrequent(nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ return [num for num, count in c(nums).most_common(k)]
def commonChars(A): """ :type A: List[str] :rtype: List[str] """ d = c(A[0]) for string in A[1:]: d1 = c(string) d2 = {} for key, val in d1.items(): if key in d: d2[key] = min(d[key], d1[key]) d = d2 res = [] for key, val in d.items(): res.extend([key] * val) return res
def hasGroupsSizeX(deck): """ :type deck: List[int] :rtype: bool """ if reduce(gcd, c(deck).values()) == 1: return False return True
def solve(n, array): d = c(array) count = 0 for num in d: for i in range(1, d[num] + 1): if i in d and d[i] >= num: count += 1 return count
def findDuplicates(nums): """ :type nums: List[int] :rtype: List[int] """ d = c(nums) res = [] for key, val in d.items(): if val == 2: res.append(key) return res
def uncommonFromSentences(A, B): """ :type A: str :type B: str :rtype: List[str] """ res = [] for word, count in c(A.split() + B.split()).items(): if count == 1: res.append(word) return res
def solve(dishes): d = c(dishes) n = len(d) res = 0 keys = d.keys() for i in range(n): if len(keys[i]) == 5: res += d[keys[i]] * (d[keys[i]] - 1) / 2 for j in range(i + 1, n): if len(set(keys[i] + keys[j])) == 5: res += d[keys[i]] * d[keys[j]] return res
def canReorderDoubled(A): """ :type A: List[int] :rtype: bool """ d = c(A) for num in sorted(A, key=abs): if d[num] == 0: continue if d[num * 2] == 0: return False d[num] -= 1 d[num * 2] -= 1 return True
def f(n, word, d): d1 = c(word) all_in = True flag = False for k, v in d.items(): if d1.get(k) == None: all_in = False elif d1.get(k) < v: all_in = False if k in d1: flag = True if not flag: all_in = False return all_in, flag
def longestPalindrome(s): """ :type s: str :rtype: int """ d = c(s) res = odd = 0 for val in d.values(): if val % 2 == 0: res += val else: res += val - 1 odd = 1 return res + odd
def customSortString(S, T): """ :type S: str :type T: str :rtype: str """ res = [] d = c(T) for cc in S: if cc in d: res.extend([cc] * d[cc]) d.pop(cc) for key, val in d.items(): res.extend([key] * val) return ''.join(res)
def findPairs(nums, k): """ :type nums: List[int] :type k: int :rtype: int """ if k < 0: return 0 d = c(nums) count = 0 for key, val in d.items(): if k == 0: if val > 1: count += 1 else: if key + k in d: count += 1 return count
def topKFrequent(nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ count = [] for key, val in c(nums).items(): count.append([val, key]) count.sort(reverse=True) res = [] i = 0 while i < k: res.append(count[i][1]) i += 1 return res
def solve(n, array): if sum(array) % 4 != 0: return -1 for i in range(n): array[i] %= 4 d = c(array) count = d[2] / 2 d[2] = d[2] % 2 count += min(d[1],d[3]) tmp = abs(d[3] - d[1]) count += 2 * d[2] tmp -= 2 * d[2] count += 3 * tmp / 4 return count
def mostCommonWord(paragraph, banned): """ :type paragraph: str :type banned: List[str], in lowercase, and free of punctuation :rtype: str """ adjusted_paragraph = [] for word in paragraph.lower().split(): tmp = word.strip("!?',;.") if not tmp in banned: adjusted_paragraph.append(tmp) d = c(adjusted_paragraph) count = 0 res = '' for word, num in d.items(): if num > count: res = word count = num return res
def reorganizeString(S): """ :type S: str :rtype: str """ d = c(S) n = len(S) res = [''] * n tmp = zip(d.values(), d.keys()) tmp.sort(reverse=True) start = 0 for v, k in tmp: if v > (n + 1) / 2: return '' for _ in range(v): if start < n: res[start] = k else: start = 1 res[start] = k start += 2 return ''.join(res)
def thirdMax(nums): """ :type nums: List[int] :rtype: int """ d = c(nums) key = d.keys() n = len(key) if n < 3: return max(key) maxi1, maxi2, maxi3 = key[0], float('-inf'), float('-inf') for num in key[1:]: if num > maxi1: maxi3 = maxi2 maxi2 = maxi1 maxi1 = num elif num > maxi2: maxi3 = maxi2 maxi2 = num elif num > maxi3: maxi3 = num return maxi3
ratings=[float(x) for x in ratings] datafile='/Users/davidgreenfield/socialfinalproject/variance_time.txt' f=open(datafile,'r') variances= f.read().splitlines() variances=[float(x) for x in variances] agerate=zip(ages,ratings) agerate=sorted(agerate,key=lambda x: x[0]) stats=[] for key, rows in groupby(agerate,lambda x: x[0]): stats.append((key, sum(r[1] for r in rows))) finstats=[] x=c(ages) for age in stats: finstats.append((age[1]/x[age[0]])) print finstats[0:10] h=np.histogram(ages,bins=200) print h plt.scatter(range(0,len(finstats)),finstats) plt.xlabel('Age after 1st Review') plt.ylabel('Average Rating') plt.ylim(1,5) plt.title('Average Rating by Age') plt.show() plt.plot(variances)
def duplicates(s): return [x for x, y in c(s).items() if y > 1]
from collections import Counter as c from string import ascii_lowercase as l para = raw_input().lower() a = c(para) for ch in l: if a[ch]: print ch.upper(), ":", a[ch]
def solve(s1, s2): d1, d2 = c(s1), c(s2) for key, val in d1.items(): if d2[key] < val: return 'No' return 'Yes'
def yTimes(A): t = c(A) for k, v in sorted(t.items(), key=lambda x: -x[1]): if k != 1 and c(t.values())[v] == 1: return k return -1