text
stringlengths
37
1.41M
class Solution: def is_valid(self, coordinates): return 0 <= coordinates[0] < 8 and 0 <= coordinates[1] < 8 def queensAttacktheKing(self, queens, king): attacking_queens = {str(queen[0]) + str(queen[1]): False for queen in queens} directions = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)] for i in range(8): curr_coordinates = king curr_coordinates = [curr_coordinates[0] + directions[i][0], curr_coordinates[1] + directions[i][1]] while self.is_valid(curr_coordinates): queen = str(curr_coordinates[0]) + str(curr_coordinates[1]) if queen in attacking_queens: attacking_queens[queen] = True break curr_coordinates = [curr_coordinates[0] + directions[i][0], curr_coordinates[1] + directions[i][1]] return [queen for queen in queens if attacking_queens[str(queen[0]) + str(queen[1])] == True]
import unittest def string_compression(s): l = list() temp_char = '' count = 0 for char in s: if char == temp_char: count += 1 else: if temp_char != '': l.append(temp_char + str(count)) temp_char = char count = 1 l.append(temp_char + str(count)) compressed = ''.join(l) if len(compressed) > len(s): return(s) else: return(''.join(l)) class TestStringCompression(unittest.TestCase): def setUp(self): pass def test_string_compression(self): self.assertEqual(string_compression('aabcccccaaa'), 'a2b1c5a3') self.assertEqual(string_compression('abcccdeab'), 'abcccdeab') if __name__ == '__main__': unittest.main()
from math import sqrt from itertools import count, islice T = int(input()) def check_if_prime(n): if n < 2: print('Not prime') return False for number in islice(count(2), int(sqrt(n) - 1)): if n % number == 0: print('Not prime') return False print('Prime') return True for i in range(T): n = int(input()) check_if_prime(n)
class Solution: def wordPattern(self, pattern, s): d_symb, d_word, words = {}, {}, s.split() if len(words) != len(pattern): return False for symb, word in zip(pattern, words): if symb not in d_symb: if word in d_word: return False else: d_symb[symb] = word d_word[word] = symb elif d_symb[symb] != word: return False return True
import re regex = re.compile("^[a-z\.][email protected]$") accounts = dict() N = int(input().strip()) for _ in range(N): firstName, email = input().strip().split(' ') if regex.match(email): accounts[email] = firstName sorted_names = sorted(accounts.values()) print(*sorted_names, sep="\n")
x, y, z = "Orange", "Banana", "Cherry" print(x, y, z) x = y = z = "Orange" print(x, y, z) x = "Sven" y = "Kohn" print(x + " " + y) print(f"{x} {y}")
import logging import threading import time def thread_function(name): logging.info("Thread %s: starting", name) time.sleep(2) logging.info("Thread %s: finishing", name) if __name__ == "__main__": format = "%(asctime)s: %(message)s" logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S") # Non-deamon threads - the program will wait for the threads to complete before it exits logging.info("Main : before creating thread") x = threading.Thread(target=thread_function, args=(1,)) logging.info("Main : before running thread") x.start() logging.info("Main : wait for the thread to finish") logging.info("Main : all done") time.sleep(3.0) print("-" * 50) # join - tell one thread to wait for another thread to finish logging.info("Main : before creating thread") y = threading.Thread(target=thread_function, args=(1,), daemon=True) logging.info("Main : before running thread") y.start() logging.info("Main : wait for the thread to finish") y.join() logging.info("Main : all done") time.sleep(1.0) print("-" * 50) # Deamon threads - are just killed wherever they are when the program is exiting # This deamon thread does not have enough time to finish before the program exits logging.info("Main : before creating thread") x = threading.Thread(target=thread_function, args=(1,), daemon=True) logging.info("Main : before running thread") x.start() logging.info("Main : wait for the thread to finish") logging.info("Main : all done")
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist) print(thislist[1]) # will start at index 2 (included) and end at index 5 (not included) print(thislist[2:5]) # returns items from beginning to "orange" print(thislist[:4]) # returns items from "cherry" to the end of list print(thislist[2:]) # check if item is present in a list if "apple" in thislist: print("Yes, apple is in the list") # add item to the end of the list thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) # add item at the specific index thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist) # remove an item thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) # remove the last item thislist = ["apple", "banana", "cherry"] thislist.pop() print(thislist) # remove item at specific index thislist = ["apple", "banana", "cherry"] thislist.pop(1) print(thislist) thislist = ["apple", "banana", "cherry"] del thislist[1] print(thislist) # clear a list thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist) # copy a list thislist = ["apple", "banana", "cherry"] mylist = thislist.copy() print(mylist) thislist = ["apple", "banana", "cherry"] mylist = list(thislist) print(mylist) # join two lists list1 = ["apple", "banana", "cherry"] list2 = ['Sven', 'Barbara', 'Valentina'] list3 = list1 + list2 # or list3 = list1.append(list2) print(list3) list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list1.extend(list2) print(list1) # the list constructor thislist = list(("apple", "banana", "cherry")) # more list methods # count() # reverse() # sort()
#!/usr/bin/env python3 """ ---------------------------------------------------------------------------------------------------------------- Classes - Subclassing - Creating a subclass - Overwriting class methods ---------------------------------------------------------------------------------------------------------------- """ class Dog: def __init__(self, name, age): self.name = name self.age = age def get_info(self) -> tuple: return self.name, self.age class Breed: def __init__(self, breed): self.breed = breed def get_breed(self) -> str: return self.breed class SpecialDog(Dog): def __init__(self, name, age, breed): super().__init__(name, age) # Instantiating the class (Breed) inside a class and calling the method [get_breed()] of that class self.breed = Breed(breed).get_breed() # Overwrites parent class (Dog) method (get_info) because it has the same method name def get_info(self) -> tuple: return self.name, self.age, self.breed # ------------------------------------------------------------------------------------------------------ # Instantiating a class object (Dog) LEIKA = Dog('Leika', 3) print(f"Dog name: {LEIKA.get_info()[0]}") # OUTPUT: Dog name: Leika print(f"Dog age: {LEIKA.get_info()[1]}") # OUTPUT: Dog age: 3 print("-----" * 10) # ------------------------------------------------------------------------------------------------------ # Instantiating a class object (SpecialDog) which subclasses (Dog) SANDY = SpecialDog('Sandy', 5, 'Schlangenhund') print(f"Dog name: {SANDY.get_info()[0]}") # OUTPUT: Dog name: Sandy print(f"Dog age: {SANDY.get_info()[1]}") # OUTPUT: Dog age: 5 print(f"Dog type: {SANDY.get_info()[2]}") # OUTPUT: Dog type: Schlangenhund print("-----" * 10)
#Write a recursive Python function, given a non-negative integer N, to calculate and return the sum of its digits. #Hint: Mod (%) by 10 gives you the rightmost digit (126 % 10 is 6), while doing integer division by 10 removes the rightmost digit (126 // 10 is 12). #This function has to be recursive; you may not use loops! #This function takes in one integer and returns one integer. def sumDigits(N): ''' N: a non-negative integer sums every digit of the number N and not the sum of the range 1 to N ''' if N==0: return 0 elif N > 0: return sumDigits(N//10) + N%10
#!/usr/bin/python import turtle pen = turtle.Turtle() pen.up() pen.backward(100) pen.down() def flake_side(angle, length): pen.left(angle) pen.forward(length) if length > 1: flake_point(angle, length / 3) else: pen.forward(length) pen.forward(length) pen.right(angle) def flake_point(angle, length): flake_side(angle, length) pen.right(180 - angle) flake_side(angle, length) pen.right(180 + angle) for i in range(4): flake_point(60, 90) pen.right(90)
import sys import math from signaturefunctions import * from printing_to_files import * # This is just part of documentation: # A signature is a tuple of strings (each an affix). # Signatures is a map: its keys are signatures. Its values are *sets* of stems. # StemToWord is a map; its keys are stems. Its values are *sets* of words. # StemToSig is a map; its keys are stems. Its values are individual signatures. # WordToSig is a Map. its keys are words. Its values are *lists* of signatures. # StemCounts is a map. Its keys are words. Its values are corpus counts of stems. # SignatureToStems is a dict: its keys are tuples of strings, and its values are dicts of stems. class CWordList: def __init__(self): self.mylist = list() def GetCount(self): return len(self.mylist) def AddWord(self, word): self.mylist.append(Word(word)) def at(self, n): return self.mylist[n] def sort(self): self.mylist.sort(key=lambda item: item.Key) # for item in self.mylist: # print item.Key for i in range(len(self.mylist)): word = self.mylist[i] word.leftindex = i templist = list() for word in self.mylist: thispair = (word.Key[::-1], word.leftindex) templist.append(thispair) templist.sort(key=lambda item: item[0]) for i in range(len(self.mylist)): (drow, leftindex) = templist[i] self.mylist[leftindex].rightindex = i #not currently used def PrintXY(self, outfile): Size = float(len(self.mylist)) for word in self.mylist: x = word.leftindex / Size y = word.rightindex / Size print >> outfile, "{:20s}{8i} {:9.5} {:9.5}".format(word.Key, x, y) ## ------- ------- # ## Class Lexicon ------- # ## ------- ------- # class CLexicon: def __init__(self): self.WordList = CWordList() self.Words = list() self.WordCounts = dict() self.ReverseWordList = list() #self.Signatures = {} #not currently used... self.SignatureToStems = {} self.WordToSig = {} self.StemToWord = {} self.StemToAffix = {} self.StemCounts = {} self.StemToSignature = {} self.Suffixes={} self.Prefixes = {} self.MinimumStemsInaSignature =2 self.MinimumStemLength = 3 self.MaximumAffixLength =4 self.MaximumNumberOfAffixesInASignature = 10 self.NumberOfAnalyzedWords = 0 self.LettersInAnalyzedWords = 0 self.NumberOfUnanalyzedWords = 0 self.LettersInUnanalyzedWords = 0 self.TotalLetterCountInWords = 0 self.LettersInStems = 0 self.AffixLettersInSignatures = 0 self.TotalRobustInSignatures = 0 ## ------- ------- # ## Central signature computation ------- # ## ------- ------- # # ----------------------------------------------------------------------------------------------------------------------------# def MakeSignatures(self, lxalogfile,outfile_Rebalancing_Signatures, FindSuffixesFlag, MinimumStemLength): # ----------------------------------------------------------------------------------------------------------------------------# formatstring1 = " {:50s}{:>10,}" formatstring2 = " {:50s}" formatstring3 = "{:40s}{:10,d}" print formatstring2.format("The MakeSignatures function") # Protostems are candidate stems made during the algorithm, but not kept afterwards. Protostems = dict() self.NumberOfAnalyzedWords = 0 self.LettersInAnalyzedWords = 0 self.NumberOfUnanalyzedWords = 0 self.LettersInUnanalyzedWords = 0 AnalyzedWords = dict() #Lexicon.TotalLetterCountInWords = 0 self.TotalRobustnessInSignatures = 0 self.LettersInStems = 0 self.TotalLetterCostOfAffixesInSignatures = 0 # 1 ------- self.FindProtostems(self.WordList.mylist, Protostems, self.MinimumStemLength, FindSuffixesFlag) print formatstring1.format("1a. Finished finding proto-stems.", len(Protostems)) self.FindAffixes( Protostems, FindSuffixesFlag) print formatstring1.format("1b. Finished finding affixes for protostems.", len(self.Suffixes)+ len(self.Prefixes)) # 2 It is possible for a stem to have only one affix at this point. We must eliminate those analyses. ------- ListOfStemsToRemove = list() for stem in self.StemToAffix: if len(self.StemToAffix[stem]) < 2: ListOfStemsToRemove.append(stem) print formatstring1.format("2. Number of stems to remove due to mono-fixivity:", len(ListOfStemsToRemove)) for stem in ListOfStemsToRemove: del self.StemToWord[stem] del self.StemToAffix[stem] # 3 Execute Stems-to-signatures. This is in a sense the most important step. ------- self.LettersInStems =0 self.TotalLetterCostOfAffixesInSignatures =0 self.StemsToSignatures(FindSuffixesFlag) print formatstring1.format("3. Finished first pass of finding stems, affixes, and signatures.", len(self.SignatureToStems)) # 4 Rebalancing now, which means: ------- # We look for a stem-final sequence that appears on all or almost all the stems, and shift it to affixes. # Make changes in Lexicon.SignatureToStems, and .StemToSig, and .WordToSig, and .StemToWord, and .StemToAffix and signature_tuples.... threshold = 0.80 count = self.RebalanceSignatureBreaks2 (threshold, outfile_Rebalancing_Signatures, FindSuffixesFlag) print formatstring1.format("4. Find signature structure function.",count) if FindSuffixesFlag: Affixes = self.Suffixes else: Affixes = self.Prefixes self.FindSignatureStructure (FindSuffixesFlag, lxalogfile, Affixes, affix_threshold=3) # 5 ------- compute robustness self.ComputeRobustness() print formatstring2.format("5. Computed robustness") #8 ------- Print print >> lxalogfile, formatstring3.format("Number of analyzed words", self.NumberOfAnalyzedWords) print >> lxalogfile, formatstring3.format("Number of unanalyzed words", self.NumberOfUnanalyzedWords) print >> lxalogfile, formatstring3.format("Letters in stems", self.LettersInStems) print >> lxalogfile, formatstring3.format("Letters in affixes", self.AffixLettersInSignatures) print >> lxalogfile, formatstring3.format("Total robustness in signatures", self.TotalRobustnessInSignatures) return # ----------------------------------------------------------------------------------------------------------------------------# # ----------------------------------------------------------------------------------------------------------------------------# def StemsToSignatures(self,FindSuffixesFlag): if FindSuffixesFlag: Affixes = self.Suffixes else: Affixes = self.Prefixes # Iterate through each stem, get its affixes and count them, and create signatures. for stem in self.StemToWord: self.LettersInStems += len(stem) signature = list(self.StemToAffix[stem]) signature.sort() signature_string = "-".join(signature) for affix in signature: if affix not in Affixes: Affixes[affix] = 0 Affixes[affix] += 1 if signature_string not in self.SignatureToStems: self.SignatureToStems[signature_string] = dict() for affix in signature: self.TotalLetterCostOfAffixesInSignatures += len(affix) self.SignatureToStems[signature_string][stem] = 1 self.StemToSignature[stem] = signature_string for word in self.StemToWord[stem]: if word not in self.WordToSig: self.WordToSig[word] = list() self.WordToSig[word].append(signature_string) for sig in self.SignatureToStems: if len(self.SignatureToStems[sig]) < self.MinimumStemsInaSignature: for stem in self.SignatureToStems[sig]: del self.StemToSignature[stem] for word in self.StemToWord[stem]: if len( self.WordToSig[word] ) == 1: del self.WordToSig[word] else: self.WordToSig[word].remove(sig) del self.StemToWord[stem] # ----------------------------------------------------------------------------------------------------------------------------# def FindSignatureStructure (self, FindSuffixesFlag, outfile, Affixes = None, affix_threshold = 1): # This function assumes that we have the set of stems already in Lexicon.SignatureToStems. It does the rest. StemList = self.StemToWord.keys() self.StemToSig = {} self.StemToAffix = {}# ok self.StemToWord = dict()# ok self.Signatures = {} self.SignatureToStems = {} self.WordToSig = {} self.StemCounts = {} NumberOfColumns = 8 number_of_affixes_per_line = 10 # Signatures with way too many affixes are spurious. # If we have already run this function before, we have a set of affixes ranked by frequency, # and we can use these now to eliminate low frequency suffixes from signatures with # just one affix. # Lexicon.MaximumNumberOfAffixesInASignature # Number of affixes we are confident in: formatstring1 = " {:50s}{:>10,}" formatstring2 = " {:50s}" formatstring3 = "\n Top {:>10,} affixes retained for use now (out of {:>5} )" print formatstring2.format("Inside Find_Signature_Structure.") print formatstring2.format("i. Finding affixes we are confident about.") # -----------------------------------------------------------------# # Block 1. This block defines affixes, confident affixes, and signatures. # -----------------------------------------------------------------# if len (Affixes ) ==0: if FindSuffixesFlag: print "No suffixes found yet." else: print "No prefixes found yet." else: ConfidentAffixes = dict() NumberOfConfidentAffixes = 50 NumberOfAffixes = len(Affixes.keys()) if NumberOfConfidentAffixes > NumberOfAffixes: NumberOfConfidentAffixes = NumberOfAffixes SortedAffixes = list(Affixes.keys()) SortedAffixes.sort(key=lambda affix:Affixes[affix], reverse=True) print formatstring3.format(NumberOfConfidentAffixes, len(SortedAffixes)) count = 0 print " "*6, for affixno in range(NumberOfConfidentAffixes): ConfidentAffixes[SortedAffixes[affixno]]=1 print "{:6s} ".format(SortedAffixes[affixno]), count += 1 if count % number_of_affixes_per_line == 0: print print " ", if (False): # not used currently for sig in self.SignatureToStems: stems = self.SignatureToStems[sig] newsig = list() if len(stems) == 1: for affix in sig: if affix in ConfidentAffixes: newsig.append(affix) print #-----------------------------------------------------------------# # Block 2: This block loops through all words # -----------------------------------------------------------------# # Creates Lexicon.StemToWord, Lexicon.StemToAffix. column_no = 0 print print formatstring2.format("ii. Reanalyzing words, finding both stems and affixes.") if True: print " "*12 + "Word number:", for i in range(len(self.WordList.mylist)): if i % 2500 == 0: print "{:7,d}".format(i), sys.stdout.flush() column_no += 1 if column_no % NumberOfColumns == 0: column_no = 0 print "\n" + " "*11, word = self.WordList.mylist[i].Key WordAnalyzedFlag = False for i in range(len(word)-1 , self.MinimumStemLength-1, -1): # loop on positions in the word, left to right if FindSuffixesFlag: stem = word[:i] else: stem = word[-1*i:] if stem in StemList: affixlength = len(word)-i if FindSuffixesFlag: affix = word[i:] else: affix = word[:affixlength] if len(affix) > self.MaximumAffixLength: continue # the next line involves putting a threshold on frequencies of affixes. if Affixes and affix in Affixes and Affixes[affix] < affix_threshold: continue #print stem, suffix if stem not in self.StemToWord: self.StemToWord[stem] = dict() self.StemToWord[stem][word]=1 if stem not in self.StemToAffix: self.StemToAffix[stem] = dict() self.StemToAffix[stem][affix] = 1 if stem in self.WordCounts: # this is for the case where the stem is a free-standing word also self.StemToWord[stem][stem] = 1 self.StemToAffix[stem]["NULL"] = 1 if stem not in self.StemCounts: self.StemCounts[stem] = 0 self.StemCounts[stem]+= self.WordCounts[word] print self.LettersInStems =0 self.TotalLetterCostOfAffixesInSignatures =0 # -------------------------------------------------------------------- if (False): for stem in self.StemToAffix: if len(self.StemToAffix[stem]) > self.MaximumNumberOfAffixesInASignature: for sig in self.SignatureToStems: stems = self.SignatureToStems[sig] newsig = list() if len(stems) == 1: for affix in sig: if affix in ConfidentAffixes: newsig.append(affix) # -------------------------------------------------------------------- print " iii. Finding a set of signatures." self.StemsToSignatures(FindSuffixesFlag) # Print output -------------------------------------------------------- print " "* 6, "iv. Signatures (count): ", len(self.SignatureToStems) print formatstring2.format("v. Finished redoing structure") print >>outfile, formatstring2.format("iv. Finished redoing structure\n") print >>outfile, "Number of sigs: ", len(self.SignatureToStems) #-----------------------------------------------------------------------------------------------------------------------------# def FindProtostems(self, wordlist, Protostems,minimum_stem_length, FindSuffixesFlag ,maximum_stem_length = -1): # A "maximum_stem_length" is included here so that we can use this function to explore # for stems shorter than the minimum that was assumed on an earlier iteration. previousword = "" if FindSuffixesFlag: for i in range(len(wordlist)): word = wordlist[i].Key differencefoundflag = False if previousword == "": # only on first iteration previousword = word continue if maximum_stem_length > 0: span = min(len(word), len(previousword), maximum_stem_length) else: span = min(len(word), len(previousword)) for i in range(span): if word[i] != previousword[i]: #will a stem be found in the very first word? differencefoundflag = True stem = word[:i] if len(stem) >= minimum_stem_length : if stem not in Protostems: Protostems[stem] = 1 else: Protostems[stem] += 1 previousword = word break if differencefoundflag: continue if len(previousword) > i + 1: previousword = word continue if (len(word)) >= i: if len(previousword) >= minimum_stem_length: if (previousword not in Protostems): Protostems[previousword] = 1 else: Protostems[previousword] += 1 previousword = word else: #print "prefixes" ReversedList = list() TempList = list() for word in wordlist: key = word.Key key = key[::-1] TempList.append(key) TempList.sort() for word in TempList: ReversedList.append(word[::-1]) for i in range(len(ReversedList)): word = ReversedList[i] differencefoundflag = False if previousword == "": # only on first iteration previousword = word continue span = min(len(word), len(previousword)) for i in range(1,span,): if word[-1*i] != previousword[-1*i]: differencefoundflag = True stem = word[-1*i+1:] if len(stem) >= minimum_stem_length: if stem not in Protostems: Protostems[stem] = 1 else: Protostems[stem] += 1 #print previousword, word, stem previousword = word break if differencefoundflag: continue if len(previousword) > i + 1: previousword = word continue if (len(word)) >= i: if len(previousword) >= minimum_stem_length: if (previousword not in Protostems): Protostems[previousword] = 1 else: Protostems[previousword] += 1 previousword = word #----------------------------------------------------------------------------------------------------------------------------# def FindAffixes(self, Protostems, FindSuffixesFlag): wordlist=self.WordList.mylist MinimumStemLength = self.MinimumStemLength MaximumAffixLength = self.MaximumAffixLength if FindSuffixesFlag: for i in range(len(wordlist)): word = wordlist[i].Key WordAnalyzedFlag = False #print (word) for i in range(len(word)-1 , MinimumStemLength-1, -1): stem = word[:i] if stem in Protostems: suffix = word[i:] if len(suffix) > MaximumAffixLength: continue if stem not in self.StemToWord: self.StemToWord[stem] = dict() self.StemToWord[stem][word]=1 if stem not in self.StemToAffix: self.StemToAffix[stem] = dict() self.StemToAffix[stem][suffix] = 1 if stem in self.WordCounts: self.StemToWord[stem][stem] = 1 self.StemToAffix[stem]["NULL"] = 1 self.Suffixes[suffix]=1 else: for i in range(len(wordlist)): word = wordlist[i].Key WordAnalyzedFlag = False for i in range(MinimumStemLength-1, len(word)-1): stem = word[-1*i:] if stem in Protostems: j = len(word) - i prefix = word[:j] if len(prefix) > MaximumAffixLength: continue if stem not in self.StemToWord: self.StemToWord[stem] = dict() self.StemToWord[stem][stem]=1 if stem not in self.StemToAffix: self.StemToAffix[stem] = dict() self.StemToAffix[stem][prefix]=1 if stem in self.WordCounts: self.StemToWord[stem][word] = 1 self.StemToAffix[stem]["NULL"]=1 self.Prefixes[prefix]=1 # ----------------------------------------------------------------------------------------------------------------------------# def RebalanceSignatureBreaks2 (self, threshold, outfile, FindSuffixesFlag): # this version is much faster, and does not recheck each signature; it only changes stems. # ----------------------------------------------------------------------------------------------------------------------------# count=0 MinimumNumberOfStemsInSignaturesCheckedForRebalancing = 5 SortedListOfSignatures = sorted(self.SignatureToStems.items(), lambda x, y: cmp(len(x[1]), len(y[1])), reverse=True) for (sig,wordlist) in SortedListOfSignatures: sigstring="-".join(sig) numberofstems=len(self.SignatureToStems[sig]) if numberofstems <MinimumNumberOfStemsInSignaturesCheckedForRebalancing: print >>outfile, " Too few stems to shift material from suffixes", sigstring, numberofstems continue print >>outfile, "{:20s} count: {:4d} ".format(sigstring, numberofstems), shiftingchunk, shiftingchunkcount = TestForCommonEdge(self.SignatureToStems[sig], outfile, threshold, FindSuffixesFlag) if shiftingchunkcount > 0: print >>outfile,"{:5s} count: {:5d}".format(shiftingchunk, shiftingchunkcount) else: print >>outfile, "no chunk to shift" if len(shiftingchunk) >0: count +=1 chunklength = len(shiftingchunk) newsignature = list() sigstring2 = "" for affix in sig: if affix == "NULL": affix = "" if FindSuffixesFlag: newaffix = shiftingchunk + affix sigstring2 += newaffix + " - " shiftpair = (affix, newaffix) sigstring2 = sigstring2[:-2] ##???? else: newaffix = affix + shiftingchunk sigstring2 += "-" + newaffix shiftpair = (affix, newaffix) sigstring2 = sigstring2[2:] ##??? newsignature.append(newaffix) formatstring = "{:30s} {:10s} {:35s} Number of stems {:5d} Number of shifters {:5d}" print >>outfile, formatstring.format(sigstring, shiftingchunk, sigstring2, numberofstems, shiftingchunkcount) if shiftingchunkcount >= numberofstems * threshold : ChangeFlag = True stems_to_change = list(self.SignatureToStems[sig]) for stem in stems_to_change: if FindSuffixesFlag: if stem[-1*chunklength:] != shiftingchunk: continue else: if stem[:chunklength] != shiftingchunk: continue if FindSuffixesFlag: newstem = stem[:len(stem)-chunklength] else: newstem = stem[chunklength:] if newstem not in self.StemToWord: self.StemToWord[newstem] = dict() for word in self.StemToWord[stem]: self.StemToWord[newstem][word] = 1 del self.StemToWord[stem] # is this too general? if newstem not in self.StemToAffix: self.StemToAffix[newstem] = {} for affix in newsignature: self.StemToAffix[newstem][affix] = 1 del self.StemToAffix[stem] if newstem not in self.StemToSignature: self.StemToSignature[newstem]=dict() self.StemToSignature[newstem]=[newsignature] del self.StemToSignature[stem] outfile.flush() return count #--------------------------------------------------------------------------------------------------------------------------# def printSignatures(self, lxalogfile, outfile_signatures, outfile_wordstosigs, outfile_stemtowords, outfile_stemtowords2, outfile_SigExtensions, outfile_suffixes, encoding, FindSuffixesFlag): # ----------------------------------------------------------------------------------------------------------------------------# print " Print signatures from within Lexicon class." # 1 Create a list of signatures, sorted by number of stems in each. DisplayList is that list. Its triples have the signature, the number of stems, and the signature's robustness. ColumnWidth = 35 stemcountcutoff = self.MinimumStemsInaSignature SortedListOfSignatures = sorted(self.SignatureToStems.items(), lambda x, y: cmp(len(x[1]), len(y[1])), reverse=True) DisplayList = [] for sig, stems in SortedListOfSignatures: #print "486 ", sig if len(stems) < stemcountcutoff: continue; DisplayList.append((sig, len(stems), getrobustness(sig, stems))) DisplayList.sort singleton_signatures = 0 doubleton_signatures = 0 for sig, stemcount, robustness in DisplayList: if stemcount == 1: singleton_signatures += 1 elif stemcount == 2: doubleton_signatures += 1 totalrobustness = 0 for sig, stemcount, robustness in DisplayList: totalrobustness += robustness initialize_files(self, outfile_signatures,singleton_signatures,doubleton_signatures,DisplayList ) initialize_files(self, lxalogfile,singleton_signatures,doubleton_signatures,DisplayList ) initialize_files(self, "console",singleton_signatures,doubleton_signatures,DisplayList ) if False: for sig, stemcount, robustness in DisplayList: if len(self.SignatureToStems[sig]) > 5: self.Multinomial(sig,FindSuffixesFlag) # Print signatures (not their stems) sorted by robustness print_signature_list_1(outfile_signatures, DisplayList, stemcountcutoff,totalrobustness) # Print suffixes suffix_list = print_suffixes(outfile_suffixes,self.Suffixes ) # Print stems print_stems(outfile_stemtowords, outfile_stemtowords2, self.StemToWord, self.StemToSignature, self.WordCounts, suffix_list) # print the stems of each signature: print_signature_list_2(outfile_signatures, DisplayList, stemcountcutoff,totalrobustness, self.SignatureToStems, self.StemCounts, FindSuffixesFlag) # print WORDS of each signature: print_words(outfile_wordstosigs, lxalogfile, self.WordToSig,ColumnWidth ) # print signature extensions: print_signature_extensions(outfile_SigExtensions, lxalogfile, DisplayList, self.SignatureToStems) ## ------- ------- # ## Utility functions ------- # ## ------- ------- # def PrintWordCounts(self, outfile): formatstring = "{:20s} {:6d}" words = self.WordCounts.keys() words.sort() for word in words: print >>outfile, formatstring.format(word, self.WordCounts[word]) def Multinomial(self,this_signature,FindSuffixesFlag): counts = dict() total = 0.0 #print "{:45s}".format(this_signature), for affix in this_signature: #print "affix", affix counts[affix]=0 for stem in self.SignatureToStems[this_signature]: #print "stem", stem if affix == "NULL": word = stem elif FindSuffixesFlag: word = stem + affix else: word= affix + stem #print stem,":", affix, "::", word #print "A", counts[affix], self.WordCounts[word] counts[affix] += self.WordCounts[word] total += self.WordCounts[word] frequency = dict() for affix in this_signature: frequency[affix] = counts[affix]/total #print "{:12s}{:10.2f} ".format(affix, frequency[affix]), #print def ComputeRobustness(self): self.NumberOfAnalyzedWords= len(self.WordToSig) self.NumberOfUnanalyzedWords= self.WordList.GetCount() - self.NumberOfAnalyzedWords for sig in self.SignatureToStems: numberofaffixes = len(sig) mystems = self.SignatureToStems[sig] numberofstems = len(mystems) AffixListLetterLength = 0 for affix in sig: if affix == "NULL": continue AffixListLetterLength += len(affix) StemListLetterLength = 0 for stem in mystems: StemListLetterLength += len(stem) self.TotalRobustnessInSignatures += getrobustness(mystems,sig) self.AffixLettersInSignatures += AffixListLetterLength class Word: def __init__(self, key): self.Key = key self.leftindex = -1 self.rightindex = -1 def makeword(stem, affix, sideflag): if sideflag == True: return stem + affix else: return affix + stem def byWordKey(word): return word.Key class CSignature: count = 0 def __init__(self, signature_string): self.Index = 0 self.Affixes = tuple(signature_string.split("-")) self.StartStateIndex = CSignature.count self.MiddleStateIndex = CSignature.Count + 1 self.EndStateIndex = CSignature.count + 2 self.count += 3 self.StemCount = 1 self.LetterSize = len(signature_string) - len(self.Affixes) print "710 ", signature_string, self.LetterSize def Display(self): returnstring = "" affixes = list(self.Affixes) affixes.sort() return "-".join(affixes) # ------------------------------------------------------------------------------------------##------------------------------------------------------------------------------------------# class parseChunk: def __init__(self, thismorph, rString, thisedge=None): # print "in parsechunk constructor, with ", thismorph, "being passed in " self.morph = thismorph self.edge = thisedge self.remainingString = rString if (self.edge): self.fromState = self.edge.fromState self.toState = self.edge.toState else: self.fromState = None self.toState = None # print self.morph, "that's the morph" # print self.remainingString, "that's the remainder" def Copy(self, otherChunk): self.morph = otherChunk.morph self.edge = otherChunk.edge self.remainingString = otherChunk.remainingString def Print(self): returnstring = "morph: " + self.morph if self.remainingString == "": returnstring += ", no remaining string", else: returnstring += "remaining string is " + self.remainingString if self.edge: return "-(" + str(self.fromState.index) + ")" + self.morph + "(" + str( self.toState.index) + ") -" + "remains:" + returnstring else: return returnstring + "!" + self.morph + "no edge on this parsechunk" # ----------------------------------------------------------------------------------------------------------------------------# class ParseChain: def __init__(self): self.my_chain = list() def Copy(self, other): for parsechunk in other.my_chain: newparsechunk = parseChunk(parsechunk.morph, parsechunk.remainingString, parsechunk.edge) self.my_chain.append(newparsechunk) def Append(self, parseChunk): # print "Inside ParseChain Append" self.my_chain.append(parseChunk) def Print(self, outfile): returnstring = "" columnwidth = 30 for i in range(len(self.my_chain)): chunk = self.my_chain[i] this_string = chunk.morph + "-" if chunk.edge: this_string += str(chunk.edge.toState.index) + "-" returnstring += this_string + " " * (columnwidth - len(this_string)) print >> outfile, returnstring, print >> outfile def Display(self): returnstring = "" for i in range(len(self.my_chain)): chunk = self.my_chain[i] returnstring += chunk.morph + "-" if chunk.edge: returnstring += str(chunk.edge.toState.index) + "-" return returnstring # ----------------------------------------------------------------------------------------------------------------------------# def RemakeSignatures(WordToSig, SignatureToStems, StemToWord, StemToAffix, StemToSig): # ----------------------------------------------------------------------------------------------------------------------------# return "" # ----------------------------------------------------------------------------------------------------------------------------# def TestForCommonEdge(stemlist, outfile, threshold, FindSuffixesFlag): # ----------------------------------------------------------------------------------------------------------------------------# WinningString = "" WinningCount = 0 MaximumLengthToExplore = 6 ExceptionCount = 0 proportion = 0.0 FinalLetterCount = {} NumberOfStems = len(stemlist) WinningStringCount = dict() #key is string, value is number of stems for length in range(1,MaximumLengthToExplore): FinalLetterCount = dict() for stem in stemlist: if len(stem) < length + 2: continue if FindSuffixesFlag: commonstring = stem[-1*length:] else: commonstring= stem[:length] if not commonstring in FinalLetterCount.keys(): FinalLetterCount[commonstring] = 1 else: FinalLetterCount[commonstring] += 1 if len(FinalLetterCount) == 0: # this will happen if all of the stems are of the same length and too short to do this. continue sorteditems = sorted(FinalLetterCount, key=FinalLetterCount.get, reverse=True) # sort by value CommonLastString = sorteditems[0] CommonLastStringCount = FinalLetterCount[CommonLastString] WinningStringCount[CommonLastString]=CommonLastStringCount if CommonLastStringCount >= threshold * NumberOfStems: Winner = CommonLastString WinningStringCount[Winner]=CommonLastStringCount continue else: if length > 1: WinningString = Winner # from last iteration WinningCount = WinningStringCount[WinningString] else: WinningString = "" WinningCount = 0 break # ----------------------------------------------------------------------------------------------------------------------------# return (WinningString, WinningCount ) # ----------------------------------------------------------------------------------------------------------------------------# # def getrobustness(sig, stems): # ----------------------------------------------------------------------------------------------------------------------------# countofsig = len(sig) countofstems = len(stems) lettersinstems = 0 lettersinaffixes = 0 for stem in stems: lettersinstems += len(stem) for affix in sig: lettersinaffixes += len(affix) # ----------------------------------------------------------------------------------------------------------------------------# return lettersinstems * (countofsig - 1) + lettersinaffixes * (countofstems - 1) # ----------------------------------------------------------------------------------------------------------------------------# # ---------------------------------------------------------# def FindSignature_LetterCountSavings(Signatures, sig): affixlettercount = 0 stemlettercount = 0 numberOfAffixes = len(sig) numberOfStems = len(Signatures[sig]) for affix in sig: affixlettercount += len(affix) + 1 for stem in Signatures[sig]: stemlettercount += len(stem) + 1 lettercountsavings = affixlettercount * (numberOfStems - 1) + stemlettercount * (numberOfAffixes - 1) return lettercountsavings # ----------------------------------------------------------------------------------------------------------------------------# # -- # ----------------------------------------------------------------------------------------------------------------------------# def MakeStringFromAlternation(s1,s2,s3,s4): if s1== "": s1 = "nil" if s2== "NULL": s2 = "#" if s3== "": s3 = "nil" if s4== "NULL": s4 = "#" str = "{:4s} before {:5s}, and {:4s} before {:5s}".format(s1,s2,s3,s4) return str # ----------------------------------------------------------------------------------------------------------------------------#
import wordfreq from collections import Counter def main(): letters = Counter() _2gram = Counter() _3gram = Counter() for word, freq in wordfreq.get_frequency_dict('en', wordlist='best').items(): sofar = '…' # we're including space at the beginning of the word for letter in word.upper(): if letter not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': sofar = '' continue letters[letter] += freq / (len(word)) sofar += letter if len(sofar) > 1: _2gram[sofar[-2:]] += freq / (len(word) + 1) if len(sofar) > 2: _3gram[sofar[-3:]] += freq / (len(word)) sofar += '…' if len(sofar) > 1: _2gram[sofar[-2:]] += freq / (len(word) + 1) if len(sofar) > 2: _3gram[sofar[-3:]] += freq / (len(word)) with open("1grams.txt", "w") as out: for gram, count in letters.most_common(): out.write(gram + ' ' + str(count) + '\n') with open("2grams.txt", "w") as out: for gram, count in _2gram.most_common(): out.write(gram + ' ' + str(count) + '\n') with open("3grams.txt", "w") as out: for gram, count in _3gram.most_common(6000): out.write(gram + ' ' + str(count) + '\n') if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """ Created on Thu Feb 9 23:56:23 2017 Solving mazes using Python: Simple recursivity and A* search We use a nested list of integers to represent the maze. Diagonal movement not allowed The values are the following: 0: empty cell 1: unreachable cell: e.g. wall 2: ending cell 3: visited cell @author: SROY """ grid = [[0, 0, 0, 0, 0, 1], [1, 1, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0], [0, 1, 1, 0, 0, 1], [0, 1, 0, 0, 1, 0], [0, 1, 0, 0, 0, 2]] # x,y -> 5,0 to 5,5 x=0; y=0 print("Starting at (x,y)=("+ str(x) + "," + str(y)+")") steps = 0 # Counting the steps visited = 3 # Visited Flag check = 8 # Check flag when we have two routes while (1==1): # One move per counter # to reach 5,5 lets consider down and right movement preference # This preference will only be reversed based on relative distance if (x < 5 and grid[x+1][y] == 0) and (y <5 and grid[x][y+1] == 0): # Two routes confusion grid[x][y] = visited print("Two routes confusion at ("+ str(x) + "," + str(y)+")") i=0;j=0 for i in range(6): for j in range(6): if grid[i][j] == check: grid[i][j] = 3 visited = check route1 = [x+1, y] #Down route2 = [x, y+1] #Right recount = steps # Check down cell if x < 5 and grid[x+1][y] == 0: print("down") grid[x][y] = visited # Assign traversed cell to 3 x= x+1; y = y # Set X,Y to new Value steps +=1 # Count Steps continue # Loop to next if job done # Check right cell if y < 5 and grid[x][y+1] == 0: print("right") grid[x][y] = visited x= x; y = y+1 steps +=1 continue # Check top cell if x > 0 and grid[x-1][y] == 0: print("top") grid[x][y] = visited x= x-1; y = y steps +=1 continue # Check left cell if y > 0 and grid[x][y-1] == 0: print("left") grid[x][y] = visited x= x; y = y-1 steps +=1 continue if (x == 5 and y < 5 and grid[x][y+1] == 2) or (x < 5 and y ==5 and grid[x+1][y] == 2): print("Reached at (x,y)=(5,5)") print ("It took " + str(steps) + " steps to reach destination") i=0;j=0 for i in range(6): for j in range(6): if grid[i][j] == check: grid[i][j] = 3 break print("!!!Stalemate!!!") print("........Choose alternate route........") i=0;j=0 for i in range(6): for j in range(6): if grid[i][j] == check: grid[i][j] = 0 # Start route 2 visited = 3; x = route2[0]; y = route2[1]; steps = recount print("........Restarting at (x,y) = ("+str(x)+","+str(y)+")")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 17 21:58:53 2017 @author: supperxxxs """ import numpy as np import math x= 'asgrsd' y= 'rsd' n=4 def isunique(x): status=[0 for i in range(2**8)] for i in range(len(x)): if status[ord(x[i])] == 0: status[ord(x[i])] = 1 else: return False return True def unique(x): for i in range(len(x)): for j in range(i): if x[j] == x[i]: return False return True def reverse(x): #c style string rev = [] for i in range(len(x)): rev.append(x[len(x)-i-2]) x_rev= "".join(rev) return x_rev def remove_duplicate(x): x_list= list(x) s =[] for i in range(len(x_list)): flag=0 for j in range(i): if x_list[j] == x_list[i]: flag=1 break if flag==0: s.append(x[i]) x_remove="".join(s) return x_remove def remove(x): x_list = list(x) tail =1 for i in range(1,len(x_list)): j=0 while j<tail: if x_list[j] == x_list[i]: break j+=1 if j == tail: x_list[tail]= x_list[i] tail += 1 x_list= x_list[0:tail] return "".join(x_list) def anagram(x,y): # return sorted(x) == sorted(y) status = [0 for i in range(2**8)] if len(x) != len(y): return False for i in range(len(x)): status[ord(x[i])] += 1 for i in range(len(y)): if status[ord(y[i])] == 0: return False else: status[ord(y[i])] -= 1 return True def replace(x): x_replace = list(x) count = 0 for i in range(len(x_replace)): if x_replace[i] == ' ': count +=1 for i in range(len(x_replace)+count*2): if x_replace[i] ==' ': x_replace[i] ='%' x_replace.insert(i+1,'2') x_replace.insert(i+2,'0') return "".join(x_replace) def rotate(n): s= np.array([[chr(i+n*j+97) for i in range(n)]for j in range(n)]) matrix= np.array([['' for i in range(n)]for j in range(n)]) for i in range(n): matrix[:,n-1-i]=s[i,:] return matrix def rotated(n): s= [[chr(i+n*j+97)for i in range(n)] for j in range(n)] for layer in range(math.ceil(n/2)): for i in range(layer,n-1-layer): temp = s[i][n-1-layer] s[i][n-1-layer] = s[layer][i] s[layer][i] = s[n-1-i][layer] s[n-1-i][layer] =s[n-1-layer][n-1-i] s[n-1-layer][n-1-i] =temp return s s = np.array([[1,3,4],[3,0,5],[2,6,0]]) def ToBeZero(s): row=[] column=[] for i in range(len(s)): for j in range(len(s[0])): if s[i][j] == 0: row.append(i) column.append(j) for i in row: s[i,:] = 0 for i in column: s[:,i] = 0 return s def isSubstring(x,y): for i in range(len(x)): for j in range(len(y)): if x[i+j]!= y[j]: break else: if j == len(y)-1: return True return False def substring(x,y): for i in range(len(x)): if x[i:i+len(y)]==y: return True return False def isRotated(x,y): if len(x) != len(y): return False x_double= x+x return substring(x_double,y)
import os import sys #A function that clears the screen def clear_screen(): #Use the "cls" command on Windows and the "clear" command on other systems. if os.name == "nt": os.system("cls") else: os.system("clear") #Prints the word that the user is guessing with underscores for unknown letters. def print_word(word): #Space characters from each other and make all letters upper-case. to_print = "" for character in word: to_print += character.upper() + " " clear_screen() print(to_print + "\n") #The function that loads the file with all the words def load_words(filepath): #Open the file with all the words in it. try: file = open(filepath) #Read all the contents of the file and close it contents = file.read() file.close() except: #Failed to load the dictionary. Stop the program and warn the user. print("Unable to open the dictionary file. Stopping . . .") exit() #The file was loaded successfully. Because there is a different word on every line, split the #file by lines. contents = contents.splitlines() #Make every word lower-case (because there's no distinction between upper and lower case letters #in hangman). return [val.lower() for val in contents] #This function takes in a list of words and asks the user for a length. Only words with that length #will be returned. def filter_by_length(words): #Try to get an integer input from the user. Keep trying until the value provided is a valid #integer. while True: input_string = input("Insert the length of the word: ") #Try to convert the string to an integer. try: clear_screen() input_integer = int(input_string) #Filter the words with only the length the user inputted. words_tmp = [word for word in words if len(word) == input_integer] #If there are no words with that length, ask for it again. Otherwise, return the list of #words. if len(words_tmp) != 0: return words_tmp except: #Failed to convert the string to an integer. Keep trying. pass #This function guesses the most common letter in a list of words. It is the most likely letter to be #in the word being guessed. If some letters have already been shown to the user, don't suggest them #again. def most_likely_letter(words, letters_to_exclude): #Create a dictionary to store the number of occurrences of every character. characters = {} #Register the number of occurrences of every character in all the words. Don't register already #suggested letters. for word in words: for character in word: if character not in letters_to_exclude: #If there isn't an entry for this character, create it if character in characters.keys(): characters[character] += 1 else: characters[character] = 1 #Return the character with the most occurrences return max(characters, key=characters.get) #Asks the user where a letter is in the word and processes that input. Returns the indices of where #that character is in the string (or False if the function failed) def letter_location(letter, guessed_word): #Ask where the letter is and split all the indices string_input = input("Indices of the letter " + letter + ": ") indices = string_input.split(" ") #Remove all empty strings from indices (because the user can leave the input black if the #character isn't present in the word or the user might accidentally insert 2 spaces) indices = [value for value in indices if value != ""] for i in range(0, len(indices)): try: #Remove one from the index (the 1st character has index 0 on a string) indices[i] = int(indices[i]) - 1 if (0 <= indices[i] < len(guessed_word)) == False or guessed_word[indices[i]] != "_": #The index isn't inside the word or the character has already been set yet. Raise an #exception. raise Exception() except: #Invalid index. Return False. return False #All indices were valid. Return them. return indices #Edits the guessed word by adding the suggested letter in the locations inputted by the user and #returning that result. def edit_string(letter, locations, guessed_word): #Convert the string to an list to edit it lst = list(guessed_word) #Do all changes to the string for location in locations: lst[location] = letter #Convert the list back to a string and return it. return "".join(lst) #Returns the list of words (subset of the inputted list) that follow the condition of having the #newest letter in the inputted locations (or not having it) def filter_by_condition(words, letter, locations): #If there are no instances of the character, return the words that don't have it. if len(locations) == 0: return [word for word in words if letter not in word] else: filtered = [] #Add all the words that follow the condition to the list for word in words: fits_criteria = True for i in range(0, len(word)): #If this is a location where the character should be and it isn't there, this word #doesn't fit the criteria if word[i] != letter and i in locations: fits_criteria = False break #If the letter exists out of the locations, this word has to be removed. elif word[i] == letter and i not in locations: fits_criteria = False break #If this words fits all the conditions (letter in the locations), add it to the filtered #word list. if fits_criteria: filtered.append(word) #Return the list of filtered words return filtered #The entry point of the program def main(): #The first argument should be processed as the file with the words. If nothing is set, words.txt #should be used. filepath = "words.txt" if len(sys.argv) == 2: filepath = sys.argv[1] #Clear the screen to start the game clear_screen() #Load the dictionary and ask the user for the length of the word being guessed words = load_words(filepath) words = filter_by_length(words) #Start the game loop. Keep track of the letters already shown to the user and the word guessed. guessed_word = "_" * len(words[0]) letters_suggested = [] while True: #If the number of words reached 0, there are no possible words left if len(words) == 0: clear_screen() print("No possible words left. Stopping . . .") exit() elif len(words) == 1: #There's only one possible word left. clear_screen() print("The word is: " + words[0].upper()) exit() #Print the current word after clearing the screen. print_word(guessed_word) #Calculate the most-likely letter in the words and ask the user where it is in the word. likely = most_likely_letter(words, letters_suggested) #Ask where that letter is (if it is in the word) locations = letter_location(likely, guessed_word) if locations != False: #If finding the letter location didn't succeed, try again. Otherwise, fill the word with #the new characters. guessed_word = edit_string(likely, locations, guessed_word) #Filter the words that follow the condition of having these letters in the right place #and don't have the excluded letters. words = filter_by_condition(words, likely, locations) #Set this letter as suggested. letters_suggested.append(likely) #Start the program if this file isn't being included if __name__ == "__main__": main()
#!/usr/bin/env python # His Name Is Willard Game # Author: Dave Russell (drussell) import random import smithjokes possibleValues = ['Will Smith', 'Willard Smith', 'Will', 'Willard'] wsmith = random.choice(possibleValues) actor = random.choice(possibleValues) if (wsmith == actor): smithjokes.insertRandomJoke() else: print('His name is Willard!')
import random as r sayi = r.randint(1,100) print(" Texmin oyunu ") print("Reqemi 0-100 arasi secin") while True : print("================") tahmin = int(input("Reqemi texmin edin")) if tahmin == sayi : print("***************") for i in range(10): print("Duzgun texmin etdiniz") print("***************") break elif tahmin < sayi : print("===============") print("Daha boyuk") elif tahmin > sayi : print("===============") print("Daha kicik")
import gym import numpy as np import keras from keras.models import Sequential from keras.layers.core import Dense, Dropout, Flatten def main(): # generate data f_data, l_data = generate_data(10, 10, 0) # build model and train it model = getModel() model.fit(f_data, l_data, epochs=2, verbose=1) # play games with random and model agents, print results print("playing game with random agent") play_game(10, 50) print("playing game with model agent") play_game(10, 50, model) def getStateSize(): state = env.reset() action = env.action_space.sample() obs, _, _, _ = env.step(action) return len(obs) def getModel(): model = Sequential() model.add(Dense(100, input_shape=(210, 160, 3))) model.add(Dropout(0.2)) model.add(Dense(50, activation="relu")) model.add(Dropout(0.5)) model.add(Dense(25, activation="relu")) model.add(Flatten()) model.add(Dropout(0.8)) model.add(Dense(6, activation="softmax")) model.compile(optimizer='rmsprop', loss='categorical_crossentropy') return model def generate_data(number_of_games, max_turns, threshold_score): # variable initializations for data generation feat_data = [] lbl_data = [] l_1hot = [0 for i in range(n_actions)] # loop through number of games specified for i in range(number_of_games): # reset gym environment env.reset() # variable initiailizations for each playthrough game_memory = [] prev_obs = [] score = 0 # loop through gym steps until max_turns is reached for turn in range(max_turns): # pick an action at random action = env.action_space.sample() # step environment with chosen action obs, reward, done, info = env.step(action) # add reward to current score for this playthrough score += int(reward) # if not the first turn, append game state / action # pair to game_memory list if turn > 0: game_memory.append([prev_obs, int(action)]) prev_obs = obs # if simulation completes successfully, break if done == True: break # for each playthrough, record obs/action pairs for # steps on which score was above the threshold if score >= threshold_score: for item in game_memory: label = np.array(list(l_1hot)) label[item[1]] = 1 # append each feature and label to respective lists feat_data.append(item[0]) lbl_data.append(label) # print number of games played through and return data print("{} examples were made.".format(len(feat_data))) return np.array(feat_data), np.array(lbl_data) def play_game(number_of_games, number_of_moves, model=None): for i in range(number_of_games): print(i) state = env.reset() score = 0 for step in range(number_of_moves): # start with a non-action action = None if model == None: # if no model was passed, choose a random action action = env.action_space.sample() else: # if a model was passed, use it to choose action state = state.reshape(1, 210, 160, 3) action = np.argmax(model.predict(state)) # record results of action obs, reward, done, info = env.step(action) score += int(reward) state = obs # if any playthrough completes, print score and return if done == True: print("Score: {}".format(score)) break # setting up our gym environment env = gym.make("SpaceInvaders-v0") env.reset() # variable initializations n_actions = env.action_space.n n_states = getStateSize() main()
import seaborn as sns import matplotlib.pyplot as plt from sklearn.datasets import make_blobs from sklearn.cluster import KMeans # generate randomized data set data = make_blobs(n_samples=200, n_features=2, centers=4, cluster_std=1.2, random_state=101) # build model and fit it model = KMeans(n_clusters = 4) model.fit(data[0]) # get input from the user in_x = input("Supply an X value:") in_y = input("Supply a Y value:") # convert input strings to float values in_x = float(in_x) in_y = float(in_y) # construct a data set from our input values data_point = [[in_x, in_y]] # generate a prediction set for our constructed data set prediction = model.predict(data_point) # print out the first (in this case only) prediction print(prediction[0])
#!/usr/bin/env python """hungry_birds.py - example of concurrent multi-thread application""" __copyright__ = "Copyright (C) 2015 Andrea Sindoni, Paolo Rovelli" __author__ = "Andrea Sindoni, Paolo Rovelli" __email__ = "[email protected]" import threading import time import random NUM_BIRDS = 7 NUM_WORMS = 13 def parent_bird(): global worms while True: empty.acquire() with lock: try: worms = NUM_WORMS print " + parent bird brings", worms, "worms\n" for i in range(NUM_WORMS): any.release() except Exception as e: print e.message def baby_bird(id): global worms while True: time.sleep(random.random() * NUM_BIRDS/NUM_WORMS) any.acquire() with lock: worms = worms - 1 try: if worms: print " - baby bird", id, "eats (dish:", worms, "worms)" else: print " - baby bird", id, "eats (dish:", worms, "worms)" \ " and screams\n" empty.release() except Exception as e: print e.message if __name__ == "__main__": birds = [] worms = NUM_WORMS print "\n + intitial dish:", worms, "worms\n" lock = threading.Lock() empty = threading.Semaphore(0) any = threading.Semaphore(NUM_WORMS) t = threading.Thread(target=parent_bird) t.start() birds.append(t) for i in range(NUM_BIRDS): t = threading.Thread(target=baby_bird, args=(i,)) t.start() birds.append(t) for t in birds: t.join()
DEFAULT_INPUT = 'day9.txt' def day_9(loc=DEFAULT_INPUT): with open(loc) as f: data = f.readline() i = 0 group_score = 0 score = 0 in_garbage = False garbage_size = 0 while i < len(data): char = data[i] if in_garbage: if char == '!': i += 1 elif char == '>': in_garbage = False else: garbage_size += 1 else: if char == '<': in_garbage = True elif char == '{': group_score += 1 elif char == '}': score += group_score group_score -= 1 i += 1 return score, garbage_size if __name__ == '__main__': print('Solution for Part One: {}\nSolution for Part Two: {}'.format(*day_9()))
# -*- coding: UTF-8 -*- ''' A_____A / = . =\ < Developed by CKB > / w \ current version: 1.3 update log: ver 1.0 - initial release ver 1.1 - fix weird acceleration ver 1.2 - fix "ball stuck in wall" problem ver 1.3 - add more balls, with collision ''' from visual import * ########important variables########## r = 0.05 #radius of ball N = 50 #####functions##### def dist(x1,y1,x2,y2): return sqrt((x1-x2)**2+(y1-y2)**2) def reflect(w,v): #ball hit wall ''' w,v must be list/array/vector with ''' w,v = vector(w),vector(v) f = vector(-w[1],w[0],0) #法向量 unit_f=f/abs(f) #法向量的單位向量 re = v + abs(dot(v,f)/abs(f))*unit_f*2 # return re #''' if abs(abs(re)-abs(v)) <= 0.001*abs(v): if dot(v,f)<0: return re else: #print('!!!!!!!!!!!!!!!!false hit!!!!!!!!!!!!!!!') return v else: #print("back hit") w=-w f = vector(-w[1],w[0],0) #法向量 unit_f=f/abs(f) #法向量的單位向量 if dot(v,f)<0: re = v + abs(dot(v,f)/abs(f))*unit_f*2 return re else: #print('!!!!!!!!!!!!!!!!false hit!!!!!!!!!!!!!!!') return v #''' def vcollision(a1p, a2p, a1v,a2v): #ball hit ball v1prime = a1v - (a1p - a2p) * sum((a1v-a2v)*(a1p-a2p)) / sum((a1p-a2p)**2) v2prime = a2v - (a2p - a1p) * sum((a2v-a1v)*(a2p-a1p)) / sum((a2p-a1p)**2) return v1prime, v2prime def checkhit(w1,w2,b): wx1,wy1 = w1[0],w1[1] wx2,wy2 = w2[0],w2[1] bx ,by = b[0], b[1] area = 0.5*abs(wx1*wy2+wx2*by+bx*wy1-wy1*wx2-wy2*bx-by*wx1) wall = sqrt((wx1-wx2)**2+(wy1-wy2)**2) f = vector(-w[1],w[0],0) #法向量 if ((2*area/wall)<=r or (dist(bx,by,wx1,wy1)<=r or dist(bx,by,wx2,wy2)<=r)) and not(dist(bx,by,wx1,wy1)>wall or dist(bx,by,wx2,wy2)>wall): ''' print(wall) print(dist(bx,by,wx1,wy1)) print(dist(bx,by,wx2,wy2)) #''' return True else: return False #initialize! scene = display(width=800, height=800,background=(0.0,0.0,0)) #wall = [[1,1],[1,-1],[-1,-1],[-0.8,0],[0,0],[0,-0.8],[1,1]] #L shape wall = [[2,2],[2,-2],[-2,-2],[-2,2],[2,2]] #square #wall = [[1,1],[1,0],[-1,-1],[-1,0],[1,2],[1,3]] #wall = [[780,0],[1150,-140],[1180,-130],[1170,-90],[970,0],[780,0]] #wall = [[0,60],[300,60],[850,240],[900,250],[940,220],[950,170],[940,130],[900,100],[730,60],[1170,40], # [1400,60], # [1400,0],[1070,0],[1200,-60],[1230,-90],[1240,-130],[1230,-170],[1180,-190],[1130,-180],[610,0],[300,20], # [0,0],[0,60]] container = curve(pos=wall) random.seed(1) v = random.uniform(-10,10,(N,3)) for i in range(len(v)): v[i][2] = 0 for i in range(len(wall)): wall[i] = vector(wall[i]) pos_arr = random.uniform(-2,2,(N,3)) for i in range(len(pos_arr)): pos_arr[i][2] = 0 ball = [sphere(radius = r,make_trail=False, color=color.yellow) for i in range(N)] ball[0].color = color.red ball[0].make_trail = True for i in range(N): ball[i].pos = vector(pos_arr[i]) #testing area #main code t = 0 dt =0.0005 while True: rate(500) t+=dt for j in range(N): for k in range(2): pos_arr[j][k] += v[j][k]*dt ball[j].pos = vector(pos_arr[j]) #''' r_array = pos_arr-pos_arr[:,newaxis] # all pairs of atom-to-atom vectors rmag = sum(square(r_array),-1) # atom-to-atom distance squared hit = nonzero((rmag < 4*r**2) - identity(N)) hitlist = zip(hit[0], hit[1]) for p,q in hitlist: if sum((pos_arr[p]-pos_arr[q])*(v[p]-v[q])) < 0 : # check if approaching v[p], v[q] = vcollision(pos_arr[p], pos_arr[q], v[p], v[q]) #''' for i in range(len(wall)-1): w = wall[i]-wall[i+1] f = vector(-w[1],w[0]) #法向量 if checkhit(wall[i],wall[i+1],ball[j].pos) and dot([v[j][0],v[j][1],0],f)<0: #print("hit: wall %d and %d"%(i,i+1)) v[j] = reflect(wall[i]-wall[i+1],v[j]) #print(t,abs(v))
import math def main(): print('Hello world!') print('=====================') print('This is me.') print('You\'re looking for.') print('I can see it in your eyes.') print('I can see it in your smile.') print('You\'re all i ever wanted.') print('And my arms are open wide.') price=12.30 print(price * math.pi) a=2 b=3 c=addStuff(a, b) print(c) print(2 * 3) uselessprice=1209312312.12 price1 = 12.6 price2 = 100.56 result = addStuff(price1, price2) print(result) str_one = 'Gusti' str_two = 'Hello' str_three = addStuff(str_one, str_two) print(str_three) print(addStuff(str_one, price1)) def addStuff(a, b): c=a+b return c if __name__ == "__main__": main()
x = 0 y = 0 total_population = 25520468 main_data = ((6, 5663322, 39.92077, 32.85411), (34, 15462452, 41.00527, 28.97696 ), (35, 4394694, 38.41885, 27.12872)) for i in range(3): x += (main_data[i][1] * main_data[i][2] / total_population) print ("Latitude:", x) #for loop above, multiplies population and latitude of each city and divides it to total population of Turkey for e in range(3): y += (main_data[e][1] * main_data[e][3] / total_population ) print ("Longitude:", y) #for loop above, multiplies population and longitude of each city and divides it to total population of Turkey
#!/usr/bin/env python # # # Here we can implement a basic set of classes to handle creating # recommendations from a given data set from similaritymeasures import Similarity import operator class Recommender(): """ What kind of recommender am I? The existential question remains. """ def __init__(self): self.measures = Similarity() self.dataset = { "Claudia" : [('Moana', 5), ('Frying Nemo', 6), ('Pocahontas', 8), ('Full Metal Racket', 5), ('LionKing', 9), ('Frozen', 8)] , "Kenneth" : [('Moana', 7), ('Frying Nemo', 7), ('Spitoon', 8), ('ToyStory', 4), ('LionKing', 7), ('Frozen', 8)] , "Joe" : [('Moana', 7), ('Simple Green', 5), ('Pocahontas', 5), ('ToyStory', 0), ('LionKing', 8), ('Frozen', 4)] , "Janice" : [('Moana', 3), ('Frying Nemo', 7), ('Freaky Friday', 4), ('ToyStory', 9), ('LionKing', 9), ('Frozen', 7)] , "Peter" : [('Moana', 5), ('Frying Nemo', 8), ('Pocahontas', 8), ('Date Night', 8), ('LionKing', 10), ('Frozen', 9)] , "Bob" : [('Moana', 7), ('Frying Nemo', 5), ('Pocahontas', 5), ('Titanic', 3), ('LionKing', 8), ('Frozen', 8)] , } def get_suggestions(self, k, username): if not reviews_for(username): print "Please add an initial rating set for user!" distance_array = generate_distance_array_for(username) most_similar_reviewer = get_most_similar_from(distance_array) top_k_suggerstions = find_suggestions_using(most_similar_reviewer) return top_k_suggerstions def add_user_ratings(self, username, ratings): self.dataset[username] = ratings def common_titles(self, movie_list1, movie_list2): titles1 = set(dict(movie_list1).keys()) titles2 = set(dict(movie_list2).keys()) common_titles = titles1.intersection(titles2) return common_titles def values_for(self, rating_list): return set(dict(rating_list).values()) def generate_common_ratings(self, movie_list, titles): return [m for m in movie_list if m[0] in titles] def movies_in_common(self, movie_list1, movie_list2): common_titles = self.common_titles(movie_list1, movie_list2) common_ratings1 = self.generate_common_ratings(movie_list1, common_titles) common_ratings2 = self.generate_common_ratings(movie_list2, common_titles) return (sorted(common_ratings1), sorted(common_ratings2)) def build_distance_array_for(self, username, scores=None): matches = {} if not scores: scores = self.dataset.get(username) print "Scores: %s" % scores current_dataset = self.dataset del(current_dataset[username]) for reviewer in current_dataset: user_common_movies, reviewer_common_movies = self.movies_in_common(scores, current_dataset[reviewer]) matches[reviewer] = self.measures.euclidean_distance( self.values_for(user_common_movies), self.values_for(reviewer_common_movies)) sorted_matches = sorted(matches.items(), key=operator.itemgetter(1)) return sorted_matches def distance_matrix(self): distance_matrix = {} for reviewer in self.dataset: distance_matrix[reviewer] = self.make_me_a_match(self.dataset[reviewer]) return distance_matrix
squares = [] # Initialization for value in range(1, 11): square = value**2 # 1 to 10 Squares them and, puts them in the Variable square squares.append(square) # appends values of square into the list squares. print(squares) # Output # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
from random import randint import os, sys # Functions def result(points, AIpoints, Wins, Losses): if points > AIpoints: print(f"You win you had {points} points and computer had {AIpoints}") Wins += 1 elif AIpoints > points: print(f"You lose you had {points} points and computer had {AIpoints}") Losses += 1 print(f"Wins: {Wins}") print(f"Losses: {Losses}") # Variables AIpoints = 0 points = 0 totalGames = 0 Ties = 0 Wins = 0 Losses = 0 clear = lambda: os.system("cls") # Create a list of play options t = ["Rock", "Paper", "Scissors"] # Assign a random play to the computer computer = t[randint(0, 2)] # Player player = True AI = False while points != 3 or AIpoints != 3: if points == 3 or AIpoints == 3: break player = input("Rock, Paper, Scissors?\n") if player == computer: print("Tie") elif player == "Rock" and computer == "Paper": # Rock VS Paper print(f"You loose\nComputer Chooses {computer}\n") AIpoints += 1 elif player == "Rock" and computer == "Scissors": # Rock VS Scissors. print(f"You win\nComputer Chooses {computer}\n") points += 1 elif player == "Paper" and computer == "Scissors": # Paper Vs Scissors. print(f"You loose\nComputer Chooses {computer}\n") AIpoints += 1 elif player == "Paper" and computer == "Rock": # Paper Vs Rock. print(f"You Win\nComputer Chooses {computer}\n") points += 1 elif player == "Scissors" and computer == "Rock": print(f"You Loose\nComputer Chooses {computer}\n") AIpoints += 1 elif player == "Scissors" and computer == "Paper": print(f"You Win\nComputer Chooses {computer}\n") points += 1 # Results result(points, AIpoints, Wins, Losses) # Restart. restart = str(input("Do you want to play again Y/N\n")) if restart == "y" or "Y": clear() os.system("HackerRank.py") else: sys.exit("HackerRank.py")
import itertools import networkx as nx import numpy as np class TaskGraph(object): """A directed graph defining dependencies between tasks In the MTLabelModel, the TaskGraph is used to define a feasible subset of all t-dimensional label vectors Y = [Y_1,...,Y_t]; for example, in a mutually exclusive hierarchy, an example cannot have multiple non-zero leaf labels. In the MTEndModel, the TaskGraph is optionally used for auto-compilation of an MTL network that attaches task heads at appropriate levels and passes relevant information between tasks. Args: edges: A list of (a,b) tuples meaning a is a parent of b in a tree. cardinalities: A t-length list of integers corresponding to the cardinalities of each task. Defaults to a single binary task. """ def __init__(self, cardinalities=[2], edges=[]): self.K = cardinalities # Cardinalities for each task self.t = len(cardinalities) # Total number of tasks self.edges = edges # Create the graph of tasks self.G = nx.DiGraph() self.G.add_nodes_from(range(self.t)) self.G.add_edges_from(edges) # Pre-compute parents, children, and leaf nodes self.leaf_nodes = [i for i in self.G.nodes() if self.G.out_degree(i) == 0] self.parents = {t: self.get_parent(t) for t in range(self.t)} self.children = {t: self.get_children(t) for t in range(self.t)} # Save the cardinality of the feasible set self.k = len(list(self.feasible_set())) def __eq__(self, other): return self.edges == other.edges and self.K == other.K def get_parent(self, node): return sorted(list(self.G.predecessors(node))) def get_children(self, node): return sorted(list(self.G.successors(node))) def is_feasible(self, y): """Boolean indicator if the given y vector is valid (default: True)""" return True def feasible_set(self): """Iterator over values in feasible set""" for y in itertools.product(*[range(1, k + 1) for k in self.K]): yield np.array(y) class TaskHierarchy(TaskGraph): """A mutually-exclusive task hierarchy (a tree)""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Check that G is a tree if not nx.is_tree(self.G): raise ValueError( f"G is not a tree with edges {self.edges}. " "If a tree is not required, use the generic TaskGraph class." ) def is_feasible(self, y): return y in list(self.feasible_set()) def feasible_set(self): # Every feasible vector corresponds to a leaf node value in # {1, ..., K[t]-1}, with the K[t] value reserved for special "N/A" val if self.t > 1: for t in self.leaf_nodes: for yt in range(1, self.K[t]): # By default set all task labels to "N/A" value to start # The default "N/A" value for each task is the last value y = np.array(self.K) # Traverse up the tree y[t] = yt pt = t while pt > 0: ct = pt pt = list(self.G.predecessors(pt))[0] y[pt] = list(self.G.successors(pt)).index(ct) + 1 yield y # Handle the trivial single-node setting, since technically this is a # hierarchy still... else: for yt in range(self.K[0]): yield np.array([yt + 1])
def area_circulo(radio=5): # area = PI * radio ** 2 return 3.1416 * (radio ** 2) def main(): radio = int(input("Introduce el radio del circulo\n")) print(area_circulo(radio)) if __name__ == "__main__": main()
n = int(input("Enter no. of lines - ")) for var in range(n): if var < n//2 : for x in range((n//2+1)-var) : print(" ",end='') for y in range(var): print("*",end='') for y in range(var): print("*",end='') elif var == n//2: continue else: for x in range(var-(n//2)): print(" ",end='') for y in range((n//2)-(var-(n//2))): print("*",end='') for y in range((n//2)-(var-(n//2))): print("*",end='') print()
import re # Receives a word, that might contain a delimiter (for example '&'), which comes after a letter that is optional. # Returns a list of all the possible ways to write the word, with or without each delimiter. # For example: for input 'main', the uotput should be ['main', 'man']. import math ## My version - had a small calculation defect: # def create_words_from_delimiter(word, delimiter): # bad_inputs = ["\n", " ", "", ".", ",", "-", ":"] # if len(word) == 0 or word in bad_inputs: # return [word] # # # Finding all the occurrences of the delimiter in the word # delim_indices = list(map(int, [m.start() for m in re.finditer(delimiter, word)])) # num_of_delims = len(delim_indices) # power_set_delim = int(math.pow(2, num_of_delims)) # result = [""] * power_set_delim # # start_index = 0 # n = power_set_delim # for i in range(num_of_delims): # current_sub_str = word[start_index:delim_indices[i]] # print(current_sub_str) # TODO DELETE # print("n = " + str(n)) # TODO DELETE # # while n >= 1: # for m in range(0,int(power_set_delim / n)): # m = m * (n // 2) # A PROBLEM WITH THE CONSTANT WE MULTIPLY BY # for k in range(0, n // 2): # print("(i) * m + k = " + str((i) * m + k)) # result[(i ) * m + k] += current_sub_str # print("(i ) * m + k + (n // 2) = " + str((i) * m + k + (n // 2))) # result[(i ) * m + k + (n // 2)] += current_sub_str[0:-1] # # result[i * m + k] += current_sub_str # # result[i * m + k + int(n / 2)] += current_sub_str[0:-1] # n //= 2 # start_index = delim_indices[i] + 1 # print(result) # TODO DELETE # for i in range(power_set_delim): # result[i] += word[start_index:] # # return result # dIFFERENT VERSION: import copy # For wiki features we want to search all forms in base form of words def create_words_from_delimiter(word, delimiter="&"): bad_inputs = ["\n", " ", "", ".", ",", "-", ":"] if len(word) == 0 or word in bad_inputs: return [word] # Finding all the occurrences of the delimiter in the word delim_indices = list(map(int, [m.start() for m in re.finditer(delimiter, word)])) if len(delim_indices) == 0: return [word] l1 = word.split(delimiter) l2 = [x[0:-1] for x in l1] l2[-1] = copy.deepcopy(l1[-1]) if delim_indices[-1] == len(word) - 1: l1.pop() l2.pop() all_lists = [] for i in range(len(l1)): all_lists.append([l1[i], l2[i]]) r = [[]] for x in all_lists: t = [] for y in x: for i in r: t.append(i + [y]) r = t res = [] for tup in r: res.append("".join(tup)) return res[0:len(r)//2] if __name__ == '__main__': # EXAMPLES: # --------- del1 = create_words_from_delimiter("mai&n", "&") print(del1) del2 = create_words_from_delimiter("mas&t&er", "&") print(del2) del3 = create_words_from_delimiter("mas&t&er&ant", "&") print(del3) del4 = create_words_from_delimiter("mas&t&er&ant&ing", "&") print(del4)
# File: pos_tagging.py # Template file for Informatics 2A Assignment 2: # 'A Natural Language Query System in Python/NLTK' # John Longley, November 2012 # Revised November 2013 and November 2014 with help from Nikolay Bogoychev # Revised November 2015 by Toms Bergmanis # PART B: POS tagging from statements import * # The tagset we shall use is: # P A Ns Np Is Ip Ts Tp BEs BEp DOs DOp AR AND WHO WHICH ? # Tags for words playing a special role in the grammar: function_words_tags = [('a','AR'), ('an','AR'), ('and','AND'), ('is','BEs'), ('are','BEp'), ('does','DOs'), ('do','DOp'), ('who','WHO'), ('which','WHICH'), ('Who','WHO'), ('Which','WHICH'), ('?','?')] # upper or lowercase tolerated at start of question. function_words = [p[0] for p in function_words_tags] def unchanging_plurals(): single = set() plural = set() unchange = [] with open("sentences.txt", "r") as f: for line in f: # add code here for wordtag in line.split(): if wordtag.split('|')[1] == "NN": single.add(wordtag.split('|')[0]) elif wordtag.split('|')[1] == "NNS": plural.add(wordtag.split('|')[0]) for check in single: if check in plural: unchange.append(check) return unchange unchanging_plurals_list = unchanging_plurals() def noun_stem (s): """extracts the stem from a plural noun, or returns empty string""" # add code here if s in unchanging_plurals_list: return s elif re.match (".*men$",s): snew = s[:-3] + "man" elif re.match(".*[aeiou]ys$",s): snew = s[:-1] elif re.match(".*([^sxyzaeiou]|[^cs]h)s$",s): snew = s[:-1] elif re.match("[^aeiou]ies$",s): snew = s[:-1] elif re.match(".*[^s]ses$",s): snew = s[:-1] elif re.match(".*[^z]zes$",s): snew = s[:-1] elif re.match(".*([^iosxzh]|[^cs]h)es$",s): snew = s[:-1] elif len(s)>=5 and re.match(".*[^aeiou]ies$",s): snew = s[:-3] + 'y' elif re.match(".*([ox]|[cs]h|ss|zz)es$",s): snew = s[:-2] else: snew = "" return snew def tag_word (lx,wd): """returns a list of all possible tags for wd relative to lx""" # add code here tagOfWord = [] if wd in function_words: for t in function_words_tags: if t[0] == wd: return [t[1]] for tag in ["P", "A"]: if wd in lx.getAll(tag): tagOfWord.append(tag) if (wd in lx.getAll('N')) or (noun_stem(wd) in lx.getAll('N')): if wd in unchanging_plurals_list: tagOfWord.append('Np') tagOfWord.append('Ns') elif noun_stem(wd) == "": tagOfWord.append('Ns') else: tagOfWord.append('Np') for tag in ["I","T"]: if (wd in lx.getAll(tag)) or (verb_stem(wd) in lx.getAll(tag)) : if verb_stem(wd) == "": tagOfWord.append(tag + "p") else: tagOfWord.append(tag + "s") return tagOfWord def tag_words (lx, wds): """returns a list of all possible taggings for a list of words""" if (wds == []): return [[]] else: tag_first = tag_word (lx, wds[0]) tag_rest = tag_words (lx, wds[1:]) return [[fst] + rst for fst in tag_first for rst in tag_rest] # End of PART B. if __name__ == "__main__": lx = Lexicon() lx.add('John', 'P') lx.add('like', 'T') lx.add('duck','N') wds = ['Who', 'are', 'ducks', '?'] print tag_words(lx, wds)
# -*- coding: utf-8 -*- """ Created on Tue Jan 5 20:38:39 2021 @author: Bruna Aparecida """ ''' -------------------------------------------****** DESAFIO ******---------------------------------------------------- Criar a classe "Carro" com no mínimo três atributos e três métodos -------------------------------------------****** DESAFIO ******---------------------------------------------------- ''' # Definição da classe: class Carro: # Definição do método construtor: def __init__(self, marca, modelo, cor): self.marca = marca self.modelo = modelo self.cor = cor # Definição dos métodos: def Vistoria(self): print("Carro ainda não vistoriado após a compra") def TrocaDeOleo(self): print("última troca de óleo: 6 meses atrás") def ExibirInformacoesDoVeiculo(self): print("Marca: ", self.marca, ", Modelo: ", self.modelo, ", Cor: ", self.cor) # Criação da instância da classe Carro: carro = Carro('Fiat', 'Punto', 'Cinza') # Acesso aos atributos da classe através da instância (objeto/variável de atribuição) print(carro.marca) # Acesso aos métodos da classe: carro.Vistoria() carro.TrocaDeOleo() carro.ExibirInformacoesDoVeiculo()
#!/usr/bin/env python3 """Report if the given word is a palindrome""" import sys import os def main(): """main""" args = sys.argv[1:] if len(args) != 1: print('Usage: {} STR'.format(os.path.basename(sys.argv[0]))) sys.exit(1) word = args[0] rev = ''.join(reversed(word)) print('"{}" is{} a palindrome.'.format( word, '' if word.lower() == rev.lower() else ' NOT')) if __name__ == '__main__': main()
#!/usr/local/bin/python3 # coding: utf-8 """ Title: py_house_treasure.py Author(s): Jonathan A. Gibson Description: Goals: 1. Be able to play multiple different house maps. Store all in "maps" directory with set CSV info to import. 2. Let user choose the house map at the command line, or choose to play a random map. 3. Display the key array to the user based on the total number of keys, not all 5 if there are not 5 keys on the map. 4. Display the key inventory in a more friendly way rather than just a 0-based array. Notes: > """ #--------------------------------------------- Import Necessary Libraries --------------------------------------------# import sys import math import random import os.path import pandas as pd import py_house_treasure_utils as phtu #---------------------------------------------- Define Main Functionality --------------------------------------------# def main(): # Load the CSV data for the maps metadata = sys.argv[2] if(os.path.exists(metadata)): print("\nLoading map data...") maps_df = pd.read_csv(metadata) print("Done.") else: print("ERROR::002::FILE_NOT_FOUND") print("Map metadata not found. Please provide valid CSV data for each house map.\n") print("For guidance on building a CSV data file, see \'maps/maps_info.csv\'.\n") print("Program run command should follow the following format: \"python3 py_house_treasure.py <house_file_name>.txt maps/<map_data>.csv\" or use one of the default \"Makefile\" commands.\n") sys.exit() # Print the program command line arguments print("\nProgram Name:", sys.argv[0]) print("Number of command line arguments:", len(sys.argv)) print("The command line argument(s) are:", str(sys.argv), '\n') # Determine if we need to pull random house data or just the data about the file from the command line argument if(sys.argv[1] == "houseR.txt"): hfs = "house" valid_rows = len(maps_df.index) - 1 # exclude the "houseR.txt" row r_int = random.randint(0, valid_rows - 1) # remove the inclusivity of the "randint()" function on the upper bound hfs += str(r_int) hfs += ".txt" chosen_map = hfs else: chosen_map = sys.argv[1] # Get the correct house (map) data for idx, row in maps_df.iterrows(): if(row["HOUSE_FILE"] == chosen_map): map_data = maps_df.iloc[idx,:] print(map_data) # Initialize variables keys = [False] * int(map_data["NUM_KEYS"]) num_treasures = int(map_data["NUM_TREASURES"]) # total number of treasures in the house t_count = 0 # number of treasures found t_loc = False # if location is a treasure ; if there is a 't' in our way or not k_loc = False # if location is a key passage = False # if can go through door valid_move = False # a '*' in our way quit = False # Read the house file into a matrix (list of lists) house = phtu.build_house(map_data["HOUSE_FILE"]) # Set the spawn location spawn_r = int(map_data["SPAWN_ROW"]) spawn_c = int(map_data["SPAWN_COL"]) # Print instructions print("\nMove around the house by entering \'W\' for North, \'S\' for South, \'A\' for East, or \'D\' for West.") print("You cannot move through walls (marked by the \'*\' characters).") print("Find the keys and collect all the treaure!") phtu.print_house(house, spawn_r, spawn_c) # Set the current and travel locations trav_r = cur_r = spawn_r trav_c = cur_c = spawn_c while(t_count < num_treasures): command = input("Move: ").upper() phtu.print_keys(keys) print("\nTreasure:", str(t_count) + '/' + str(num_treasures)) # Reset the travel indices trav_r = cur_r trav_c = cur_c if(command == 'W'): trav_r = cur_r - 1 elif(command == 'S'): trav_r = cur_r + 1 elif(command == 'A'): trav_c = cur_c - 1 elif(command == 'D'): trav_c = cur_c + 1 elif(command == "QUIT"): quit = True break else: print("Not a valid direction, try again.") continue loc = house[trav_r][trav_c] valid_move = phtu.room(house, trav_r, trav_c) t_loc = phtu.get_treasure(house, trav_r, trav_c) k_loc = phtu.get_key(house, keys, trav_r, trav_c) passage = phtu.can_unlock(house, keys, trav_r, trav_c) # If we are picking up treasure if(t_loc): house[trav_r][trav_c] = ' ' t_count += 1 # If we are accessing a door if(passage): phtu.open_door() # Cant go through door if dont have proper key if(phtu.is_door(house, trav_r, trav_c) and not keys[int(loc)-5]): valid_move = False if(not valid_move): phtu.stop() else: cur_r = trav_r cur_c = trav_c phtu.print_house(house, cur_r, cur_c) if(not quit and t_count >= num_treasures): print("Congrats, you found all the treasure!") else: print("You quit the game.") main() # call the main function
#!/usr/bin/python2.7 class Tree: def __init__(self, data): self.value = data self.children = [] def add_child(self, obj): self.children.append(obj) def get(self): ret = self.children ret = filter(lambda s: not s.children, ret) for r in ret: print r.value def show(self, space): print ' '*space, self.value for r in self.children: r.show(space+2) def main(): a1 = Tree('A-1') a2 = Tree('A-2') b1 = Tree('B-1') b2 = Tree('B-2') a1.add_child(b1) a2.add_child(b2) a2.add_child(Tree('B-3')) b2.add_child(Tree('C-1')) b2.add_child(Tree('C-2')) a1.get() b2.get() print "Tree a1:" a1.show(0) print "Tree a2:" a2.show(0) if __name__ == '__main__': main()
import sqlite3 connection = sqlite3.connect("pets.db") cursor = connection.cursor() # cursor.execute("select kind, sound from sounds") # row = cursor.fetchone() # (kind, sound) = row # print (kind, sound) #for row in cursor.execute("select kind, sound from sounds"): # print (row) #cursor.execute("select kind, sound from sounds") #rows = cursor.fetchall() #print (rows) #cursor.execute ("select name, sound from sample,sounds where sample.kind = sounds.kind") #rows = cursor.fetchall() #print (rows) name = "Steven" # A REALLY, REALLY BAD IDEA: # # cursor.execute (""" # select name, sound # from sample,sounds # where # sample.kind = sounds.kind and # sample.name = """ + '"' + name + '"' + """ # """) # A MUCH, MUCH BETTER IDEA: # cursor.execute (""" # select name, sound # from sample,sounds # where # sample.kind = sounds.kind and # sample.name = ? # """,(name,)) # # # or you can use: # """,[name]) # rows = cursor.fetchall() # print (rows) cursor.execute (""" update sounds set sound = "moo moo" where kind = "cow" """) connection.commit() connection.close()
soma = 0 for i in range(3): nome = input() distancia = int(input()) soma = soma + distancia media = float(soma/3) print("%.1f" % media)
#got tired of manually recalculating nothing fancy here #KH 2016 def app_header(): print ('-------------------------------------------------') print ('---------- Tank Weight Calculator----------------') print ('-------------------------------------------------') return () def tank_math(thickness, density, dimension): width = dimension[0] # I think I'm probably abusing arrays here... length = dimension[1] height = dimension[2] tank_volume = width*length*height volume = thickness * (((length*height)*2) + ((height*width)*2) + (length*width)) # calculate tank weight and volume weight = volume * density return weight, tank_volume def rib_math(thickness, density): volume = thickness * 1418 # calculate weight of support structure. user can input 0 if no structure needed weight = volume * density return weight def user_prompt(): width = int(input('-tank width [inches]: ')) length = int(input('-tank length [inches]: ')) height = int(input('-tank height[inches]: ')) dimensions = [width, length, height] tank_thickness = int(input('-tank wall thickness [inches]: ')) # getting data from user rib_thickness = int(input('-rib thickness [inches]: ')) density = int(input('-material density [lbs/in^3]: ')) return tank_thickness, rib_thickness, density, dimensions i = 0 # while loop escape variable x = 1 # while loop counter for clean 'UI' while i != 1: if x == 1: app_header() # added this logic to make final print out cleaner else: print('') print('') print ('-------------------------------------------------') print('') print('') tank_gauge, rib_gauge, material_density, tank_dimensions = user_prompt() rib_weight = rib_math(rib_gauge, material_density) tank_weight, tank_capacity = tank_math(tank_gauge, material_density, tank_dimensions) total_weight = rib_weight + tank_weight tank_capacity_gal = tank_capacity * .00433 tank_weight_full = tank_capacity * .036 working_capacity = tank_capacity_gal/1.5 print('') print ("rib weight:", rib_weight, "lbs") print ('tank weight (empty):', tank_weight, 'lbs') print ('total weight (empty):', total_weight, 'lbs') print ('total weight (full):', tank_weight_full + tank_weight + rib_weight, 'lbs') print ('tank capacity:', tank_capacity_gal, 'gallons') print ('working tank capacity:', working_capacity, 'gallons') print('') i = input('recalculate? 0: yes 1: no') x += 1
import random a = [5,6,7,8,random.randint(0,20)] b = [] for x in a: print(x) b.append(x*2) print(a) print(b) #total = 0 #for x in range(0, len(a)): # total = total + a[x] #print("Sum of all numbers in given list:", total) #BEGINNING OF PRIME.PY #work on this when you are done with other work # #implement this function, isPrime(n) #which should return True if n is prime #and False otherwise #examples: # isPrime(1) returns False # isPrime(5) returns True # isPrime(28) returns False # def isPrime(n): #replace this return statement with your code return False #implement generatePrimes(n) #which should return a list containing all the primes up to n #Examples: # generatePrimes(1) should return [] # generatePrimes(5) should return [2,3,5] generatePrimes(20) should return [2,3,5,7,11,13,17,19] def generatePrimes(n): return [] #END OF PRIME.PY
#2520 is the smallest number that can be divided by each of #the numbers from 1 to 10 without any remainder. #What is the smallest positive number that is evenly divisible #by all of the numbers from 1 to 20? def MasterMultiple(n): for x in range(1, 21): if n % x != 0: return False return True number = 2520 while True: number += 1 if MasterMultiple(number): print(number) break
# OOP Lesson 2 class Wallet: def __init__(self, starting_amount): self.cash = starting_amount def spend(self, amount): new_amount = self.cash - amount print("Spending Money...") print("${} >> ${}".format(self.cash, new_amount)) self.cash = new_amount class SchoolSupply: def __init__(self, cost, wallet): self.cost = cost self.wallet = wallet self.wallet.spend(self.cost) class Pencil (SchoolSupply): def __init__(self, wallet): super().__init__(1, wallet) class Binder (SchoolSupply): def __init__(self, wallet): super().__init__(15, wallet) my_wallet = Wallet(100) Pencil(my_wallet) Binder(my_wallet)
def linear_search(list, key): """If key is in the list returns its position in the list, otherwise returns -1.""" for i, item in enumerate(list): if item == key: return i return -1
# Regular Expressions log = "July 31 7:51:48 mycomputer bad_process[12345]: ERROR Perfroming package upgrade" index = log.index('[') # Brittle way to extracing numbers by using index function print(log[index+1:index+6]) # re module allows for search function to find regular expressions inside strings import re log = "July 31 7:51:48 mycomputer bad_process[12345]: ERROR Perfroming package upgrade" regex = r"\[(\d+)\]" result = re.search(regex, log) print(result[1]) # ========================================================================================= # Basic Regular Expressions # Simple Matching in Python # The "r" at the beginning of the pattern indicates that this is a rawstring # Always use rawstrings for regular expressions in Python result = re.search(r'aza', 'plaza') print(result) result = re.search(r'aza', 'bazaar') print(result) # None is a special value that Python uses that show that there's none actual value there result = re.search(r'aza', 'maze') print(result) # The match attribute always has a value of the actual sub string that match the search pattern # The span attribute indicates the range where the sub string can be found in the string print(re.search(r"^x", "xenon")) print(re.search(r"p.ng", "penguin")) print(re.search(r"p.ng", "sponge")) # Additional options to the search function can be added as a third parameter # The re.IGNORECASE option returns a match that is case insensitive print(re.search(r"p.ng", "Pangaea", re.IGNORECASE)) # ----------------------------------------------------------------------------------------- # Wildcards and Character Classes # Character classes are written inside square brackets # It list the characters to match inside of the brackets # A range of characters can be defined using a dash print(re.search(r"[a-z]way", "The end of the highway")) print(re.search(r"[a-z]way", "What a way to go")) print(re.search(r"cloud[a-zA-Z0-9]", "cloudy")) print(re.search(r"cloud[a-zA-Z0-9]", "cloud9")) # Use a ^, circumflex, inside the square brackets to match any characters that aren't in a group print(re.search(r"[^a-zA-Z]", "This is a sentence with spaces.")) print(re.search(r"[^a-zA-Z ]", "This is a sentence with spaces.")) # Use a |, pipe symbol to match either one expression or another # The search function returns the first matching string only when there are multiple matches print(re.search(r"cat|dog", "I like cats.")) print(re.search(r"cat|dog", "I like dogs.")) # Use the findall function provided by the re module to get all possible matches print(re.findall(r"cat|dog", "I like both cats and dogs.")) # ----------------------------------------------------------------------------------------- # Repetition Qualifiers # Repeated matches is a common expressions that include a . followed by a * # It matches any character repeated as many times as possible including zero - greedy behavior print(re.search(r"Py.*n", "Pygmalion")) print(re.search(r"Py.*n", "Python Programming")) print(re.search(r"Py[a-z]*n", "Python Programming")) print(re.search(r"Py.*n", "Pyn")) # Use a +, plus character, to match one or more occurrences of the character that comes before it print(re.search(r"o+l+", "goldfish")) print(re.search(r"o+l+", "woolly")) print(re.search(r"o+l+", "boil")) # Use a ?, question mark symbol, for either zero or one occurrence of the character before it # It is used to specified optional characters print(re.search(r"p?each", "To each their own")) print(re.search(r"p?each", "I like peaches")) # ----------------------------------------------------------------------------------------- # Escaping Characters # A pattern that includes a \ could be escaping a special regex character or a special string character # Use a \, escape character, to match one of the special characters print(re.search(r".com", "welcome")) print(re.search(r"\.com", "welcome")) print(re.search(r"\.com", "mydomain.com")) # Use \w to match any alphanumeric character including letters, numbers, and underscores # Use \d to match digits # Use \s for matching whitespace characters like space, tab or new line # Use \b for word boundaries print(re.search(r"\w*", "This is an example")) print(re.search(r"\w*", "And_this_is_another")) # ----------------------------------------------------------------------------------------- # Regular Expressions in Action # "Azerbaijan" returns "Azerbaija" because we did not specify the end print(re.search(r"A.*a", "Argentina")) print(re.search(r"A.*a", "Azerbaijan")) # "Azerbaijan" returns None print(re.search(r"^A.*a$", "Azerbaijan")) print(re.search(r"^A.*a$", "Australia")) pattern = r"^[a-zA-Z0-9_]*$" print(re.search(pattern, "this_is_a_valid_variable_name")) print(re.search(pattern, "this isn't a valid variable name")) print(re.search(pattern, "my_variable1")) print(re.search(pattern, "2my_variable1")) # ========================================================================================= # Advanced Regular Expressions # Capturing Groups # Use parentheses to capture groups which are portions of the pattern that are enclosed in # Below line defines two separate groups result = re.search(r"^(\w*), (\w*)$", "Lovelace, Ada") print(result) # The group method returns a tuple of two elements print(result.groups()) # Use indexing to access these groups # The first element contains the text matched by the entire regular expression # Each successive element contains the data that was matched by every subsequent match group print(result[0]) print(result[1]) print(result[2]) print("{} {}".format(result[2], result[1])) def rearrange_name(name): result = re.search(r"^(\w*), (\w*)$", name) if result is None: return print(name) return print("{} {}".format(result[2], result[1])) rearrange_name("Lovelace, Ada") rearrange_name("Ritchie, Dennis") rearrange_name("Hopper, Grace M.") def rearrange_name_updated(name): result = re.search(r"^([\w \.-]*), ([\w \.-]*)$", name) if result is None: return print(name) return print("{} {}".format(result[2], result[1])) rearrange_name_updated("Hopper, Grace M.") # ----------------------------------------------------------------------------------------- # More on Repetition Qualifiers # Use {}, curly brackets and one or two numbers to specify a range with numeric repetition qualifiers print(re.search(r"[a-zA-Z]{5}", "a ghost")) print(re.search(r"[a-zA-Z]{5}", "a scary ghost appeared")) print(re.findall(r"[a-zA-Z]{5}", "a scary ghost appeared")) # Use \b, which matches word limits at the beginning and end of the pattern, to match full words print(re.findall(r"\b[a-zA-Z]{5}\b", "A scary ghost appeared")) print(re.findall(r"\w{5,10}", "I really like strawberries")) print(re.search(r"s\w{,20}", "I really like strawberries")) # ----------------------------------------------------------------------------------------- # Extracting a PID Using regexes in Python log = "July 31 07:51:48 mycomputer bad_process[12345]: ERROR Performing package upgrade" regex = r"\[(\d+)]" result = re.search(regex, log) print(result[1]) result = re.search(regex, "A completely different string that also has numbers [34567]") print(result[1]) # Trying to access the index 1. Therefore returs None # result = re.search(regex, "99 elephants in a [cage]") # print(result[1]) def extract_pid(log_line): regex = r"\[(\d+)]" result = re.search(regex, log_line) if result is None: return "" return result[1] print(extract_pid(log)) print(extract_pid("99 elephants in a [cage]")) # ----------------------------------------------------------------------------------------- # Splitting and Replacing # Split function from the re module works by taking any regular expression as a separator # Use capturing parentheses to split list to include the elements that is used to split tje values print(re.split(r"[.?!]", "One sentence. Another one? And the last one!")) print(re.split(r"([.?!])", "One sentence. Another one? And the last one!")) # Sub function from the re module is used for creating new strings by substituting all or part of them for a different string # It uses regular expressions for both the matching and the replacing print(re.sub(r"[\w.%+-]+@[\w.-]+", "[REDACTED]", "Received an email for [email protected]"))
# ------------------------------------------------------------------------ # # Title: Assignment 08 # Description: Working with classes # ChangeLog (Who,When,What): # RRoot,1.1.2030,Created started script # RRoot,1.1.2030,Added pseudo-code to start assignment 8 # CRoss,12.7.20,Modified code to complete assignment 8 # ------------------------------------------------------------------------ # # Data -------------------------------------------------------------------- # strFileName = 'products.txt' lstOfProductObjects = [] class Product(object): """Stores data about a product: properties: product_name: (string) with the product's name product_price: (float) with the product's standard price methods: ___str__(self): returns product name and price formatted correctly and as a string changelog: (When,Who,What) RRoot,1.1.2030,Created Class CRoss,12.5.2020,Modified code to complete assignment 8 """ # Constructor def __init__(self, product_name="", product_price=0): self.product_name = product_name self.product_price = product_price # Properties @property def product_name(self): return str(self.__product_name).title() @product_name.setter def product_name(self, value): if str(value).isnumeric() == False: self.__product_name = value else: raise Exception("Name cannot be numbers") @property def product_price(self): return self.__product_price @product_price.setter def product_price(self, value): if isinstance(value, float) == True: self.__product_price = value else: raise Exception("Prices must be numbers.") # Methods def __str__(self): return self.product_name + ",$" + "%.2f" % self.product_price # Processing ------------------------------------------------------------- # class FileProcessor: """Processes data to and from a file and a list of product objects: methods: save_data_to_file(file_name, list_of_product_objects): read_data_from_file(file_name): -> (a list of product objects) changelog: (When,Who,What) RRoot,1.1.2030,Created Class CRoss,12.5.2020,Modified code to complete assignment 8 """ @staticmethod def read_data_from_file(file_name, list_of_objects): """ Reads data from .txt file and translates to list of objects :param file_name: name of file you want to read from :param list_of_objects: list of objects you want to add file data to :return: list_of_objects """ # clear out current list if applicable try: list_of_objects.clear() # open file in read mode file = open(file_name, "r") # iterate over file, remove newline character # split on comma and initialize each row into a new instance of Person object for line in file: line.strip() file_product, file_price = line.split(",$") row_object = Product(file_product, float(file_price)) list_of_objects.append(row_object) file.close() return list_of_objects except FileNotFoundError: print("File not found! No items loaded.") def write_data_to_file(file_name, list_of_objects): """Write data to file from list of objects :param file_name: name of file you want to write to :param list_of_objects: list of objects you want to write from :return: nothing """ file = open(file_name, "w") for item in list_of_objects: file.write(f"{item}\n") file.close() # Presentation (Input/Output) -------------------------------------------- # class IO: """Manages user input and program output methods: print_menu_tasks: input_menu_choice: show_current_data(list_of_objects): --> print list of objects input_new_item: changelog: CRoss,12.5.20,Added new methods """ @staticmethod def print_menu_tasks(): """ Display a menu of choices to the user :return: nothing """ print(''' Menu of Options 1) Add a new item 2) Save Data to File 3) Reload Data from File 4) Exit Program ''') print() # Add an extra line for looks @staticmethod def input_menu_choice(): """ Gets the menu choice from a user :return: string """ choice = str(input("Which option would you like to perform? [1 to 4] - ")).strip() print() # Add an extra line for looks return int(choice) @staticmethod def show_current_data(list_of_objects): """Show curret data in list :return: none """ for item in list_of_objects: print(item) # TODO: Add code to get product data from user @staticmethod def input_new_item(): """ Get user input for new item and price :return: string, string """ try: user_item = input("Please input item: ") while user_item.isnumeric(): print("Please enter valid name. Must not be numbers.") user_item = input("Please input name: ") user_price = input("Please input price: ") user_price = float(user_price) except Exception: print("Please enter valid price. Must be numbers.") # user_price = float(input("Please input price: ")) return Product(user_item, user_price) # Exceptions -------------------------------------------- # class InvalidChoice(Exception): def __str__(self): return "Please choose option 1, 2, 3, or 4" # Main Body of Script ---------------------------------------------------- # # Load data from file into list of objects FileProcessor.read_data_from_file(strFileName, lstOfProductObjects) while True: try: # show user menu of options IO.print_menu_tasks() # get users choice and assign to variable intChoice intChoice = IO.input_menu_choice() if intChoice == 1: # get new item and price from user # strItem, fltPrice = IO.input_new_item() newItem = IO.input_new_item() # initialize new instance of Product object w/ user data # newItem = Product(strItem, fltPrice) # add new object to current list lstOfProductObjects.append(newItem) # show current list to user print("Item added! Current data is:") IO.show_current_data(lstOfProductObjects) elif intChoice == 2: # call file processor function to write data to file FileProcessor.write_data_to_file(strFileName, lstOfProductObjects) # show status to user print("Items saved!") elif intChoice == 3: # call file processor function to read data from the file FileProcessor.read_data_from_file(strFileName, lstOfProductObjects) # show current data IO.show_current_data(lstOfProductObjects) elif intChoice == 4: # exit program break else: raise InvalidChoice() except ValueError as e: print(f"Built-in Python error message is:\n{e}") except Exception as e: print(f"Error! Built-in Python error message is:\n{e}") print(e)
#!/usr/bin/env python from math import ceil,sqrt from functools import reduce product = reduce((lambda x, y: x * y), [1, 2, 3, 4]) import sys def euclidn(n): A = [True]*(n + 1) en = [] for i in range(2,ceil(sqrt(n)+1)): if A[i]: for j in range(i*i,n+1,i): A[j] = False e = [i for i in range(len(A)) if A[i]== True][2:] j = 1 for i in e: j*=i en.append(j+1) return en if __name__ == "__main__": a = int(sys.argv[1]) try: print(euclidn(a)) except: print("Please use the script like this \"./euclidn 100")
import random import time from datetime import datetime class Limiter: """Can be used to slow down processing""" def __init__(self, fps=2): """Construct limiter Args: fps (number/tuple): Requested number of processing steps per second. Will pause between start() and stop_and_delay() to reach fps. Requested fps can be an int or a tuple (indicating a random range to choose from). """ self._fps = fps self._started_at = None def start(self): """Start the limiter""" self._started_at = datetime.utcnow() def _requested_duration(self): """Requested duration of a step between start and stop_and_delay Returns: float: duration in seconds based on requested fps """ if isinstance(self._fps, (float, int)): fps = self._fps else: fps = random.uniform(self._fps[0], self._fps[1]) return 1 / fps def stop_and_delay(self): """Stop the limiter and pause when necessary to reach requested fps Returns: (tuple): three floats representing respectively Requested duration to be between start and stop_and_delay Actual duration between start and stop_and_delay. Duration that was paused. """ requested_duration = self._requested_duration() duration = (datetime.utcnow() - self._started_at).microseconds / 1000000 remaining_duration = requested_duration - duration paused_duration = max(remaining_duration, 0) time.sleep(paused_duration) return requested_duration, duration, paused_duration
# Uses python3 def get_fibonacci_last_digit_naive(n): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current % 10, (previous + current) % 10 return current % 10 def fib(n): if n <= 1: return n previous = 0 current = 1 for i in range(n - 1): previous, current = current, previous + current return current def gcd(a, b): if b == 0: return a if a % b == 0: return b a, b = b, a % b return gcd(a, b) def fibonacci_huge(n, m): if n <= 1: return n previous = 0 current = 1 if m == 2: return fib(n % 3) % m if m == 3: return fib(n % 8) % m else: for _ in range(n - 1): previous, current = current % m, (previous + current) % m return current % m # a, b = map(int, input().split()) # print(fibonacci_huge(a, b))
arr = [1, 2, 3, 4, 5, 6] flag= -1 for i in range(0, len(arr), 2): arr.insert(i,arr[flag]) arr.pop() print(arr)
# -*- coding: utf-8 -*- """ Created on Wed Sep 16 14:53:59 2020 @author: Ron """ import random import math # The Agent class: # Variables: y and x (coordinates) # Methods: move and get for each variable class Agent: def __init__(self, y, x, environment, agents, cannibal): self.y = y self.x = x self.environment = environment self.agents = agents self.cannibal = True if cannibal < 0.2 else False self.alive = True self.store = 0 def __str__(self): string = "ID: " + str(self.agents.index(self)) + " Y: " + str(self.y) + " X: " + str(self.x) + " store: " + str(self.store) return string # get_y and get_x act to retrieve # the values of the y and x coordinates def get_y(self): return self.y def get_x(self): return self.x def get_store(self): return self.store def set_store(self, store): self.store = store def get_cannibal(self): return self.cannibal def get_life_signs(self): return self.alive def die(self): self.alive = False def move(self): random_y = random.random() random_x = random.random() if random_y > 0.5 and self.y < len(self.environment)-2: self.y += 1 elif random_y < 0.5 and self.y > 0: self.y -= 1 if random_x > 0.5 and self.x < len(self.environment)-2: self.x += 1 elif random_x < 0.5 and self.x > 0: self.x -= 1 def eat(self): y = int(self.y) x = int(self.x) try: elements = self.environment[y][x] except IndexError: elements = 0 if elements > 10: self.store += 10 self.environment[y][x] -= 10 elif elements > 0: self.store += elements self.environment[y][x] -= elements if self.store > 100: self.environment[y][x] += (self.store /2) self.store = self.store / 2 def distance_between(self, agent): y = 0 x = 0 other = self.agents[agent] if self.y > other.get_y(): y = (self.y - other.get_y()) ** 2 else: y = (other.get_y() - self.y) ** 2 if self.x > other.get_x(): x = (self.x - other.get_x()) ** 2 else: x = (other.get_x() - self.x) ** 2 return math.sqrt(y+x) def share_with_neighbours(self, neighbours): for i in range(neighbours): if i != self.agents.index(self): try: distance = self.distance_between(i) except IndexError: distance = neighbours+1 if distance <= neighbours: total = self.store + self.agents[i].store self.store = total/2 self.agents[i].set_store(total/2) #print("sharing " + str(distance) + " " + str(total/2)) def steal_from_neighbours(self, neighbours): for i in range(neighbours): if i != self.agents.index(self): distance = self.distance_between(i) if (distance <= neighbours) and (self.agents[i].get_store() - self.store > 20): self.store += self.agents[i].get_store() / 2 self.agents[i].set_store(self.agents[i].get_store() / 2) def eat_neighbour(self, neighbours): full = False i = 0 while (full == False and i < neighbours): if i != self.agents.index(self) and self.agents[i].get_life_signs(): distance = self.distance_between(i) if distance <= neighbours and self.cannibal: self.store += self.agents[i].get_store() self.agents[i].die() full = True i += 1
#!/usr/local/bin/python3 from weather import Weather, Unit from sys import argv def get_weather(city): weather = Weather(unit = Unit.CELSIUS) location = weather.lookup_by_location(city) condition = location.condition print(condition.text) print(condition.temp + '° C') if len(argv) > 2: print('Please specify only one city') elif len(argv) == 1: print('Please specify a city') else: get_weather(argv[1])
# -*- coding: utf-8 -*- #set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。要创建一个set,需要提供一个list作为输入集合 s1list = [1,1,1,2,2,3,3,3,4] print('s1list = %s'%str(s1list)) s1 = set(s1list) print(s1) s = set([1,2,3]) print(s) x = input('请为set添加一个元素') s.add(int(x)) print(s) y = input('请为set删除一个元素') s.remove(int(y)) print(s) #set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作 set1 = set([1,2,3,4,5,6,7]) set2 = set([5,5,6,7,7,8,8,9,0,0]) print('set1 = %s'%str(set1)) print('set2 = %s'%str(set2)) print('set1 & set2 = %s' %str(set1 & set2)) print('set1 | set2 = %s' %str(set1 | set2))
# -*- coding: utf-8 -*- def power(a,b=1):#计算b个a相乘,b为位置参数,默认是1 sum = 1 while b>0: sum = sum * a b = b -1 return sum #单例 def add_end(L = None): if L is None: L = [] L.append('初始化') else: L.append('end') return L x = int(input('请输入第一个数')) y = int(input ('请输入第二个数')) if (not isinstance(x,int)) | (not isinstance(y,int)): print('输入错误') else: print(str(y)+'个'+str(x)+'相乘 = %d'%power(x,y)) print('--------------------------------------------------') print(add_end([1])) print(add_end()) #可变参数:::::: def add(*nums):#在不确定参数个数的时候前面加*,想用list一样使用这个参数 sum = 0 for num in nums: sum = sum + int(num) return sum mynums = input('请输入您想加的数字,用逗号隔开') print(mynums) numlist = mynums.split(',') print(str(numlist)+'中的数加起来 = %d'%add(*numlist)) #关键字参数-->可以扩展函数功能 #定义一个person的构造方法 def person(name,age,**other): print('name = ',name,'age = ',age,'other = ',other) myname = input('请输入姓名') myage = input('请输入年龄') person(myname,myage) sex = input('请输入性别') height = input ('请输入身高') myother = {'sex':sex,'height':height} person(myname,myage,**myother) print('------------------------------------------------------') #命名关键字参数-->就是参数必须有命名 def person1(name,age,*args,city='beijing',job): #也可以写作person1(name,age,*,city='beijing',job) print(name,age,args,city,job) person1(myname,myage,myother,job='haha')#由于city为默认参数,所以可以不传 #但是'haha'必须要指定job这个名字 #参数组合 #顺序:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。 def fun1(a,b,c=1,*args,**argss): pass def fun2(a,b,c=1,*,d,**argss): pass #可变参数接收的是一个tuple,关键字参数接收的是一个dict
# Vitaly Osipenkov # ID: 324716448 from contact import Contact, ProfessionalContact, FriendContact, ProfessionalFriendContact contacts = [] # Adds a new contact into the phone book, by chosen type of contact. def addContact(): while True: print("Should this contact be Simple (S), Friend (F), Professional (P) or Both (B)?\n" "press (x) to exit.") choice = input("--> ") if choice.lower() == 's': contacts.append(Contact()) elif choice.lower() == 'f': contacts.append(FriendContact()) elif choice.lower() == 'p': contacts.append(ProfessionalContact()) elif choice.lower() == 'b': contacts.append(ProfessionalFriendContact()) elif choice.lower() == 'x': return else: continue contacts.sort() return # The function prints all existing contacts from the phone book, # Also can print lists of contacts from another funcs instead of the phone book - optional parameter. def showContacts(formFindMatches = None): if not formFindMatches: if contacts: for c in contacts: print("contact number " + str(c.contactNumber) + ": " + str(c)) else: print("There is no contacts in the phoneBook!\n") else: for c in formFindMatches: print("contact number " + str(c.contactNumber) + ": " + str(c)) # The function edits a contact by inserted number of contact if exists in the phone book. def editContact(): if contacts: print("Enter a valid number of the contact you wish to edit:") while True: try: choice = int(input("--> ")) break except ValueError: errorMessage() contactReplace = next((contact for contact in contacts if contact.contactNumber == choice), None) if contactReplace: print("Should this contact be Simple (S), Friend (F), Professional (P) or Both (B)? (x) for exit") while True: choice = input("--> ") print("For the following fields click enter if there's no change," "a new value if you want to replace the field," "or x if you want to delete the field (the name field cannot be deleted).") if choice.lower() == 's': contacts[contacts.index(contactReplace)] = Contact(contactReplace) elif choice.lower() == 'f': contacts[contacts.index(contactReplace)] = FriendContact(contactReplace) elif choice.lower() == 'p': contacts[contacts.index(contactReplace)] = ProfessionalContact(contactReplace) elif choice.lower() == 'b': contacts[contacts.index(contactReplace)] = ProfessionalFriendContact(contactReplace) elif choice.lower() == 'x': return else: errorMessage() contacts.sort() return else: print("There is no contact with id: " + str(choice) + " in the phonebook!") else: print("There is no contacts in the phoneBook!\n") # The function generates a new list of contacts which match the given condition def findContact(): print("Type contact details (name, phone, email):") inputs = input("--> ").split(',') matchContacts = [] for element in inputs: matchContacts.extend([x for i, x in enumerate(contacts) if x.Match(element.strip())]) if matchContacts: showContacts(matchContacts) else: print("There is no matches in the phone book!") # Delete contact after checking if exists in the phone book. def deleteContact(): if contacts: while True: print("Enter a valid number of the contact you wish to delete:") try: contactID = int(input("--> ")) break except ValueError: errorMessage() contactDelete = next((contact for contact in contacts if contact.contactNumber == contactID), None) if contactDelete: contacts.remove(contactDelete) else: print("There is no contact with id: " + str(contactID) + " in the phonebook!") else: print("There is no contacts in the phoneBook!\n") # The main function - displays the menu to user. def start(): print("Welcome to the Phone Book!") while True: choice = menu() try: choice = int(choice) if choice == 1: addContact() elif choice == 2: showContacts() elif choice == 3: editContact() elif choice == 4: findContact() elif choice == 5: deleteContact() elif choice == 6: print("\nGoodbye!") quit(0) else: errorMessage() except ValueError: errorMessage() def menu(): print("What would you like to do?\n" "1 - Add a new contact\n" "2 - Show all contacts\n" "3 - Edit a contact\n" "4 - Find a contact\n" "5 - Delete a contact\n" "6 - Exit") choice = input("--> ") return choice # Displays to user error message, when inserted data values are invalid. def errorMessage(): print("That is not a valid entry. Please try again.\n") # The program starts here: start()
class profile(object): email = "" name = "" city = "" def __init__(self, email, name, city): self.email = email self.name = name self.city = city def to_csv(self): return self.email + "," \ + self.name + "," \ + self.city
#Dice Simulator import random class Dice_Sim: def __init__(self): self.lst=[] self.count=0 def Cust_Dice(self): dice=random.randint(1,6) #dice output will be saved in list self.lst.append(dice) #calling the count of 6 self.count=self.lst.count(6) #check whether the count is odd then bring the 6 in game if self.count%2!=0: #appending another 6 to avoid 6 again and again self.lst.append(6) return(6) return dice def Dice(self): dice=random.randint(1,6) return dice def Player(): d=Dice_Sim() #we asked user whether he wanna switch to the custom dice or not??? choice=str(input("Do you want to switch the dice where no of occurence of 6 is great?? Y?N:")) user=str(input("Do you want to play Y/N:")) if choice =="N": #took the input and keep in loop which asks user again and again if decision is N so terminate the game else keep running while user: if user == 'Y': print(d.Dice()) user=str(input("Do you want to play Y/N:")) else: print('Closing') break else: while user: if user == 'Y': print(d.Cust_Dice()) user=str(input("Do you want to play Y/N:")) else: print('Closing') break #-----Driver Code----- #Player()
flag = True while flag == True: while True: try: x = int(input('Enter your time: ')) break except ValueError: print('Enter correct time') color_time = x % 6 if 0 <= color_time < 3: print('Green') elif 3 <= color_time < 4: print('Yellow') else: print('Red') print(f'You want to continue?') text = input('') if text == 'yes': flag = True else: flag = False
#!/bin/python3 import math import os import random import re import sys # # Complete the 'reverse_words_order_and_swap_cases' function below. # # The function is expected to return a STRING. # The function accepts STRING sentence as parameter. # def reverse_words_order_and_swap_cases(sentence): # Write your code here result_sentence = [] new_sentence = sentence.split()[::-1] tempo = [] for word in new_sentence: for char in word: if char.isupper(): tempo.append(char.lower()) else: tempo.append(char.upper()) result_sentence.append(tempo) tempo = [] return ' '.join(''.join(word) for word in result_sentence) print(reverse_words_order_and_swap_cases('aWESOME is cODING'))
""" Charlie has been given an assignment by his Professor to strip the links and the text name from the html pages. """ import re for _ in range(int(input())): html_link_match = re.findall(r'<a href="([^"]+)[^>]*>(?:<[^>]+>)*([^<]*)', input()) for html, title in html_link_match: print('{0},{1}'.format(html, title))
#!/bin/python3 # # Complete the 'plusMinus' function below. # # The function accepts INTEGER_ARRAY arr as parameter. # from collections import defaultdict def plusMinus(arr): # Write your code here length = len(arr) positive = 0 negative = 0 zeros = 0 result = [] for num in arr: if num > 0: positive += 1 elif num < 0: negative += 1 else: zeros += 1 result.append(positive / length) result.append(negative / length) result.append(zeros / length) return [print(f'{num:.6f}') for num in result] def plusMinus_ver2(array): result = defaultdict(int) for num in array: if num > 0: result['positive'] += 1 elif num < 0: result['negative'] += 1 else: result['zeros'] += 1 return list(map( lambda x: print(f'{(x / len(array)):.6f}'), result.values() )) plusMinus_ver2([-4, 0, 1, -6, 8, 9]) if __name__ == '__main__': n = int(input().strip()) arr = list(map(int, input().rstrip().split())) plusMinus(arr)
""" Read a given string, change the character at a given index and then print the modified string. """ def mutate_string(string, position, character): return '{before}{char}{after}'.format( before=string[:position], char=character, after=string[position + 1:], ) if __name__ == '__main__': s = input() i, c = input().split() print(mutate_string(s, int(i), c))
#8.4 Open the file romeo.txt and read it line by line. #For each line, split the line into a list of words using the split() method. #The program should build a list of words. #For each word on each line check to see if the word is already in the list and if not append it to the list. #When the program completes, sort and print the resulting words in alphabetical order. #You can download the sample data at http://www.py4e.com/code3/romeo.txt fname = input("Enter file name: ") fh = open(fname) x = 0 y = 0 oneword = list() emptylist = list() newlist = list() for line in fh: x = x + 1 line = line.rstrip() splitline = line.split() for element in splitline: if element in emptylist : continue emptylist.append(element) emptylist = sorted(emptylist) print(emptylist) #newlist = sorted(n)
''' Name : Bubble sort implementation using python 3.4 Author, Md Imran Sheikh Dept. of CSE, JUST ''' def bubble_sort(L): n = len(L) for i in range(0, n): for j in range(0, n-i-1): if L[j] > L[j+1]: L[j], L[j+1] = L[j+1], L[j] return L if __name__=="__main__": L = [3,1,7,6,2] print(bubble_sort(L))
from queue import PriorityQueue class Graph: def __init__(self, num_of_vertex): self.vertexs = num_of_vertex self.edges = [[-1 for i in range(num_of_vertex)] for i in range(num_of_vertex)] self.visited = [] def add_edge(self, vertex1, vertex2, weight): self.edges[vertex1][vertex2] = weight self.edges[vertex2][vertex1] = weight def dijkstra(self, start_vertex): D = {vertex: float('inf') for vertex in range(self.vertexs)} D[start_vertex] = 0 pq = PriorityQueue() pq.put((0, start_vertex)) while not pq.empty(): (dist, u) = pq.get() self.visited.append(u) for v in range(self.vertexs): if self.edges[u][v] != -1: distance = self.edges[u][v] if v not in self.visited: old_cost = D[v] new_cost = D[u] + distance if new_cost < old_cost: pq.put((new_cost, v)) D[v] = new_cost return D if __name__ == "__main__": g = Graph(4) g.add_edge(0, 1, 2) g.add_edge(0, 2, 1) g.add_edge(1, 3, 3) g.add_edge(2, 3, 2) D = g.dijkstra(0) print(D)
''' A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Also, a self-dividing number is not allowed to contain the digit zero. Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. Example 1: Input: left = 1, right = 22 Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] Note: The boundaries of each input argument are 1 <= left <= right <= 10000. ''' class Solution: def selfDividingNumbers(self, left: int, right: int) -> List[int]: result = [] for n in range(left, right+1): temp = n isdividing = True while temp != 0: digit = temp % 10 if digit == 0 or n % digit != 0: isdividing = False break temp = temp // 10 if isdividing: result.append(n) return result
''' Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 1 Recursion class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: def judge_return(node, isLeft): if not node: return 0 if isLeft and not node.left and not node.right: return node.val + judge_return(node.right, False) else: return judge_return(node.left, True) + judge_return(node.right, False) return judge_return(root, False) # 2 Iteration class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: queue = [(root, False)] left_sum = 0 while queue: head = queue.pop(0) if head[0]: if head[1] and not head[0].left and not head[0].right: left_sum += head[0].val queue.append((head[0].left, True)) queue.append((head[0].right, False)) else: continue return left_sum
''' Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4 ''' # 1 count() class Solution: def singleNumber(self, nums: List[int]) -> int: for i in nums: if nums.count(i) == 1 : return i # 2 Using dictionary to judge uniqueness class Solution: def singleNumber(self, nums: List[int]) -> int: compare = {} for i in nums: if compare.__contains__(i) : del compare[i] else : compare[i] = None return compare.popitem()[0]
''' Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 2: Input: [1,2,3,4] Output: 24 Note: The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. ''' class Solution: def maximumProduct(self, nums: List[int]) -> int: nums2 = nums.copy() min1, min2 = 0, 0 for i in nums: min1 = min(min1, i) for n in range(len(nums)): if min1 == nums[n]: nums.pop(n) break for i in nums: min2 = min(min2, i) for n in range(len(nums)): if min2 == nums[n]: nums.pop(n) break max1, max2, max3 = min1, min1, min1 for i in nums2: max1 = max(max1, i) nums2.remove(max1) for i in nums2: max2 = max(max2, i) nums2.remove(max2) for i in nums2: max3 = max(max3, i) nums2.remove(max3) return max(max1*max2*max3, min1*min2*max1) # min/max method class Solution: def maximumProduct(self, nums: List[int]) -> int: nums2 = nums.copy() min1 = min(0, min(nums)) if min1 != 0: nums.remove(min1) min2 = min(0, min(nums)) else: min2 = 0 max1 = max(nums2) nums2.remove(max1) max2 = max(nums2) nums2.remove(max2) max3 = max(nums2) return max(max1*max2*max3, min1*min2*max1) # This sucks.
''' Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. After doing so, return the array. Example 1: Input: arr = [17,18,5,4,6,1] Output: [18,6,6,6,1,-1] Constraints: 1 <= arr.length <= 10^4 1 <= arr[i] <= 10^5 ''' class Solution: def replaceElements(self, arr: List[int]) -> List[int]: rightmax = -1 for n in range(len(arr)-1, -1, -1): rightmax, arr[n] = max(rightmax, arr[n]), rightmax return arr
""" Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its minimum depth = 2. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 1 Iteration class Solution: def minDepth(self, root: TreeNode) -> int: if not root: return 0 level1 = [root] level2 = [] count = 1 while True: level2 = [] for i in level1: if not i.left and not i.right: return count if i.left: level2.append(i.left) if i.right: level2.append(i.right) level1 = level2.copy() level2.clear() count += 1 # 2 Recursion class Solution: def minDepth(self, root: TreeNode) -> int: if not root: return 0 elif root.left and not root.right: return self.minDepth(root.left) + 1 elif root.right and not root.left: return self.minDepth(root.right) + 1 else: return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
''' Given an integer n. No-Zero integer is a positive integer which doesn't contain any 0 in its decimal representation. Return a list of two integers [A, B] where: A and B are No-Zero integers. A + B = n It's guarateed that there is at least one valid solution. If there are many valid solutions you can return any of them. Example 1: Input: n = 2 Output: [1,1] Explanation: A = 1, B = 1. A + B = n and both A and B don't contain any 0 in their decimal representation. Example 2: Input: n = 11 Output: [2,9] Example 3: Input: n = 10000 Output: [1,9999] Example 4: Input: n = 69 Output: [1,68] Example 5: Input: n = 1010 Output: [11,999] Constraints: 2 <= n <= 10^4 ''' # 1 For class Solution: def getNoZeroIntegers(self, n: int) -> List[int]: for m in range(1, n): if (not '0' in str(m)) and (not '0' in str(n-m)): return [m, n-m] # 2 Scan from right to left class Solution: def getNoZeroIntegers(self, n: int) -> List[int]: A = n base = 1 while A // base >= 10: bit = (A // base) % 10 if bit == 9: A -= 2 * base else: A -= (bit + 1) * base base *= 10 if A == n: return [1, n-1] else: return [A, n-A]
''' In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: The town judge trusts nobody. Everybody (except for the town judge) trusts the town judge. There is exactly one person that satisfies properties 1 and 2. You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b. If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1. Example 1: Input: N = 2, trust = [[1,2]] Output: 2 Example 2: Input: N = 3, trust = [[1,3],[2,3]] Output: 3 Example 3: Input: N = 3, trust = [[1,3],[2,3],[3,1]] Output: -1 Example 4: Input: N = 3, trust = [[1,2],[2,3]] Output: -1 Example 5: Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]] Output: 3 Constraints: 1 <= N <= 1000 0 <= trust.length <= 10^4 trust[i].length == 2 trust[i] are all different trust[i][0] != trust[i][1] 1 <= trust[i][0], trust[i][1] <= N ''' class Solution: def findJudge(self, N: int, trust: List[List[int]]) -> int: if N == 1: if trust: return -1 else: return 1 in_degree = [0 for i in range(N + 1)] out_degree = [0 for i in range(N + 1)] for pair in trust: out_degree[pair[0]] += 1 in_degree[pair[1]] += 1 for n in range(N + 1): if in_degree[n] == N - 1 and out_degree[n] == 0: return n return -1
''' Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example 1: Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). Constraints: 3 <= nums.length <= 10^3 -10^3 <= nums[i] <= 10^3 -10^4 <= target <= 10^4 ''' class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: error = sum(nums[:3]) - target for n in range(len(nums)): target2 = target - nums[n] # print(target, nums[n], target2) nums2 = nums[:n] + nums[n+1:] p, q = 0, 1 error2 = nums2[p] + nums2[q] - target2 for r in range(2, len(nums2)): delta1 = abs(error2) delta2 = abs(nums2[r] + nums2[q] - target2) delta3 = abs(nums2[p] + nums2[r] - target2) # print(n, p, q, r, delta1, delta2, delta3, error2) if delta2 <= delta3 and delta2 < delta1: error2 = nums2[r] + nums2[q] - target2 p = q q = r elif delta3 < delta2 and delta3 < delta1: error2 = nums2[p] + nums2[r] - target2 q = r if abs(error2) < abs(error): error = error2 return error + target
''' You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example 1: Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807. Example 2: Input: l1 = [0], l2 = [0] Output: [0] Example 3: Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1] ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # Note: when a pointer enters .next and points to another node, the original .next isn't changed accordingly class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: c = 0 ans = l1 last = ListNode(next=l1) # merge front while l1 and l2: l1.val, c = (l1.val + l2.val + c) % 10, (l1.val + l2.val + c) // 10 l1 = l1.next l2 = l2.next last = last.next # merge back if l2: last.next = l2 l1 = l2 while l1: l1.val, c = (l1.val + c) % 10, (l1.val + c) // 10 l1 = l1.next last = last.next # rear check if c == 1: last.next = ListNode(val=1) return ans
''' Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer. You may return the answer in any order. Example 1: Input: ["bella","label","roller"] Output: ["e","l","l"] Example 2: Input: ["cool","lock","cook"] Output: ["c","o"] Note: 1 <= A.length <= 100 1 <= A[i].length <= 100 A[i][j] is a lowercase letter ''' class Solution: def commonChars(self, A: List[str]) -> List[str]: from collections import Counter for n in range(len(A)): A[n] = Counter(A[n]) common = A[0] for count in A[1:]: for item in common.items(): if count.__contains__(item[0]): common[item[0]] = min(count[item[0]], item[1]) else: common[item[0]] = 0 result = [] for item in common.items(): result += item[1] * [item[0]] return result # Simplified class Solution: def commonChars(self, A: List[str]) -> List[str]: from collections import Counter for n in range(len(A)): A[n] = Counter(A[n]) common = A[0] for count in A[1:]: common &= count # Use '&' to merge Counters result = [] for item in common.items(): result += item[1] * [item[0]] return result
''' Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Example 1: Input: [1,2,3,1] Output: true Example 2: Input: [1,2,3,4] Output: false Example 3: Input: [1,1,1,3,3,4,3,2,4,2] Output: true ''' # 1 Basic method class Solution: def containsDuplicate(self, nums: List[int]) -> bool: for n in range(len(nums)): if nums[n] in nums[n+1:]: return True return False # 2 Hash class Solution: def containsDuplicate(self, nums: List[int]) -> bool: appeared = {} for i in nums: if appeared.__contains__(i): return True else: appeared[i] = None return False # 3 Sort() class Solution: def containsDuplicate(self, nums: List[int]) -> bool: nums.sort() last = None for i in nums: if i == last: return True last = i return False
''' Given a string s, return the longest palindromic substring in s. Example 1: Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: s = "cbbd" Output: "bb" Example 3: Input: s = "a" Output: "a" Example 4: Input: s = "ac" Output: "a" Constraints: 1 <= s.length <= 1000 s consist of only digits and English letters (lower-case and/or upper-case), ''' # Comparing from the center class Solution: def longestPalindrome(self, s: str) -> str: ans = s[0] for n in range(len(s)): p, q = n, n + 1 if p >= 0 and q < len(s) and s[p] == s[q]: while p >= 0 and q < len(s) and s[p] == s[q]: p -= 1 q += 1 if q - p > len(ans): ans = s[p + 1:q] p, q = n, n + 2 if p >= 0 and q < len(s) and s[p] == s[q]: while p >= 0 and q < len(s) and s[p] == s[q]: p -= 1 q += 1 if q - p > len(ans): ans = s[p + 1:q] return ans
''' Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Explanation: 20 = 1 Example 2: Input: 16 Output: true Explanation: 24 = 16 Example 3: Input: 218 Output: false ''' # 1 Basic method class Solution: def isPowerOfTwo(self, n: int) -> bool: while n >= 1: if n == 1: return True n = n / 2 return False # 2 bit -> dec class Solution: def isPowerOfTwo(self, n: int) -> bool: bit = '1' while n >= int(bit, 2): if n == int(bit, 2): return True bit += '0' return False # 3 Recursion class Solution: def isPowerOfTwo(self, n: int) -> bool: if n == 0: return False elif n == 1: return True elif n != int(n): return False else: return self.isPowerOfTwo(n / 2)
''' You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true Example 2: Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] Output: false Constraints: 2 <= coordinates.length <= 1000 coordinates[i].length == 2 -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4 coordinates contains no duplicate point. ''' # If unable to divide by zero, then transform it into multiplication class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: if coordinates[0][0] == coordinates[1][0]: x = coordinates[0][0] return all(c[0] == x for c in coordinates) else: k = (coordinates[1][1] - coordinates[0][1]) / (coordinates[1][0] - coordinates[0][0]) return all((coordinates[n+1][0] - coordinates[n][0]) * k == (coordinates[n+1][1] - coordinates[n][1]) for n in range(len(coordinates)-1))
''' Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times. You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed. Example 1: Input: name = "alex", typed = "aaleex" Output: true Explanation: 'a' and 'e' in 'alex' were long pressed. Example 2: Input: name = "saeed", typed = "ssaaedd" Output: false Explanation: 'e' must have been pressed twice, but it wasn't in the typed output. Example 3: Input: name = "leelee", typed = "lleeelee" Output: true Example 4: Input: name = "laiden", typed = "laiden" Output: true Explanation: It's not necessary to long press any character. Constraints: 1 <= name.length <= 1000 1 <= typed.length <= 1000 The characters of name and typed are lowercase letters. ''' class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: if name[0] != typed[0]: return False p, q = 1, 1 while q < len(typed): if p == len(name) or name[p] != typed[q]: p -= 1 if name[p] != typed[q]: return False p += 1 q += 1 return (p == len(name))
''' You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number. Example 1: Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. Output: [-1,3,-1] Explanation: For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. For number 1 in the first array, the next greater number for it in the second array is 3. For number 2 in the first array, there is no next greater number for it in the second array, so output -1. Example 2: Input: nums1 = [2,4], nums2 = [1,2,3,4]. Output: [3,-1] Explanation: For number 2 in the first array, the next greater number for it in the second array is 3. For number 4 in the first array, there is no next greater number for it in the second array, so output -1. Note: All elements in nums1 and nums2 are unique. The length of both nums1 and nums2 would not exceed 1000. ''' # 1 Basic method class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: nextnum = {} for n in range(len(nums2)): found = False for i in nums2[n + 1:]: if i > nums2[n]: nextnum[nums2[n]] = i found = True break if not found: nextnum[nums2[n]] = -1 for n in range(len(nums1)): nums1[n] = nextnum[nums1[n]] return nums1 # 2 Stack class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: nextnum = {} stack = [] pointer = 0 while pointer < len(nums2): if not stack or nums2[pointer] < stack[-1]: stack.append(nums2[pointer]) pointer += 1 elif nums2[pointer] > stack[-1]: nextnum[stack.pop()] = nums2[pointer] while stack: nextnum[stack.pop()] = -1 for n in range(len(nums1)): nums1[n] = nextnum[nums1[n]] return nums1
''' Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1. Example 1: Given the following tree [3,9,20,null,null,15,7]: 3 / \ 9 20 / \ 15 7 Return true. Example 2: Given the following tree [1,2,2,3,3,null,null,4,4]: 1 / \ 2 2 / \ 3 3 / \ 4 4 Return false. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 1 Height: Iteration, isBalanced: Recursion class Solution: def height(self, node): if not node: return 0 level = [node] count = 1 while level: level = [i.left for i in level if i.left] + [i.right for i in level if i.right] count += 1 return count - 1 def isBalanced(self, root: TreeNode) -> bool: if not root: return True else: return self.isBalanced(root.left) and self.isBalanced(root.right) and abs( self.height(root.left) - self.height(root.right)) <= 1 # 2 Height: Recursion, isBalanced: Iteration (Inorder) class Solution: def height(self, node): if not node: return 0 else: return max(self.height(node.left), self.height(node.right)) + 1 def isBalanced(self, root: TreeNode) -> bool: stack = [] p = root while True: if p: stack.append(p) p = p.left else: if not stack: return True p = stack.pop(-1) if abs(self.height(p.left) - self.height(p.right)) > 1: return False p = p.right
''' Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example 1: Input: 16 Output: true Example 2: Input: 5 Output: false Follow up: Could you solve it without loops/recursion? ''' # 1 Basic Method class Solution: def isPowerOfFour(self, num: int) -> bool: if num <= 0: return False while num == int(num): if num == 1: return True num /= 4 return False # 2 Base 2 class Solution: def isPowerOfFour(self, num: int) -> bool: if num <= 0: return False num = num ** 0.5 if num != int(num): return False num = bin(int(num)) if num[2] != '1': return False for i in num[3:]: if i != '0': return False return True
from sys import argv import time import itertools import numpy as np import time def guess_password_generators(passwd, chars, password_length): attempts = 0 for guess in itertools.product(chars, repeat=password_length): attempts += 1 guess = ''.join(guess) if guess == passwd: return(True, attempts) return (False, attempts) def containedin(passwd, chars): """ See if all of the characters in the password are contained in this list of chars """ for p in passwd: if not p in chars: return False return True def guess_password(passwd, skipsimulation = False): lowercase = [chr(ord('a') + i) for i in range(26)] uppercase = [chr(ord('A') + i) for i in range(26)] numeric = ["%i"%i for i in range(10)] upperlower = lowercase + uppercase alphanum = lowercase + uppercase + numeric attempts = 0 fin = open("words.txt") print("Looking in dictionary") dictwords = [s.strip() for s in fin.readlines()] fin.close() for s in [dictwords[i] for i in np.random.permutation(len(dictwords))]: attempts += 1 if s == passwd: print("Found password after %i attempts"%attempts) return print("Looking in names") fin = open("names.txt") names = [s.strip() for s in fin.readlines()] for s in [names[i] for i in np.random.permutation(len(names))]: attempts += 1 if s == passwd: print("Found password after %i attempts"%attempts) return attempts += 1 if s.capitalize() == passwd: print("Found password after %i attempts"%attempts) return for password_length in range(1, 20): for name, chars in zip(['numeric', 'lower case', 'upper case', 'alpha', 'alphanumeric'], [numeric, lowercase, uppercase, upperlower, alphanum]): print("Trying all %s combinations on passwords of length %i"%(name, password_length)) if skipsimulation: n_combos = len(chars)**password_length if len(passwd) > password_length: attempts += n_combos else: if not containedin(passwd, chars): attempts += n_combos else: attempts += int(np.random.rand()*n_combos) print("Found password after %i attempts"%attempts) return attempts else: charsparam = [chars[i] for i in np.random.permutation(len(chars))] res = guess_password_generators(passwd, charsparam, password_length) attempts += res[1] if res[0]: print("Found password after %i attempts"%attempts) return attempts print("Did not find password!!") return attempts if __name__ == '__main__': tic = time.time() guess_password(argv[1], skipsimulation=True) print("Elapsed Time: %.3g"%(time.time()-tic))
def words_per_article(df, col): '''Returns descriptive statistics for variable of interest in terms of words per article. Returns a histogram of the frequency of words observed. df: dataframe you wish to call col: column/feature that is to be counted''' lens = df[col].str.split().apply(lambda x: len(x)) print(f'Descriptive statistics for {col}') print('-------------------------------------------------------') print(lens.describe()) print('-------------------------------------------------------') print(f'\nNumber of words in each {col}; length distribution') lens.hist() def visualise_value_counts(df, col, threshold=0.02): title = col prob = df[col].value_counts(normalize=True) print(prob[:5]) mask = prob > threshold tail_prob = prob.loc[~mask].sum() prob = prob.loc[mask] prob['other'] = tail_prob prob.plot(kind='bar') plt.title(f'Normalised frequency distribution of {title}') plt.xticks(rotation=90) plt.show()
import time import random from elevatorSystem import ElevatorSystem def simulate_floorrequest(): num_elevators = 3 first_elevator = 0 second_elevator = 1 lowest_floor = 0 highest_floor = 20 es = ElevatorSystem(num_elevators, lowest_floor, highest_floor) index = 0 print("############################################################") while index <= 15: #print("AT TIME ", index) print("############################################################") """ Now we can assign some floor to any elevator randomly for simulation as well """ floor = random.randint(lowest_floor,highest_floor) elevator_number = random.randint(0,num_elevators-1) print("Request from within the lift " + str(elevator_number) + " to go to " + str(floor)) es.step() es.status() es.target_floor_request(elevator_number,floor) """ For just simulation purposes we assume for n randome seconds between 2 and 10, no new requests comes""" n = random.randint(2,10) for time in range(1,n): print("AT TIME ", index+time) es.step() es.status() print("Queue status for each elevator is: ") for elevator_number in range(len(es.elevators)): print(es.elevator_queues[elevator_number]) index +=1 print("############################################################") if __name__ == "__main__": simulate_floorrequest()
print("Welcome to Python Pizza Deliveries!") size = input("What size pizza do you want? S, M, or L ") if size == "s": s = 15 p = input("do you want pepperoni? Y or N ?") if p == "y": s +=2 c = input("do you want extra-cheese? Y or N ?") if c == "y": s +=1 print(f"please pay ${s}") else: print(f"please pay ${s}") elif size == "m": m = 20 p = input("do you want pepperoni? Y or N ?") if p == "y": m +=2 c = input("do you want extra-cheese? Y or N ?") if c == "y": m +=1 print(f"please pay ${m}") else: print(f"please pay ${m}") elif size == "l": l = 25 p = input("do you want pepperoni? Y or N ?") if p == "y": l +=2 c = input("do you want extra-cheese? Y or N ?") if c == "y": l +=1 print(f"please pay ${l}") else: print(f"please pay ${l}") else : print("please choose the correct size using the letter l, m, s")
name_fast = input('Give a Name to Your Fast but Lazy Buddy') name_slow = input('Give a Name to Your Slow but Steady Buddy') town = input('Give a Name to Imaginary Town') activity = input(f'Which activity did {name_fast.title()} start doing thinking he was in the lead?') print(f'In the old town of {town}, the fast {name_fast.title()} challenged the slow {name_slow.title()} to a race.\n' f'Even though {name_fast.title()} was fast he was also very overconfident.\n' f'{name_slow.title()} on the other hand practiced a lot and was very persistent.\n' f'On the day of the race {name_slow.title()} took a very early lead but then \nbecame relaxed and decided to do some {activity}' f'Alas he got tired and fell asleep while {name_slow.title()} \nslowly overtake him by the time he woke up it was too late and \n{name_slow.title()} had defeated him.')
class Canvas: def __init__(self, row, col): self.matrix = [[] * col] * row self.rectangle_hash = {} for i in range(row): for j in range(col): cell = Cell(i, j ) self.matrix[i][j] = cell def draw(self, left_top, right_bottom): length = self.rectangle_hash index = length rectangle = Rectangle(index, left_top, right_bottom) self.rectangle_hash[index] = rectangle for i in range(len(rectangle.filled)): for j in range(len(rectangle.filled[0])): if rectangle.filled[i][j] is True: cell = self.matrix[i][j] if not cell.color: cell.color = True cell.info.append(rectangle.index) def drag(self): self.delete() self.draw() def move_to_top(self): pass def delete(self): pass def print(self): pass class Cell: def __init__(self, i, j): self.i = i self.j = j self.color = False self.info = [] class Rectangle: def __init__(self, index, left_top, right_bottom): self.index = index self.left_top = left_top self.right_bottom = right_bottom self.filled = [] for i in range(left_top[0], right_bottom[0] + 1): self.filled[i] = [] for j in range(left_top[1], right_bottom[1] + 1): self.filled[i].append(True)
#Aim: Write a python program to delete the last row of the dataframe. import pandas as pd data = {'names': ['a1', 'a2', 'a3', 'a4'], "marks": [60, 90, 50, 40]} df = pd.DataFrame(data) df.drop(3,inplace=True) print(df)
n1=int(input("enter the no")) n2=int(input("enter the no")) n3=int(input("enter the no")) max=n1 if n2>max: max=n2 if n3>max: max=n3 print("the greather no is",max)
class Pet: totalPets = 0 def __init__(self, name, age): self.name = name self.age = age self.health = 60 Pet.totalPets = Pet.totalPets + 1 def speak(self): print(self.name + " is speaking") def feed(self, value=10): self.health = self.health + value if self.health > 100: self.health = 100 print(self.name + " is full !!") else: print(self.name + " is still hungry") def sit(self): print(self.name + " sits") def sold(self): print(self.name + " got sold") Pet.totalPets = Pet.totalPets - 1 class Fish(Pet): def __init__(self, name, age): self.name = name self.age = age self.health = 100 Pet.totalPets = Pet.totalPets + 1 def speak(self): print(self.name + " bubbles")
def reverseWordsInString(string): lst = [] returnstring = "" for index in string: if index != " ": returnstring += index else: lst.append(returnstring) returnstring = "" lst.append(returnstring) lst = " ".join(lst[::-1]) return lst def reverseWordsInStringAlt(string): words = [] startOfWord = 0 for idx in range(len(string)): character = string[idx] if character == " ": words.append(string[startOfWord:idx]) startOfWord = idx elif string[startOfWord] == " ": words.append(" ") startOfWord = idx words.append(string[startOfWord:]) reverseList(words) return "".join(words) def reverseList(lst): start, end = 0, len(lst) - 1 while start < end: lst[start], lst[end] = lst[end], lst[start] start += 1 end -= 1 def reverseWordsInStringHard(string): characters = [char for char in string] reversedListRange(characters, 0, len(characters) - 1) startOfWord = 0 while startOfWord < len(characters): endOfWord = startOfWord while endOfWord < len(characters) and characters[endOfWord] != " ": endOfWord += 1 reversedListRange(characters, startOfWord, endOfWord - 1) startOfWord = endOfWord + 1 return "".join(characters) def reversedListRange(lst, start, end): while start < end: lst[start], lst[end] = lst[end], lst[start] start += 1 end -= 1
def minimumCharactersForWordsAlt(words): hashmap = {} for word in words: _ = {} for letter in word: if letter in _: _[letter] += 1 else: _[letter] = 1 for character in _: if character in hashmap: if _[character] > hashmap[character]: hashmap[character] = _[character] else: hashmap[character] = _[character] lst = [] for character in hashmap: _ = [character for i in range(hashmap[character])] lst += _ return lst def minimumCharactersForWords(words): maximumCharacterFrequencies = {} for word in words: characterFrequencies = countCharacterFrequencies(word) updateMaximumFrequencies(characterFrequencies, maximumCharacterFrequencies) return makeArrayFromCharacterFrequencies(maximumCharacterFrequencies) def countCharacterFrequencies(string): characterFrequencies = {} for character in string: if character not in characterFrequencies: characterFrequencies[character] = 0 characterFrequencies[character] += 1 return characterFrequencies def updateMaximumFrequencies(frequencies, maximumFrequencies): for character in frequencies: frequency = frequencies[character] if character in maximumFrequencies: maximumFrequencies[character] = max(frequency, maximumFrequencies[character]) else: maximumFrequencies[character] = frequency def makeArrayFromCharacterFrequencies(characterFrequencies): characters = [] for character in characterFrequencies: frequency = characterFrequencies[character] for _ in range(frequency): characters.append(character) return characters
# Definition for singly-linked list. class ListNode: def __init__(self, value): self.value = value self.next = None # O(N) time | O(N) space def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: # init condition tot = l1.value + l2.value carry = int(tot / 10) l3 = ListNode(tot % 10) p1 = l1.next p2 = l2.next p3 = l3 while p1 is not None or p2 is not None: tot = carry + (p1.value if p1 else 0) + (p2.value if p2 else 0) carry = int(tot/10) p3.next = ListNode(tot % 10) p3 = p3.next p1 = p1.next if p1 else None p2 = p2.next if p2 else None if(carry > 0): p3.next = ListNode(carry) return l3 # O(N) space | O(N) time def sumOfLinkedLists(linkedListOne, linkedListTwo): pointer = ListNode(0) currentNode = pointer carry = 0 nodeOne = linkedListOne nodeTwo = linkedListTwo while nodeOne is not None or nodeTwo is not None or carry != 0: valueOne = nodeOne.value if nodeOne is not None else 0 valueTwo = nodeTwo.value if nodeTwo is not None else 0 sumofValues = valueOne + valueTwo + carry newValue = sumofValues % 10 newNode = ListNode(newValue) currentNode.next = newNode currentNode = newNode carry = sumofValues // 10 nodeOne = nodeOne.next if nodeOne is not None else None nodeTwo = nodeTwo.next if nodeTwo is not None else None return pointer.next
def threeNumberSum(array, targetSum): array.sort() resarr = [] for index in range(len(array)-2): i, j, k = index, index+1, len(array)-1 while j < k: currentSum = array[i] + array[j] + array[k] if currentSum == targetSum: resarr.append([array[i], array[j], array[k]]) j += 1 k -= 1 elif currentSum > targetSum: k -= 1 else: j += 1 return resarr
from cs50 import get_int # get input from the user while True: n = get_int("Height:") # cheking if int is in range if n in range(1, 9): break m = n + 1 # printing each row for i in range(1, m): # print spaces print(" " * (n - i), end='') # print hashes print("#" * i, end='') # print two sapces print(" ", end='') # print hashes print("#" * i, end='') # printing new line print()
'''Create a program that reads the length and width of a farmer’s field from the user in feet. Display the area of the field in acres. Hint: There are 43,560 square feet in an acre.''' length = int(input('Enter length of area: ')) width = int(input('Enter width of area: ')) square_feet = 43.560 square = length*width/square_feet print('The square of area is {:.2f} in acres'.format(square))
def jumpingOnClouds(c): steps=0 jump=0 end=len(c) while jump <(end-1): if jump+2<end and c[jump+2]==0: jump+=2 steps+=1 else: jump+=1 steps+=1 return steps