text
stringlengths
37
1.41M
# Question 1: Accept two integer numbers from a user and return their product and if the product is greater than 1000, then return their sum # Expected Output: # ------------------ # Enter first number 10 # Enter second number 20 # The result is 200 a,b = input("Enter first number: "), input("Enter second number: ") a,b = int(a), int(b) # print(a) # print(b) print("product of a & b is", a * b) if a * b > 1000: print("sum of a & b is", a + b)
# Question 3: Accept string from a user and display only those characters which are present at an even index number. # For example str = "pynative" so you should display ‘p’, ‘n’, ‘t’, ‘v’. # Expected Output: # Enter String pynative # Orginal String is pynative # Printing only even index chars # index[ 0 ] p # index[ 2 ] n # index[ 4 ] t # index[ 6 ] v STRING = input("Enter String: ") print("Orginal String is ",STRING) print("Printing only even index chars") for i in range(0,len(STRING)): if i % 2 == 0: print("index[",i,"] ",STRING[i]) # F:\Python\Practice>python 03PrintEvevnIndexChar.py # Enter String: sirineni shireesha saikiran # Orginal String is sirineni shireesha saikiran # Printing only even index chars # index[ 0 ] s # index[ 2 ] r # index[ 4 ] n # index[ 6 ] n # index[ 8 ] # index[ 10 ] h # index[ 12 ] r # index[ 14 ] e # index[ 16 ] h # index[ 18 ] # index[ 20 ] a # index[ 22 ] k # index[ 24 ] r # index[ 26 ] n
import random number_of_trials = 10 ** 6 one_count=0 two_count=0 three_count=0 four_count=0 five_count=0 six_count=0 coutcome=0 count=0 while count < number_of_trials: # head - 0 ; tail - 1 outome = random.randint(1, 6) count += 1 if outome == 1: one_count += 1 if outome == 2: two_count += 1 if outome == 3: three_count += 1 if outome == 4: four_count += 1 if outome == 5: five_count += 1 if outome == 6: six_count += 1 print("one_count: {}, percentage {}".format(one_count,(one_count/number_of_trials)*100)) print("two_count: {}, percentage {}".format(two_count,(two_count/number_of_trials)*100)) print("three_count: {}, percentage {}".format(three_count,(three_count/number_of_trials)*100)) print("four_count: {}, percentage {}".format(four_count,(four_count/number_of_trials)*100)) print("five_count: {}, percentage {}".format(five_count,(five_count/number_of_trials)*100)) print("six_count: {}, percentage {}".format(six_count,(six_count/number_of_trials)*100)) # F:\Programming\Python\Prob & Stats>python RollAFailDice.py # one_count: 16667045, percentage 16.667044999999998 # two_count: 16668182, percentage 16.668182 # three_count: 16671245, percentage 16.671245000000003 # four_count: 16665032, percentage 16.665032 # five_count: 16667642, percentage 16.667642 # six_count: 16660854, percentage 16.660854
# if name is "XYZ" and age is below 40, # print "suitable" else if age is greater # than 50, print "old", else print "OK" # For all other names, print "not known" #name = "ABC" #name = input("Give Name:") #age_1 = input("Give Age:") #age = int(input("Give Age:")) #Execute as below #python second.py ABC 40 import sys name = sys.argv[1] if len(sys.argv) > 1 else "XYZ" #1st arg # if len(sys.argv) > 2: # age = int(sys.argv[2]) # 2nd Arg # else: # age = 40 age = int(sys.argv[2]) if len(sys.argv) > 2 else 40 #print(sys.argv) #['second.py', 'ABC', '40'] if name == "XYZ": if age < 40: print("suitable") elif age > 50: print("old") else: print("OK") else: print("not known") print("END")
# Challenge: https://www.hackerrank.com/challenges/a-very-big-sum/problem def aVeryBigSum(a): sum = 0 Array = a for i in Array: sum += int(i) return sum num = input() numbers = input() number_list = numbers.split(' ') if len(number_list) != int(num): print("Not ",num," number of intergers enter") sum_of_nums = aVeryBigSum(number_list) print(sum_of_nums)
Q0: Nested If if name is "XYZ" and age is below 40, print "suitable" else if age is greater than 50, print "old", else print "OK" For all other names, print "not known" name = "XYZ" age = 40 if name == "XYZ": if age < 40: print("suitable") elif age > 50: print("old") else: print("OK") else: print("not known") Q0.1: Print prime numbers between 0 to 10 check = int(sys.argv[1]) print("2 is prime") for nu in range(3,check,2): #Check when you divide nu by 2...nu-1 #the reminder should not be zero #if so, it is prime prime = True for x in range(2,nu-1,1): if nu % x == 0: #print this is not prime prime = False break if prime: print(nu , "is prime") #OR check = int(sys.argv[1]) print("2 is prime") for nu in range(3,check,2): #Check when you divide nu by 2...nu-1 #the reminder should not be zero #if so, it is prime #prime = True for x in range(2,nu-1,1): if nu % x == 0: #print this is not prime #prime = False break else:#if prime: print(nu , "is prime") Q0.2: Print Pythogorus number below 100 ie (x,y,z) which satisfy z*z == x*x +y*y for x in range(1,100): for y in range(x,100): for z in range(y,100): if z*z == x*x + y*y: print(x,y,z) Q0.3: Given:D1 = {'ok': 1, 'nok': 2} D2 = {'ok': 2, 'new':3 } Create below: # union of keys, #value does not matter D_UNION = { 'ok': 1, 'nok': 2 , 'new':3 } # intersection of keys, #value does not matter D_INTERSECTION = {'ok': 1} D1- D2 = {'nok': 2 } #values are added for same keys D_MERGE = { 'ok': 3, 'nok': 2 , 'new':3 } #Merge solution m_dict = {} for k1 in in1: m_dict[k1] = in1[k1] #Initial values if k1 in in2: m_dict[k1] = in1[k1] + in2[k1] # merge for k2 in in2: # remaining elements if k2 not in in1: m_dict[k2] = in2[k2] print(m_dict) Q1: input_str = "Hello world print frequency of each alphabets H-1 e-1 l-3 and so on for other alphabets s = "Hello World" for ch in s: # initialize counter counter = 0 # Take each char(ch1) from s #for for ch1 in s: # if ch and ch1 are same #if if ch == ch1: # increment counter counter = counter + 1 # print ch and counter # print print(ch, '-', counter) Q2:Find out the flaw in above program How can you solve that ?(Hint: use correct data structure ) Solve .. s = "Hello World" for ch in set(s): # initialize counter counter = 0 # Take each char(ch1) from s #for for ch1 in s: # if ch and ch1 are same #if if ch == ch1: # increment counter counter = counter + 1 # print ch and counter # print print(ch, '-', counter) Q3: Actually, above data structure is dict, don't you think so? So, formally solve with dict where key is aplhabet and value it's count s = "Hello World" #create empty dict d = {} #Take each char(ch) from s for ch in s: #if ch key does not exit in empty dict if ch not in d: #create new key, ch and initialize d[ch] = 1 else: #increment ch'key value d[ch] = d[ch] + 1 print(d) Q3.1 input = "aaabbbbaaac" output = "abc" output = "" #Take each char(ch) from input #for for ch in input: #if ch does not exist in output #not in if ch not in output: output = output + ch print(output, ch) print(output) Q4: Given input, find output input = [1,2,3,4] output = [1,9] res = [] for e in input: if e % 2 == 1 : res.append(e*e) Q5: Given input, find output input = '[1,2,3,4]' output = [1,2,3,4] res = [] for e in input.strip('[]').split(","): res.append(int(e)) Q5.1: Can you implement above with slice res = [] for e in list(input)[1:-1:2]: res.append(int(e)) Q6: Given input, find output input = 'Name:ABC,age=20|Name:XYZ,age=30' output = 'Name:Abc,age=20|Name:Xyz,age=30' #split input with "|" and store to s2 s2 = input.split("|') #create empty list res = [] #Take each element(e) from s2 for e in s2: # split that with ',', take first part e2 = e.split(",")[0].split(":")[1] # then split with ':', take 2nd part # title() it , # then replace e , old = original, new= title res.append(e.replace(e2, e2.title())) # append to empty list #join that empty list with "|" "|".join(res0 Q7: Find checksum input="ABCDEF1234567890" Take two two character(one byte) from above (which are in hex digit ) Convert to int (Hint: use int function with base) Sum all and then find mod with 255, that is your checksum out = [int("".join(e),16) for e in zip(input[::2],input[1::2])] sum(out) % 255 Q8: Sub process and Regex hands on Execute below command and extract some info tracert www.google.com netstat -an ipconfig /all powercfg /lastwake driverquery -v nslookup www.google.com tasklist -m ##4 patterns nslookup www.google.com echo %errorlevel% nslookup www.google.com > out.txt type out.txt | findstr /c:"Server" """ Server:\t\t192.168.43.1\nAddress:\t192.168.43.1#53\n\nNon-authoritative answer: \nName:\twww.google.com\nAddress: 172.217.26.228\n\n' """ ''' class subprocess.Popen(args, bufsize=0, stdin=None, stdout=None, stderr=None, shell=False, universal_newlines=False) ''' #1 import subprocess as S command = "nslookup www.google.com" proc = S.Popen(command, shell=True, stdout=S.PIPE, stderr=S.PIPE, universal_newlines=True) outs, oute = proc.communicate() print(outs) import re res = re.findall(r"Address: (.+?)\n\n" , outs) res =re.findall (r"Addresses:\s+((.+)\n\t\s*(.+)\n\n)",s) com1 = r"c:\windows\system32\ping %s" % res[0][-1] proc = S.Popen(com1, shell=True, stdout=S.PIPE, stderr=S.STDOUT, universal_newlines=True) outs, oute = proc.communicate() print(outs) #2 command = "nslookup www.google.com" proc = S.Popen(command, shell=True, stdout=S.PIPE, stderr=S.PIPE, universal_newlines=True) outs, oute = proc.communicate() print(proc.returncode) #3 nslookup www.google.com > out.txt with open("out.txt", "wt") as f : command = "nslookup www.google.com" proc = S.Popen(command, shell=True, stdout=f, stderr=S.STDOUT, universal_newlines=True) proc.wait() proc2 = S.Popen("type out.txt", shell=True, stdout=S.PIPE, stderr=S.PIPE, universal_newlines=True) outs, oute = proc2.communicate() print(outs) #4 type out.txt | findstr /c:"Server" command = "type out.txt" com2 = 'findstr /c:"Server"' proc = S.Popen(command, shell=True, stdout=S.PIPE, stderr=S.STDOUT, universal_newlines=True) proc2 = S.Popen(com2, shell=True, stdin= proc.stdout, stdout=S.PIPE, stderr=S.STDOUT, universal_newlines=True) proc.stdout.close() outs, oute = proc2.communicate() # proc = S.Popen(command + "| "+com2, shell=True, stdout=S.PIPE, stderr=S.STDOUT, universal_newlines=True) outs, oute = proc2.communicate() Q8.1: escapiing the pipe by ^, /v means lines other than matching , /c:"" - matching, /r - regex #To strip out the top 2 lines pipe the output to findstr /v "Active Proto". for /f "tokens=2,5" %i in ('netstat -n -o ^| findstr /v "Active Proto"') do @echo Local Address = %i, PID = %j #OR for /f "tokens=2,5" %i in ('netstat -n -o ^| findstr /C:"ESTABLISHED"') do @echo Local Address = %i, PID = %j 1. Execute above with big bufsize and get Unique port 2. get detail of each PID by command: tasklist /fi "pid eq PID" /nh Q8.2: Get return code of executing: taskkill -im iexplore.exe while redirecting both stdout and stderr to devnull Q8.2 : Execute via pipe , dir /B | findstr /r /c:"[mp]" Q8.3: Redirect tasklist /fi "imagename eq iexplore.exe"' > test.txt and then display the content via type test.txt ##Example - escapiing the pipe by ^, /v means lines other than matching , /c:"" - matching, /r - regex #To strip out the top 2 lines pipe the output to findstr /v "Active Proto". for /f "tokens=2,5" %i in ('netstat -n -o ^| findstr /v "Active Proto"') do @echo Local Address = %i, PID = %j #OR for /f "tokens=2,5" %i in ('netstat -n -o ^| findstr /C:"ESTABLISHED"') do @echo Local Address = %i, PID = %j command = """for /f "tokens=2,5" %i in ('netstat -n -o ^| findstr /C:"ESTABLISHED"') do @echo Local Address = %i, PID = %j""" import subprocess as S bufsize = 2**20 p = S.Popen(command, bufsize =bufsize, shell=True, stdout=S.PIPE, stderr=S.PIPE, universal_newlines=True) (out,err) = p.communicate() #Unique Port import re sp = r":(\d+)," res = re.findall(sp, out) unique = {int(e) for e in res } #details of process sp = r"PID = (\d+)\n" unique = {int(e) for e in re.findall(sp, out) } command = r"""tasklist /fi "pid eq %d" /nh""" stat = {} for pid in unique: p = S.Popen(command % pid , shell=True, stdout=S.PIPE, stderr=S.STDOUT, universal_newlines=True) stat[pid] = p.communicate()[0] #no header- nh D:\Desktop\PPT>tasklist /fi "pid eq 6340" Image Name PID Session Name Session# Mem Usage ========================= ======== ================ =========== ============ iexplore.exe 6340 Console 7 1,33,468 K ##Example of only return code command = """taskkill -im iexplore.exe""" #echo %errorlevel% or echo $? , note 0 means success import subprocess as S, os , sys #Py3.5, S.DEVNULL with open(os.devnull, 'w') as DEVNULL: exit = S.Popen(command, shell=True, stdout=DEVNULL, stderr=DEVNULL).returncode #then exit sys.exit(exit) ##Example of pipe #dir /B | findstr /r /c:"[mp]" import subprocess as S, os , sys command = 'dir /B | findstr /r /c:"[mp]"' output = S.check_output(command, shell=True, stderr=S.STDOUT, universal_newlines=True) #OR command1 = 'dir /B' command2 = 'findstr /r /c:"[mp]"' #Py3.5, S.DEVNULL with open(os.devnull, 'w') as DEVNULL: p1 = S.Popen(command1, shell=True, stdout=S.PIPE, stderr=DEVNULL) p2 = S.Popen(command2, shell=True, stdin=p1.stdout, stdout= S.PIPE, stderr=DEVNULL) p1.stdout.close() ## Allow p1 to receive a SIGPIPE if p2 exits (out, err) = p2.communicate() ##Example of Redirect command = 'tasklist /fi "imagename eq iexplore.exe"' #> test.txt file = "test.txt" with open(file , "wt") as f : proc = S.Popen(command, shell=True, stdout=f, stderr=S.STDOUT) proc.wait() command = "type %s" contents = S.Popen(command % file, shell=True, stdout=S.PIPE, stderr=S.STDOUT).stdout.read() Q9 : Os hands on 1. Create below env vars containing below HOST hostname DT todays date using pattern "%m%d%y%H%M%S" SCRIPT this script name only (without extension) SCRIPT_PID this script pid OUTDIR C:/tmp/adm LOGFIL $OUTDIR/$SCRIPT.$DT.log (in unix expansion of variable 2. Then dump in parent and in child these values (Use Subprocess) 3. create a diction of filename and it's size only in given dir(without recursively going into subdirs) 4. Rename any files, *.txt in a given dir to *.txt.bak 4. Print cwd in python and go to parent dir and again print 5. Walk each dir & subdirs and create .done file containing today's date and no of file found , file names and each file size 6. walk each dir and remove .done file 1. import os, os.path, sys, subprocess as S, time, datetime as D, shlex direct_environ = dict(HOST=os.uname()[1], #platform.uname().node DT=D.datetime.today().strftime("%m%d%y%H%M%S"), SCRIPT=os.path.splitext(os.path.basename(sys.argv[0]))[0], SCRIPT_PID=str(os.getpid()), OUTDIR=r"/var/adm/aaas", ) #Update, could have called os.environ.update(direct_environ), ensure all are string for k,v in direct_environ.items(): os.environ[str(k)] = str(v) #Add all environs which are dependent on other environs , must after above indirect_environ = dict(LOGFILE=os.path.expandvars(r"$OUTDIR/$SCRIPT.$DT.log")) for k,v in indirect_environ.items(): os.environ[str(k)] = str(v) 2. for k,v in os.environ.items(): if k in direct_environ or k in indirect_environ: print(k,'=',v) print("Print in subprocess") #both in windows and shell proc = S.Popen("printenv", shell=True, stdout=S.PIPE, stderr=S.STDOUT, universal_newlines=True) outs, errs = proc.communicate(timeout=10) final_keys = direct_environ.keys() | indirect_environ.keys() for line in outs.split(): k,*v = line.split("=") if k in final_keys: print("\t",line) 3. create a dict of filename and it's size only in given dir(without recursively going into subdirs) g_dir = "." d = {} for f in glob.glob(g_dir+"/*"): if os.path.isfile(f): d[f] = os.path.getsize(f) 4. Rename any files, *.txt in a given dir to *.txt.bak g_dir = "." d = {} for f in glob.glob(g_dir+"/*"): if os.path.isfile(f): new_f = f + ".bak" with open(f,"rt") as inf: with open(new_f, "wt") as outf: outf.writelines(inf.readlines()) 4. Print cwd in python and go to parent dir and again print os.path.abspath(os.curdir) os.chdir("..") os.path.abspath(os.curdir) 5. Walk each dir & subdirs and create .done file containing today's date and no of file found , file names and each file size #os.walk(top, topdown=True, onerror=None, followlinks=False) #For each directory ,, yields a 3-tuple (dirpath, dirnames, filenames). import os, os.path,datetime for root, dirs, files in os.walk('.'): #print(root, dirs, files) res = [str(datetime.datetime.now())+"\n"] res.append( "No of Files:%d\n" % len(files)) for f in files: file = os.path.join(root, f) s = os.path.getsize(file) created = datetime.datetime.fromtimestamp(os.path.getctime(file)) res.append("%s,%d,%s\n" %(file, s, created)) with open(os.path.join(root, ".done"), "wt") as f : f.writelines(res) 6. walk each dir and remove .done file import os, os.path,datetime for root, dirs, files in os.walk('.'): file = os.path.join(root, ".done") if os.path.exists(file): os.remove(file) Q-FUNC:Write functions of below , lst = list of numerics Mean(lst) = Sum of lst/length of lst Median(lst) = sort and midddle value or average of two middle if length is even sd(lst) = sqrt of( SUM of square of ( each elemnt - mean) / length of lst ) freq(lst) = returns dict with key as element and value is count Mode(lst) = sort with frequency, highest frequency merge(in1,in2) in1, in2 are dict, values are added for same keys Given: D1 = {'ok': 1, 'nok': 2} D2 = {'ok': 2, 'new':3 } returns { 'ok': 3, 'nok': 2 , 'new':3 } checksum(string) Using regex Take two two character(one byte) from above (which are in hex digit ) Convert to int (Hint: use int function with base) Sum all and then find mod with 255, that is your checksum Test with input="ABCDEF1234567890" sliding(lst, windowSize, step) Take elements from lst with windowSize and step with 'step' eg given lst = [2,4,6,3,5,7] and sliding(lst, 2, 1) returns [[2, 4], [4, 6], [6, 3], [3, 5], [5, 7]] grouped(lst, n) create each n elements of lst eg given lst = [2,4,6,3,5,7] and grouped(lst, 2) returns [[2, 4], [6, 3], [5, 7]] group_by(lst, key) returns a dict of key(element) and values are list of those element of lst which satisfy's key function key is function which takes each element eg given lst = [2,4,6,3,5,7] and group_by(lst, lambda e : e%2) returns { 1:[3,5,7], 0:[2,4,6]} take(lst, n, start=0) Takes n element from start drop(lst, n, start=0) takes all element after droping n from start agg(in_d, agg_d) Aggregation where agg_d is dict of column name and fn(lst), lst is values of in_d for each key eg in_d = { 1:[3,5,7], 0:[2,4,6]} agg_d = {'max': max, 'mean': lambda lst: sum(lst)/len(lst) , 'sum': sum } returns {0: {'max': 6, 'mean': 4.0, 'sum': 12}, 1: {'max': 7, 'mean': 5.0, 'sum': 15}} read_csv(fileName) Return list of rows where each element is converted to int, then float, then str whichever succeeds read_csv(filename, dates_index= None, datetime_format=None) Extend that with datetime parseing for those indexes given in dates_index if datettime_format is none, use dateutils.parser.parse function to autodetect the format write_csv(fileName, lst, headers) write headers and then lst to fileName execute_and_watchdog(command, TIMEOUT=15, WAIT_FOR_KILL=60, **kwargs) Execute the command and keep on polling to check command is completed within TIMEOUT If not, manually kill that and then sleep for WAIT_FOR_KILL OS hands ON 1.Create below env vars containing below HOST hostname DT todays date using pattern "%m%d%y%H%M%S" SCRIPT this script name only (without extension) SCRIPT_PID this script pid OUTDIR C:/tmp/adm LOGFIL $OUTDIR/$SCRIPT.$DT.log (in unix expansion of variable 2. Then write functions to dump environs in parent and in child these values 3. write mslog with takes any message and dumps that message to LOGFIL and console with below format , message may contain any env var and that should be expanded HOST:DT:message 4. Given a filename and no of breaks, generate that many files with chunks from original file names 5. Concatenate many .txt file into one file 6. Recurively go below a dir and based on filter, dump those files in to single file ## #Mean(lst) = Sum of lst/length of lst @trace @mea # mean = mea(mean) def mean(lst): time.sleep(5) return sum(lst)/len(lst) #Median(lst) = sort and midddle value or average of two middle if length is even def median(lst): a = sorted(lst) b = len(a) if b % 2 == 0: c = a[b//2] + a[b//2-1] return c/2 else: return a[b//2] #sd(lst) = sqrt of( SUM of square of ( each elemnt - mean) / length of lst ) def sd(lst): import math m = mean(lst) #res = [] #for e in lst: # res.append( (e-m)*(e-m) ) res = [ (e-m)*(e-m) for e in lst] return math.sqrt(sum(res)/len(lst)) def merge(in1,in2, op=lambda x,y:x+y): """ in1, in2 are dict, values are added for same keys Given: D1 = {'ok': 1, 'nok': 2} D2 = {'ok': 2, 'new':3 } returns { 'ok': 3, 'nok': 2 , 'new':3 } """ D = in1.copy() for k,v in in2.items(): if k in D: D[k] = op(D[k] ,v) else: D[k] = v return D def checksum(string): ''' Take two two character(one byte) from above (which are in hex digit ) Convert to int (Hint: use int function with base) Sum all and then find mod with 255, that is your checksum Test with input="ABCDEF1234567890" ''' import re data = [ int(x, 16) for x in re.findall(r"\w\w", string) ] return sum(data) % 256 def read_csv(filename, dates= None, datetime_format=None): def convert(x, fn): try: res = fn(x) except Exception: res = None return res def one_by_one(x, *fn): for f in fn: res = convert(x,f) if res != None: return res return x from csv import reader with open(filename, "rt") as f : rd = reader(f) rows = list(rd) tryFn = [int, float, str] first = [ [ one_by_one(e.strip(), *tryFn) for e in row] for row in rows if len(row) > 0 ] #convert dates from dateutil.parser import parse from datetime import datetime if datetime_format and type(datetime_format) is str: date_parse = lambda e: datetime.strptime(e, datetime_format) elif datetime_format and type(datetime_format) is function : date_parse = datetime_format else: date_parse = parse def convert_date(row, which): res = [] if type(which) is int: cols = [which] else: cols = which #print(date_parse,cols) for i, e in enumerate(row) : if i in cols: #print("converting", i) try: res.append(date_parse(e)) except Exception: res.append(e) else: res.append(e) return res if dates != None: second = [convert_date(row,dates) for row in first] else: second = first return second def write_csv(filename, lst, headers ): from csv import writer with open(filename, "wt", newline='') as f : wr = writer(f) wr.writerows([headers] + lst) def sliding(lst, w, s): res = [] n = ((len(lst)-w)/s)+1 for i in range(0, int(n)): start = i*s end = w + s*i res.append(lst[start:end]) #last segment if lst[end:]: res.append(lst[end:]) return res def sliding2(lst, w, s): assert s <= w res = list(zip(*[lst[i::s] for i in range(w)])) #last segment end = w + s*((len(lst)-w)//s) if lst[end:]: res.append(tuple(lst[end:])) return res def grouped(lst, n): return sliding(lst, n, n) def group_by(lst, key): d = {} for e in lst: k = key(e) if k in d: d[k].append(e) else: d[k] = [e] return d def take(lst, n, start=0): return list(lst)[start:n] def drop(lst, n, start=0): return list(lst)[start+n:] def agg(in_d, agg_d): out_d = {} for key, lst in in_d.items(): out_d[key] = agg_d.copy() for col, fn in agg_d.items(): out_d[key][col] = fn(lst) return out_d def execute_and_watchdog(command, TIMEOUT=15, KILL_TMOUT=60, **kwargs): import errno def test_d(pid): try: os.kill(pid, 0) except OSError as err: if err.errno == errno.ESRCH: return False return True args = shlex.split(command) proc = S.Popen(args, **kwargs) timeout = TIMEOUT + 1 while proc.poll() is None and timeout > 0 : time.sleep(1) timeout -= 1 if timeout == 0: print("INFO:Time out period reached. Killing process %d." % (proc.pid,)) if test_d(proc.pid): proc.terminate() time.sleep(KILL_TMOUT) if test_d(proc.pid): proc.kill() time.sleep(KILL_TMOUT) outs, errs = proc.communicate() if test_d(proc.pid): print("INFO:Process %d cound not be kiilled. Please verify manually" % (proc.pid,)) return (9, outs, errs) outs, errs = proc.communicate() return (proc.returncode, outs, errs) #Os hands on import os, os.path, sys, subprocess as S, time, datetime as D, shlex direct_environ = dict(HOST=os.uname()[1], DT=D.datetime.today().strftime("%m%d%y%H%M%S"), SCRIPT=os.path.splitext(os.path.basename(sys.argv[0]))[0], SCRIPT_PID=str(os.getpid()), OUTDIR=r"/var/adm/aaas", ) #Update, could have called os.environ.update(direct_environ), ensure all are string for k,v in direct_environ.items(): os.environ[str(k)] = str(v) #Add all environs which are dependent on other environs , must after above indirect_environ = dict(LOGFILE=os.path.expandvars(r"$OUTDIR/$SCRIPT.$DT.log")) for k,v in indirect_environ.items(): os.environ[str(k)] = str(v) ##Dumps all environ variable def print_parent_env(): for k,v in os.environ.items(): if k in direct_environ or k in indirect_environ: print(k,'=',v) def print_child_env(): print("Print in subprocess") #both in windows and shell proc = S.Popen("printenv", shell=True, stdout=S.PIPE, stderr=S.STDOUT, universal_newlines=True) outs, errs = proc.communicate(timeout=10) final_keys = direct_environ.keys() | indirect_environ.keys() for line in outs.split(): k,*v = line.split("=") if k in final_keys: print("\t",line) def msglog(text, file=True): import os LOGFILE = os.environ["LOGFILE"] HOST = os.environ["HOST"] DT = os.environ["DT"] line = "%s:%s:%s" % (HOST, DT, os.path.expanduser(os.path.expandvars(text))) if file : with open(LOGFILE, "at") as f : f.writelines([line+"\n"]) print(line) 5. Given a filename and no of breaks, generate that many files with chunks from original file names def breakFiles(file, n, ext_length = 3): import os.path def write(fileName, lst): with open(fileName, "wt") as f: f.writelines(lst) #print(fileName, "written", len(lst)) def sliding(lst, w, s): res = [] n = ((len(lst)-w)/s)+1 for i in range(0, int(n)): start = i*s end = w + s*i res.append(lst[start:end]) #last segment if lst[end:]: res.append(lst[end:]) return res def grouped(lst, n): return sliding(lst, n, n) onlyFileName, ext = file[0: len(file)-ext_length-1], file[len(file)-ext_length:] with open(file, "rt") as f: lines = f.readlines() howmany = len(lines) // n gr = grouped(lines, howmany) if len(gr) > n : #extra last part gr[-2] += gr[-1] del gr[-1] #now len(gr) == n names = [ onlyFileName+str(i)+"."+ext for i in range(1,len(gr)+1)] #print(names, n, len(gr)) for lst, n in zip(gr, names): write(n,lst) breakFiles("../data/WindowsUpdate.log", 3) 5. Concatenate many .txt file into one file def concatenate(*files, out): import os.path def read(fileName): if os.path.exists(fileName): with open(fileName, "rt") as f: lines = f.readlines() return lines with open(out, "wt") as fout: for f in files: if os.path.exists(f): fout.writelines(read(f)) #done 6. Recurively go below a dir and based on filter, dump those files in to single file def print_files(g_dir, out_file, filter_path=r"\.py$"): import re , os, os.path def read(fileName): if os.path.exists(fileName): with open(fileName, "rt") as f: lines = f.readlines() return lines def write(fileName, inf_f, msg=None): header = ("\n\n##->file:%s\n" %(inf_f,)) if not msg else msg with open(fileName, "at") as f: f.writelines([header]) f.writelines(read(inf_f)) #done if not os.path.exists(g_dir): return 1 if os.path.exists(out_file): os.remove(out_file) for root, dirs, files in os.walk(g_dir): in_files = [os.path.join(root, f) for f in files if re.search(filter_path,f)] for f in in_files: write(out_file, f) return 0 print_files(".", "total.py") #Recursion flatten(lst) Flattens the list ie input = [1,2,3, [1,2,3,[3,4],2]] output = [1,2,3,1,2,3,3,4,2] convert(x) Converts like below input = [[[ '(0,1,2)' , '(3,4,5)'], ['(5,6,7)' , '(9,4,2)']]] output = [[[[0,1,2],[3,4,5]],[[5,6,7],[9,4,2]]]] checksum(string) Implement checksum with recursion quicksort(lst) Implement quicksort 1. Take pivot as middle value 2. Take left list which is smaller tha pivot 3. Take right list which is higher than pivot 4. return list which is append of quicksort of left, pivot and quicksort of right binsearch(value, items, low=0, high=None) Items are sorted 1. Get high either given or len of list Get middle pos 2. if items's pos is value, return pos 3. if pos is length of items or high is same as low or pos is low, return not found 4. if items's pos is less than value call binsearch with low=pos+1 and high 5. else call binsearch with low and high=pos def flatten(lst): """ Flattens the list ie input = [1,2,3, [1,2,3,[3,4],2]] output = [1,2,3,1,2,3,3,4,2] """ #Create empty list #take each element from lst # Check the type of element , if list # call flatten(element) and append to empty list # if not # append that element to empty list #return that empty list res = [] for e in lst: if type(e) is list : res += flatten(e) else: res.append(e) return res def convert(x): if isinstance(x, list): return [convert(y) for y in x] else: return [int(y) for y in x.strip('()').split(',')] o = convert(l) def checksum(string): ''' Take two two character(one byte) from above (which are in hex digit ) Convert to int (Hint: use int function with base) Sum all and then find mod with 255, that is your checksum Test with input="ABCDEF1234567890, answer:15" ''' def hexsum(s): return 0 if not s else int(s[0:2], base=16) + hexsum(s[2:]) res = hexsum(string) return res % 255 def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[int(len(arr) / 2)] #or // in Py3.x or in Py2.x if from __future import division left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right) print quicksort([3,6,8,10,1,2,1]) # Prints "[1, 1, 2, 3, 6, 8, 10]" def binary_search(value, items, low=0, high=None): #items are sorted high = len(items) if not high else high pos = (high + low) // 2 #print(low, pos, high) if items[pos] == value: return pos elif pos == len(items) or high == low or pos == low: return False elif items[pos] < value: return binary_search(value, items, pos + 1, high) else: return binary_search(value, items, low, pos) ###DataStructure #ELement description:longitude,latitude,housing_median_age,total_rooms,total_bedrooms,population,households,median_income,median_house_value,ocean_proximity lst = [ "-122.23,37.88,41.0,880.0,129.0,322.0,126.0,8.3252,452600.0,NEAR BAY", "-122.22,37.86,21.0,7099.0,1106.0,2401.0,1138.0,8.3014,358500.0,NEAR BAY", "-122.24,37.85,52.0,1467.0,190.0,496.0,177.0,7.2574,352100.0,NEAR BAY", "-122.25,37.85,52.0,1274.0,235.0,558.0,219.0,5.6431,341300.0,NEAR BAY", "-122.25,37.85,52.0,1627.0,280.0,565.0,259.0,3.8462,342200.0,NEAR BAY", "-122.25,37.85,52.0,919.0,213.0,413.0,193.0,4.0368,269700.0,NEAR BAY", "-122.25,37.84,52.0,2535.0,489.0,1094.0,514.0,3.6591,299200.0,NEAR BAY", "-122.25,37.84,52.0,3104.0,687.0,1157.0,647.0,3.12,241400.0,NEAR BAY", "-122.26,37.84,42.0,2555.0,665.0,1206.0,595.0,2.0804,226700.0,NEAR BAY", "-122.25,37.84,52.0,3549.0,707.0,1551.0,714.0,3.6912,261100.0,NEAR BAY", "-122.26,37.85,52.0,2202.0,434.0,910.0,402.0,3.2031,281500.0,NEAR BAY", "-118.46,34.16,16.0,4590.0,1200.0,2195.0,1139.0,3.8273,334900.0,<1H OCEAN", "-118.47,34.15,7.0,6306.0,1473.0,2381.0,1299.0,4.642,457300.0,<1H OCEAN", "-118.47,34.16,30.0,3823.0,740.0,1449.0,612.0,4.6,392500.0,<1H OCEAN", "-118.47,34.15,43.0,804.0,117.0,267.0,110.0,8.2269,500001.0,<1H OCEAN", "-118.48,34.15,31.0,2536.0,429.0,990.0,424.0,5.4591,495500.0,<1H OCEAN", "-118.48,34.16,30.0,3507.0,536.0,1427.0,525.0,6.7082,500001.0,<1H OCEAN", "-118.48,34.14,31.0,9320.0,1143.0,2980.0,1109.0,10.3599,500001.0,<1H OCEAN", "-118.46,34.14,34.0,5264.0,771.0,1738.0,753.0,8.8115,500001.0,<1H OCEAN", "-118.47,34.14,36.0,2873.0,420.0,850.0,379.0,8.153,500001.0,<1H OCEAN", "-118.47,34.14,34.0,3646.0,610.0,1390.0,607.0,7.629,500001.0,<1H OCEAN", "-118.43,34.14,44.0,1693.0,239.0,498.0,216.0,10.9237,500001.0,<1H OCEAN", "-118.43,34.13,37.0,4400.0,695.0,1521.0,666.0,8.2954,500001.0,<1H OCEAN", "-118.45,34.14,33.0,1741.0,274.0,588.0,267.0,7.9625,490800.0,<1H OCEAN", "-118.35,34.15,52.0,1680.0,238.0,493.0,211.0,9.042,500001.0,<1H OCEAN", "-118.36,34.15,41.0,3545.0,698.0,1221.0,651.0,4.3,500001.0,<1H OCEAN", "-118.36,34.15,34.0,3659.0,921.0,1338.0,835.0,3.6202,366100.0,<1H OCEAN", "-118.37,34.15,23.0,4604.0,1319.0,2391.0,1227.0,3.1373,263100.0,<1H OCEAN", "-117.21,32.85,15.0,2593.0,521.0,901.0,456.0,4.2065,277800.0,NEAR OCEAN", "-117.21,32.85,26.0,2012.0,315.0,872.0,335.0,5.4067,277500.0,NEAR OCEAN", "-117.24,32.83,18.0,3109.0,501.0,949.0,368.0,7.4351,445700.0,NEAR OCEAN", "-117.25,32.82,19.0,5255.0,762.0,1773.0,725.0,7.8013,474000.0,NEAR OCEAN", "-117.25,32.82,23.0,6139.0,826.0,2036.0,807.0,9.5245,500001.0,NEAR OCEAN", "-117.26,32.83,24.0,1663.0,199.0,578.0,187.0,10.7721,500001.0,NEAR OCEAN", "-117.26,32.82,34.0,5846.0,785.0,1817.0,747.0,8.496,500001.0,NEAR OCEAN", "-117.27,32.83,35.0,1420.0,193.0,469.0,177.0,8.0639,500001.0,NEAR OCEAN", "-117.29,32.92,25.0,2355.0,381.0,823.0,358.0,6.8322,500001.0,NEAR OCEAN", "-117.25,32.86,30.0,1670.0,219.0,606.0,202.0,12.4429,500001.0,NEAR OCEAN", "-117.25,32.86,25.0,2911.0,533.0,1137.0,499.0,5.1023,500001.0,NEAR OCEAN", "-117.25,32.86,27.0,2530.0,469.0,594.0,326.0,7.2821,500001.0,NEAR OCEAN", "-120.69,37.59,27.0,1170.0,227.0,660.0,222.0,2.3906,81800.0,INLAND", "-120.76,37.61,30.0,816.0,159.0,531.0,147.0,3.2604,87900.0,INLAND", "-120.8,37.61,30.0,918.0,154.0,469.0,139.0,3.9688,175000.0,INLAND", "-120.76,37.58,35.0,1395.0,264.0,756.0,253.0,3.6181,178600.0,INLAND", "-120.83,37.58,30.0,1527.0,256.0,757.0,240.0,3.6629,171400.0,INLAND", "-120.85,37.57,27.0,819.0,157.0,451.0,150.0,3.4934,193800.0,INLAND", "-120.88,37.57,22.0,1440.0,267.0,774.0,249.0,3.9821,204300.0,INLAND", "-120.87,37.62,30.0,455.0,70.0,220.0,69.0,4.8958,142500.0,INLAND", "-120.87,37.6,32.0,4579.0,914.0,2742.0,856.0,2.6619,86200.0,INLAND", "-120.86,37.6,25.0,1178.0,206.0,709.0,214.0,4.5625,133600.0,INLAND"] Q1: Find unique value for 'ocean_proximity' Hint: split each element with , to get list Take the last value of above split and collect into list then convert to ? data structure ( can you identify the data structure?) #Note: .. means similar structure or values from above list res = [] for e in lst: res.append(e.split(",")[-1]) >>> set(res) {'<1H OCEAN', 'NEAR BAY', 'NEAR OCEAN', 'INLAND'} Q2: Create a list of dict with each dict as below {'housing_median_age': .. , 'total_bedrooms' :.., 'median_income':.. ,'median_house_value':..,'ocean_proximity':.. } required = { 'housing_median_age' :float,'total_bedrooms':float , 'median_income' :float,'median_house_value':float,'ocean_proximity':str} h = "longitude,latitude,housing_median_age,total_rooms,total_bedrooms,population,households,median_income,median_house_value,ocean_proximity" headers = {} for k,v in enumerate(h.split(',')): headers[v] = k output = [] for e in lst: d = {} for re,fn in required.items(): d[re] = fn(e.split(',')[headers[re]]) output.append(d) #OR required = { 'housing_median_age' :float,'total_bedrooms':float , 'median_income' :float,'median_house_value':float,'ocean_proximity':str} h = "longitude,latitude,housing_median_age,total_rooms,total_bedrooms,population,households,median_income,median_house_value,ocean_proximity" headers = {v:k for k,v in enumerate(h.split(','))} output = [{re: fn(e.split(',')[headers[re]]) for re,fn in required.items()} for e in lst] Q3: Create a dict where values are list of each column ie {'housing_median_age':[..,..,...] , 'total_bedrooms' :[..,..,...], 'median_income':[..,..,...] ,'median_house_value':[..,..,...],'ocean_proximity':[..,..,...] } #output=list of dict or each row, from above q3output = {'median_house_value': [], 'median_income': [], 'total_bedrooms': [], 'housing_median_age': [], 'ocean_proximity': []} for e in output: for k,v in e.items(): q3output[k].append(v) #OR #output from above q3output = {} for e in output: for k,v in e.items(): if k not in q3output: q3output[k] = [v] else: q3output[k].append(v) Q4: Create dict with key as unique value of 'ocean_proximity' as below {'INLAND' :{'housing_median_age':[..,..,...] , 'total_bedrooms' :[..,..,...], 'median_income':[..,..,...] ,'median_house_value':[..,..,...]} , '<1H OCEAN':{..} , 'NEAR OCEAN':{..}, 'NEAR BAY':{..}} #output=list of dict or each row, from above , don't use q3output q4output = {} for e in output: key = e['ocean_proximity'] if key not in q4output: q4output[key] = {} for k,v in e.items(): if k != 'ocean_proximity': if k not in q4output[key]: q4output[key][k] = [v] else: q4output[key][k].append(v) Q5: Create a dict of {'INLAND' :{'max':{'housing_median_age':maxvalue , 'total_bedrooms' :maxvalue}, 'sum':{'housing_median_age':sumvalue , 'total_bedrooms' :sumvalue}} '<1H OCEAN':{..} , 'NEAR OCEAN':{..}, 'NEAR BAY':{..}} #q4output=dict of ocean_proximity and value is dict of housing_median_age,... from above q5output = {} for ocean, another_dict in q4output.items(): if ocean not in q5output: q5output[ocean] = {'max':{}, 'sum':{}} for k,v in another_dict.items(): q5output[ocean]['max'][k] = max(v) q5output[ocean]['sum'][k] = sum(v) {'<1H OCEAN': {'max': {'housing_median_age': 52.0, 'median_house_value': 500001.0, 'median_income': 10.9237, 'total_bedrooms': 1473.0}, 'sum': {'housing_median_age': 556.0, 'median_house_value': 7800210.0, 'median_income': 115.698, 'total_bedrooms': 11823.0}}, 'INLAND': {'max': {'housing_median_age': 35.0, 'median_house_value': 204300.0, 'median_income': 4.8958, 'total_bedrooms': 914.0}, 'sum': {'housing_median_age': 288.0, 'median_house_value': 1455100.0, 'median_income': 36.4965, 'total_bedrooms': 2674.0}}, 'NEAR BAY': {'max': {'housing_median_age': 52.0, 'median_house_value': 452600.0, 'median_income': 8.3252, 'total_bedrooms': 1106.0}, 'sum': {'housing_median_age': 520.0, 'median_house_value': 3426300.0, 'median_income': 53.1639, 'total_bedrooms': 5135.0}}, 'NEAR OCEAN': {'max': {'housing_median_age': 35.0, 'median_house_value': 500001.0, 'median_income': 12.4429, 'total_bedrooms': 826.0}, 'sum': {'housing_median_age': 301.0, 'median_house_value': 5475008.0, 'median_income': 93.3656, 'total_bedrooms': 5704.0}}} # actual = {'<1H OCEAN': {'max': {'housing_median_age': 52.0, 'total_bedrooms': 1473.0}, 'sum': {'housing_median_age': 556.0, 'total_bedrooms': 11823.0}}, 'INLAND': {'max': {'housing_median_age': 35.0, 'total_bedrooms': 914.0}, 'sum': {'housing_median_age': 288.0, 'total_bedrooms': 2674.0}}, 'NEAR BAY': {'max': {'housing_median_age': 52.0, 'total_bedrooms': 1106.0}, 'sum': {'housing_median_age': 520.0, 'total_bedrooms': 5135.0}}, 'NEAR OCEAN': {'max': {'housing_median_age': 35.0, 'total_bedrooms': 826.0}, 'sum': {'housing_median_age': 301.0, 'total_bedrooms': 5704.0}}} {'<1H OCEAN': {'max': {'housing_median_age': 52.0, 'total_bedrooms': 1473.0}, 'sum': {'housing_median_age': 556.0, 'total_bedrooms': 11823.0}}, 'INLAND': {'max': {'housing_median_age': 35.0, 'total_bedrooms': 914.0}, 'sum': {'housing_median_age': 288.0, 'total_bedrooms': 2674.0}}, 'NEAR BAY': {'max': {'housing_median_age': 52.0, 'total_bedrooms': 1106.0}, 'sum': {'housing_median_age': 520.0, 'total_bedrooms': 5135.0}}, 'NEAR OCEAN': {'max': {'housing_median_age': 35.0, 'total_bedrooms': 826.0}, 'sum': {'housing_median_age': 301.0, 'total_bedrooms': 5704.0}}} ###Class examples #File(dir) class with getMaxSizeFile() import datetime,re class File: def __init__(self, dir, pattern=r".", dynamic=False): self.dir = dir self.file_dict = None self.refresh = dynamic self.pattern = pattern def _isToBeRead(self): return not self.file_dict or self.refresh def getAllFiles(self): def recurse(root, acc={} ): import os.path, glob lst = [os.path.normpath(f) for f in glob.glob(os.path.join(root, "*"))] acc.update( { f:{'size':os.path.getsize(f), 'mtime': datetime.date.fromtimestamp(os.path.getmtime(f)), 'ctime': datetime.date.fromtimestamp(os.path.getctime(f))} for f in lst if os.path.isfile(f) and re.search(self.pattern,f) } ) [recurse(f, acc) for f in lst if os.path.isdir(f)] return acc if self._isToBeRead(): self.file_dict = recurse(self.dir) def getMaxSizeFile(self, howmany=1): self.getAllFiles() maxnames = sorted(self.file_dict.keys(), key = lambda n: self.file_dict[n]['size'], reverse=True ) return ( [(maxnames[i],self.file_dict[maxnames[i]]['size']) for i in range(howmany)] ) def getLatestFiles(self, after=datetime.date.today()-datetime.timedelta(days=7)): """ after : datetime.date(year, month, day)""" self.getAllFiles() return [ f for f in self.file_dict if self.file_dict[f]['mtime'] >= after or self.file_dict[f]['ctime'] >= after ] #Poly import re class Poly: def __init__(self, *args): # an, an-1, ...., a0 self.a = { "a" + str(arg[0]) : arg[1] for arg in list(enumerate(args[::-1])) } #degree = max n , #of elements = degree + 1 self.degree = len(args)-1 def to_array(self): #print(self.a) res = [ self.a.setdefault("a" + str(count), 0) for count in range(0, self.degree+1)] res.reverse() return res def __str__(self): arr = self.to_array(); #print(arr) res = "".join( [ ("-" if v[1] < 0 else "+" ) + str(abs(v[1])) + "x^" + str(v[0]) for v in list(enumerate(arr[::-1]))[::-1] ]) #print(res) #re.sub(pattern, repl, string) res = res[0:-3] #chop last x^0 res = re.sub('(\+|\-)0x\^\d', '', res) # +0x^2 res = re.sub('(\+|\-)1(\.0)*x\^', 'x^', res) # +1x res = re.sub('x\^1', 'x', res) #^1 res = re.sub('^\+', '', res) #beginning + res = re.sub('(\+|\-)0(\.0)*$', '', res) #last +0 return res def expand(self, newdeg): #in place op if newdeg <= self.degree: return curdeg = self.degree + 1 for i in range(curdeg, newdeg+1): self.a["a" + str(i)] = 0 self.degree = newdeg def __add__ (self, other): in1 = self.to_array() #an is 0th element #if constant if type(other) is int : in1[0] += other elif type(other) is float: in1[0] += other else: other.expand( self.degree ) if self.degree > other.degree else self.expand(other.degree) o = other.to_array() in1 = self.to_array() for i in range(0, self.degree + 1): in1[i] += o[i] #an is 0th element return Poly(*in1) def __sub__ (self, other): in1 = self.to_array() #an is 0th element #if constant if type(other) is int : in1[0] -= other elif type(other) is float: in1[0] -= other else: other.expand( self.degree ) if self.degree > other.degree else self.expand(other.degree) o = other.to_array() in1 = self.to_array() for i in range(0, self.degree + 1): in1[i] -= o[i] #an is 0th element return Poly(*in1) def evaluate(self, x): result = 0 for ele in self.to_array(): result = result * x + ele return result def derivative(self): in1 = self.to_array() in1.pop() if len(in1) == 0: return Poly(0) deg = self.degree in2 = [] for i in range(0, deg): in2.append(in1[i] * deg ) #an is 0th element deg -= 1 return Poly(*in2) def __mul__(self, other): in1 = self.to_array() #an is 0th element #if constant if type(other) is int : in1 = [ ele * other for ele in in1] elif type(other) is float: in1 = [ ele * other for ele in in1] else: res = [ 0 for i in range(0, self.degree + other.degree +1) ] in1 = self.to_array() o = other.to_array() for i in range(0, self.degree + 1): for j in range(0, other.degree+1): res[i+j] += in1[i] * o[j] in1 = res.copy() return Poly(*in1) def __truediv__(self, other): in1 = self.to_array() #an is 0th element #if constant if type(other) is int : in1 = [ ele / other for ele in in1] return Poly(*in1) elif type(other) is float: in1 = [ ele / other for ele in in1] return Poly(*in1) else: n = self.to_array() rd = other.to_array() gd = len(rd) q = [] #print(q, n) if len(n) >= gd : while len(n) >= gd : piv = n[0]/rd[0] q.append(piv) for i in range(0, min(len(n), gd)): n[i] -= rd[i] * piv n = n[1:] #print(Poly(*q), Poly(*n), piv) return [ Poly(*q), Poly(*n) ] return [ Poly(0), Poly(*n) ]; px = Poly( 2, 1,1) print(px) qx = Poly( 3, 1,-1) print(qx) cx = px + qx print(cx) cx = qx - px print(cx) print(px.evaluate(1)) print(px.derivative()) px = Poly( 1,1) qx = Poly( 1,-1) cx = px * qx print(cx) px = Poly( 1,1) qx = Poly(1,0,-1) print(qx) print(px) cx = qx / px print("Q= %s R=%s" % (cx[0],cx[1])) Design a mixin class LoggingMixin to be used as class MyClass(LoggingMixin): def somefunction....... self.log(msg, *args, **kwargs) class LoggingMixin: def log(self, msg, *args, **kwargs): logs to a file and console together get all configuration from calling below methods loggerName = getLoggerName isFileLevelLoggingOn fileName = getLogFileName fileLogLevel = getFileLogLevel fileFormatter = getFileFormatter isConsoleLevelLoggingOn consoleLogLevel = getConsoleLogLevel consoleFormatter = getConsoleFormatter these methods can be overridden by derived class if not overriddern, then use resonable default #Ans import logging class LoggingMixin(object): logger = None curLevel = None def setCurrentLoggingLevel(self, lvl=None): self.curLevel = lvl def getCurrentLoggingLevel(self): return logging.WARNING if self.curLevel is None else self.curLevel def isFileLevelLoggingRequired(self): return True def isConsoleLevelLoggingRequired(self): return True def getLogFileName(self): return self.__class__.__name__ + ".log" def getFileLogLevel(self): return logging.WARNING def getFileFormatter(self): logFormatter = logging.Formatter("%(asctime)s [%(threadName)s] [%(levelname)s] %(message)s") return logFormatter def getConsoleLogLevel(self): return self.getFileLogLevel() def getConsoleFormatter(self): return self.getFileFormatter() def forceRoot(self): return False def getLoggerName(self): if self.forceRoot(): return None return self.__class__.__name__ def _config(self): fOn = self.isFileLevelLoggingRequired() cOn = self.isConsoleLevelLoggingRequired() fn = self.getLogFileName() fl = self.getFileLogLevel() ff = self.getFileFormatter() cl = self.getConsoleLogLevel() cf = self.getConsoleFormatter() ln = self.getLoggerName() _logger = logging.getLogger(ln) #check whether we need to update class varible or not if LoggingMixin.logger is None: LoggingMixin.logger = _logger elif LoggingMixin.logger is not _logger: self.logger = _logger else: return #file if fOn: self.fileHandler = logging.FileHandler(fn) self.fileHandler.setFormatter(ff) self.fileHandler.setLevel(fl) self.logger.addHandler(self.fileHandler) #console if cOn: self.consoleHandler = logging.StreamHandler() self.consoleHandler.setFormatter(cf) self.consoleHandler.setLevel(cl) self.logger.addHandler(self.consoleHandler) #done def log(self, msg, *args, **kwargs): lvl = self.getCurrentLoggingLevel() self._config() res = self.logger.log(lvl, msg, *args, **kwargs) return res class SomeClass(LoggingMixin): def test(self): self.log('%s before you %s', 'Look', 'leap!') ##Create a Subprocess Class which have following methods a = Subprocess(command) a.exitcode(timeout=None) a.stdout(timeout=None) a.stderr(timeout=None) a.pipeTo(rhs_command) -> returns a new Subprocess of the result a.redirectTo(fileName, timeout=None) a.get_pattern(pattern, timeout=None, isout=True) -> gets pattern from stdout if isout=True else from stderr Note there must be internal method _execute(timeout=None) which does the actual work and sets a internal flag executed=True all other methods calls execute(..) based on this flag and then returns required value import subprocess as S class Subprocess(object): def __init__(self, command, wait_after_kill=60): self.command = command self.executed = False self.proc = None self.wait_after_kill = wait_after_kill def _execute(self, timeout=None, stdin=None, stdout=S.PIPE, stderr=S.PIPE, bufsize=-1, pipeFlag=False): import time if self.executed: return "Already executed, Create again" self.proc = S.Popen(self.command, bufsize=bufsize, shell=True, stdin=stdin, stdout=stdout, stderr=stderr, universal_newlines=True) if pipeFlag: return None #other process must drain stdout tmout = timeout if timeout is not None else 9999 #very big number while tmout > 0 and self.proc.poll() is None: time.sleep(1) tmout -= 1 if tmout == 0: #timeout case self.proc.terminate() time.sleep(self.wait_after_kill) if self.proc.poll() is None: self.proc.kill() time.sleep(self.wait_after_kill) self._exitcode = -9 else: self.executed = True self._exitcode = self.proc.returncode self._out, self._err = self.proc.communicate() return None def exitcode(self, timeout=None): self._execute(timeout) return self._exitcode def stdout(self, timeout=None): self._execute(timeout) return self._out def stderr(self, timeout=None): self._execute(timeout) return self._err def redirectTo(self, fileName, timeout=None): with open(fileName, "wt") as f: self._execute(timeout, stdout=f, stderr=S.STDOUT) return self._exitcode def pipeTo(self, rhs_command, timeout=None): self._execute(timeout, stdout=S.PIPE, stderr=S.STDOUT, pipeFlag=True) proc2 = Subprocess(rhs_command) proc2._execute(timeout, stdin=self.proc.stdout) self.proc.stdout.close() return proc2 def get_pattern(self, pattern, timeout=None, isout=True): import re self._execute(timeout) if isout: res = re.findall(pattern, self._out) else: res = re.findall(pattern, self._err) return res #Testing command = "nslookup www.google.com" file= "out.txt" pattern = r"Address: (.+?)\n\n" pattern2 = r"Addresses:\s+((.+)\n\t\s*(.+)\n\n)" command1 = "type out.txt" command2 = 'findstr /c:"Server"' a = Subprocess(command) a.exitcode() a.stdout() a.stderr() #timeout case a = Subprocess(command) a.exitcode(1) a.stdout(1) a.stderr(1) #others a = Subprocess(command) a.redirectTo(file) #others a = Subprocess(command1) b = a.pipeTo(command2) b.exitcode() b.stdout() b.stderr() #others a = Subprocess(command) a.get_pattern(pattern) ##Asynchronous Subprocess import asyncio, sys import asyncio.subprocess class AsyncSubprocess(object): def __init__(self, **commands): self.procs = {} for k, v in commands.items(): self.procs[k] = {'command':v } #Create loop, on windows , subproces is supported only in ProactorEventLoop if sys.platform == "win32": self.loop = asyncio.ProactorEventLoop() #asyncio.set_event_loop(self.loop) else: self.loop = asyncio.get_event_loop() async def run(self, key): proc = await asyncio.create_subprocess_shell( self.procs[key]['command'], stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, loop=self.loop) stdout, stderr = await proc.communicate() self.procs[key]['exitcode'] = proc.returncode self.procs[key]['stdout'] = stdout.decode() self.procs[key]['stderr'] = stderr.decode() return key def get_all_results(self): result = self.loop.run_until_complete(asyncio.gather(*[self.run(key) for key in self.procs], loop=self.loop)) self.loop.close() return self.procs def get_next_result(self): coros = [self.run(key) for key in self.procs] # get commands output concurrently for f in asyncio.as_completed(coros, loop=self.loop): # f is future key = self.loop.run_until_complete(f) yield {key: self.procs[key]} self.loop.close() #Testing a = AsyncSubprocess(c1=command, c2=command, c3=command) >>> a.get_all_results() {'c1': {'exitcode': 0, 'command': 'nslookup www.google.com', 'stderr': '', 'stdout': 'Server:\t\t218.248.112.1\nAddress:\t218.248.112.1#53\n\nNon-authoritativeanswer:\nName:\twww.google.com\nAddress: 172.217.163.68\n\n'}, 'c3': {'exitcode': 0, 'command': 'nslookup www.google.com', 'stderr': '', 'stdout': 'Server:\t\t218.248.112.1\nAddress:\t218.248.112.1#53\n\nNon-authoritative answer:\nName:\twww.google.com\nAddress: 172.217.163.68\n\n'}, 'c2': {'exitcode': 0, 'command': 'nslookup www.google.com', 'stderr': '', 'stdout': 'Server:\t\t218.248.112.1\nAddress:\t218.248.112.1#53\n\nNon-authoritative answer:\nName:\twww.google.com\nAddress: 172.217.163.68\n\n'}} a = AsyncSubprocess(c1=command, c2=command, c3=command) i = iter(a.get_next_result()) >>> next(i) {'c3': {'exitcode': 0, 'command': 'nslookup www.google.com', 'stderr': '', 'stdout': 'Server:\t\t218.248.112.1\nAddress:\t218.248.112.1#53\n\nNon-authoritativeanswer:\nName:\twww.google.com\nAddress: 172.217.163.68\n\n'}} >>> next(i) {'c1': {'exitcode': 0, 'command': 'nslookup www.google.com', 'stderr': '', 'stdout': 'Server:\t\t218.248.112.1\nAddress:\t218.248.112.1#53\n\nNon-authoritativeanswer:\nName:\twww.google.com\nAddress: 172.217.163.68\n\n'}} >>> next(i) {'c2': {'exitcode': 0, 'command': 'nslookup www.google.com', 'stderr': '', 'stdout': 'Server:\t\t218.248.112.1\nAddress:\t218.248.112.1#53\n\nNon-authoritativeanswer:\nName:\twww.google.com\nAddress: 172.217.163.68\n\n'}} >>> next(i) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration ###Decorators hands ON import time from functools import wraps def mea(f): @wraps(f) def _inner(*args, **kargs): s = time.time() res = f(*args, **kargs) e = time.time() print("Time, taken by",f.__name__, e-s ) return res return _inner def trace(f): @wraps(f) def _inner(*args, **kargs): print("Entering", f.__name__) res = f(*args, **kargs) print("Exiting", f.__name__) return res return _inner ###Yield hands on #open WindowsUpdate.log, Send all WARNING one by one def getWarning(filename): f = open(filename, "rt") sp=r"(\d\d\d\d-\d\d-\d\d)\s+.+?WARNING" for line in f : s = re.findall(sp, line) if not s: continue else: yield s[0] f.close() #Usage g = getWarning(r"D:\PPT\python\initial-reference\data\WindowsUpdate.log") i = iter(g) print(next(i)) import itertools print(list(itertools.islice(i,20))) ### DB import csv with open(r"..\data\iris.csv", "rt") as f: rd = csv.reader(f) rows = list(rd) rowsd = [] for sl, sw, pl, pw, n in rows[1:]: rowsd.append([float(sl), float(sw), float(pl), float(pw),n]) #manual group by unique = {row[-1] for row in rowsd} d = { name:[row[0] for row in rowsd if row[-1] == name] for name in unique } {n:{'max':max(lst)} for n,lst in d.items()} #db group by from sqlite3 import connect con = connect(r"iris.db") cur = con.cursor() cur.execute("create table iris (sl double, sw double, pl double, pw double, name string)") for row in rowsd: s = cur.execute("insert into iris values (?,?,?,?,?)",row) con.commit() q = cur.execute("select name, max(sl) from iris group by name order by name") result= list(q.fetchall()) result #ris-virginica', 7.9), ('Iris-versicolor', 7.0), ('Iris-setosa', 5.8)] con.close() ###Requests with beautifulSoup from bs4 import BeautifulSoup import requests r = requests.get("http://www.yahoo.com") data = r.text soup = BeautifulSoup(data, 'html.parser') soup.get_text() for link in soup.find_all('a'): # tag <a href=".." print(link.get('href')) # Attribute href ###Requests module to send json data and get json data - httpbin.org/get /post import json, requests data = {'username': 'xyz'} headers = {'Content-Type': 'application/json'} r = requests.post("http://httpbin.org/post", data=json.dumps(data), headers=headers) r.json() #GET payload = {'key1': 'value1', 'key2': 'value2'} r = requests.get("http://httpbin.org/get", params=payload) print(r.url) #http://httpbin.org/get?key2=value2&key1=value1 r.headers r.text #With proxies #ofr socks, check http://docs.python-requests.org/en/master/user/advanced/#socks #update username, proxyaddress, port #password is taken from commandline proxies = { 'http': 'http://username:%s@proxyAddress:port', 'https': 'https://username:%s@proxyAddress:port', } #above is equivalent to #set http_proxy=http://username:password@proxyAddress:port #set https_proxy=https://username:password@proxyAddress:port import getpass p = getpass.getpass() #update proxies proxies = {k: v % (p,) for k,v in proxies.items()} requests.get('http://example.org', proxies=proxies) ##Verbose logging import requests import logging # for Python 3 from http.client import HTTPConnection #for python 2 #from httplib import HTTPConnection HTTPConnection.debuglevel = 1 logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True requests.get('https://httpbin.org/headers') ##FUrther r = requests.get('https://api.github.com', auth=('user', 'pass')) #r is a response, with attributes r.request.allow_redirects r.request.headers r.request.response r.request.auth r.request.hooks r.request.send r.request.cert r.request.method r.request.sent r.request.config r.request.params r.request.session r.request.cookies r.request.path_url r.request.timeout r.request.data r.request.prefetch r.request.url r.request.deregister_hook r.request.proxies r.request.verify r.request.files r.request.redirect r.request.full_url r.request.register_hook #r.request.headers gives the headers: {'Accept': '*/*', 'Accept-Encoding': 'identity, deflate, compress, gzip', 'Authorization': u'Basic dXNlcjpwYXNz', 'User-Agent': 'python-requests/0.12.1'} #Then r.request.data has the body as a mapping. #To convert this with urllib.urlencode if they prefer: import urllib b = r.request.data encoded_body = urllib.urlencode(b) ###Introduction to function and Flask framework to send json output #rest.py from flask import Flask, request, jsonify import json app = Flask(__name__) @app.route("/") def home(): return """ <html><body><h1>Hello there!!!</h1></body></html> """ @app.route("/json", methods=["POST"]) def json1(): with open(r"D:\PPT\python\initial-reference\data\example.json", "rt") as f : obj = json.load(f) resp = jsonify(obj) resp.status_code = 200 return resp @app.route('/index', methods=['POST']) def index(): user = { 'username': 'Nobody'} if 'Content-Type' in request.headers and request.headers['Content-Type'] == 'application/json': user['username'] = request.json['username'] resp = jsonify(user) resp.status_code = 200 return resp if __name__ == '__main__': app.run() #with gevent as server from gevent.pywsgi import WSGIServer from rest import app http_server = WSGIServer(('127.0.0.1', 5000), app) http_server.serve_forever() #Usage $ curl -v -H "Content-Type:application/json" -X POST http://127.0.0.1:5000/index -d "{\"username\":\"Das\"}" import requests import json user={'username': 'Das'} headers= {'Content-Type':"application/json"} r = requests.post("http://127.0.0.1:5000/index", data=json.dumps(user), headers=headers) >>> r.json() {'username': 'Das'} >>> import subprocess >>> import shlex >>> args = shlex.split(r'curl -v -H "Content-Type:application/json" -X POST http://127.0.0.1:5000/index -d "{\"username\":\"Das\"}"') >>> args ['curl', '-v', '-H', 'Content-Type:application/json', '-X', 'POST', 'http://127.0.0.1:5000/index', '-d', '{"username":"Das"}'] obj = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,universal_newlines=True) >>> obj.stdout.read() '{\n "username": "Das"\n}\n' >>> obj.stderr.read() ###Modules and doc test def square(x): """First function square >>> square(10) 100 >>> square(0) 0 """ z = x*x return z if __name__ == '__main__': import doctest doctest.testmod() ###Pytest of MyInt with mocking #pytest.ini [pytest] markers = addl: Addl testcases #conftest.py from pkg.MyInt import MyInt import pytest @pytest.fixture(scope='module') def one(request): a = MyInt(1) yield a print("shutdown code") ''' $ python -m pytest -v first_test.py #To see all builtin fixtures $ pytest --fixtures #default fixture #cache, capsys,capfd,doctest_namespace,pytestconfig,record_xml_property,monkeypatch,recwarn,tmpdir_factory,tmpdir #check default markers pytest --markers #For running marker pytest -v -m addl pytest -v -m "not addl" ''' #test_myint.py from pkg.MyInt import MyInt import pytest class TestMyInt: def test_add(self): a = MyInt(2) b = MyInt(3) assert a+b == MyInt(5) @pytest.mark.addl def test_sub(one): assert one - one == MyInt(0) #table tests def process(a,op,b): if op == '+': return a+b if op == '==': return a == b if op == '-' : return a - b #pytest -v -k "sub" test_myint.py #pytest -v -k "not sub" test_myint.py #pytest -v -k "sub and Test" test_myint.py #pytest -v -k "sub or add" test_myint.py #pytest --collect-only test_myint.py #pytest -v test_myint.py::test_sub @pytest.mark.parametrize("a,op,b,op2,result",[ (MyInt(1) , '+' ,MyInt(2), '==', MyInt(3)), pytest.param(MyInt(2),'-',MyInt(1),'==',MyInt(1), marks=pytest.mark.addl), ], ids=["Testing add2", "Testing sub2"] ) def testMany(a,op,b,op2,result): assert process(process(a,op,b),op2,result) import pkg.MyInt def test_add_monkey(request, monkeypatch): def myint(a): print("Patching") return a monkeypatch.setattr(pkg.MyInt, "MyInt", myint) assert pkg.MyInt.MyInt(2) + pkg.MyInt.MyInt(2) == pkg.MyInt.MyInt(4) ###Group_by with functions B. boston.csv :Attribute Information (in order): - CRIM per capita crime rate by town - ZN proportion of residential land zoned for lots over 25,000 sq.ft. - INDUS proportion of non-retail business acres per town - CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) - NOX nitric oxides concentration (parts per 10 million) - RM average number of rooms per dwelling - AGE proportion of owner-occupied units built prior to 1940 - DIS weighted distances to five Boston employment centres - RAD index of accessibility to radial highways - TAX full-value property-tax rate per $10,000 - PTRATIO pupil-teacher ratio by town - B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town - LSTAT % lower status of the population - MEDV Median value of owner-occupied homes in $1000s "crim", "zn", "indus", "chas", "nox", "rm", "age", "dis", "rad", "tax", "ptratio", "b", "lstat","medv" 0.00632, 18, 2.31, "0", 0.538, 6.575, 65.2, 4.09, 1, 296, 15.3, 396.9, 4.98, 24 1. read data in boston rows = read_csv(r"D:\Desktop\PPT\python\initial-reference\data\boston.csv") 2. Create a new column crimxmedv = crim X medv headers = rows[0] data = rows[1:] def get_col(key, row, headers=[]): hs = {h:i for i,h in enumerate(headers)} #print(key, row, headers) def get(k): #print(len(row), k, hs[k]) if type(k) is int: return row[k] elif type(k) is str: return row[hs[k]] else: return None g = get(key) if g != None : return g elif type(key) is tuple or type(key) is list: return tuple([ get(i) for i in key]) def withColumn(hs, data, colName, opp_fn , *cols): from copy import deepcopy new_data = deepcopy(data) headers = deepcopy(hs) headers.append(colName) for i,row in enumerate(data): value = opp_fn(*get_col(cols,row,hs)) new_data[i].append(value) return (headers, new_data) #test from functools import partial bcol = partial(get_col, headers=headers) bcol(["crim", "medv"], data[0]) #ans headers, data = withColumn(headers,data, "crimxdev", lambda a,b :a*b, "crim", "medv") 3. select columns crimxmedv , tax s_data = [get_col(["crimxdev","tax"], row, headers) for row in data] 4. what is the max value of crim crim_max = max([get_col("crim", row, headers) for row in data]) 5. what is max value of medv medv_max = max([get_col("medv", row, headers) for row in data]) 5. select rows of crim where medv is max crim_mdev = [get_col(["crim", "medv"], row, headers) for row in data] [ r[0] for r in crim_mdev if r[-1] == medv_max] 6. select rows of medv where crim is max [ r[-1] for r in crim_mdev if r[0] == crim_max] 7. how many unique value in chas and rad un = {get_col("chas", row, headers) for row in data} {get_col("rad", row, headers) for row in data} 8. what is max and min value of medv for each chas g_data = group_by(data, lambda row: get_col("chas", row, headers)) agg(g_data, dict(max=max,min=min)) #OR medv_chas = [get_col(["medv", "chas"], row, headers) for row in data] g_data = group_by(medv_chas, lambda row: row[-1]) agg(g_data, dict(max=max,min=min)) 9. put crimxmedv and tax in csv s_data = [get_col(["crimxdev","tax"], row, headers) for row in data] write_csv("process.csv", s_data, ["crimxdev","tax"]) C. windows.csv 1.read csv file 2. extract each column and then 'cast' to correct type with name eventTime,deviceId,signal col1 - timestamp, column2 - string, column3-int rows = read_csv(r"D:\Desktop\PPT\python\initial-reference\data\window.csv",dates=0) 4. group by deviceId and collect all signals into a list 'signals' headers = rows[0] data = rows[1:] g_data = group_by(data, lambda row: row[1]) n_headers = ["deviceId", "signals"] rows = [[k,[e[-1] for e in lst]] for k,lst in g_data.items()] #another group by with deviceId and minute g_data = group_by(data, lambda row: (row[1], row[0].minute)) {k:len(lst) for k,lst in g_data.items()} n_headers = ["deviceId", "signals"] rows = [[k,[e[-1] for e in lst]] for k,lst in g_data.items()] 4. select deviceId,signals, it's size and dump into csv file ' n_headers.append("size") rows = [[d,s,len(s)] for d,s in rows] write_csv("process1.csv", rows,n_headers) 5. Create 5 minutes tumbling window and create bins from min to max time Assign each to correct window def time_window(mn, mx, size): res = [] td = (mx - mn)/size start = mn while start < mx : res.append((start, start+size)) start = start + size #append last one res.append((start, start+size)) return res def find(dt, windows): for i, win in enumerate(windows): if dt >= win[0] and dt < win[1]: break return windows[i] min_t = min([r[0] for r in data]) max_t = max([r[0] for r in data]) #timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) import datetime size = datetime.timedelta(minutes=5) wns = time_window(min_t, max_t, size) headers, data = withColumn(headers,data, "window", lambda w : find(w,wns), "eventTime") g_data = group_by(data, lambda row: get_col(["deviceId","window"], row, headers)) g_data.keys() {k:len(lst) for k,lst in g_data.items()} {(k1, e-s):len(lst) for (k1,(s,e)),lst in g_data.items()} rows = [[k,[e[-2] for e in lst]] for k,lst in g_data.items()] n_headers = headers + ["size"] rows = [[d,s,len(s)] for d,s in rows] write_csv("process2.csv", rows,n_headers) ###SortyBy example #Given a dir, find out the file name which is of max file size recursively import functools import os.path import glob def createdirlist(root, acc={} ): import os.path import glob lst = [os.path.normpath(f) for f in glob.glob(os.path.join(root, "*"))] acc.update( { f:os.path.getsize(f) for f in lst if os.path.isfile(f) } ) [createdirlist(f, acc) for f in lst if os.path.isdir(f)] return acc d = createdirlist(".") maxnames = sorted(d.keys(), key = lambda n: d[n], reverse=True ) print([maxnames[0], d[maxnames[0]]]) ###Sortby example -population.csv #Country Name,Country Code,Year,Value,Country rows = read_csv(r"D:\Desktop\PPT\python\initial-reference\data\population.csv") headers = rows[0] data = rows[1:] 1. which country has the max population during 2008 countries = [ (row[0], row[-2]) for row in data if row[-1] == "Yes" and row[-3]== 2008] sorted(countries, key = lambda t: t[-1])[-1] 2. what is the total population of "World" during 2008 world_2008 = [ (row[0], row[-2]) for row in data if row[0] == "World" and row[-3]== 2008] 3. which year is the max jump in "World" population worlds = [ (row[0], row[-2], row[-3]) for row in data if row[0] == "World"] #get it sorted with year w_s = sorted(worlds, key=lambda t: t[-1]) w_s_d = [ (n1,v1,v2,y1,y2,v2-v1) for (n1,v1,y1),(n2,v2,y2) in zip(w_s, w_s[1:])] #first two sorted(w_s_d, key=lambda t: t[-1])[-1:-3:-1] 4. During 2008, which of "Low Income", "Middle Income" and "High Income" has max jump in population keys = ("Low income", "Middle income" , "High income") years = (2007, 2008) rows = [ (row[0], row[-2], row[-3]) for row in data if row[0] in keys and row[-3] in years] #sort based year and country name sr = sorted(rows, key=lambda t: (t[0], t[-1])) # f_sr = [ (n1,n2,v1,v2,y1,y2,v2-v1) for (n1,v1,y1),(n2,v2,y2) in zip( sr[::2], sr[1::2]) ] sorted(f_sr, key=lambda t : t[-1])[-1] ##More hands on #File Hands on def filecopy(src, dest): """Copy one file to another file src,dest: file name as string returns None """ with open(src, "rb") as s: with open(dest, "wb") as d: d.write(s.read()) #done def filecompare(file1,file2): """Given two files, compare file contents line by line file1,file2 : file name as string returns line number of 2nd file where first difference occurs """ with open(file1, "rt") as f1: with open(file2, "rt") as f2: for index,(l2,l1) in enumerate(zip(f2,f1)): if l2 != l1: return index+1 return -1 def filemerge(one_dir, dest_file, file_filter): """Concatenate many files with file_file_filter under one dir into one file one_dir : given dir name as str dest_file : file name where to copy file_filter = string regex of files to merge returns none """ import os.path, re, glob files = glob.glob(os.path.normpath(one_dir+"/*")) #print(files) only_files = [f for f in files if re.search(file_filter, f)] #print(only_files) def file_copy(file): with open(file, "rb") as s: with open(dest_file, "ab") as d: d.write(s.read()) for f in only_files: file_copy(f) #done def execute_and_return_code(command): """Given command, returns it's exit code""" import subprocess as S , os with open(os.devnull, "w") as DEVNULL: proc = S.Popen(command, shell=True, stdout=DEVNULL, stderr=DEVNULL, universal_newlines=True) proc.wait() return proc.returncode def execute_and_return_output(command): """Given command , returns it's stdout and stderr """ import subprocess as S , os proc = S.Popen(command, shell=True, stdout=S.PIPE, stderr=S.STDOUT, universal_newlines=True) outs, oute = proc.communicate() return outs def execute_and_redirect_to_file(command, filename): """Given command and file name, redirect stdout and stderr to file""" import subprocess as S , os with open(filename, "wt") as f : proc = S.Popen(command, shell=True, stdout=f, stderr=S.STDOUT, universal_newlines=True) proc.wait() return None def execute_with_pipe(command1, command2): """Given two commands, returns output of 2nd command after piping first command""" import subprocess as S , os proc = S.Popen(command1, shell=True, stdout=S.PIPE, stderr=S.STDOUT, universal_newlines=True) proc2 = S.Popen(command2, shell=True, stdin= proc.stdout, stdout=S.PIPE, stderr=S.STDOUT, universal_newlines=True) proc.stdout.close() outs, oute = proc2.communicate() return outs def execute_and_return_pattern_match(command, pattern): """execute the command and the find the pattern in that stdout and return result Use execute_and_return_output(command) function to implement this """ import subprocess as S , os , re outs = execute_and_return_output(command) res = re.findall(pattern, outs) return res def update_env_var(another_dict): """Given another dict of env vars , update to process env vars Note env vars may contain reference to other environment vars in form of $VAR so should expand that before updating Test above function with with below env vars containing below HOST hostname DT todays date(use datetime.datetime) using pattern "%m%d%y%H%M%S" SCRIPT this script name only (without extension) SCRIPT_PID this script pid OUTDIR C:/tmp/adm LOGFILE $OUTDIR/$SCRIPT.$DT.log (in unix expansion of variable ) """ import os , os.path #find $VAR type without_exp = {} with_exp = {} for k, v in another_dict.items(): if '$' in v: with_exp[k] = v else: without_exp[k] = v #update first os.environ.update(without_exp) #then os.environ.update({k:os.path.expandvars(v) for k, v in with_exp.items()}) #done import platform, os , sys, datetime as D d = dict(HOST=platform.uname().node, DT=D.datetime.today().strftime("%m%d%y%H%M%S"), SCRIPT=os.path.splitext(os.path.basename(sys.argv[0]))[0], SCRIPT_PID=str(os.getpid()), OUTDIR=r"/var/adm/aaas", LOGFILE="$OUTDIR/$SCRIPT.$DT.log") def dump_env_var(only_keys): """returns dict of env var of element found in 'only_keys' """ d = {} keys = [k.upper() for k in only_keys] for k,v in os.environ.items(): if k.upper() in only_keys: d[k]=v return d def dump_env_var_in_child(only_keys): """returns dict env var of element found in 'only_keys' in child process""" import sys, subprocess as S , os command = "set" if sys.platform in ["win32"] else "printenv" proc = S.Popen(command, shell=True, stdout=S.PIPE, stderr=S.STDOUT, universal_newlines=True) outs, errs = proc.communicate() d = {} keys = [k.upper() for k in only_keys] for line in outs.splitlines(): ss = line.split("=") if ss[0].upper() in only_keys: d[ss[0]]= ss[1] if ss[1:] else "" return d #recursion def get_all_files(one_dir): """Given a directory one_dir , returns dict of filenames and size including subdirs """ import os.path, glob def createdirlist(root, acc): lst = glob.glob(os.path.normpath(root+"/*")) acc.update( { f:os.path.getsize(f) for f in lst if os.path.isfile(f) } ) [createdirlist(f, acc) for f in lst if os.path.isdir(f)] return acc return createdirlist(one_dir, {}) def get_all_files_after(one_dir, after_datetime): """Given a directory one_dir , returns list of filenames which are modified or created after_datetime recursively """ import os.path, glob , datetime as D def recurFile(root, acc): lst = glob.glob(os.path.normpath(root+"/*")) acc.update( { f:{'ctime': D.datetime.fromtimestamp(os.path.getctime(f)), 'mtime': D.datetime.fromtimestamp(os.path.getmtime(f))} for f in lst if os.path.isfile(f) } ) [recurFile(f, acc) for f in lst if os.path.isdir(f)] return acc def after(d): dtime = D.datetime.strptime(after_datetime, "%Y-%m-%d") if d['mtime'] >= dtime or d['ctime'] >= dtime: return True return False all_files = [f for f, dt in recurFile(one_dir, {}).items() if after(dt)] return all_files def create_hashes_of_all_files_under_one_dir(one_dir): """ Create a .hashes file inside each dir . this file contains all file names of that dir and hash of each file""" import os.path, glob , os , sys def md5(fname): import hashlib hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() def process_one_dir(root, files): with open(os.path.join(root,".hashes"), "wt") as f: for file in files: if os.path.exists(file): f.writelines([os.path.basename(file)+"="+str(md5(file))+"\n"]) lst = glob.glob(os.path.normpath(one_dir+"/*")) process_one_dir(one_dir, [f for f in lst if os.path.isfile(f) ] ) [create_hashes_of_all_files_under_one_dir(f) for f in lst if os.path.isdir(f)] return None ###Aynchronous quick import asyncio, sys import threading, concurrent.futures #in Py2, must do, pip install futures import os.path import functools,time import asyncio.subprocess #Create loop, on windows , subproces is supported only in ProactorEventLoop if sys.platform == "win32": loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(loop) else: loop = asyncio.get_event_loop() executor = concurrent.futures.ThreadPoolExecutor(max_workers=10) loop.set_default_executor(executor) ''' ***** Asyncio primer ******* 1. await can be used inside another async def/coroutine result = await arg A Future, a coroutine or an awaitable, 'arg' is required 2. Inside main process use loop.run_until_complete(future_coroutine) #Example import asyncio import threading, concurrent.futures #in Py2, must do, pip install futures import os.path import functools,time #Create loop, on windows , subproces is supported only in ProactorEventLoop import sys if sys.platform == "win32": loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(loop) else: loop = asyncio.get_event_loop() #simple coroutines async def m2(*args): print("m2") return args[0:1] async def m1(arg1,arg2): #option 1 r1 = await m2(arg1) #blocks, m2 is executed now await asyncio.sleep(1) #option 2 with Task(is a asyncio.Future with cancel()) fut = asyncio.ensure_future(m2(arg2)) fut.add_done_callback(lambda f: print(f.result())) #f= future of m2(arg2) #or r2 = await fut #r2 is direct result await asyncio.sleep(1) #option-3 await with with timeout try: r3 = await asyncio.wait_for(m2(arg2), timeout=None) #any float , None means blocking except asyncio.TimeoutError: print('timeout!') #option-4: wait for many coroutines r4 = await asyncio.gather(m2(2),m2(3)) #r4 is list of result return [r1,r2,r3] #all the above obj in 'await obj' can be passed to 'run_until_complete' #start the events loop r2 = loop.run_until_complete(m1(2,3)) #or a list of many coroutines r2 = loop.run_until_complete(asyncio.gather(m1(2,3), m1(2,3))) #To run non coroutine based function under asyncio #Option-1: with executor executor = concurrent.futures.ThreadPoolExecutor(max_workers=10) loop.set_default_executor(executor) def m3(*args): print("m3", threading.current_thread().getName()) time.sleep(1) return len(args) #r is asyncio.Future r = loop.run_in_executor(None, m3, 2,3 ) #executor=None , means default executor or provide custom axecutor result = loop.run_until_complete(r) #await r inside coroutine #Option-2: with delayed call , can not return result h1 = loop.call_soon(m3, 2,3) h1 = loop.call_later(2, m3, 2,3) #after 2 secs, should not exceed one day. h1 = loop.call_at(loop.time()+3, m3, 2,3) #after 3 sec, should not exceed one day. async def dummy(): await asyncio.sleep(10) #some other thread function calling normal function under asyncio def callback(loop): time.sleep(1) loop.call_soon_threadsafe(m3, 2,3) t = threading.Thread(target=callback, args=(loop,)) t.start() loop.run_until_complete(dummy()) #Synchronization primitives #also has asyncio.Lock asyncio.Event asyncio.Condition asyncio.Semaphore asyncio.BoundedSemaphore #Usage count = 0 async def proc(lck): global count async with lck: print("Got it") lc = count lc += 1 count = lc lock = asyncio.Lock() # asyncio.Semaphore(2) #asyncio.BoundedSemaphore(2) loop.run_until_complete(asyncio.gather(*[proc(lock) for i in range(10)])) #Usage Event async def waiter(event): print('waiting for it ...') await event.wait() print('... got it!') async def main(): # Create an Event object. event = asyncio.Event() # Spawn a Task to wait until 'event' is set. waiter_task = asyncio.ensure_future(waiter(event)) # Sleep for 1 second and set the event. await asyncio.sleep(1) event.set() # Wait until the waiter task is finished. await waiter_task loop.run_until_complete(main()) #Queue #infinte loop async def worker(name,queue): while True: item = await queue.get() #blocks , get_nowait(): does not block, but raises QueueEmpty await asyncio.sleep(1) print("Got",name, item) queue.task_done() async def main(): queue = asyncio.Queue() #maxsize=0 , means infinite tasks = [] [queue.put_nowait(i) for i in range(10)] #does not block raises QueueFull, put():no block for i in range(3): task = asyncio.ensure_future(worker(str(i),queue)) tasks.append(task) await queue.join() # Cancel our worker tasks. for task in tasks: task.cancel() loop.run_until_complete(main()) #Subprocess async def run(cmd): proc = await asyncio.create_subprocess_shell( cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await proc.communicate() print(cmd, 'exited with ',proc.returncode) if stdout: print('[stdout]\n',stdout.decode()) if stderr: print('[stderr]\n',stderr.decode()) return stdout.decode() async def main(urls): coros = [run("nslookup "+ url) for url in urls] #for f in asyncio.as_completed(coros): # print in the order they finish # print(await f) #or return await asyncio.gather(*coros) urls = ["www.google.com", "www.yahoo.com", "www.wikipedia.org"] result = loop.run_until_complete(main(urls)) #aiohttp import aiohttp #asyncio enabled http requests async def get(session, url, *args, **kwargs): async with session.get(url, *args, **kwargs ) as resp: return (await resp.json()) async def post(session, url, *args, **kwargs): async with session.post(url, *args, **kwargs ) as resp: return (await resp.json()) async def download_get(urls, *args, **kwargs): async with aiohttp.ClientSession() as session: results = await asyncio.gather(*[get(session, url, *args, **kwargs) for url in urls]) return results async def download_post(urls, *args, **kwargs): async with aiohttp.ClientSession() as session: results = await asyncio.gather(*[post(session, url, *args, **kwargs) for url in urls]) return results urls1 = ["http://httpbin.org/get" for i in range(10)] urls2 = ["http://httpbin.org/post" for i in range(10)] headers = {'Content-Type': 'application/json'} params = { 'name': 'abc'} data = {'name': 'xyz'} import json rsults = loop.run_until_complete(download_get(urls1, params=params)) rsults = loop.run_until_complete(download_post(urls2, data=json.dumps(params),headers=headers)) loop.stop() ''' @asyncio.coroutine def get_date(): code = 'import datetime; print(datetime.datetime.now())' #python code # Create the subprocess, redirect the standard output into a pipe create = asyncio.create_subprocess_exec(sys.executable, '-c', code, stdout=asyncio.subprocess.PIPE) proc = yield from create # Read one line of output data = yield from proc.stdout.readline() line = data.decode('ascii').rstrip() # Wait for the subprocess exit yield from proc.wait() return line #asyncio.subprocess.DEVNULL, asyncio.subprocess.STDOUT, asyncio.subprocess.PIPE ''' If PIPE is passed to stdin argument, the Process.stdin attribute will point to a StreamWriter instance. If PIPE is passed to stdout or stderr arguments, the Process.stdout and Process.stderr attributes will point to StreamReader instances. class asyncio.StreamReader coroutine read(n=-1) coroutine readline() coroutine readexactly(n) coroutine readuntil(separator=b'\n') at_eof() class asyncio.StreamWriter can_write_eof() write_eof() get_extra_info(name, default=None) write(data) writelines(data) coroutine drain() writer.write(data) await writer.drain() close() is_closing() coroutine wait_closed() ''' async def run(cmd): proc = await asyncio.create_subprocess_shell( cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await proc.communicate() print(cmd, 'exited with ',proc.returncode) if stdout: print('[stdout]\n',stdout.decode()) if stderr: print('[stderr]\n',stderr.decode()) return stdout.decode() #Another way async def get_lines(shell_command): p = await asyncio.create_subprocess_shell(shell_command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT) return (await p.communicate())[0].splitlines() async def main(urls): coros = [run("nslookup "+ url) for url in urls] # get commands output concurrently for f in asyncio.as_completed(coros): # print in the order they finish print("main\n",await f) urls = ["www.google.com", "www.yahoo.com", "www.wikipedia.org"] result = loop.run_until_complete(asyncio.gather(get_date(), main(urls), *[run("nslookup "+ url) for url in urls])) print("Current date: %s" % result[0]) loop.close() #_________________________________________________________________________ 1. Write IMDB Ratings class Given a movie_id , search imdb and get it's ratings Hint: 1. class name Imdb with movie_id as constructor parameter and one method def ratings(source='Internet Movie Database') Source could be 'Internet Movie Database' or 'Metacritic' 2. Use Rest server http://omdbapi.com/ eg http://omdbapi.com/?i=tt1270797&apikey=5cdc2256 3. Movie id is receieved from https://www.imdb.com 4. Advanced class structure can be seen from existing python module https://imdbpy.sourceforge.io/ class IMDB: def __init__(self, movie_id, api_key="5cdc2256"): self.movie_id = movie_id self.json = None self.api_key = api_key def _load(self): import requests if self.json is None: r = requests.get("http://omdbapi.com/?i=%s&apikey=%s" %(self.movie_id,self.api_key)) self.json = r.json() def ratings(self, source='Internet Movie Database'): self._load() _tmp = [each['Value'] for each in self.json['Ratings'] if each['Source'] == source] return _tmp[0] if _tmp else "Not Found" 2. Pandas a. Read sales_transactions.xlsx b. What percentage of the total order value(ie ext price) does each order represent?" Hint: Use dataframe.transform along with groupby of order OR use dataframe.Join on 'order' after groupby of order , Then get % df = pd.read_excel("./data/sales_transactions.xlsx") df.groupby('order').mean() >>> df.groupby('order')["ext price"].sum().rename("Order_Total").reset_index() order Order_Total 0 10001 576.12 1 10005 8185.49 2 10006 3724.49 #how to combine this data back with the original dataframe. order_total = df.groupby('order')["ext price"].sum().rename("Order_Total").reset_index() df_1 = df.merge(order_total, on='order') >>> df_1.head(3) account name order sku quantity unit price ext price Order_Total 0 383080 Will LLC 10001 B1-20000 7 33.69 235.83 0 576.12 1 383080 Will LLC 10001 S1-27722 11 21.12 232.32 1 576.12 2 383080 Will LLC 10001 B1-86481 3 35.99 107.97 2 576.12 df_1["Percent_of_Order"] = df_1["ext price"] / df_1["Order_Total"] #Second Approach - Using Transform >>> df.groupby('order')["ext price"].transform('sum') 0 576.12 1 576.12 2 576.12 3 8185.49 4 8185.49 5 8185.49 6 8185.49 7 8185.49 8 3724.49 9 3724.49 10 3724.49 11 3724.49 Name: ext price, dtype: float64 df["Order_Total"] = df.groupby('order')["ext price"].transform('sum') df["Percent_of_Order"] = df["ext price"] / df["Order_Total"] #other problem >>> df.groupby('order')["ext price"].mean().max() 1637.098 >>> df.groupby('order')["ext price"].mean().argmax() __main__:1: FutureWarning: 'argmax' is deprecated. Use 'idxmax' argmax' will be corrected to return the positional maximum in th es.argmax' to get the position of the maximum now. 10005 >>> df.groupby('order')["ext price"].mean().values.argmax() 1 >>> df.groupby('order')["ext price"].mean().idxmax() 10005 >>> df.groupby('account')["ext price"].sum().idxmax() 412290 >>> df.groupby('account')["quantity"].sum().idxmax() 412290 >>> df.groupby('sku')["quantity"].sum().idxmax() 3. Write Django REST API server API: http://localhost:8000/get_weather?location=mumbai Result: In Json { 'todays_date':{'text': .., 'high':..., 'low': ..}, 'tomorrow_date': {...} .. like five days data} Use - module weather-api https://pypi.org/project/weather-api/ 3.2. Test using requests a. write one script get_weather.py to interact with REST server b. should take location via command line c. print json output using pprint.pprint #commands $ django-admin startproject weathersite $ python manage.py migrate $ python manage.py runserver 8000 #Urls.py from django.contrib import admin from django.urls import path, include from .views import get_weather urlpatterns = [ path('admin/', admin.site.urls), path('get_weather/', get_weather, name='get_weather21'), #for default path('get_weather/<str:location>', get_weather, name='get_weather22'), path('get_weather', get_weather, name='get_weather'), #for handling ?GET_QUERY or POST QUERY , Note no end '/' ] #views.py from weather import Weather, Unit from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import json import logging log = logging.getLogger(__name__) @csrf_exempt def get_weather(request, location='mumbai'): loc = None loc = request.GET.dict().get('location', None) log.info("GET " + str(loc)) if loc is None and 'post' in request.method.lower() : #log.info("POST " + str(request.META)) #note it is CONTENT_TYPE , not Content-Type if 'CONTENT_TYPE' in request.META and 'application/json' in request.META['CONTENT_TYPE']: loc = json.loads(request.body.decode()).get('location', None) log.info("JSON POST " + str(loc)) else: loc = request.POST.dict().get('location', None) log.info("FORM POST " + str(loc)) if loc is None: loc = location log.info("REST GET " + str(loc)) weather = Weather(unit=Unit.CELSIUS) data = {loc:{}} error = {loc: 'Not Found'} try: location = weather.lookup_by_location(loc) except Exception as ex: error[loc] = str(ex) return JsonResponse(error) if location is None: return JsonResponse(error) forecasts = location.forecast for forecast in forecasts: data[loc][forecast.date] = {} data[loc][forecast.date]['text'] = forecast.text data[loc][forecast.date]['high'] = forecast.high data[loc][forecast.date]['low'] = forecast.low return JsonResponse(data) ##testing import requests import json , pprint data = {'location':'hyderabad'} headers = {'Content-Type': 'application/json'} error = {'location':'xyz'} test = { 'test1' : {'url': "http://localhost:8000/get_weather", 'method': requests.get , 'data':{}}, 'test2' : {'url': "http://localhost:8000/get_weather", 'method': requests.get , 'data': dict(params=data)}, 'test3' : {'url': "http://localhost:8000/get_weather", 'method': requests.get , 'data': dict(params=error)}, 'test4' : {'url': "http://localhost:8000/get_weather", 'method': requests.post , 'data': dict(data=data)}, 'test5' : {'url': "http://localhost:8000/get_weather", 'method': requests.post , 'data': dict(data=json.dumps(data), headers=headers )}, 'test6' : {'url': "http://localhost:8000/get_weather/", 'method': requests.get , 'data': {}}, 'test7' : {'url': "http://localhost:8000/get_weather/delhi", 'method': requests.get , 'data': {}}, } for name, p in test.items(): r = p['method'](p['url'], **p['data']) print('for ', name) pprint.pprint(r.json()) ### #unit can be CELSIUS = 'c' FAHRENHEIT = 'f' unit = 'c' URL = 'http://query.yahooapis.com/v1/public/yql' #lookup(woeid), Lookup WOEID via http://weather.yahoo.com. woeid = 560743 url = "%s?q=select * from weather.forecast where woeid = '%s' and u='%s' &format=json" % (URL, woeid, unit) #lookup_by_location(location) location = 'mumbai' url = "%s?q=select* from weather.forecast " \ "where woeid in (select woeid from geo.places(1) where text='%s') and u='%s' &format=json" % (URL, location, unit) #lookup_by_latlng(lat, lng) lat, lng = 53.3494,-6.2601 url = "%s?q=select* from weather.forecast " \ "where woeid in (select woeid from geo.places(1) where text='(%s,%s)') and u='%s' &format=json" % (URL, lat, lng, unit) import requests r = requests.get(url) r.json() #for xml location = 'mumbai' url = "%s?q=select* from weather.forecast " \ "where woeid in (select woeid from geo.places(1) where text='%s') and u='%s' &format=xml" % (URL, location, unit) r = requests.get(url) r.content import lxml.etree as etree x = etree.fromstring(r.content) #takes byte string print(etree.tostring(x, pretty_print=True).decode()) #Json {'query': {'count': 1, 'created': '2018-11-20T01:19:24Z', 'lang': 'en-US', 'results': {'channel': {'astronomy': {'sunrise': '6:49 am', 'sunset': '5:59 pm'}, 'atmosphere': {'humidity': '90', 'pressure': '34202.54', 'rising': '0', 'visibility': '25.43'}, 'description': 'Yahoo! Weather for Mumbai, ' 'MH, IN', 'image': {'height': '18', 'link': 'http://weather.yahoo.com', 'title': 'Yahoo! Weather', 'url': 'http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif', 'width': '142'}, 'item': {'condition': {'code': '27', 'date': 'Tue, 20 Nov ' '2018 05:30 ' 'AM IST', 'temp': '24', 'text': 'Mostly ' 'Cloudy'}, 'description': '<![CDATA[<img ' 'src="http://l.yimg.com/a/i/us/we/52/27.gif"/>\n' '<BR />\n' '<b>Current ' 'Conditions:</b>\n' '<BR />Mostly ' 'Cloudy\n' '<BR />\n' '<BR />\n' '<b>Forecast:</b>\n' '<BR /> Tue - ' 'Partly Cloudy. ' 'High: 32Low: 24\n' '<BR /> Wed - ' 'Partly Cloudy. ' 'High: 32Low: 22\n' '<BR /> Thu - ' 'Partly Cloudy. ' 'High: 34Low: 23\n' '<BR /> Fri - ' 'Partly Cloudy. ' 'High: 36Low: 23\n' '<BR /> Sat - ' 'Sunny. High: ' '35Low: 22\n' '<BR />\n' '<BR />\n' '<a ' 'href="http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2295411/">Full ' 'Forecast at Yahoo! ' 'Weather</a>\n' '<BR />\n' '<BR />\n' '<BR />\n' ']]>', 'forecast': [{'code': '30', 'date': '20 Nov 2018', 'day': 'Tue', 'high': '32', 'low': '24', 'text': 'Partly ' 'Cloudy'}, {'code': '30', 'date': '21 Nov 2018', 'day': 'Wed', 'high': '32', 'low': '22', 'text': 'Partly ' 'Cloudy'}, {'code': '30', 'date': '22 Nov 2018', 'day': 'Thu', 'high': '34', 'low': '23', 'text': 'Partly ' 'Cloudy'}, {'code': '30', 'date': '23 Nov 2018', 'day': 'Fri', 'high': '36', 'low': '23', 'text': 'Partly ' 'Cloudy'}, {'code': '32', 'date': '24 Nov 2018', 'day': 'Sat', 'high': '35', 'low': '22', 'text': 'Sunny'}, {'code': '30', 'date': '25 Nov 2018', 'day': 'Sun', 'high': '33', 'low': '20', 'text': 'Partly ' 'Cloudy'}, {'code': '28', 'date': '26 Nov 2018', 'day': 'Mon', 'high': '32', 'low': '20', 'text': 'Mostly ' 'Cloudy'}, {'code': '34', 'date': '27 Nov 2018', 'day': 'Tue', 'high': '33', 'low': '18', 'text': 'Mostly ' 'Sunny'}, {'code': '30', 'date': '28 Nov 2018', 'day': 'Wed', 'high': '32', 'low': '18', 'text': 'Partly ' 'Cloudy'}, {'code': '34', 'date': '29 Nov 2018', 'day': 'Thu', 'high': '32', 'low': '18', 'text': 'Mostly ' 'Sunny'}], 'guid': {'isPermaLink': 'false'}, 'lat': '19.090281', 'link': 'http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2295411/', 'long': '72.871368', 'pubDate': 'Tue, 20 Nov 2018 05:30 ' 'AM IST', 'title': 'Conditions for Mumbai, ' 'MH, IN at 05:30 AM IST'}, 'language': 'en-us', 'lastBuildDate': 'Tue, 20 Nov 2018 06:49 AM ' 'IST', 'link': 'http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2295411/', 'location': {'city': 'Mumbai', 'country': 'India', 'region': ' MH'}, 'title': 'Yahoo! Weather - Mumbai, MH, IN', 'ttl': '60', 'units': {'distance': 'km', 'pressure': 'mb', 'speed': 'km/h', 'temperature': 'C'}, 'wind': {'chill': '77', 'direction': '45', 'speed': '4.83'}}}}} #XML <query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:count="1" yahoo:created="2018-11-20T01:24:18Z" yahoo:lang="en-US"> <results> <channel> <yweather:units xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" distance="km" pressure="mb" speed="km/h" temperature="C"/> <title>Yahoo! Weather - Mumbai, MH, IN</title> <link>http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2295411/</link> <description>Yahoo! Weather for Mumbai, MH, IN</description> <language>en-us</language> <lastBuildDate>Tue, 20 Nov 2018 06:54 AM IST</lastBuildDate> <ttl>60</ttl> <yweather:location xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" city="Mumbai" country="India" region=" MH"/> <yweather:wind xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" chill="77" direction="45" speed="4.83"/> <yweather:atmosphere xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" humidity="90" pressure="34202.54" rising="0" visibility="25.43"/> <yweather:astronomy xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" sunrise="6:49 am" sunset="5:59 pm"/> <image> <title>Yahoo! Weather</title> <width>142</width> <height>18</height> <link>http://weather.yahoo.com</link> <url>http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif</url> </image> <item> <title>Conditions for Mumbai, MH, IN at 05:30 AM IST</title> <geo:lat xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">19.090281</geo:lat> <geo:long xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">72.871368</geo:long> <link>http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2295411/</link> <pubDate>Tue, 20 Nov 2018 05:30 AM IST</pubDate> <yweather:condition xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="27" date="Tue, 20 Nov 2018 05:30 AM IST" temp="24" text="Mostly Cloudy"/> <yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="30" date="20 Nov 2018" day="Tue" high="32" low="24" text="Partly Cloudy"/> <yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="30" date="21 Nov 2018" day="Wed" high="32" low="22" text="Partly Cloudy"/> <yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="30" date="22 Nov 2018" day="Thu" high="34" low="23" text="Partly Cloudy"/> <yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="30" date="23 Nov 2018" day="Fri" high="36" low="23" text="Partly Cloudy"/> <yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="32" date="24 Nov 2018" day="Sat" high="35" low="22" text="Sunny"/> <yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="30" date="25 Nov 2018" day="Sun" high="33" low="20" text="Partly Cloudy"/> <yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="28" date="26 Nov 2018" day="Mon" high="32" low="20" text="Mostly Cloudy"/> <yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="34" date="27 Nov 2018" day="Tue" high="33" low="18" text="Mostly Sunny"/> <yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="30" date="28 Nov 2018" day="Wed" high="32" low="18" text="Partly Cloudy"/> <yweather:forecast xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" code="34" date="29 Nov 2018" day="Thu" high="32" low="18" text="Mostly Sunny"/> <description>&lt;![CDATA[&lt;img src="http://l.yimg.com/a/i/us/we/52/27.gif"/&gt; &lt;BR /&gt; &lt;b&gt;Current Conditions:&lt;/b&gt; &lt;BR /&gt;Mostly Cloudy &lt;BR /&gt; &lt;BR /&gt; &lt;b&gt;Forecast:&lt;/b&gt; &lt;BR /&gt; Tue - Partly Cloudy. High: 32Low: 24 &lt;BR /&gt; Wed - Partly Cloudy. High: 32Low: 22 &lt;BR /&gt; Thu - Partly Cloudy. High: 34Low: 23 &lt;BR /&gt; Fri - Partly Cloudy. High: 36Low: 23 &lt;BR /&gt; Sat - Sunny. High: 35Low: 22 &lt;BR /&gt; &lt;BR /&gt; &lt;a href="http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2295411/"&gt;Full Forecast at Yahoo! Weather&lt;/a&gt; &lt;BR /&gt; &lt;BR /&gt; &lt;BR /&gt; ]]&gt;</description> <guid isPermaLink="false"/> </item> </channel> </results> </query> ###Quick code ##XML import xml.etree.ElementTree as ET tr = ET.parse(r"data\example.xml") r = tr.getroot() r.tag r.attrib r.text nn = r.findall("./country/rank") [n.text for n in nn] res = [] for n in nn: res.append(n.text) [int(n.text) for n in nn] nn = r.findall("./country") [n.attrib['name'] for n in nn] res = [] for n in nn: res.append(n.attrib['name']) ##CSV import csv with open(r"data/iris.csv", "rt") as f: rd = csv.reader(f) rows = list(rd) rows[0:5] headers = rows[0] rows = rows[1:] rowsd = [] for sl, sw, pl, pw, name in rows: rowsd.append([float(sl), float(sw), float(pl), float(pw), name]) rowsd[:5] names = {row[-1] for row in rowsd } {n : max([r[0] for r in rowsd if r[-1] == n]) for n in names } ##SQL from sqlite3 import connect con = connect(r"iris.db") cur = con.cursor() cur.execute("""create table iris (sl double, sw double, pl double, pw double, name string)""") for r in rowsd: cur.execute("""insert into iris values(?,?,?,?,?) """, r) con.commit() q = cur.execute("""select name, max(sl) from iris group by name""") result = list(q.fetchall()) print(result) cur.execute("""drop table if exists iris""") con.close() ##JSON import json with open(r"data/example.json", "rt") as f: obj = json.load(f) [emp['empId'] for emp in obj] res = [] for emp in obj: res.append(emp['empId']) [emp['details']['firstName'] + emp['details']['lastName'] for emp in obj] for emp in obj: res.append(emp['details']['firstName'] + emp['details']['lastName']) ##REST and JSON url = 'http://omdbapi.com/?i=tt1285016&apikey=5cdc2256' import requests r = requests.get(url) r.json() data = r.json() [r['Value'] for r in data['Ratings']] [r['Value'] for r in data['Ratings'] if r['Source']=='Metacritic'] ##REST import json, requests data = {'username': 'xyz'} headers = {'Content-Type': 'application/json'} r = requests.post("http://httpbin.org/post", data=json.dumps(data), headers=headers) r.json() #GET payload = {'key1': 'value1', 'key2': 'value2'} r = requests.get("http://httpbin.org/get", params=payload) print(r.url) #http://httpbin.org/get?key2=value2&key1=value1 r.headers r.text ##QUick JSON Server from flask import Flask,request, jsonify import json app = Flask(__name__) @app.route("/") def home(): return """ <html><body><h1>Hello there!!!</h1></body></html> """ @app.route("/json", methods=["POST"]) def json1(): with open(r"data\example.json", "rt") as f : obj = json.load(f) resp = jsonify(obj) resp.status_code = 200 return resp @app.route('/index', methods=['POST']) def index(): user = { 'username': 'Nobody'} if 'Content-Type' in request.headers and request.headers['Content-Type'] == 'application/json': user['username'] = request.json['username'] resp = jsonify(user) resp.status_code = 200 return resp if __name__ == '__main__': app.run() ##HTML scrapping from bs4 import BeautifulSoup import requests r = requests.get("http://www.yahoo.com") data = r.text soup = BeautifulSoup(data, 'html.parser') soup.get_text() for link in soup.find_all('a'): # tag <a href=".." print(link.get('href')) # Attribute href
name = input("Name: ") age = int(input("Age: ")) print("Name: ", name) print("Age: ", age) if age <= 12: print("Child") elif age >=13 and age <= 19: print("Teen age") elif age >= 20 and age <=35: print("Young age") elif age >= 36 and age <=60: print("Middle age") else: print("Old age")
def avg(List): sum = 0 for i in List: sum += int(i) return (sum/len(List)) nums = input() List = nums.split(' ') Res = avg(List) print("{:0.2f}".format(Res))
# This program is to generate ring for alphabets N=25 Ring_Zn=[] Ring_Alphabet=[] # create ring of alphabets # a = 97 and z = 122 for alpha in range(97, 123): Ring_Alphabet.append(chr(alpha)) print("Aplhabets: ",Ring_Alphabet) # create ring of mod26 for i in range(0,N+1): Ring_Zn.append(i) print("Ring: ",Ring_Zn) for i in range(0,N+1): print("{} - {}".format(Ring_Zn[i],Ring_Alphabet[i]))
# Exercise Question 1: Accept two numbers from the user and calculate multiplication num1 = input("Enter number one: ") num1 = int(num1) num2 = input("Enter number two: ") num2 = int(num2) def Multiplication(i,j): return i * j print("Number one:",num1) print("Number two:",num2) print("Multiplication of",num1,"and",num2,"is ",Multiplication(num1,num2)) # F:\Python\Practice\pynative.com\Python Input and Output Exercise>python 01MultiplicationOfTwoNumbers.py # Enter number one: 10 # Enter number two: 12 # Number one: 10 # Number two: 12 # Multiplication of 10 and 12 is 120 # F:\Python\Practice\pynative.com\Python Input and Output Exercise>python 01MultiplicationOfTwoNumbers.py # Enter number one: 123456789 # Enter number two: 987654321 # Number one: 123456789 # Number two: 987654321 # Multiplication of 123456789 and 987654321 is 121932631112635269
''' Leetcode- 120. Triangle - https://leetcode.com/problems/triangle/ time complexity - o(n) space complexity - o(1) Approach - DP - modify the original triangle top-bottom approach ''' class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: if not triangle: return 0 for i in range(1,len(triangle)): for j in range(len(triangle[i])): if j==0: triangle[i][j]+=triangle[i-1][j] elif j==len(triangle[i])-1: triangle[i][j]+=triangle[i-1][j-1] else: triangle[i][j]+=min(triangle[i-1][j],triangle[i-1][j-1]) return min(triangle[-1]) # Bottom-up approach #time complexity - O(1) class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: if not triangle: return 0 for i in range(len(triangle)-2,-1,-1): for j in range(0,i+1,1): triangle[i][j]+=min(triangle[i+1][j],triangle[i+1][j+1]) return triangle[0][0]
import collections from sys import stdout def find_most_common_words(file, n): """ This function returns the most common words in the text file :param file: location of the text file :param n: number decides how many top occurrence needs to be returned :return: return top n frequently used word in the text file """ words = collections.Counter() if isfile_text(file): with open(file, 'r', encoding='utf-8') as text_file: for line in text_file: # Word Definition # 1. Words are case Sensitive in this Program i.e. cat , CAT , cAT are three different words # 2. Any item in a line which is separated by whitespace character # is considered as Word, by default split function splits by whitespace characters words.update(line.split()) all_words = dict(words) all_words_list = [] for key, value in all_words.items(): temp = [key, value] all_words_list.append(temp) # Returning top n words from the sorted list return sorted(all_words_list, key=lambda x: (-x[1], x[0]))[:n] def output_to_console(input_string): """ This function prints input string to console :param input_string: :return: """ print('Word - Occurrences') for x in input_string: print(*x, sep=' - ', file=stdout) stdout.flush() def isfile_text(file_name): """ This function check the file passed is text file or not :param file_name: Name of the file :return: True if the file is text file """ is_text_file = True try: with open(file_name, "r", encoding='utf-8') as file: file_data = file.read(512) except UnicodeDecodeError: print('File is not a Text File') is_text_file = False return is_text_file def run_application(file, top_n): """ This main function calls common word count and stdout functions :param file:location of the text file :param top_n : top n frequently used word in the text file :return: """ top_n_freq_word = find_most_common_words(file, top_n) if top_n_freq_word: output_to_console(top_n_freq_word) return top_n_freq_word else: return
#!/usr/bin/python3 """ Darren Hobern Assignment 4 COMP361 2017 """ import math _DIRECTIONS = { ( 1,2), ( 1,-2), # down rigth right, down left left (-1,2), (-1,-2), # up right right, up left left ( 2,1), ( 2,-1), # down down right, down down left (-2,1), (-2,-1)} # up up right, up up left def knightstour(boardsize, open_tour): """ Complete a knight's tour using slightly optimised brute force. ARGS: boardsize :: int - width and height of the board open_tour :: bool - true if the start and end points can be different """ # Set all points on the board to unvisited board = [[False for c in range(boardsize)] for r in range(boardsize)] # If it is an open tour search until all points have been visited if open_tour: return knights_bt(board, [(0,0)], boardsize, open_tour) # otherwise we must check that the end point is the same as the start else: for r in range(math.ceil(boardsize/2)): for c in range(r, math.ceil(boardsize/2)): print("Starting: {} {}".format(r,c)) success, route = knights_bt(board, [(r,c)], boardsize, open_tour) if success: return success, route return False, route def knights_bt(bd, rt, boardsize, open_tour): """ Recursively look for a solution to a knight's tour by moving to every possible location and backtracking. ARGS: bd :: [[Bool]], 2d list representing the board. rt :: [(Int,Int)], list of int pairs, showing the current route boardsize :: Int, width/height of the board. open_tour :: Bool, are we finding an open or closed tour. """ # Clone the route and board, so if the route fails we can safely backtrack. route = [p for p in rt] board = [[col for col in row] for row in bd] final_move = False i,j = route[-1] # Current position is the last cell in the route board[i][j] = True # Mark as visited # If we have covered all tiles on the board... if len(route) == boardsize*boardsize: if open_tour: # And it's an open tour, we're done. return True, route else: # else it's a closed tour, we must check if the start position # is adjacent to our current position final_move = True for dir in _DIRECTIONS: di = dir[0] + i dj = dir[1] + j # Check if we are not moving off the board if (0 <= di and di < boardsize and 0 <= dj and dj < boardsize): # Check if we're adjacent to the start position in a closed tour if final_move: si, sj = route[0] # Start position is the first cell in the route if di == si and dj == sj: # If it is adjacent to the start, end route.append((di,dj)) return True, route elif board[di][dj] == False: success, final_route = knights_bt(board, route+[(di,dj)], boardsize, open_tour) # Return the solution if success: # Only append the cell if it is part of the route route.append((di,dj)) return True, final_route return False, None if __name__ == '__main__': print("Wrong file, run using 'python3 knightstour.py'")
from Tkinter import * #often people import Tkinter as * root = Tk() canvas = Canvas(root, height=600, width=600, relief=RAISED, bg='white') canvas.grid() check = canvas.create_line(200, 0,200, 600, fill='red', width=20) line = canvas.create_line(400, 0,400, 600, fill='red', width=20) dash = canvas.create_line(0,200,600,200, fill='red', width=20) iverson = canvas.create_line(0,400,600, 400, fill='red', width=20) def move(event): x=event.x y=event.y canvas.create_oval(x-50,y-50,x+50,y+50, fill='white', width=20) canvas.bind('<ButtonPress-1>', move) def move2(event): x=event.x y=event.y canvas.create_line( x-50,y-50,x+50,y+50, width=20) canvas.create_line( x-50,y+50,x+50,y-50, width=20) canvas.bind('<ButtonPress-1>', move) canvas.bind('<ButtonPress-3>', move2) root.mainloop()
import sys def printMatrix(matrix): # write code here if not matrix: return None rows = len(matrix) - 1 cols = len(matrix[0]) - 1 i = 0 j = 0 result = [] while (i <= rows and j <= cols): for t in range(j, cols + 1): result.append(matrix[i][t]) for t in range(i + 1, rows + 1): result.append(matrix[t][cols]) if i != rows: for t in range(cols - 1, j - 1, -1): result.append(matrix[rows][t]) if j != cols: for t in range(rows - 1, i, -1): result.append(matrix[t][j]) i += 1 j += 1 rows -= 1 cols -= 1 return result # m,n = map(int,raw_input().split()) # nums = [] # for i in range(m): # temp = raw_input().split() # nums.append(temp) # stop = raw_input() # res = printMatrix(nums,m,n) # res = ','.join(res) # sys.stdout.write(res) def compareVersionNumber(s1,s2): s1 = s1.split('.') s2 = s2.split('.') m = min(len(s1),len(s2)) for i in range(m): if int(s1[i]) > int(s2[i]): return 1 elif int(s1[i]) < int(s2[i]): return -1 else: if i == (m-1): if len(s1) == len(s2): return 0 elif len(s1) > m: return 1 else: return -1 else: continue def mouseEscape(grid,n): dp = [[0 for _ in range(n)] for _ in range(n)] dp[0][0] = grid[0][0] for i in range(n): for j in range(n): if i == 0 and j > 0: dp[i][j] = dp[i][j-1]+grid[i][j] elif i > 0 and j == 0: dp[i][j] = dp[i-1][j] + grid[i][j] elif i > 0 and j > 0: dp[i][j] = min(dp[i-1][j],dp[i][j-1]) + grid[i][j] return dp[-1][-1] # n = int(raw_input()) # nums = [] # for i in range(n): # temp = list(map(int,raw_input().split(','))) # nums.append(temp) # print mouseEscape(nums,n) m,n = map(int,raw_input().split()) nums = [] for i in range(m): temp = raw_input().split() nums.append(temp) stop = raw_input() res = printMatrix(nums) res = ','.join(res) print str(res)+"\n"
x=10 x=int(x) print(x) print(type(x)) print(type(x)==int) print(id(x)) x=2.6 x=float(2.6) print(x) print(type(x)==float) print(id(x)) x=4+3j x=complex(4+3j) print(x) print(type(x)) print(type(x)==complex) print(id(x)) x="Vishal" y='Single' z="""MULTI line""" print(x) print(y) print(z) print(type(x)) print(type(y)) print(type(z)) print(type(x)==str) print(type(y)==str) print(type(z)==str) print(id(x)) x=[1,2,3,"PY"] x=list([1,2,3,"PY"]) print(x) print(type(x)) print(type(x)==list) print(id(x)) x=(1,2,3,"PY") x=tuple((1,2,3,"PY")) print(x) print(type(x)==tuple) print(id(x)) x={1:"Python",2:"Java"} x=dict({1:"Python",2:"Java",3:"Python"}) print(x) print(type(x)) print(type(x)==dict) print(id(x)) x={10,"Python",20} x=set({10,"Python",20}) print(x) print(type(x)) print(type(x)==set) print(id(x))
############################################################################# # I/O functions for Lab 3 # Alex Bartlett # # includes functions for reading input file, passing each set of sequences # to be analyzed, and printing the resultant LCSs in a human-readable format # with relevant statistics # ############################################################################# # import standard libraries import re from Lab3_LCS import * # ensure input file is valid, containing only white space and lines that # follow the format: S<number> = <DNA sequence> def validate_input(contents): # remote white space, consider each sequence separately contents = contents.strip() lines = contents.split('\n') # need at least 2 sequences to calculate LCS assert(len(lines) > 1), \ "Invalid input: need at least two sequences to compare" # validate format of each line for line in lines: line = line.strip() assert(re.fullmatch(r"S[0-9]+[\s]*=[\s]*[ACTGactg]+$", line)), \ "Invalid input: the following line in your input is invalid: \n {}".format(line) # if you reach this point, input file is valid return # parse input file, pass pairs of sequences to be LCS-ed, print # results in human-readable format def find_LCSes(contents): contents = contents.strip() # begin creating output string, including headers output = "================================\n" output += "INPUT\n" output += "================================\n\n" # echo input in output string output += contents output += "\n\n" # begin creating and storing output output += "================================\n" output += "OUTPUT\n" output += "================================\n\n" # remote white space, consider each sequence separately lines = contents.split('\n') num_seqs = len(lines) # in turn, parse the lines and form every possible # non-redundant pair of sequences for i in range(0, num_seqs-1): partsX = lines[i].split('=') seqX = partsX[1].strip().upper() for j in range(i + 1, num_seqs): partsY = lines[j].split('=') seqY = partsY[1].strip().upper() # calculate the LCS and stats for current pair of seqs lcs, comps, elapsed = find_LCS(seqX, seqY) # store which pair of seqs was being compared, the LCS, # and relevant statistics in the output output += lines[i] + '\n' output += lines[j] + '\n' output += 'LCS: ' + lcs + '\n' output += 'Comparisons: ' + str(comps) + '\n' output += 'Time Elapsed (sec): ' + str(float('%.3g' % elapsed)) + '\n\n' # when the LCS has been calculated for all possible sequence pairs, return output return output
#In mathematics, the factorial of integer 'n' is written as 'n!'. It is equal to the product of n and every integer #preceding it. For example: 5! = 1 x 2 x 3 x 4 x 5 = 120 #Your mission is simple: write a function that takes an integer 'n' and returns 'n!'. #You are guaranteed an integer argument. For any values outside the positive range, return null, nil or None . #Note: 0! is always equal to 1. Negative values should return null def factorial(n): if n < 0: return None elif n == 0: return 1 else: factorial_total = 1 while n > 1: factorial_total *= n n -= 1 return factorial_total #Casos test: assert(factorial(1) == 1) assert(factorial(5) == 120)
#Everybody knows the classic "half your age plus seven" dating rule that a lot of people follow (including myself). #It's the 'recommended' age range in which to date someone. #minimum age <= your age <= maximum age #Task: #Given an integer (1 <= n <= 100) representing a person's age, return their minimum and maximum age range. #This equation doesn't work when the age <= 14, so use this equation instead: #min = age - 0.10 * age #max = age + 0.10 * age #You should floor all your answers so that an integer is given instead of a float (which doesn't represent age). #Return your answer in the form [min]-[max] #Examples: #age = 27 => 20-40 #age = 5 => 4-5 #age = 17 => 15-20 def dating_range(age): if age <= 14: min = age - 0.10 * age max = age + 0.10 * age else: min = (age/2)+7 max = (age-7)*2 return str(int(min))+'-'+str(int(max)) #Casos test: assert(dating_range(17) == "15-20") assert(dating_range(40) == "27-66") assert(dating_range(15) == "14-16") assert(dating_range(35) == "24-56") assert(dating_range(10) == "9-11")
#When provided with a String, capitalize all vowels #For example: #Input : "Hello World!" #Output : "HEllO WOrld!" def swap(st): s = "" vowels = ['a','e','i','o','u'] for i in st: if i in vowels: s = s+i.upper() else : s = s+i return s #Casos test: assert(swap("HelloWorld!") == "HEllOWOrld!") assert(swap("Sunday") == "SUndAy")
def activity01(num1): """Determine if an input number is Even or Odd""" res = num1 % 2 == 0 if res: return "Even" return "Odd" def activity02(iv_one, iv_two): """Return the sum of two input values""" return iv_one + iv_two def activity03(num_list): """Given a list of integers, count how many are even""" count = 0 for num in num_list: if activity01(num) == "Even": count += 1 return count def activity04(input_string): """Return the input string, backward""" return input_string [::-1]
var1=int(input("Enter the first nnumber\n")) var2=int(input("Enter the second number\n")) var3=var1-var2 print(var3)
# leet code -322 # Dynamic Programming # passed all test cases # time complexity =O(N^2) #space complexity=O(N) #Approach - we need to create a matrix of size((number of coins+1 * (amount+1)). Let the first row be filled with infinity except first column in all the rows. Those values are filled with zero. Till the column reaches the coin denomination the matrix is filled with previous row values and then it compared with min value of (previous rowth column and the (current column -coin denomination)) class Solution(object): def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ i,j=0,0 rows,col=len(coins)+1,amount+1 dp=[[0 for i in range(col)] for j in range(rows)] for i in range(rows): dp[i][0]=0 for j in range(1,col): dp[0][j]=99999 for i in range(1,rows): for j in range(1,col): if j<coins[i-1]: #extra row of zero added dp[i][j]=dp[i-1][j] else: dp[i][j]=min(dp[i-1][j],dp[i][j-coins[i-1]]+1) result=dp[rows-1][col-1] if result >=99999 : return -1 else : return result # Recursive solution class Solution(object): def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ return self.helper(coins,amount,0,0) def helper(self,coins,amount,i,min_num): #base cases if (amount<0 or i> len(coins)): return -1 if (amount==0): return min_num #case1 choosing the coin case1=self.helper(coins,amount-coins[i],i,min_num+1) #case2 not choosing the coin case2 = self.helper(coins,amount,i+1,min_num) if (case1 ==-1): return case2 elif case2 ==-1: return case1 else: return min(case1,case2)
#This is the actual budget tracker in which multiple modules will run. #Open csv file with open("BankStatement.csv.txt", "r") as f: file_data = f.read() database = {} temp_input = file_data.replace("\n", ",") cost_input = temp_input.split(",") count = len(cost_input)-1 a = 0 b = 0 for x in range(3, count, 3): a = x b = x + 2 category = cost_input[b] if (x + 2) > count: continue else: if category not in database: database[category] = cost_input[a:b] else: database[category] = database[category] + cost_input[a:b] # functionality of this module = ask for budget, save budget and print budget budget_command = "Provide your budget for this month:" print(budget_command) budget = input() result_total_expense = 0 print("Thank you. Your budget for this month is {} GBP.".format(budget)) start_module = "\nThe following commands are valid: \nEnter, will allow you to add data to your expense database; \nDownload, will download a report including your latest expenses by category; \nRemaining, will calculate and print your remaining budget; \nPound, will calculate if you are 'Pound foolish' or 'Penny foolish. \n" add_costs_command = "When adding your cost to the database, please use the following format: category, name, -amount." print(start_module) print(add_costs_command) command = "\nWhat would you like to do?" while True: print(command) total_expense = [] user_input = input().split(",") if user_input[0] == "Enter": category = user_input[1] if category not in database: database[category] = user_input[2:4] #Should the amounts be summed by name too? else: database[category] = database[category] + user_input[2:4] elif user_input[0] == "Download": for category in database: list_amount = [] if category == "INCOME": for x in range(len(database[category])): if x % 2 == 0: continue else: list_amount.append(float(database[category][x])) result = sum(list_amount) else: for x in range(len(database[category])): if x % 2 == 0: continue else: list_amount.append(float(database[category][x])) total_expense.append(float(database[category][x])) result = sum(list_amount)*-1 result_total_expense = sum(total_expense)*-1 print("Your total expense for %s is %.2f GBP." % (category, result)) print("Your total expense for this month is %.2f GBP." % (result_total_expense)) elif user_input[0] == "Remaining": income_amount = [] for x in range(len(database["INCOME"])): if x % 2 == 0: continue else: income_amount.append(float(database["INCOME"][x])) result_income = sum(income_amount) remaining_budget = float(budget) - float(result_total_expense) + float(result_income) print("Your remaining budget for this month is %.2f GBP." % (remaining_budget)) elif user_input[0] == "Pound": pound_penny = [] pound_foolish = [] penny_foolish = [] for new_category in database: for y in range(len(database[new_category])): if y % 2 == 0: continue else: pound_penny.append(float(database[new_category][y])) for amount in range(len(pound_penny)): if pound_penny[amount] < 10: penny_foolish.append(pound_penny[amount]) else: pound_foolish.append(pound_penny[amount]) result_penny = sum(penny_foolish) result_pound = sum(pound_foolish) if result_penny > result_pound: print("You are penny foolish!") else: print("You are pound foolish!") else: print("This command is invalid, please try again.")
#!/usr/bin/env python3 """ this module creates a class FIFOcache inherited from BaseCaching """ from base_caching import BaseCaching class FIFOCache(BaseCaching): """ this class is a FIRST IN FIRST OUT caching system """ cache_list = [] def put(self, key, item): """ edits cache based on FIFO method """ if key and item is not None: self.cache_data[key] = item if key not in self.cache_list: self.cache_list.append(key) if len(self.cache_data) > BaseCaching.MAX_ITEMS: remove = self.cache_list.pop(0) print('DISCARD: ' + remove) del self.cache_data[remove] def get(self, key): """ class method to return a value from cache dict """ return self.cache_data.get(key)
#!/usr/bin/env python3 """ this module creates a new class BasicCache inherited from BaseCaching """ from base_caching import BaseCaching class BasicCache(BaseCaching): """ this class inherits from BaseCaching """ def put(self, key, item): """ class method to put item in cache dict """ if key and item is not None: self.cache_data[key] = item def get(self, key): """ class method to return a value from cache dict """ return self.cache_data.get(key)
#!/usr/bin/env python3 """ this module defines and type-annotates a to_kv function that returns a tuple """ from typing import Union, Tuple def to_kv(k: str, v: Union[int, float]) -> Tuple[str, float]: """ this function returns a tuple with str and float elements """ return k, v ** 2
#!/usr/bin/env python3 """ this module writes an async coroutine with random delay """ import random import asyncio async def wait_random(max_delay: int = 10) -> float: """ this coroutine waits for a random delay then returns the delay time """ delay = random.uniform(0, max_delay) await asyncio.sleep(delay) return delay
from pandas_to_tree import pandas_to_tree from tree import Tree import pandas as pd from keywords import keywords def best_branch(tree, text_in): """A function that returns the branch of TREE that has the most matching keywords with TEXT_IN""" keys_in = keywords(text_in) #print(keys_in) best_intersect = 0 best_branch = Tree('No matching issues found') for branch in tree.branches: intersect = len(list(set(keys_in).intersection(set(branch.keywords)))) #print(branch.keywords) if best_intersect < intersect: best_intersect = intersect best_branch = branch return best_branch def best_branches(tree, text_in): """A function that returns the branches of TREE in order of matching the keywords of TEXT_IN""" keys_in = keywords(text_in) s = lambda x: len(list(set(keys_in).intersection(set(x.keywords)))) branches = tree.branches branches.sort(reverse = True, key = s) return branches def best_children(node, text_in): """A function that returns a list of the children of NODE sorted by how much their keywords match TEXT_IN""" keys_in = keywords(text_in) s = lambda x: len(list(set(keys_in).intersection(set(x.keywords)))) childs = node.children childs.sort(key = s) return childs ##edited for ranking branches. might discard - C # def best_branch(tree, text_in): # """A function that returns the branch of TREE that has the most matching keywords with TEXT_IN""" # keys_in = keywords(text_in) # #print(keys_in) # best_intersect = 0 # branches_order = [] # best_branch = Tree('No matching issues found') # for branch in tree.branches: # intersect = len(list(set(keys_in).intersection(set(branch.keywords)))) # #print(branch.keywords) # if best_intersect < intersect: # best_intersect = intersect # best_branch = branch # branches_order.append(best_branch) # return best_branch, branches_order """ dataframe = pd.read_csv('edm_milling.csv') tree = pandas_to_tree(dataframe) text_in = input('Keywords') print(best_branch(tree, text_in).label) """
import random import numpy def mainMenu(): running = True player_one=Player() player_two=Player() player_ai=PlayerAI() while(running): print("") print("<>---<>---<> BATTLE OF NUMBERS <>---<>---<>") print(" | <>---<> ONE PLAYER <>---<> | ") print(" | <>---<> TWO PLAYERS <>---<> | ") print(" | <>---<> EXIT <>---<> | ") print(" *\_____________________________________/* ") print("") userOption = int(input("Choose an option: ")) if(userOption == 1): print("One player mode running ...") player_one.reload() player_ai.reload() gameThread(player_one, player_ai) elif(userOption == 2): print("Two players mode running ...") player_one.reload() player_two.reload() gameThread(player_one, player_two) elif(userOption == 3): print("Good bye bitch !") running = False else: print("Yeah? Good") running = False def gameThread(player_one, player_two): running = True players_list = [player_one,player_two] turn = 0 while(running): print(">< Player",turn,"><",end="\n\r\n\r") print(player_one.showValues(turn)) print(player_two.showValues(turn)) players_list[nextTurn(turn)].tryShot(players_list[turn].shot(),turn) if(players_list[nextTurn(turn)].isAlive(turn) == False): running = False print("Player",turn,"wins!") else: turn = nextTurn(turn) def nextTurn(turn): return (turn+1)%2 #----------------------- PLAYER CLASS --------------------------------------------------- class Player(object): numbers = numpy.empty(shape=[0,0],dtype=int) def __init__(self): print("Human Player created ...") @classmethod def tryShot(self, number,turn): if number in self.numbers: hittedNums = numpy.where(self.numbers == number) for i in hittedNums[turn][1:]: self.numbers[turn][i] = -1 print("\n\r... HITTED!\n\r") @classmethod def isAlive(self, turn): cont = 0 for i in self.numbers[turn]: if i == -1: cont+=1 return cont!=5 @classmethod def shot(self): try: shot = int(input("SHOT! -> ")) except ValueError: print("ValueError D:! ") shot = 0 finally: return shot @classmethod def showValues(self,turn): ocult_values = "[" for x in range(5): if self.numbers[turn][x]==-1: ocult_values = ocult_values + " X" else: ocult_values = ocult_values + " ?" ocult_values = ocult_values + " ]" return ocult_values @classmethod def reload(self): self.numbers = numpy.random.randint(1,10,size=(2,5)) #---------------------------------------------------------------------------------------- #------------------------ PLAYER-AI CLASS ------------------------------------------------ class PlayerAI(object): numbers = [] numbersShoted = [] def __init__(self): print("AI Player created ...") @classmethod def tryShot(self, number,turn): if number in self.numbers: self.numbers[self.numbers.index(number)] = -1 print("\n\r... HITTED!\n\r") @classmethod def isAlive(self,turn): return self.numbers.count(-1)!=5 @classmethod def shot(self): shot = random.randint(0,11) while(shot in self.numbersShoted): shot = random.randint(0,11) self.numbersShoted.append(shot) print("SHOT! -> ",end="") print(shot) return shot @classmethod def showValues(self,turn): ocult_values = "[" for x in range(5): if self.numbers[x]==-1: ocult_values = ocult_values + " X" else: ocult_values = ocult_values + " ?" ocult_values = ocult_values + " ]" return ocult_values @classmethod def reload(self): self.numbers = random.sample(range(10),5) numbersShoted = [] #---------------------------------------------------------------------------------------- mainMenu()
"""Pacman, classic arcade game. Exercises 1. Change the board. 2. Change the number of ghosts. 3. Change where pacman starts. 4. Make the ghosts faster/slower. 5. Make the ghosts smarter. """ from random import choice from turtle import * from freegames import floor, vector state = {'score': 0} path = Turtle(visible=False) writer = Turtle(visible=False) aim = vector(5, 0) pacman = vector(-40, -80) ghosts = [ [vector(-180, 160), vector(5, 0)], [vector(-180, -160), vector(0, 5)], [vector(100, 160), vector(0, -5)], [vector(100, -160), vector(-5, 0)], ] "Cada fantasma se comporta diferente" ghostA = ghosts[0][0] ghostB = ghosts[1][0] ghostC = ghosts[2][0] ghostD = ghosts[3][0] course1 = ghosts[0][1] course2 = ghosts[1][1] course3 = ghosts[2][1] course4 = ghosts[3][1] tiles = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ] def square(x, y): "Draw square using path at (x, y)." path.up() path.goto(x, y) path.down() path.begin_fill() for count in range(4): path.forward(20) path.left(90) path.end_fill() def offset(point): "Return offset of point in tiles." x = (floor(point.x, 20) + 200) / 20 y = (180 - floor(point.y, 20)) / 20 index = int(x + y * 20) return index def valid(point): "Return True if point is valid in tiles." index = offset(point) if tiles[index] == 0: return False index = offset(point + 19) if tiles[index] == 0: return False return point.x % 20 == 0 or point.y % 20 == 0 def world(): "Draw world using path." bgcolor('black') path.color('blue') for index in range(len(tiles)): tile = tiles[index] if tile > 0: x = (index % 20) * 20 - 200 y = 180 - (index // 20) * 20 square(x, y) if tile == 1: path.up() path.goto(x + 10, y + 10) path.dot(2, 'white') def move(): "Move pacman and all ghosts." writer.undo() writer.write(state['score']) clear() if valid(pacman + aim): pacman.move(aim) index = offset(pacman) if tiles[index] == 1: tiles[index] = 2 state['score'] += 1 x = (index % 20) * 20 - 200 y = 180 - (index // 20) * 20 square(x, y) up() goto(pacman.x + 10, pacman.y + 10) dot(20, 'yellow') if valid(ghostA + course1): ghostA.move(course1) else: plan = track(aim) course1.x = plan.x course1.y = plan.y up() goto(ghostA.x + 10, ghostA.y + 10) dot(20, 'red') if valid(ghostB + course2): ghostB.move(course2) else: course2.x = aim.x course2.y = aim.y up() goto(ghostB.x + 10, ghostB.y + 10) dot(20, 'green') if valid(ghostC + course3): ghostC.move(course3) else: options = [ vector(8, 0), vector(-8, 0), vector(0, 8), vector(0, -8), ] plan = choice(options) course3.x = plan.x course3.y = plan.y up() goto(ghostC.x + 10, ghostC.y + 10) dot(20, 'orange') if valid(ghostD + course4): ghostD.move(course4) else: options = [ vector(2, 0), vector(-2, 0), vector(0, 2), vector(0, -2), ] plan = choice(options) course4.x = plan.x course4.y = plan.y up() goto(ghostD.x + 10, ghostD.y + 10) dot(20, 'pink') update() for point, course in ghosts: if abs(pacman - point) < 20: return ontimer(move, 25) def change(x, y): "Change pacman aim if valid." if valid(pacman + vector(x, y)): aim.x = x aim.y = y def track(pac): if pac.x == 5: return vector(-5, 0) elif pac.x == -5: return vector(5, 0) elif pac.y == 5: return vector(0, -5) else: return vector(0, -5) setup(420, 420, 370, 0) hideturtle() tracer(False) writer.goto(160, 160) writer.color('white') writer.write(state['score']) listen() onkey(lambda: change(5, 0), 'Right') onkey(lambda: change(-5, 0), 'Left') onkey(lambda: change(0, 5), 'Up') onkey(lambda: change(0, -5), 'Down') world() move() done()
""" Active Directory In Windows Active Directory, a group can consist of user(s) and group(s) themselves. We can construct this hierarchy as such. Where User is represented by str representing their ids. Write a function that provides an efficient look up of whether the user is in a group. """ class Group(object): def __init__(self, _name): self.name = _name self.groups = [] self.users = [] def add_group(self, group): self.groups.append(group) def add_user(self, user): self.users.append(user) def get_groups(self): return self.groups def get_users(self): return self.users def get_name(self): return self.name def is_user_in_group(user, group): """ Return True if user is in the group, False otherwise. Args: user(str): user name/id group(class:Group): group to check user membership against """ """ def search(self): if user in self.users: return True for sub_group in self.groups: if search(sub_group): return True return False return search(group) """ if (user in group.get_users()) or (user == group.get_name()): return True for sub_group in group.get_groups(): return is_user_in_group(user, sub_group) return False parent = Group("parent") child = Group("child") sub_child = Group("subchild") unknown = Group("unknown") sub_child_user = "sub_child_user" sub_child.add_user(sub_child_user) child.add_group(sub_child) parent.add_group(child) # Test Cases print("Pass" if (is_user_in_group(sub_child_user, sub_child) == True) else "Fail") print("Pass" if (is_user_in_group(sub_child_user, child) == True) else "Fail") print("Pass" if (is_user_in_group(sub_child_user, parent) == True) else "Fail") print("Pass" if (is_user_in_group(sub_child_user, unknown) == False) else "Fail")
tenNumber = input("Please, enter a 10 digit number") if len(tenNumber) != 10: print ("Please, try again") tenListEven = [] tenListOdd = [] for i in range (0,9): if int(tenNumber[i])%2 == 0: tenListEven.append (tenNumber[i]) else : tenListOdd.append (tenNumber[i]) print (tenListEven) for k in range (0,5): print (tenListOdd[k],end=' ') print() print(end=" ") for l in range (0,3): print (tenListEven[l],end=' ')
import math valueA = float(input("Please, enter the a value of your quadratic equation:")) valueB = float(input("Please, enter the b value of your quadratic equation:")) valueC = float(input("Please, enter the c value of your quadratic equation:")) D = valueB**2 - (4*valueA*valueC) if D < 0: print("No real solutions exist for the given values.") else : xOne = ((-valueB) + math.sqrt(D))/(2*valueA) xTwo = ((-valueB) - math.sqrt(D))/(2*valueA) print ("The solutions of your quadratic equation are:",xOne,xTwo)
from tkinter import * #from Tkinter import * import sqlite3 a=sqlite3.Connection('infodb') cur=a.cursor() cur.execute('create table if not exists gym(id number,name varchar(20),sex varchar(8),height number,weight number)') root=Tk() Label(root,text="Enter gym id").grid(column=0,row=0) v0=Entry(root) v0.grid(row=1,column=0) Label(root,text="Enter Name").grid(column=0,row=2) v1=Entry(root) v1.grid(row=3,column=0) Label(root,text="Select Sex : ").grid(row=4,column=0) v5=IntVar() v6=IntVar() v7=IntVar() r1=Radiobutton(root,text='Male',variable=v5,value=1).grid(row=6,column=0) r2=Radiobutton(root,text='Female',variable=v6,value=2).grid(row=7,column=0) r2=Radiobutton(root,text='Other',variable=v7,value=3).grid(row=8,column=0) Label(root,text="Enter Height").grid(column=9,row=0) v3=Entry(root) v3.grid(row=9,column=0) Label(root,text="Enter Weight").grid(column=0,row=10) v4=Entry(root) v4.grid(row=0,column=11) p=[] def fun(): b=[v0.get(),v1.get(),v5.get(),v6.get(),v7.get(),v3.get(),v4.get()] i=0 p.append(v0.get()) cur.executemany("insert into infodb values(?,?,?,?,?,?,?)",b) a.commit() def fun2(): cur.execute('select * from stu') t=cur.fetchall() print (t) def fun3(): cur.execute('''update infodb set name=? where id=?''',(v9.get(),v10.get())) a.commit() Button(root,text='insert',command=fun).grid(row=24,column=0) Button(root,text='showall',command=fun2).grid(row=24,column=2) root.mainloop()
# diseñar una red de 6 nodos y encontrar todos los posibles # caminos entre un nodo origen y un nodo destino import networkx import matplotlib.pyplot as plt graph = networkx.Graph() graph.add_nodes_from(['a', 'b', 'c', 'd', 'e', 'f']) graph.add_edges_from([ ('a', 'b'), ('a', 'c'), ('b', 'e'), ('b', 'd'), ('c', 'f'), ('a', 'f') ]) source = input('Enter the source node >> ') target = input('Enter the target node >> ') print('Todos los caminos posibles de nodo %s para nodo %s: ' %(source, target)) for path in networkx.all_simple_paths(graph, source, target): print(path) networkx.draw(graph, with_labels=True, font_weight='bold') plt.show() edges = list(graph.edges()) for n in range(len(edges)): print(edges) print(edges[1])
from turtle import * from random import randrange from freegames import square, vector #Elaborado por: """Salvador Alejandro Gaytán Ibañez A01730311 Ituriel Mejia Garita A01730875 Myroslava Sánchez Andrade A01730712 Víctor Alfonso Mancera Osorio A01733749""" #Establecemos el vector que contiene la posiciones de comida al igual que la de snake, y la de la dirección d food = vector(0, 0) snake = [vector(10, 0)] aim = vector(0, -10) #Creamois un arreglo con los colores disponibles tanto para la serpiente como para la comdia colores = ["green", "red", "yellow", "black", "blue"] #Establecemos que el color serpiente y colorCOmida seráa un color al azar, de acuerdo a un valor numerico al azar en tr0 y 4 colorSerpiente = colores[randrange(5)] colorComida = colores[randrange(5)] #Funcion que se encarga de cambiar la direccion de la serpiente def change(x, y): print("Andamos cambiando lmao") aim.x = x aim.y = y def change_food(x, y): #Funcion que se encarga de cambiar la posicion de la comida de acuerdo a los argumentos provistos print("Cambiando la posición de la comida") #Asignamos los componentes vectoriales de mi vector comida a lo que se nos brinde como argumento food.x = x food.y = y def inside(head): #Funcion que nos indica si la serpiente se encuentra en los boundaries "Return True if head inside boundaries." return -200 < head.x < 190 and -200 < head.y < 190 def move(): "Move snake forward one segment." head = snake[-1].copy() #Accedemos al ultimo cuadro de la serpiente (El cual es la cabeza) head.move(aim) #Lo movemos hacia el aim if not inside(head) or head in snake: #Si nuestra serpiente se sale de sus boundaries... square(head.x, head.y, 9, 'red') #Establecemos la cabeza como un cuadro rojo update() #Actualizamos el canvas return #Regresamos snake.append(head) #Añadimos a nuestra snake la cabeza if head == food: #Si la cabeza se encuentra en el mismo lugar de la comdia print('Snake:', len(snake)) #Imprimimos que se han encontrado # Colocamos la comida en un valor al azar food.x = randrange(-15, 15) * 10 food.y = randrange(-15, 15) * 10 else: #De cualquier otra forma, eliminamos la cola de la serpíente parta simular el movimiento snake.pop(0) clear() #Limpiamos el canvas for body in snake: #Construimos de nueva cuenta el snake square(body.x, body.y, 9, colorSerpiente) numero = randrange(1, 10) #Obtenemos una variable de numero al azar entre 1 y 10 if numero == 5: #Si ese numero es 5... change_food(randrange(1,5)*10, randrange(1, 6)*10) #Cambiamos la posicion de la comida a un valor al azar while(not inside(food)): #Evaluamos que este dentro de los limites del canvas #Si no lo está, volvemos a reubicarla hasta que esté dentro de los limites change_food(randrange(0, 5) * 10, randrange(0, 6) * 10) #Finalmente dibujamos la comida square(food.x, food.y, 9, colorComida) #Actualizamos el canvas update() ontimer(move, 100) setup(420, 420, 370, 0) #Establecemos el tamaño de la venta hideturtle() #Esondemos la tortuga que dibuja tracer(False) #Eliminamos el tracer del dibujo listen() #Estableces un escucha que esta atento a las instrucciones del usuario #Serie listeners que se encargan de ejecutar una funcion de acuerdo a la tecla preisonada onkey(lambda: change(10, 0), 'Right') onkey(lambda: change(-10, 0), 'Left') onkey(lambda: change(0, 10), 'Up') onkey(lambda: change(0, -10), 'Down') #Ejecutamos la funcion mover move() #Establecemos que hasta aquí llega el ciclo del programa done()
#!/usr/bin/python #!encoding: UTF-8 x=-b/a a=float(raw_input('valor de a: ')) b=float(raw_input('valor de b: ')) print'solucion: ', x #El programa lee dos números y realiza el cociente entre ellos. Hace la operación antes de saber el valor de las variables, es decir, antes de pedirlas, por lo que esta mal.
# Library for opening url and creating # requests import urllib.request # pretty-print python data structures from pprint import pprint # for parsing all the tables present # on the website from html_table_parser import HTMLTableParser # for converting the parsed data in a # pandas dataframe import pandas as pd # Opens a website and read its # binary contents (HTTP Response Body) def url_get_contents(url): # Opens a website and read its # binary contents (HTTP Response Body) #making request to the website req = urllib.request.Request(url=url) f = urllib.request.urlopen(req) #reading contents of the website return f.read() # defining the html contents of a URL. xhtml = url_get_contents('https://clearquest.alstom.hub/cqweb/restapi/CQat/atvcm/QUERY/47363098?format=HTML&noframes=true').decode('utf-8') # Defining the HTMLTableParser object #p = HTMLTableParser() # feeding the html contents in the # HTMLTableParser object #p.feed(xhtml) # Now finally obtaining the data of # the table required #pprint(p.tables[1]) # converting the parsed data to # datframe print("\n\nPANDAS DATAFRAME\n") df_list = pd.read_html('C:/PD/MooN/CR&CQ/Automation/cq-moon-cr.html') df = df_list[-1] print(df_list) #print(pd.DataFrame(p.tables[1]))
print('Welcome to "Lovers-Point".\n') print("Let's Check your love-percentage.\n") name1 = str(input('Enter your name: ')) name2 = str(input('Enter your Lover name: ')) if name1 == name2: print('Wow, What a Couple, Yaar!!!\n'); print('%s + %s, Got 100'%(name1,name2))
print('Start>>>') print('What is the Length?') length = input() print('What is the Width?') width = input() RectangleArea = int(length) * int(width); print('Your RectangleArea is:',RectangleArea); print('End');
def fib(n): a =0 b=1 while a<n: print(a) a, b=b,a+b print()
a = 7 b = 6 c = a%b if(a < b): print("a % b = " + str(c)) else: print("a > b")
import random class Player: """ player is on a single team, with many other players player play in a game for a team """ def __init__(self, name, skill): self.name = name # player skill rankings self.skill = skill def salary(self): return 5000 + self.skill * 100 # to get the string representation of the object def __str__(self): return (f'{self.name}\tSkill: {self.skill}\tSalary: ${self.salary()}') def generate_player(): first_names = [ 'Liam', 'Noah', 'Oliver', 'Lucas', 'Elijah', 'Mason', 'Logan', 'Ethan', 'James', 'Aiden', 'Carter', 'Jackson', 'Sebastian', 'Benjamin', 'Alexander', 'Michael', 'Jacob', 'Daniel', 'William' ] last_names = [ 'Smith', 'Jones', 'Williams', 'Taylor', 'Brown', 'Davies', 'Evans', 'Wilson', 'Thomas', 'Johnson', 'Roberts', 'Robinson', 'Thompson', 'Wright', 'Walker', 'White', 'Edwards', 'Hughes', 'Green', 'Hall', 'Lewis', 'Harris', 'Clarke', 'Patel', 'Jackson', 'Wood', 'Turner', 'Martin', 'Cooper', 'Hill', 'Ward', 'Morris', 'Moore', 'Clark' ] first_name = random.choice(first_names) last_name = random.choice(last_names) full_name = f'{first_name} {last_name}' skill = 10 + random.randint(0, 90) return Player(full_name, skill)
''' Write a python script that converts one currency into some other user-chosen currency. https://api.exchangerate-api.com/v4/latest/USD Package : Forex-Python ''' from forex_python.converter import CurrencyRates c = CurrencyRates() amount = int(input("Enter The Amount You Want To Convert\n")) from_currency = input("From\n").upper() to_currency = input("To\n").upper() print(from_currency,"To",to_currency,amount) result = c.convert(from_currency, to_currency, amount) print(result)
''' Write a python script that shortens a given URL using an API. ''' from __future__ import with_statement import contextlib try: from urllib.parse import urlencode except ImportError: from urllib import urlencode try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen import sys def make_tiny(url): request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url})) with contextlib.closing(urlopen(request_url)) as response: return response.read().decode('utf-8') def main(): for tinyurl in map(make_tiny, sys.argv[1:]): print(tinyurl) if __name__ == '__main__': main() ''' python url_shortener.py https://www.wikipedia.org/ https://tinyurl.com/buf3qt3 '''
#Algoritmo de Busqueda binaria o metodo de biseccion # Otro algoritmo en computer science es la Busqueda Binaria. Esto es, cuando la respuesta se encuentra en un conjunto ordenado, podemos utilizar búsqueda binaria. Es altamente eficiente, pues corta el espacio de búsqueda en dos por cada iteración. # En la búsqueda binaria podemos acortar nuestro espacio de búsqueda a la mitad cada vez, entonces el espacio de búsqueda se va haciendo mas pequeña y eficiente. # Si tenemos un conjunto de números del 1 al 10 y queremos encontrar el 7, podemos empezar en 5 que es la mitad, y entre 6 y 10 la mitad es 8 y como 7 no es mayor que 8, el espacio de busqueda se quedara entre el 6 y el 7. OJO. el Conjunto de los numeros debe estar ordenado. # Para realizar un ejemplo práctico crearemos un programa para buscar raíces cuadradas. # 1. definimos nuestra variable objetivo donde guardaremos como valor el int, que mediante el input, el usuario nos ingrese # 2. Definimos nuestra variable épsilon y la inicializamos en 0.01 # 3. Definimos nuestro bajo que será nuestro limite inferior que será de 0.0 # 4. Definimos nuestro alto y contendrá una nueva función que se llama max() que nos regresa el valor mas alto entre dos valores, y dentro de esta, le diremos que nos regrese (1.0, objetivo) # 5. Definimos nuestra variable respuesta que contendrá nuestra respuesta inicial y recordemos que debemos encontrar la mitad de alto y bajo, esto será (alto + bajo) / 2 # 6. Ahora definimos nuestro ciclo while abs(respuesta**2 - objetivo) >= épsilon: Y no ponemos la segunda condición, porque con alto estamos garantizando, que nuestro objetivo, lo mínimo que va poder ser es 1.0 y asi garantizamos que no es un numero negativo # 7. dentro de nuestro ciclo generamos el if statement o condición con la siguiente lógica: si respuesta al cuadrado es menor que objetivo: entonces bajo es nuestra nueva respuesta, else, alto es nuestra nueva respuesta. Con eso definimos si nos vamos a bajo nos vamos a alto. # Una vez completado el ciclo, la respuesta en cada iteración la volveremos mas pequeña esto lo hacemos con la sintaxis respuesta = (alto + bajo) / 2. Es decir, que en cada iteración estamos dividiendo entre dos nuestro espacio de búsqueda y estamos redefiniendo tanto bajo como alto # 8. Por ultimo le pedimos al usuario mediante un string de formato que # print(f’La raíz cuadrada de {objetivo} es {respuesta}’) # 9. Para ver que esta sucediendo en la ejecución del algoritmo, agregaremos a nuestro ciclo while un print statement # print(f’bajo={bajo}, alto={alto}, respuesta={respuesta}’). objetivo = int(input('Escoge un numero: ')) epsilon = 0.01 bajo = 0.0 alto = max(1.0, objetivo) respuesta = (alto + bajo) / 2 while abs(respuesta**2 - objetivo) >= epsilon: print(f'bajo={bajo}, alto={alto}, respuesta={respuesta}') if respuesta**2 < objetivo: bajo = respuesta else: alto = respuesta respuesta = (alto + bajo) / 2 print(f'La raiz cuadrada de {objetivo} es {respuesta}')
#Recursion o recursividad, o funciones recursivas, en python, con un ejemplo de Factoriales # La recursividad se puede definir de manera algorítmica como una forma de crear soluciones utilizando el principio de divide y vencerás, significa que un problema podemos resolverlo utilizando versiones más pequeñas del mismo problema. Es decir, un problema que al principio parecería difícil, se puede encontrar una solución base para construir iterativamente la solución final a este problema. # Y de manera programática como una técnica programática mediante la cual una función se llama a si misma. # Como implementamos recursividad en código? Pues haciendo que una función dentro de su ejecución, se llame a si misma otra vez. # Para empezar a entender la recursividad vamos a ver un primer problema que son los factoriales. # Lo que vemos más notable es el símbolo de producto, que es una iteración, es como un for loop. Asi que lo que nos dice el ejercicio es que una n! (el signo de admiración significa factorial) es un loop que empieza en 1 (i = 1) y termina en n. Asi que si queremos el factorial de 10 y tenemos que si i empieza en 1 y termina en 10. Y finalmente, para poder llegar a 10, esta el símbolo i al lado de el símbolo de producto, que nos dice que multiplicaremos por el mismo valor hasta llegar a n, es decir que multiplicaríamos 1 por si mismo hasta llegar a 10. # Tanto en la programación como en las matemáticas nosotros podemos definir una función recursiva tanto en un loop como en la propia recursividad. La forma factorial de definir la recursividad seria en programación: # n! = n * ( n – 1)! # Y una recursión al final del dia seria simplemente una forma de iterar y cualquier función recursiva, podemos representarla como un loop. # Si nosotros queremos obtener 4 factorial # 4! = 4 * (4 – 1)! # 4! = 4 * (3)! #y que es 3 factorial? # 3! = 3 * (2)! #y que es 2 factorial? # 2! = 2 * (1)! # 1! = 1 # Y ahora, ese 1 lo multiplicamos por 2, lo que nos de lo multiplicamos por 3 y luego lo que nos de, lo multiplicamos por 4, y entonces estamos llegando a la solución de que # 4! = 4*3*2*1 # Ahora un ejemplo en codigo # 1. Crearemos una función que se llama def factorial(n): # 2. Ahora escribiremos nuestro docstring, que como buenas practicas siempre hay que escribirlo porque nos hará pensar en lo que escribiremos. # Nuestra especificación será: # Descripcion: Calcula el factorial de n # definimos: n es un entero que es mayor que 0 # regresa n factorial # 3. Ahora que tenemos nuestro docstring, escribiremos nuestro caso base, es decir hasta donde iremos en esta iteración. En la forma en la que esta construido Python no nos generaría un infinite loop, pero si nos generaría un error porque llegamos al limite máximo de recursividad. # Asi que si queremos escribir n! nuestro caso base es que si n es igual a 1 entonces regresa 1. # if n == 1: # return 1 # nota: para conocer el limite máximo de recursividad hay que importar la librería sys. print(sys.getrecursionlimit()) 1000 # 4. Ahora si, lo que tenemos que hacer es regresar nuestra definición matemática regresa n factorial por el factorial de n menos 1 # return n * factorial(n – 1) # Con esto ya tenemos nuestra primera funcion recursiva. Y la lógica de lo que va pasar es que si recibimos por ejemplo 3, como parámetro n, entonces si 3 no es igual a 1, no se ejecuta esa primera condicional, y luego retornara el resultado de 3 * 3(3 – 1) y luego regresa a la función y repite. # Aquí es importante tener en cuenta el concepto de los stacks, porque cada vez que la función se ejecuta, se va poniendo un stack nuevo encima. # 5. Ahora declararemos la variable n y le ordenaremos al usuario que nos diga un numero entero, y simplemente imprimiremos cual es la factorial de n # n = int(input(‘Escribe un entero: ‘)) # print(factorial(n)) def factorial(n): """Calcula el factorial de n n int > 0 returns n! """ print(n) #Print statement para saber cual es el valor de n en cada iteracion if n == 1: return 1 return n * factorial(n - 1) n = int(input('Escribe un entero: ')) print(factorial(n)) # Como reto hay que investigar como se implementa la recursividad en python
def es_bisiesto (year): if year%4==0: if year%100==0 and year%400==0: bisiesto=True elif year%100==0 and year%400!=0: bisiesto=False else: bisiesto=True else: bisiesto=False return bisiesto def main(): a=int(input()) z=es_bisiesto(a) print(z) pass if __name__=='__main__': main()
def autoriza_voto(anoNascimento): #Verifica se o eleitor está apto a votar, obrigado a votar ou tem o voto opcional anoAtual = 2021 idade = anoAtual - anoNascimento if idade >= 18 and idade <= 70: autorizacao = "Obrigatório" return autorizacao elif idade < 16 and idade >= 0: autorizacao = "Negado" return autorizacao else: autorizacao = "Opcional" return autorizacao def votacao(autorizacao,voto): #Valida e computa o voto no seu respectivo canditato guardando em um dicionário. if voto == 1: apuracao[candidato1] += 1 elif voto == 2: apuracao[candidato2] += 1 elif voto == 3: apuracao[candidato3] += 1 elif voto == 4: apuracao["Votos nulos"] += 1 elif voto == 5: apuracao["Votos em branco"] += 1 if autorizacao == "Negado": return "Você não pode Votar!" elif autorizacao == "Opcional": return "Voto opcional!" else: return "Voto obrigatório!" candidato1 = "Bolsonaro" candidato2 = "Lula" candidato3 = "Janice" maior = 0 #variavel pra verificar qual é o candidato com maior numero de votos eleito = 0 # variavel que salva o nome do candidato com maior numero de votos apuracao = {candidato1: 0, candidato2: 0, candidato3: 0, "Votos nulos": 0, "Votos em branco": 0} continuar = "0" while continuar == "0": anoNascimento = int(input("Informe seu ano de nascimento: ")) print("Seja bem - vindo!") print("Dê o seu voto:") print(f"[1] {candidato1}") print(f"[2] {candidato2}") print(f"[3] {candidato3}") print(f"[4] Voto nulo") print(f"[5] Voto em branco") voto = int(input()) if voto < 1 or voto > 5: #verificação pra garantir que o usuario escolha apenas os candidatos disponiveis print("Comando inválido!") else: print(votacao(autoriza_voto(anoNascimento), voto)) continuar = input("Deseja computar outro voto? [SIM/NÃO]").upper()[0].replace("S", "0").replace("N", "1") print() print("Resultado da votação") for c in apuracao: #printar o resultado da votaçao print(c + ":",apuracao[c]) for i in apuracao: # verificar dentre os valores do dicionario qual é o maior numero e qual seu respectivo candidato if apuracao[i] > maior: maior = apuracao[i] eleito = i contador = 0 for empate in apuracao: # verificar se esse numero(que é o maior) se repete mais de uma vez, havendo assim um empate if maior == apuracao[empate]: contador += 1 if contador > 1: print("A votação terminou empatada!") else: print() print(eleito, "venceu a votação!")
# Escreva uma função que, dado um número nota representando a nota de um estudante, # converte o valor de nota para um conceito (A, B, C, D, E e F). def conceito(nota): if nota >= 9: notaLetra = "A" elif nota >= 8: notaLetra = "B" elif nota >= 7: notaLetra = "C" elif nota >= 6: notaLetra = "D" elif nota > 4: notaLetra = "E" else: notaLetra = "F" return notaLetra nota = float(input("Inform sua nota: ").replace(",",".")) if nota > 10 or nota < 0: print("Nota inválida") else: print(f"Sua nota em conceito: {conceito(nota)}")
# #01 - Crie um programa que leia dois valores e mostre um menu na tela: # [ 1 ] somar # [ 2 ] multiplicar # [ 3 ] maior # [ 4 ] novos números # [ 5 ] sair do programa print() opcao = 0 maior = 0 valor1 = float (input("Digite o primeiro valor: ")) valor2 = float (input("Digite o segundo valor: ")) while opcao != 5: print("\nSelecione uma das opções: ") print("[ 1 ] somar") print("[ 2 ] multiplicar") print("[ 3 ] maior") print("[ 4 ] novos números") print("[ 5 ] sair do programa") opcao = int (input()) if opcao < 1 or opcao > 5: print() print("Número inválido!!") elif opcao == 1: print() print(f"Resultado da soma entre {valor1} e {valor2} é = {valor1 + valor2}\n") elif opcao == 2: print() print(f"Resultado da multiplicação entre {valor1} e {valor2} é = {valor1 * valor2}\n") elif opcao == 3: print() if valor1 > valor2: print(f"O maior entre os dois números é: {valor1}") elif valor1 < valor2: print(f"O maior entre os dois números é: {valor2}") else: print("Os números são iguais!") elif opcao == 4: print() valor1 = float (input("Digite o primeiro valor: ")) valor2 = float (input("Digite o segundo valor: ")) else: print() print("Muito obrigado!") if opcao < 1 or opcao > 5: print("Número inválido!!")
def operacao(largura, comprimento): area = largura * comprimento print(f"A área do seu terreno é: {area} m²") largura = int(input("Informe a largura do terreno: ")) comprimento = int(input("Informe o comprimento do terreno: ")) operacao(largura,comprimento)
# Faça um programa que calcule o salário de um colaborador na empresa XYZ. # O salário é pago conforme a quantidade de horas trabalhadas. # Quando um funcionário trabalha mais de 40 horas ele recebe um adicional de 1.5 nas horas extras trabalhadas. def calculoSalario(horasTrabalhadas,reaisHora): if horasTrabalhadas > 40: horasTrabalhadas = horasTrabalhadas - 40 salarioComExtra = reaisHora * 1.5 horasTrabalhadas = horasTrabalhadas * salarioComExtra salario = horasTrabalhadas + (40 * reaisHora) else: salario = horasTrabalhadas * reaisHora return salario reaisHora = 7 horasTrabalhadas = int(input("Quantas horas você trabalhou? ")) print(f"O seu salário é:{calculoSalario(horasTrabalhadas,reaisHora)}")
"""for i in range(10): print(i) if i is 9: print( i + 1) simple_list = list(range(0, 100, 1)) for i in simple_list: print(i) """ merch = ['pens', 'playboy stuff', 'notes', 'books'] # returns items, no control cuz no index # for index in merch: # print(index) for i in range(len(merch)): print("Index : " + str(i) + " Item : " + merch[i])
import re message = "some message having 123-555-999 nummbers. Call 111-333-111" # regex basics till line 20 # we pass raw string to compile() # call re.compile() function to create regex object phoneregex = re.compile(r'\d\d\d-\d\d\d-\d\d\d') # d for digit match_object = phoneregex.search(message) # search() creates a match object as the name depicts print(match_object.group()) # group method to get matched string # it returns the digits above which is so cool # now this method of search() returns the first occurance, we need more. print(phoneregex.findall('Here goes my number 555-999-111 and 999-000-777')) # returns all the occurances found in a string in a list
# Given an integer number n, define a function named printDict() which can print a dictionary where the keys are numbers between 1 and n (both included) and the values are square of keys. # The function printDict() doesn't take any argument. # Input Format: # The first line contains the number n. # Output Format: # Print the dictionary in one line. # Example: # Input: # 5 # Output: # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # Program: def printDict(): x = int(input()) d = {} for i in range(x): d[i+1] = (i+1)**2 print(d, end='') printDict() printDict()
# Programming Assignments-1: Addition # In this assignment, you will have to take two numbers (integers) as input and print the addition. # Input Format: # The first line of the input contains two numbers separated by a space. # Output Format: # Print the addition in single line # Example: # Input: # 4 2 # Output: # 6 # Program: a, b = input().split() a = int(a) b = int(b) print(a+b, end="")
input1 = input("Please enter an integer: ") try: number1 = int(input1) except ValueError: print("That's not an int!") else: print(number1) number2 = int(input("Please enter another integer: ")) if number1 > number2: print "Your first number is larger than your second number" elif number1 < number2: print "Your second number is larger than your first number" else: print "Your numbers are the same"
#Set up lists:￿ name = [None*30] player_names = [None]*30 squad_shot = [None]*30 squad_assits = [None]*30 squad_goals = [None]*30 success_index = [None]*30 #Variables index = 0 highest_success = 0 best_player = ￿"" for index in range(0,30): name[index] = input(￿"What is your name￿") Squad_goals = int(input(￿"Goals?￿")) player_names[index] = name while True: player_Shot = ￿int(input(￿"Number of goals scored")) if player_Shot < 100: squad_shot[index] = player_Shot break else: print(￿"Error") while True: player_assist = int(input(￿"Maximum goals")) if player_assist < 100: squad_assits[index] = player_assist break else: print(￿"Error") while True: Squad_goals = int(input(￿"Goals?￿")) if Squad_goals: squad_goals[index] = Squad_goals break else: print(￿"Error￿￿") success_index[index] = player_assist+(2*player_Shot)+(3*squad_goals) squad_added_sucess =+ success_index[index if success_index[index] > highest_success: highest_success = success_index best_player = name[index] squad_average_sucess = squad_added_sucess_sucess / 30 print(name) print(player_names) print(squad_shot) print(squad_assits) print(success_index) print(squad_goals) print(￿"The best player is￿￿", best_player, ￿￿"and his success index is", highest_success) print("￿Average squad average sucess index is￿￿", squad_average_sucess)
# calculator gui from tkinter import * # Functions goes here def change_text(): my_label.config(text=gender.get()) # create main tkinter window window = Tk() window.title('My application') # add an empty tkinter label widget and place at grid lock my_label = Label(window, width=25, height=1, text='') my_label.grid(row=0, column=0) # add an tkinter button widget, place in a grid layout and attach to change text button my_button = Button(window, text='Submit', width=10, command=change_text) my_button.grid(row=1, column=0) # Create a Tkinter string variable object for the radio buttons gender = StringVar() # add 2 radio buttons use optional sticky argument to align left radio1 = Radiobutton(window, text='Female', variable=gender, value='female') radio1.grid(row=2, column=0, sticky=W) radio1.select() # free selects radio button for user radio2 = Radiobutton(window, text='Male', variable=gender, value='male') radio2.grid(row=3, column=0, sticky=W) window.mainloop()
""" Exercise 1: Create an algorithm that will ask the user for two numbers and print their sum. """ number1 = int(input("Input first number to add")) number2 = int(input("Input second number to add")) sum = number1 + number2 print(sum) """ Exercise 2: Create an algorithm that asks the user for a number, and then adds all the numbers that come before it starting at 1. Example: User types 5, the printed answer should be 5+4+3+2+1 which is 15. The program should print 15. """ number = int(input("What number do you want to print out?")) sum = 0 for i in range(number + 1): sum = sum + i print(sum) """ Exercise 3: Prompt a user for a number. Then divide that number into the variable a and print the variable a. """ numberToDivide = int(input("Number to divide?")) a = 6 # can't change a = a / numberToDivide print(a) # can't change """ Exercise 4: Create an algorithm that will ask for a number from the user, and use a for loop to add 3 to a sum the number of times that the user entered. Example: Enter a number please: 5 Behind the scenes: sum with three more, then three more, #hen three more.. until we reach 5 times. Result: 15 """ number_input = int(input("Enter a number please: ")) sum = 0 for i in range(number_input): sum = sum + 3 print("Result: " + str(sum)) """ Exercise 5 Create an algorithm that asks the user for a number and print the message: "You need a better for loop" that number of times on a new line each time. """ number = int(input("number")) for i in range(number): print("You need a better for loop")
# hello-gui from tkinter import * # function called by clicking on my window def change_text(): my_label.config(text='Hello world') # create main tkinter window window = Tk() window.title('My application') # Add an empty tkinter window my_label = Label(window, width=25, height=1, text='') my_label.grid(row=0, column=0) # add a tknter butoon wudgetm place it in the grid layout and attach change_text function my_button = Button(window, text='Say Hi', width=10, command=change_text) my_button.grid(row=1, column=0) window.mainloop()
# coding: utf-8 import numpy as np def random_distribution(n_items): """ Returns a random probability distribution over n items. Formally, we choose a point uniformly at random from the n-1 simplex. """ return np.random.dirichlet([1.0 for i in range(n_items)]) def uniformly_random_strategy(game, player): """ Returns a dictionary from information set identifiers to probabilities over actions for the given player. The distribution is always uniform over actions. - game is an ExtensiveGame instance. """ info_sets = game.info_set_ids # Restrict to information sets where the given player has to take an action. player_info_sets = {k: v for k, v in info_sets.items() if k.player == player} # Now randomly generate player 1's strategy and player 2's strategy. Define # a strategy as being a dictionary from information set identifiers to # probabilities over actions available in that information set. strategy = {} for node, identifier in player_info_sets.items(): actions = node.children.keys() # Only need to add to the strategy for nodes whose information set has # not been included already. if identifier not in strategy: # Sample actions uniformly at random. Can change this later. strategy[identifier] = {a: 1.0 / float(len(actions)) for a in actions} return strategy def dirichlet_random_strategy(game, player): """ We return a dictionary from information set identifiers to probabilities over actions for the given player. - game is an ExtensiveGame instance. """ info_sets = game.build_information_sets(player) # Restrict to information sets where the given player has to take an action. player_info_sets = {k: v for k, v in info_sets.items() if k.player == player} # Now randomly generate player 1's strategy and player 2's strategy. Define # a strategy as being a dictionary from information set identifiers to # probabilities over actions available in that information set. strategy = {} for node, identifier in player_info_sets.items(): actions = node.children.keys() # Only need to add to the strategy for nodes whose information set has # not been included already. if identifier not in strategy: # Sample actions uniformly at random. Can change this later. probs = random_distribution(len(actions)) strategy[identifier] = {a: p for a, p in zip(actions, probs)} return strategy def constant_action_strategy(game, player, action): """ This strategy always plays action 'action'. We return a dictionary from information set identifiers to probabilities over actions for the given player. - game is an ExtensiveGame instance. """ info_sets = game.build_information_sets(player) # Restrict to information sets where the given player has to take an action. player_info_sets = {k: v for k, v in info_sets.items() if k.player == player} # Now randomly generate player 1's strategy and player 2's strategy. Define # a strategy as being a dictionary from information set identifiers to # probabilities over actions available in that information set. strategy = {} for node, identifier in player_info_sets.items(): actions = node.children.keys() # Only need to add to the strategy for nodes whose information set has # not been included already. if identifier not in strategy: # Play the action specified. If it's not available, play uniformly # over all actions. strategy[identifier] = {a: 0.0 for a in actions} if action in actions: strategy[identifier][action] = 1.0 else: strategy[identifier] = {a: 1.0 / len(actions) for a in actions} return strategy
# Brenda Woodard # 873464752 # Takes a list of file names, which are assumed to contain raw HTML, # and uses BeautifulSoup to parse the HTML in each of those files by # searching for every table tag import csv import sys from bs4 import BeautifulSoup def table_to_list(table_tag): ''' Iterates through the rows of a table, extracting every column entry from that row, and returns the data as a list of lists. ''' tr_tags = [] for row in table_tag.find_all('tr'): tr = row.getText() tr_tag = tr.strip() tr_tags.append([tr_tag + ',']) return tr_tags def main(): argi = 1 while argi < len(sys.argv): arg = sys.argv[argi] # open the file name, create a BeautifulSoup object with its contents with open(arg) as f: table_tag = BeautifulSoup(f.read(), features="html5lib") # iterate over all table tags in that file table_tag.find_all('table') # convert each table into a two-dimensional list for table in table_tag: table_list = table_to_list(table) # print first row only print(table_list[0:1:1]) # prompt user for file name name = input('enter file name:') # if user enters nothing, pass if name == '': pass # if user enters a name, open that file for writing & save as a CSV else: print(f'Saving {table_list} to {name}...') with open('name.csv', 'w') as f: wr = csv.writer(f) wr.writerows(table_list) f.close() # run main if script is executed if __name__ == '__main__': main()
import math class Vertice: """Clase que define los vértices de los gráficas""" def __init__(self, i): """Método que inicializa el vértice con sus atributos id = identificador vecinos = lista de los vértices con los que está conectado por una arista visitado = flag para saber si fue visitado o no padre = vértice visitado un paso antes costo = valor que tiene recorrerlo""" self.id = i self.vecinos = [] self.visitado = False self.padre = None self.costo = float('inf') def agregarVecino(self, v, p): """Método que agrega los vertices que se encuentre conectados por una arista a la lista de vecinos de un vertice, revisando si éste aún no se encuentra en la lista de vecinos""" if v not in self.vecinos: self.vecinos.append([v, p]) class Grafica: """Clase que define los vértices de las gráficas""" def __init__(self): """vertices = diccionario con los vertices de la grafica""" self.vertices = {} def agregarVertice(self, id): """Método que agrega vértices, recibiendo el índice y la heuristica (para A* puede que no se reciba) revisando si éste no existe en el diccionario de vértices""" if id not in self.vertices: self.vertices[id] = Vertice(id) def agregarArista(self, a, b, p): """Método que agrega aristas, recibiendo el índice de dos vertices y revisando si existen estos en la lista de vertices, además de recibir el peso de la arista , el cual se asigna a ambos vértices por medio del método agregar vecino""" if a in self.vertices and b in self.vertices: self.vertices[a].agregarVecino(b, p) self.vertices[b].agregarVecino(a, p) def imprimirGrafica(self): """Método que imprime el gráfo completo arista por arista con todas sus características(incluye heurística)""" for v in self.vertices: print("El costo del vértice "+str(self.vertices[v].id)+" es "+ str(self.vertices[v].costo)+" llegando desde "+str(self.vertices[v].padre)) def camino(self, a, b): """Método que va guardando en la lista llamada 'camino' los nodos en el orden que sean visitados y actualizando dicha lista con los vértices con el menor costo""" camino = [] actual = b while actual != None: camino.insert(0, actual) actual = self.vertices[actual].padre return [camino, self.vertices[b].costo] def bellmanFord(self, a): """Método que sigue el algortimo de Bellman-Ford 1. Asignar a cada nodo una distancia y un nodo predecesor tentativos: 0 para el nodo inicial e infinito para todos los restantes, predecesor nulo para todos los nodos 2. Repetir |V| - 1 veces a)Para cada arista (u, v) con peso w: si la distancia del nodo actual u sumada al peso w de la arista que llega a v es menor que la distancia tentativa a v, sobreescribir la distancia a v con la suma mencionada y guardar a u como predecesor de v 3. Verificar que no existan ciclos de pesos negativos a) Para cada arista (u, v) con peso w: si la distancia del nodo actual u sumada al peso w de la arista que llega a v es menor que la distancia tentativa a v, mandar un mensaje de error indicando que existe un ciclo de peso negativo """ # 1 if a in self.vertices: self.vertices[a].costo = 0 for v in self.vertices: if v != a: self.vertices[v].costo = float('inf') self.vertices[v].padre = None # 2 for x in range(len(self.vertices) - 1): # 2.a for actual in self.vertices: for vec in self.vertices[actual].vecinos: if self.vertices[actual].costo + vec[1] < self.vertices[vec[0]].costo: self.vertices[vec[0]].costo = self.vertices[actual].costo + vec[1] self.vertices[vec[0]].padre = actual # 3 for actual in self.vertices: # 3.a for vec in self.vertices[actual].vecinos: if self.vertices[actual].costo + vec[1] < self.vertices[vec[0]].costo: return "Error: Existe un ciclo con peso negativo en la gráfica" else: return False class main: """Clase principal donde se crean objetos(grafos) de la clase indicada y se llaman sus métodos""" g = Grafica() g.agregarVertice(1) g.agregarVertice(2) g.agregarVertice(3) g.agregarVertice(4) g.agregarVertice(5) g.agregarVertice(6) g.agregarArista(1, 6, 14) g.agregarArista(1, 2, 7) g.agregarArista(1, 3, 9) g.agregarArista(2, 3, 10) g.agregarArista(2, 4, 15) g.agregarArista(3, 4, 11) g.agregarArista(3, 6, 2) g.agregarArista(4, 5, 6) g.agregarArista(5, 6, 9) print("\n\nLa ruta más rápida por Bellman-Ford junto con su costo es:") g.bellmanFord(1) print(g.camino(1, 6)) print("\nLos valores finales de la gráfica son los siguietes:") g.imprimirGrafica()
# clase que define a un vertice en general class Vertice: # constructor def __init__(self, i): self.id = i self.visitado = False # para algunos recorridos o búsquedas self.nivel = -1 self.vecinos = [] # conexión con otros nodos def agregarVecino(self, v): if v not in self.vecinos: self.vecinos.append(v) # clase que define a una gráfica class Grafica: def __init__(self): self.vertices = {} def agregarVertice(self, v): if v not in self.vertices: # vertices que tendrá la gráfica self.vertices[v] = Vertice(v) def agregarArista(self, a, b): if a in self.vertices and b in self.vertices: self.vertices[a].agregarVecino(b) self.vertices[b].agregarVecino(a) def bfs(self, r): if r in self.vertices: cola = [r] self.vertices[r].visitado = True self.vertices[r].nivel = 0 print("(" + str(r) + ", " + str(self.vertices[r].nivel) + ")") while len(cola) > 0: act = cola[0] cola = cola[1:] for v in self.vertices[act].vecinos: if self.vertices[v].visitado == False: cola.append(v) self.vertices[v].visitado = True self.vertices[v].nivel = self.vertices[act].nivel + 1 print("(" + str(v) + ", " + str(self.vertices[v].nivel) + ")") else: print("Vertice inexistente") def Main(): g = Grafica() # lista de vértices l = [0, 1, 2, 3, 4, 5, 6] for n in l: g.agregarVertice(n) # lista de aristas. Cada par de numeros es una arista (union entre dos vértices) l = [1, 4, 4, 3, 4, 6, 3, 5, 3, 2, 6, 5, 5, 2] for i in range(0, len(l) - 1, 2): g.agregarArista(l[i], l[i + 1]) for v in g.vertices: print(v, g.vertices[v].vecinos) print("\n\n") g.bfs(2) Main()
"""Write a recursive function named "branch" that takes as arguments a list of indices and a nested list structure. It should return the item indexed by the first argument. It works like "[]" operator is applied multiple times to the second list. Sample Run: >>> branch([2], [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]) ['e', 'f'] >>> branch([2, 1], [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]) 'f' >>> branch([1, 2, 0, 1], [['a', 'b'], [['c', 'd'], ['e', 'f'], [['g', 'h'], ['i', 'j']], 'k'], ['l', 'm']]) 'h' """ def branch(count,items): if len(count)==1: return items[count[0]] return branch(count[1:],items[count[0]]) ----------------------------------- """ 2. Flatten Write a function named "flatten" that flattens a nested list. Sample Run: >>> flatten([1,2,3,4]) [1, 2, 3, 4] >>> flatten([1,[2],3,4]) [1, 2, 3, 4] >>> flatten([1,[[2],3],4]) [1, 2, 3, 4] >>> flatten([1,[[2],3],[[[4]]]]) [1, 2, 3, 4] """ def helper(item): if len(item)==1: if type(item[0])==int: return [item[0]] else: return helper(item[0]) else: if item[0]==int: return item[0]+helper[1:] else: return helper(item[0]) def flatten(items): if type(items[0])==int: return flatten(items[1:]) else: items[0]=help(items[0]) return items[0]+flatten(items[1:]) #!!! DIDNT WORK
#!/usr/bin/python import math import sys import time import os def get_first_derivative(x): ret = 4 * int(sys.argv[6]) * math.pow(x, 3) + 3 * int(sys.argv[5]) * math.pow(x, 2) + 2 * int( sys.argv[4]) * x + int(sys.argv[3]) return ret def my_function(x): ret = int(sys.argv[6]) * math.pow(x, 4) + int(sys.argv[5]) * math.pow(x, 3) + int(sys.argv[4]) * math.pow(x, 2) + \ int(sys.argv[3]) * x + int(sys.argv[2]) return ret def check_interval(): counter = 0 if my_function(0) < 0: isNegative = True else: isNegative = False i = 0.0 while (i <= 1.0): if my_function(i) > 0 and isNegative is True: counter += 1 isNegative = False elif my_function(i) < 0 and isNegative is False: counter += 1 isNegative = True i += 0.01 if counter != 1: sys.exit(84) return 0 def newton(): out = 1 tmp_x = 0.5 print("x = 0.5") x = tmp_x - my_function(tmp_x) / get_first_derivative(tmp_x) start_time = time.time() while (round(my_function(x), int(sys.argv[7])) != 0): if (1 >= x >= 0 and out == 1): out = 0 elif ((1 < x or x < 0) and out == 0): sys.exit(84) print("x = %.{}f".format(sys.argv[7]) % x) tmp_x = x x = tmp_x - my_function(tmp_x) / get_first_derivative(tmp_x) if (float(time.time()) - float(start_time) > 9.0): os.system('clear') sys.exit(84) print("x = %.{}f".format(sys.argv[7]) % x) return tmp_x def bisection(): higher = 1 middle = 0.0 lower = 0 i = 0 start_time = time.time() while (abs(higher - lower) > math.pow(10, -int(sys.argv[7]))): res = my_function(middle) if (res < 0): lower = middle else: higher = middle middle = (lower + higher) / 2 if (i < int(sys.argv[7])): print("x = %.{}g".format(sys.argv[7]) % middle) else: print("x = %.{}f".format(sys.argv[7]) % middle) i += 1 if (float(time.time()) - float(start_time) > 9.0): os.system('clear') sys.exit(84) sys.exit(0) def secant(): left = 0 right = 1 x = 1 first = True start_time = time.time() while(round(my_function(x), int(sys.argv[7]) - 1) != 0): x = right - (right - left) / (my_function(right) - my_function(left)) * my_function(right) left = right right = x if (float(time.time()) - float(start_time) > 9.0): os.system('clear') sys.exit(84) if (first): print("x = %.{}g".format(sys.argv[7]) % x) else: print("x = %.{}f".format(sys.argv[7]) % x) first = False sys.exit(0) def get_which_algorithm(): check_interval() if (sys.argv[1] == '1'): bisection() elif (sys.argv[1] == '2'): newton() elif (sys.argv[1] == '3'): secant() else: sys.exit(84) def check_for_error(): try: for i in range(1, 8): int(sys.argv[i]) if (int(sys.argv[7]) < 0): sys.exit(84) except ValueError: sys.exit(84) def my_input(): if (len(sys.argv) == 2 and sys.argv[1] == "-h"): print("USAGE") print(" ./105torus opt a0 a1 a2 a3 a4 n") print("\nDESCRIPTION") print(" opt method option:") print(" 1 for the bisection method") print(" 2 for Newton's method") print(" 3 for the secant method") print(" a[0-4] coefficients of the equation") print(" n precision (the application of the polynomial to the solution should") print(" be samller than 10^-n)") elif len((sys.argv)) != 8: sys.exit(84) else: check_for_error() get_which_algorithm() sys.exit(0) my_input()
def is_palindrome(x): """ :param x: integer :return: True if x is a Palindrome False if x is not a Palindrome """ rev = list(reversed(str(x))) if list(str(x)) == rev: return True else: return False #print(is_palindrome(121)) # True #print(is_palindrome(-121)) # False because -121 != 121- # print(is_palindrome(123)) # False
# Return the number of times that the string "code" appears anywhere in the given string variable (text), # except we'll accept any letter for the 'd', so "cope" and "cooe" count. text = 'testing_code' i = 0 count = 0 for x in text: # Check for the length of the remaining string is at least the size of search word (code) if len(text)-i >= 4 and text[i:i+2] + text[i+3] == 'coe': count = count + 1 i += 1 print(count) # Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period # So "xxyz" counts but "x.xyz" does not. xyz_string = 'abc.xyzxyz' dot_list = xyz_string.split('.') # Split all the texts by period wise xyz_check = False i = 0 for x in dot_list: if i == 0: # This section is meant for the first block of string, as it is not prefixed by a .dot Eg.'xyz.abc' i += 1 if 'xyz' in x: xyz_check = True elif 'xyz' in x[1:]: xyz_check = True print(xyz_check) # We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). # Return the number of small bars to use, assuming we always use big bars before small bars. # Return -1 if it can't be done small = 9 big = 3 goal = 18 big_required = int(goal/5) # Computing no. of big bars required in completing the goal if big >= big_required: small_required = goal - (big_required * 5) # Shedding out extra big bars available from the goal else: small_required = goal - (big * 5) # Shedding out given big bars from the goal if small >= small_required: # Checking the available small bars to met the goal requirement print(small_required) else: print(-1) # List 2 section # Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1 nums = [2, 1, 2, 3, 4] count = 0 for x in nums: if x % 2 == 0: count += 1 print(count) # Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. # Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values nums = [10, 3, 5, 6] maxv = max(nums) minv = min(nums) print(maxv-minv) # Return the "centered" average of an array of ints, which we'll say is the mean average of the values, # except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, # ignore just one copy, and likewise for the largest value. Use int division to produce the final average. # You may assume that the array is length 3 or more. lt = [-10, -4, -2, -4, -2, 0] minv = min(lt) maxv = max(lt) sumv = sum(lt)-minv-maxv print(int(sumv/(len(lt)-2))) # Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, # so it does not count and numbers that come immediately after a 13 also do not count nums = [1, 2, 2, 1, 13] # Initialize variables sum_list = 0 px = 0 for x in nums: if x != 13 and px != 13: # Skip the summation if the current & previous value is 13 sum_list += x px = 0 # Reset the previous value of 13 if set any elif px == 13 and x != 13: # Reset the previous value of 13 if the current value is not 13 px = 0 elif x == 13: # If current value is 13, assign 13 to previous x (px) variable px = x print(sum_list) # Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 # and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers. nums = [1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7] sum67 = 0 skip = 0 for x in nums: if x != 6 and skip == 0: sum67 += x elif x == 6: skip = 1 elif x == 7: skip = 0 print(sum67) # Given an array of ints, return True if the array contains a 2 next to a 2 somewhere nums = [4, 2, 4, 2, 2, 5] px = 0 has22 = False for x in nums: if x == 2 and px == 2: has22 = True break else: px = x print(has22) # Given a non-empty string like "Code" return a string like "CCoCodCode" text = 'Code' i = 0 sum_str = '' while i < len(text): sum_str = sum_str + text[0:i + 1] i += 1 print(sum_str) # Given a string, return the count of the number of times that a substring length 2 appears in the string # and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring). text = 'axxxaaxx' key = text[len(text) - 2:] # Getting the recurring substring count = 0 if key in text: # Only move into the for loop if there is any key in the given input for x in range(len(text) - 2): # Iterate till the last string excluding the key sub_str = text[x:x + 2] if sub_str == key: # Compare and increment the count value on match count += 1 print(count) # Given an array of ints, return True if one of the first 4 elements in the array is a 9. # The array length may be less than 4 nums = [1, 2, 3, 4, 5] count = 0 nine = False for x in nums: count += 1 if x == 9 and count < 5: nine = True elif count == 5: break print(nine) # Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere nums = [1, 1, 2, 1, 2, 3] if 1 in nums and 2 in nums and 3 in nums: print(True) else: print(False) # Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. # So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings a = 'aabbccdd' b = 'abbbxxd' str_length = min(len(a), len(b)) count = 0 # without the -1 in the for loop, when the control reaches the end of the string, # it will take the length of substring as 1 as opposed to 2 Eg, at the last when x value # reaches 7, the substring value of b would be 'd' for x in range(str_length -1): a_sub_str = a[x:x + 2] b_sub_str = b[x:x + 2] if a_sub_str == b_sub_str: count += 1 print(count) # Alternative solution to a similar problem expect we check the a substring across all the index of b a = 'xxcaazz' b = 'xxbaaz' count = 0 for x in range(len(a)-1): sub_str_a = a[x:x + 2] for y in range(len(b)-1): sub_str_b = b[y:y + 2] if sub_str_a == sub_str_b: count += 1 print(count)
resultado=0 numero1=raw_input("teclee un numero") print numero1 numero2=raw_input("Teclee otro numero") resultado = int(numero1)+ int(numero2) resultado=numero1+numero2 print resultado
nome_func = (input("Digite o nome do funcionário:")) salario = int(input("Digite o salário do funcionário:")) tempo_trab = int(input("Digite o tempo de trabalho:")) bonus_20 = salario * 0.20 bonus_10 = salario * 0.10 if (tempo_trab >=5): print("O funcionário vai receber o bônus de 20%:", bonus_20) else: print("O funcionário vai receber o print de 10%:",bonus_10)
# #define class User # class User: # # this method to run every time a new object is instantiated # def __init__(self, name, email): # # instance attributes # self.name = name # self.email = email # self.logged = True # # login method changes the logged status for a single instance (the instance calling the method) # def login(self): # self.logged = True # print(self.name + " is logged in.") # return self # # logout method changes the logged status for a single instance (the instance calling the method) # def logout(self): # self.logged = False # print(self.name + " is not logged in") # return self # # print name and email of the calling instance # def show(self): # print("My name is {self.name}. You can email me at {self.email}.") # return self # class bike: # def __init__(self, price, max_speed, miles=0): # self.price= price # self.max_speed= max_speed # self.miles= miles # def displayinfo(self): # print(self.price, self.max_speed, self.miles) # return self # def ride(self): # self.miles += 10 # print("riding") # return self # def reverse(self): # self.miles -=5 # if self.miles < 0: # self.miles=0 # print("reversing") # return self # bike1 = bike(200, "25mph").ride().ride().ride().reverse().displayinfo() # file vehicles.py # class Vehicle: # def __init__(self, wheels, capacity, make, model): # self.wheels = wheels # self.capacity = capacity # self.make = make # self.model = model # self.mileage = 0 # def drive(self,miles): # self.mileage += miles # return self # def reverse(self,miles): # self.mileage -= miles # return self # class Bike(Vehicle): # def vehicle_type(self): # return "Bike" # class Car(Vehicle): # def set_wheels(self): # self.wheels = 4 # return self # class Airplane(Vehicle): # def fly(self, miles): # self.mileage += miles # return self # v = Vehicle(4,8,"dodge","minivan") # print(v.make) # b = Bike(2,1,"Schwinn","Paramount") # print(b.vehicle_type()) # c = Car(8,5,"Toyota", "Matrix") # c.set_wheels() # print(c.wheels) # a = Airplane(22,853,"Airbus","A380") # a.fly(580) # print(a.mileage) class Card: def __init__(self, value, type): self.value = value self.type = type def show(self): print("Value: ", self.value, "Type: ", self.type) class Deck: def __init__(self, name): self.deck = [] self.name = name for i in ["clubs", "diamonds", "hearts", "spades"]: for j in range(1,14): self.deck.append( Card(j, i ) ) def show(self): print("\n", "*"*30, self.name, "*"*30) for card in self.deck: card.show() d1 = Deck("First Deck") d1.show() d2 = Deck("Second Deck") d2.show()
import math print("\t\t\t\t\t***** Amount Matrix\t*****") print("\n\nAmount to Borrow\tMonthly Interest\tQuarterly Interest\tSemi-Annual Interest\t\Annual Interest") A = input("\nEnter Amount: ") M = input("Enter Months: ") print("Choose Terms of Payment: ") print("[1] MOnthly") print("[2] Quarterly") print("[3] Semi-Annual") print("[4] Annual") num = input("Enter Choice: ") num = int(num) if num == 1: print("Your Monthly Payment is: ") if num == 2: print("Your Quarterly Payment is:") if num == 3: print("Your Semi-Annual Payment is:") if num == 4: print("Your Annual Payment is:")
# domahes44 t = int(input('Введите первое число ')) t2 = int(input('Введите второе число ')) f = input() if f == '+': print(t+t2) if f == '-': print(t-t2) if f == '*': print(t*t2) if f == '**': print(t**t2) if f == '/': print(t/t2) if f == '//': print(t//t2) if f == '%': print(t%t2)
#Author Nathan Hansen #nathanhansen2010@gmail.com #NathanHansenLAX on Twitter #Creates a manual brightness and contrast circuit for the PiCamera to take #time-lapse photos from picamera import PiCamera from gpiozero import MCP3008, Button from time import sleep from datetime import datetime pot1 = MCP3008(channel=0) #reads the potentiometer from channel 0 on the MCP pot2 = MCP3008(channel=1) #reads potentiometer to channel 1 on the MCP button = Button(17) #lets the program know that the button is connected to GPIO 17 camera = PiCamera() #create a connection to the PiCamera #this function captures the image and gives it a time-stamp def capture(): for i in range(timer): timestamp = datetime.now().isoformat() camera.capture('/home/pi/%s.jpg' % timestamp) sleep(delay) #starts the script by creating a preview window camera.start_preview(fullscreen=False, window = (0, 0, 640, 480)) #get the user input, settings and waits for the signal to start capturing try: timer=int(input("How many photos should the camera capture in the time-lapse?")) delay=int(input("How many seconds between shots?")) while True: brightness = round(pot1.value * 100) #turns the potentiometer value into a value between 0-100 print("Brightness",brightness) contrast = round(pot2.value * 100) #turns the potentiometer value into a value between 0-100 print("Contrast",contrast) camera.brightness=brightness camera.contrast=contrast settings="Brightness: "+str(brightness)+"Contrast: "+str(contrast) print(settings) camera.annotate_text=settings #places the settings in the preview window sleep(0.1) button.when_held=capture #Lets the user exit by entering CTRL+C except KeyboardInterrupt: camera.stop_preview() finally: print("TIMELAPSE EXITING")
import random tower = 50 player = 20 def tower_image(): print("|----------|") print("| / |") print("| / |") print("|----------|") print("| / |") print("| / |") print("|----------|") tower_image() print(" ") print("Welcome to Tower Defence") print(" ") bullet = int(input("How may armour will you carry: ")) while True: random_shoot = random.randint(0, bullet) shot = int(input("How many bullets will you shoot: ")) bullet -= shot if shot == random_shoot: tower -= shot*2 print("Tower is hit with", shot*2, "shots") print("Tower is left with", tower, "life") else: player -= shot/2 print("Tower defends, Player is hit with", shot/2,"shots") print("You have", player, "life left") if tower < 1: print("You won the Game") break
""" The ItemProcessor is a class for processing the effects of item schematics in a given context. """ from .exceptions import NoTargetSpecifiedException class ItemProcessor(object): """Class which processes item schematics in their relevant contexts.""" def __init__(self, bot): self.bot = bot def process_item(self, character, item, target=None): """ This method processes an item schematic. args: character: The character which is using the item. item: An item schematic. """ # Make sure a target is specified somewhere if target is None: if item.target is None: raise NoTargetSpecifiedException target = item.target # Set or validate target if target == 'self': target = character # TODO: more target types # Perform the item's actions for verb in item.actions: if verb.action == 'add_health': if target.model.health + int(verb.value) > \ target.model.health_max: target.model.health = target.model.health_max else: target.model.health += int(verb.value) # Do damage to target # Buff stats # Debuff Stats # Teleport (End event/sequence)
#!/usr/bin/env python3 """ Author : Ken Youens-Clark <kyclark@gmail.com> Date : 2021-03-11 Purpose: Find reversible words """ import argparse from typing import NamedTuple, TextIO class Args(NamedTuple): """ Command-line arguments """ file: TextIO # -------------------------------------------------- def get_args() -> Args: """ Get command-line arguments """ parser = argparse.ArgumentParser( description='Find reversible words', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-f', '--file', help='Words file', metavar='FILE', type=argparse.FileType('rt'), default='/usr/share/dict/words') args = parser.parse_args() return Args(args.file) # -------------------------------------------------- def main() -> None: """ Make a jazz noise here """ args = get_args() seen = set() for line in args.file: for word in map(str.lower, filter(lambda w: len(w) > 2, line.split())): rev = ''.join(reversed(word[1:] + word[0])) if word == rev: if word not in seen: print(word) seen.add(word) # -------------------------------------------------- if __name__ == '__main__': main()
from random import randint def create_array(size=10,max=50): return [randint(0,max) for _ in range(size)] def quickSort(a): if len(a)<=1: return a smaller,equal,larger = [],[],[] pivot = a[randint(0,len(a)-1)] for x in a: if x<pivot: smaller.append(x) elif x==pivot: equal.append(x) else: larger.append(x) return quickSort(smaller)+equal+quickSort(larger) def bubbleSort(arr): print("lel") #benchmark quicksort vs bubblesort def benchmark(samples,array): times = {'quick':[],'bubble':[]} from time import time for size in array: tot_time=0.0 for _ in range(samples): a=create_array(size,size) t0=time() s=bubbleSort(a) t1=time() tot_time+=(t1-t0) times['bubble'].append(tot_time/float(samples)) tot_time=0.0 for _ in range(samples): a=create_array(size,size) t0=time() s=quickSort(a) t1=time() tot_time+=(t1-t0) times['quick'].append(tot_time/float(samples)) print ("n\tQuickSort\tBubbleSort") print (40*"_") for i,size in enumerate(array): print ("%d\t%0.5f\t%0.5f"%( size, times['quick'][i], times['bubble'][i])) samples = 5 array=[10,100,1000,10000,100000] benchmark(samples,array)
def flowShopPermutation(order, matrix): final = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))] largest = 0; for i in range(len(order)): for j in range(len(matrix[0])): if i == 0: if j == 0: final[order[i]][j] = matrix[order[i]][j]; else: final[order[i]][j] = final[order[i]][j-1] + matrix[order[i]][j]; else: if j == 0: final[order[i]][j] = final[order[i-1]][j] + matrix[order[i]][j]; else: final[order[i]][j] = max(final[order[i]][j-1],final[order[i-1]][j]) + matrix[order[i]][j]; #final[order[i]][j] = int(max(2, 3)) + matrix[order[i]][j]; if final[order[i]][j] > largest: largest = final[order[i]][j]; return largest; def printMatrix(matrix): print('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in matrix]));
#!/usr/bin/python3 def remove_char_at(str, n): idx = 0 str1 = "" for i in str: if idx != n: str1 = str1 + i idx = idx + 1 return str1
#!/usr/bin/python3 """This Module holds a funtion to decodificate with json """ import json def from_json_string(my_str): """Returns an object (Python data structure) represented by a JSON string Arguments: my_str {[str]} -- string to represent in object Returns: [obj] -- Python data structure, object """ return json.loads(my_str)
#!/usr/bin/python3 """Class Square""" class Square: """Class Square that defines a square. attributes: size: Variable that represents the size of the square. """ # method to initialize an object def __init__(self, size): self.__size = size
from tkinter import * from backend import * def view_command(): list1.delete(0,END) result=view() for i in result: list1.insert(END,i) def search_command(): list1.delete(0, END) result =search(title_text.get(),author_text.get(),isbn_text.get(),year_text.get()) for i in result: list1.insert(END, i) def insert_command(): insert(title_text.get(),author_text.get(),isbn_text.get(),year_text.get()) list1.delete(0, END) list1.insert(END,title_text.get(),author_text.get(),isbn_text.get(),year_text.get()) def delete_command(): delete(title_text.get()) window=Tk() window.wm_title("BookStore") l1=Label(window,text="Title") l1.grid(row=0,column=0) title_text=StringVar() e1=Entry(window,textvariable=title_text) e1.grid(row=0,column=1) l2=Label(window,text="author") l2.grid(row=0,column=2) author_text=StringVar() e2=Entry(window,textvariable=author_text) e2.grid(row=0,column=4) l3=Label(window,text="year") l3.grid(row=1,column=0) year_text=StringVar() e3=Entry(window,textvariable=year_text) e3.grid(row=1,column=1) l4=Label(window,text="isbn") l4.grid(row=1,column=2) isbn_text=StringVar() e4=Entry(window,textvariable=isbn_text) e4.grid(row=1,column=4) list1=Listbox(window,height=6,width=35) list1.grid(row=2,column=0,rowspan=6, columnspan=2) sbl=Scrollbar(window) sbl.grid(row=2,column=2,rowspan=6) list1.configure(yscrollcommand=sbl) sbl.configure(command=list1.yview()) b1=Button(window,text='View all',command=view_command) b1.grid(row=2,column=3) b2=Button(window,text="search entry",command=search_command) b2.grid(row=3,column=3) b4=Button(window,text="insert",command=insert_command) b4.grid(row=5,column=3) b5=Button(window,text="delete",command=delete_command) b5.grid(row=6,column=3) window.mainloop()
def react_polymer(polymer): previous_length = len(polymer) while True: print(previous_length) pairs = list(react_iteration(polymer)) polymer = reaction_to_string(pairs) new_length = len(polymer) if new_length == previous_length: break previous_length = new_length result = reaction_to_string(polymer) return result def reaction_to_string(reaction): result = ''.join(reaction) return result def react_iteration(polymer): STOP = '|' padded_polymer = polymer + STOP total_pairs = len(padded_polymer) - 1 remove_next = False for pair in range(total_pairs): first, second = padded_polymer[pair:pair+2] if remove_next: remove_next = False continue if first.lower() == second.lower(): if first != second: remove_next = True continue yield first if __name__ == '__main__': with open('input') as input_file: input_string = input_file.read() print(len(react_polymer(input_string)))
# rating: the average rating on a 1-5 scale achieved by the book # review_count: the number of Goodreads users who reviewed this book # isbn: the ISBN code for the book # booktype: an internal Goodreads identifier for the book # author_url: the Goodreads (relative) URL for the author of the book # year: the year the book was published # genre_urls: a string with '|' separated relative URLS of Goodreads genre pages # dir: a directory identifier internal to the scraping code # rating_count: the number of ratings for this book (this is different from the number of reviews) # name: the name of the book import numpy as np #import matplotlib.pyplot as plt import pandas as pd #import seaborn as sns #Write a function that accepts an author url and returns the author's name based on your experimentation above def get_author(url): ####### # Insert your code name = url.split('.')[-1] ####### return name #Write a function that accepts a genre url and returns the genre name based on your experimentation above def split_and_join_genres(url): ####### # Insert your code gener = url.split('|') ####### return gener pd.set_option('display.width', 500) pd.set_option('display.max_columns', 100) #Read the data into a dataframe df = pd.read_csv("data/goodreads.csv") #Examine the first couple of rows of the dataframe ####### # Insert your code #print(df.head()) ####### df=pd.read_csv("data/goodreads.csv", header=None, names=["rating", 'review_count', 'isbn', 'booktype', 'author_url', 'year', 'genre_urls', 'dir','rating_count', 'name']) #Examine the first couple of rows of the dataframe ####### # Insert your code #print(df.head()) ####### #Start by check the column data types ####### # Insert your code #print (df.dtypes) ####### #Come up with a few other important properties of the dataframe to check ####### # Insert your code #First let's drop missing values and nan cleanedDf = df.dropna(axis = 0, how ='any') #We might need to convert some columns datatypes cleanedDf['review_count'] = cleanedDf['review_count'].astype(int) #print(cleanedDf.dtypes) #print (cleanedDf.head()) ####### #Get a sense of how many missing values there are in the dataframe. ####### # Insert your code missingValues = df.isnull().sum() #print(missingValues) ####### #Treat the missing or invalid values in your dataframe ####### # Insert your code #We can replace the nan values with some static values df = df.replace(np.nan,'not-found') ####### #Check the column data types again ####### # Insert your code #print(df.dtypes) ####### #Convert rating_count, review_count and year to int ####### # .Insert your code cleanedDf['rating_count'] = cleanedDf['rating_count'].astype(float) cleanedDf['review_count'] = cleanedDf['review_count'].astype(int) cleanedDf['year'] = cleanedDf['year'].astype(int) cleanedDf.loc[cleanedDf.genre_urls.isnull(), 'genre_urls']="" cleanedDf.loc[cleanedDf.isbn.isnull(), 'isbn']="" #print(cleanedDf.dtypes) ####### #Part 3: We will need author and genre to proceed! Parse the author column from the author_url and genres column from the genre_urls. Keep the genres column as a string separated by '|'. cleanedDf['author'] = cleanedDf['author_url'].map(get_author) cleanedDf['genres'] = cleanedDf['genre_urls'].map(split_and_join_genres) print(cleanedDf.head())
# Author: Leonardo Bolek import random def play(): print('****************************************************') print('*** Hello, welcome to the Guess the Number Game! ***') print('****************************************************') secret_number = random.randrange(1, 101) chances = 0 points = 1000 print('Levels of difficulty:') print('(1) Easy | (2) Medium | (3) Hard') level = int(input('Choose your level: ')) if(level == 1): chances = 20 elif(level == 2): chances = 10 else: chances = 5 for round in range(1, chances + 1): print(f'Chance {round} of {chances}') guess = int(input('Guess the number from 1 to 100: ')) print(f'You typed: {guess}') right_answer = guess == secret_number bigger = guess > secret_number lower = guess < secret_number if(guess < 1 or guess > 100): print('You must type a number from 1 to 100.') continue if(right_answer): print(f'You guessed the right number and scored {points} points! Congratulations!!!') break else: if(bigger): print('Wrong! You guessed a bigger number.') elif(lower): print('Wrong! You guessed a lower number.') lost_points = abs(secret_number - guess) # 40 - 20 = 20 points points = points - lost_points print(f'Game over! You scored {points} points. Thank you for playing!') if(__name__ == '__main__'): play()
print("welcome to the love calculator") name1 = input("Write your Name: \n ") name2 = input("Write Their Name: \n ") combined_string = name1 + name2 lower_case_string = combined_string.lower() t = lower_case_string.count("t") r = lower_case_string.count("r") u = lower_case_string.count("u") e = lower_case_string.count("e") true = t+r+u+e l = lower_case_string.count("l") o = lower_case_string.count("o") v = lower_case_string.count("v") e = lower_case_string.count("e") love = l+o+v+e love_score =int(str(true) + str(love)) if(love_score<20) or (love_score>90): print(f"Your love score is {love_score}, you are not made for each other ") elif(love_score>=40) and (love_score<=70): print("you are perfect for each other,your love is outstanding") else: print(f"Your love score is {love_score} you both are loving too much")
import abc class Typed(abc.ABC): @property @abc.abstractmethod def type(self) -> str: pass @property @abc.abstractmethod def display(self) -> str: pass @property @abc.abstractmethod def data(self) -> dict: pass def dict(self): _type = 'type' _display = 'display' data = self.data for key in [_type, _display]: if key in data: raise TypeError('Key \'{}\' not allowed in data dictionary of class'.format(key)) data[_type] = self.type data[_display] = self.display return data
class Student: #constructor def __int__(self,name,age,roll no,branch): self.name = name self.age = age self.roll no = roll no self.branch = branch # Function to add new student def addStudent(): new = Student(self,name,age,roll no,branch,GPA = 0) # add to the students list ls.append(new) #function to update student bio def bioUpdate(self,address,phone number): self.address = address self.phone number = phone number i = int(input(" enter student roll no ")) # print name and roll no of the student to verify the correct match or not print("name: ",new.name) print("roll no: ", new.roll no) # add address and phone number address = input(" enter student address ") phone number = input(" enter 10 digits phone number ") print( "address: ", new.address) print("phone number: ", new.phone number) print("\n") # function to update the score def scoreUpdate(self,m1,m2,m3,m4,m5): self.marks1 = m1 self.marks2 = m2 self.marks3 = m3 self.marks4 = m4 self.marks5 = m5 new_scores = input('m1','m2','m3','m4','m5') print("new_scores") # function to delete a student def rustricate(self,roll no): #for i in rage(ls()): # if (ls[i].roll no == remove) # return i del ls[i] # function to graduate students def graduate(): print("enter marks obtained: ") m1 = int(m1); m2 = int(m2); m3 = int(m3); m4 = int(m4); m5 = int(m5); sum = m1+m2+m3+m4+m5; average = sum/5 if (average >= 80): print('Grade A'); elif(average >= 60): print('Grade B'); elif(average >= 50): print('Grade C'); elif(average <= 40): print('Fail'); else: print("Roll no not found");
# Intermediate data visualisation with Seaborn # Seaborn uses matplotlib to generate statistical visualisations # Panda is a foundational library for analysing data, it also supports basic plotting capability # Seaborn supports complex visualisations of data - it is build on matplotlib and works best with pandas' dataframes # The distplot is similar to a histogram - by default generates a Guassian Kernel Density Estimate (KDE) import seaborn as sns sns.distplot(df['alcohol'']) # Displot has multiple optional arguments # In order to plot a simple histogram, you can disable the KDE and specify the number of bins to use # E.g. Creating a simple histogram sns.distplot(df['alcohol']), kde=False, bins=10) # Alternative data distributions # A rug plot is an alternative way to view the distribution of data # A kde plot and rug plot can be combined sns.distplot(df['alcohol'], hist=False, rug=True]) # It is possible to further customise a plot by passing arguments to the underlying function sns.distplot((df['alcohol'], hist=False, rug=True, kde_kws={'shade':True})) # Passing kde kewords dictionary - used to shade # Regression plots in Seaborn # Histogram - univariate analysis # Regression - bi-variate analysis # regplot function generates a scatterplot with a regression line # Usage is similar to distplot # data and x and y variables must be defined sns.regplot(x="alcohol", y="pH", data=df) # lmplot() builds on top of the base regplot() # regplot() - low level # lmplot() - high level # lmplot faceting # Organise data by hue sns.lmplot(x="quality", y="alcohol", data=df, hue="type") # Organise data by col sns.lmplot(x="quality", y="alcohol", data=df, col="type") # Using seaborn styles # Seaborn has default configurations that can be applied with sns.set() # These styles can override matplotlib and pandas plots as well sns.set() # Sets default theme - also called dark grid df['Tuition'].plot.hist() # Theme examples with sns.set_style() for style in ['white', 'dark', 'whitegrid', 'darkgrid', 'ticks']: sns.set_style(style) sns.distplot(df['Tuition']) plt.show() # Removing axes with despine() sns.set_style('white') sns.distplot(df['Tuition']) sns.despine(left=True) # Colors in seaborn # Seaborn supports assigning colors using matplotlib color codes sns.set(color_codes=True) sns.distplot(df['Tuition'], color=g) # Palettes # Seaborn uses the set_palette() function to define a palette # Can set a palette of colours that can be cycled through in a plot for p in sns.palettes.SEABORN_PALETTES: sns.set_palette(p) sns.distplot(df['Tuition']) # sns.palplot() function displays a palette # sns.color_palette() function returns the current palette for p in sns.palettes.SEABORN_PALETTES: sns.set_palette(p) sns.palplot(sns.color_palette()) plt.show() # Displays a palette in swatches in a jupyter notebook # Defining custom palettes # Circular colors = when the data is not ordered sns.palplot(sns.color_palette("Paired", 12)) # Sequential colors = when the data has a consistent range from high to low sns.palplot(sns.color_palette("Blues", 12)) # Diverging colors = when both the high and low values are interesting sns.palplot(sns.color_palette("BrBG", 12)) # Customizing with matplotlib # Most customisation is available through matplotlib Axes objects # Axes can be passed to seaborn functions import matplotlib as plt fig, ax = plt.subplots() sns.distplot(df['Tuition'], ax=ax) ax.set(xlabel="Tuition 2013-14") # Customises x data fig, ax = plt.subplots() sns.distplot(df['Tuition'], ax=ax) ax.set(xlabel="Tuition 2013-14", ylabel="Distribution", xlim=(0, 5000), title="2013-14 Tuition and Fees Distribution") # It is possible to combine and configure multiple plots fix, (ax0, ax1) = plot.subplots( nrows=1, ncols=2, sharey=True, figsize=(7,4)) sns.distplot(df['Tuition'], ax=ax0) sns.distplot(df.query("State == 'MN'")['Tuition'], ax=ax1) # Only plots data for the state of MN ax1.set(xlabel = "Tuition (MN)", xlim=(0, 7000)) ax1.axvline(x=20000, label="My Budget", linestyle="--") # Shows the max amount that can be budgeted for tuition ax1.legend() # Categorical plot types # Categorical data = takes on a limited and fixed number of values # Normally combined with numeric data # Examples include - geography, gender, ethnicity, blood type, eye color # Plot types # Show each observation - Stripplot and swarmplot # Abstract representations - Boxplot, violinplot, lvplot # Statistical estimates - barplot, pointplot, countplot # Stripplot - shows every observation in the dataset, can be difficult to see individual datapoints sns.stripplot(data=df, y='DRG Definition', x='Average Covered Charges', jitter=True) # Swarmplot - more sophisticated visualisation of all the data sns.swarmplot(data=df, y="DRG Definition", x="Average Covered Charges") # Places observations in a non-overlapping manner # Does not scale well to large datasets # Boxplot - used to show several measures related to dist of data incl median, upper and lower quartiles and outliers sns.boxplot(data=df, y="DRG Definition", x="Average Covered Charges") # Violinplot - combination of kernel density plot and boxplot, suitable for providing an alternative view of the dist of data sns.violinplot(data=df, y="DRG Definition", x="Average Covered Charges") # As uses a kernel density function, does not show all datapoints # Useful for large datasets, can be computationally intensive to create # lvplot - letter value plot sns.lvplot(data=df, y="DRG Definition", x="Average Covered Charges") # API same as boxplot and violin plot # Hybrid between boxplot and violin plot # Relatively quick to render and easy to interpret # Barplot - shows estimate of value and confidence interval sns.barplot(data=df, y="DRG Definition", x="Average Covered Charges", hue="Region") # Pointplot - similar to barplot, shows summary measure and confidence interval # Can be useful for observing how values change across categorical values sns.pointplot(data=df, y="DRG Definition", x="Average Covered Charges", hue="Region") # Countplot - displays the number of instances of each variable sns.countplot(data=df, y="DRG_Code", hue="Region") # Regression plots # PLotting with regplot() sns.regplot(data=df, x='temp', y='total_rentals', marker='+') # Evaluating regression with residplot() # Useful for evaluating fit of a model sns.residplot(data=df, x='temp', y='total_rentals') # Ideally residual markers should be plotted randomly across the horizontal line # If curved - may suggest that a non-linear model might be appropriate # Polynomial regression - using order parameters sns.regplot(data=df, x='temp', y='total_rentals', order=2) # Attempts polynomial fit using numpy functions # Residual plot with polynomial regression sns.regplot(data=df, x='temp', y='total_rentals', order=2) # Regression plots with categorical variables sns.regplot(data=df, x='mnth', y='total_rentals', x_jitter=.1, order=2) # x_jitter makes it easier to see values for each month # In some cases x_estimator can be useful for highlighting trends sns.regplot(data=df, x='mnth', y='total_rentals', x_estimator=np.mean, order=2) # Uses an estimator for x value (shows mean and CI) # Binning the data - x_bins can be used to divide the data into discrete bins # The regression line is still fit against all the data # Useful for a quick read on continuous data sns.regplot(data=df, x='temp', y='total_rentals', x_bins=4) # Matrix plots - heatmap most common type # heatmap() function requires data to be in a grid format # pandas crosstab() is frequently used to manipulate data pd.crosstab(df['mnth'], df['weekday'], values=df["total_rentals"],aggfunc='mean').round(0) # Build a heatmap sns.heatmap(pd.crosstab(df['mnth'], df['weekday'], values=df["total_rentals"],aggfunc='mean')) # Customise a heatmap sns.heatmap(df_crosstab, annot=True, # Turns on annotations in the individual cells fmt="d", # Ensures results are displayed as integers cmap="YlGnBu", # Changes the shading used cbar=False, # Color bar is not displayed linewidths=.5) # Lines between cells # Centering the heatmap color scheme on a specific value sns.heatmap(df_crosstab, annot=True, fmt="d", cmap="YlGnBu", cbar=True, center=df_crosstab.loc[9.6]) # Centered around saturdays in June # Plotting a correlation matrix # Pandas corr function calculates correlations between columns in a dataframe # The output can be converted to a heatmap with seaborn sns.heatmap(df.corr()) # Using FacetGrid, factorplot and lmplot # Can combine multiple smaller plots into a larger visualisation # Using small multiples is helpful for comparing trends across multiple variables - trellis or lattice plot # Also frequently called faceting # Seaborn's grid plots requires "tidy" format - one observation per row of data # FacetGrid # Fondational for many data aware grid # Allows the user to control how data is distributed across columns, rows and hue # Once a FacetGrid is created, its plot type must be mapped to the grid # Must use two step process - defining the facets and mapping the plot type # FacetGrid categorical example g = sns.FacetGrid(df, col="HIGHDEG") # Set up FacetGrid with col has highest degree awarded g.map(sns.boxplot, 'Tuition', # Plot a boxplot of the tuition values order=['1','2','3','4']) # Specifies the order # Factorplot simpler way of using FacetGrid for categorical data # Combines facetting and mapping into 1 function sns.factorplot(x="Tuition", data=df, col="HIGHDEG", kind="box") # FacetGrid for scatter or regression plots g = sns.FacetGrid(df, col="HIGHDEG") g.map(plt.scatter, 'Tuition', 'SAT_AVG_ALL') # lmplot plots scatter and regression plots on a FacetGrid sns.lmplot(data=df, x="Tuition", y="SAT_AVG_ALL", col="HIGHDEG", fit_reg=False) # Disabled regression lines sns.lmplot(data=df, x="Tuition", y="SAT_AVG_ALL", col="HIGHDEG", row="REGION") # Row used to filter data by region # Using PairGrid and pairplot # Also allow us to see interactions across different columns of data # Only define the columns of data we want to compare # Pairwise relationships # PairGrid shows pairwise relationships between data elements # Diagonals contain histograms # Contains scatter plot alternating which variable is on the x and y axis # Similar API to FacetGrid, but do not define the row and column parameters g = sns.PairGrid(df, vars=["Fair_Mrkt_Rent", "Median_Income"]) # Define variables - dataframe cols we want to look at g = g.map(plt.scatter) # Customising the PairGrid diagonals g = sns.PairGrid(df, vars=["Fair_Mrkt_Rent", "Median_Income"])] g = g.map_diag(plt.hist) g = g.map_offdiag(plt.scatter) # Pairplot is a shortcut for PairGrid sns.pairplot(df, vars=["Fair_Mrkt_Rent", "Median_Income"], kind=reg, # Plots regression line diag_kind='hist') sns.pairplot(df.query('BEDRMS < 3'), vars=["Fair_Mrkt_Rent", "Median_Income", "UTILITY"]\ ,hue='BDRMS', palette='husl', plot_kws={'alpha': 0.5}) # 3 variables results in 9 plots # Using JointGrid and jointplot # Compares the distribution of data between two variables # Input - x and y variable # Centre contains scatter plot of two variables # Plots along x and y axis show the distribution of data for each variable # Can configure by specifying the types of joint plots and marginal plots g = sns.JointGrid(data=df, x="Tuition", y="ADM_RATE_ALL") # Define grid g.plot(sns.regplot, sns.distplot) # Map plots onto grid # Advanced JointGrid g = sns.JointGrid(data=df, x="Tuition", y="ADM_RATE_ALL") g = g.plot_joint(sns.kdeplot) # Specifies KDE plot in center g = g.plot_marginals(sns.kdeplot, shade=True) g = g.annotate(stats.pearsonr) # Provides additional information about the relationship of the variables (pearson correl value) # Jointplot - easier to use, less available customisations sns.jointplot(data=df, x="Tuition", y="ADM_RATE_ALL", kind="hex") # Specifies hex plot # Customising a jointplot - shows the pearson r by default for a regplot g = (sns.jointplot(x="Tuition", y="ADM_RATE_ALL", kind="scatter", xlim=(0,25000), # Set limits for x axis marginal_kws=dict(bins=15, rug=True), # Pass keywords to marginal plot to control structure of hist data=df.query('UG < 2500 & Ownership == "Public"')) # Filters data .plot_joint(sns.kdeplot)) # KDE plot is overlaid on scatter plot # Supports adding overlay plots to enhance the final output # Selecting seaborn plots # distplot() is a good place to start for dist analysis # rugplot() and kdeplot() can be useful alternatives # For two variables # lmplot() performs regression analysis and supports facetting # Good for determining linear relationships between data # Explore data with the categorical plots and facet with FacetGrid # Pairplot and Jointplot - more useful after preliminary analysis completed # Good for regression analysis with lmplot # Good for analysing distributions with distplot
''' Matplotlib - complete control over properties of your plot pyplot submodule''' import matplotlib.pyplot as plt # Subplots creates figure object and axes object # Figure - container, holds everything on page # Axes - holds the data (the canvas) # Adding data to axes fig, ax = plt.subplots() ax.plot(seattle_weather['MONTH'], seattle_weather['MLY-TAVG-NORMAL']) ax.plot(austin_weather['MONTH'], austin_weather['MLY-TAVG-NORMAL']) plt.show() # Can plot multiple plots on one axes # Customising your plots # Adding markers ax.plot(austin_weather['MONTH'], austin_weather['MLY-TAVG-NORMAL'], marker="o") plt.show() # Also: "v", check library for more # Setting linestyle ax.plot(austin_weather['MONTH'], austin_weather['MLY-TAVG-NORMAL'], marker="o", linestyle="--") plt.show() # linestyle="None" - no line # Chosing colour ax.plot(austin_weather['MONTH'], austin_weather['MLY-TAVG-NORMAL'], marker="o", linestyle="--", color="r") plt.show() # Axes object has several methods that starts with "set" - methods can be used to change properties of object before show # Customising axis labels ax.set_xlabel("Time (months)") ax.set_ylabel("Average temperature (Farenheit degrees)") ax.set_title("Weather in Seattle") plt.show() #Small multiples #Multiple small plots that show similar data across different conditions fig, ax=plt.subplots() #Creates one subplot # Typically arranged as a grid with rows and columns fig, ax=plt.subplots(3, 2) # Axes - now an array of axes objects with shape 3x2 ax.shape #3,2 # Now need to call the plot method on an element of the array # Special case for only one row or column of plots fig, ax=plt.subplots(2, 1, sharey="True") #sharey ensures y-axis range is fixed the same for both ax[0].plot(seattle_weather["MONTH"], seattle_weather["MLY-PRCP-NORMAL"]), color="b") ax[0].plot(seattle_weather["MONTH"], seattle_weather["MLY-PRCP-25PCTL"]), linestyle="--", color="b") ax[0].plot(seattle_weather["MONTH"], seattle_weather["MLY-PRCP-75PCTL"]), linestyle="--", color="b") ax[1].plot(austin_weather["MONTH"], austin_weather["MLY-PRCP-NORMAL"]), color="r") ax[1].plot(austin_weather["MONTH"], austin_weather["MLY-PRCP-25PCTL"]), linestyle="--", color="r") ax[1].plot(austin_weather["MONTH"], austin_weather["MLY-PRCP-75PCTL"]), linestyle="--", color="r") ax[0].set_ylabel("Precipitation") ax[1].set_ylabel("Precipitation") ax[1].set_xlabel("Time (months)") # Only add x-axis label to bottom plot plt.show() # PLotting time series data import matplotlib.pyplot as plt fig, ax=plt.subplots() ax.plot(climate_change.index, climate_change["co2"]) ax.set_xlabel('Time') ax.set_ylabel("CO2 (ppm)") plt.show() # Zooming in on a decade sixties = climate_change["1960-01-01":"1969-12-31"] fig, ax=plt.subplots() ax.plot(sixties.index, sixties["co2"]) ax.set_xlabel('Time') ax.set_ylabel("CO2 (ppm)") plt.show() # Plotting time series with different variables # Using twin axes import matplotlib.pyplot as plt fig, ax=plt.subplots() ax.plot(climate_change.index, climate_change["CO2"], color="blue") ax.set_xlabel('Time') ax.set_ylabel('CO2 (ppm)', color="blue") ax.tick_params('y',colors='blue') #Sets tick color to blue ax2 = ax.twinx() #Share the same x axis, but y axis separate ax2.plot(climate_change.index, climate_change["relative_temp"], color='red') ax2.set_ylabel('Relative temperature (Celsius)', color='red') ax2.tick_params('y', color='red') plt.show() # A function that plots time series def plot_timeseries(axes, x, y, color, xlabel, ylabel) : axes.plot(x, y, color=color) axes.set_xlabel(xlabel) axes.set_ylabel(ylabel, color=color) axes.tick_params('y', colors=color) # Using our function fig, ax=plt.subplots() plot_timeseries(ax, climate_change.index, climate_change['CO2'], 'blue', 'Time', 'CO2 (ppm)') ax2 = ax.twinx() plot_timeseries(ax, climate_change.index, climate_change['relative_temp'], 'red', 'Time', 'Relative temperature (Celsius)') plt.show() # Adding annotations to time series data fig, ax=plt.subplots() plot_timeseries(ax, climate_change.index, climate_change['CO2'], 'blue', 'Time', 'CO2 (ppm)') ax2 = ax.twinx() plot_timeseries(ax, climate_change.index, climate_change['relative_temp'], 'red', 'Time', 'Relative temperature (Celsius)') ax2.annotate(">1 degree", xy=(pd.TimeStamp("2015-10-06"),1), xytext=(pd.TimeStamp('2008-10-06'),-0.2), arrowprops={"arrowstyle":"->","color":"grey"}) #Pandas timestamp obj used to define date # xytext object allows positioning of text # arrowprops - connects text to data, empty dictionary - default properties # can define the properties of arrows - customising annotations, matplot lib documentation plt.show() # Quantitative comparisons - bar charts medals = pd.read_csv('medals_by_country_2016.csv', index_col=0) fig, ax=plt.subplots() ax.bar(medals.index, medals["Gold"]) ax.set_xticklabels(medals.index, rotation = 90) # Rotates tick labels ax.set_ylabel("Number of medals") #Set ylabels plt.show() # Creating a stacked bar chart fig, ax=plt.subplots() ax.bar(medals.index, medals["Gold"], label="Gold") #Labels allow for legend ax.bar(medals.index, medals["Silver"], bottom=medals["Gold"], label="Silver") ax.bar(medals.index, medals["Bronze"], bottom=medals["Gold"]+medals["Silver"], label="Bronze") ax.set_xticklabels(medals.index, rotation=90) ax.set_ylabel("Number of medals") ax.legend() plt.show() # Histograms - shows distribution of values within a variable fig, ax=plt.subplots() ax.hist(mens_rowing["Height"], label="Rowing", bins=5, histtype="step") ax.hist(mens_gymnastic["Height"], label="Gymnastics", bins=5, histtype="step") ax.set_xlabel("Height (cm)") ax.set_ylabel("# of observations") ax.legend() plt.show() # Bins - default = 10 # Can set a sequence of values - sets boundaries between the bins, e.g bins=[150, 160, 170, 180, 190, 200, 210] # Transparency histtype="step" #Statistical plotting #Adding error bars to bar charts - additional markers that tell us something sbout the dist of data fig, ax=plt.subplots() ax.bar("Rowing", mens_rowing["Height"].mean(), yerr=mens_rowing["Height"].std()) ax.bar("Gymnastics", mens_gymnastics["Height"].mean(), yerr=mens_gymnastics["Height"].std()) ax.set_ylabel("Height (cm)") plt.show() # Adding error bars to line plots fig, ax = plt.subplots() ax.errorbar(seattle_weather['MONTH'] #Sequence of x values seattle_weather['MLY-TAVG-NORMAL'], #Sequence of y values yerr=seattle_weather['MLY-TAVG-STDEV']) #yerr keyword, takes std devs of avg monthly temps ax.errorbar(austin_weather['MONTH'], austin_weather['MLY-TAVG-NORMAL'], yerr=austin_weather['MLY-TAVG-STDEV']) ax.set_ylabel("Temperature (Farenheit)") plt.show() #Adding boxplots fig, ax=plt.subplots() ax.boxplot([mens_rowing["Height"], mens_gymnastics["Height"]]) ax.set_xticklabels(["Rowing", "Gymnastics"]) ax.set_ylabel("Height (cm)") plt.show() # Line = mean # Box = IQR # Whiskers = 1.5x IQR # SHould be around 99% of the distribution, if normal # Points beyond whiskers - outliers # Quant comparisons, scatter plots # Bivariate comparison - scatter is standard visualisation fig, ax=plt.subplots() ax.scatter(climate_change["co2"], climate_change["relative_temp"]) ax.set_ylabel("Relative temperature (Celcius)") ax.set_xlabel("CO2 (ppm)") plt.show() #Customising scatter plots eighties = climate_change["1980-01-01":"1989-12-31"] nineties = climate_change["1990-01-01":"1999-12-31"] fig, ax=plt.subplots() ax.scatter(eighties["co2"], eighties["relative_temp"], color="red", label="eighties") ax.scatter(nineties["co2"], eighties["relative_temp"], color="blue", label="nineties") ax.legend() ax.set_xlabel("CO2") ax.set_ylabel("Relative temperature (Celsius)") plt.show() #Encoding a third variable by color fig, ax=plt.subplots() ax.scatter(climate_change["co2"], climate_change["relative_temp"], c=climate_change.index) #Variable becomes encoded as color (different to color keyword) ax.set_xlabel("CO2") ax.set_ylabel("Relative temperature (Celsius)") plt.show() # Preparing your figures to share with others # Changing plot style plt.style.use("ggplot") #Emulates the style of the R library ggplot, changes multiple elements ax.plot(austin_weather['MONTH'], austin_weather['MLY-TAVG-NORMAL'], marker="o", linestyle="--", color="r") ax.set_xlabel("Time (months)") ax.set_ylabel("Average temperature (Farenheit degrees)") ax.set_title("Weather in Seattle") plt.show() plt.style.use("default") #Go back to default # Several different styles available at matplotlib documentation # e.g. bmh, seaborn-colorblind # Seaborn software library for statistical visualisation based on matplotlib # (some styles adopted back by matplotlib) # Dark backgrounds less visible - discouraged # Consider colourblind friendly styled, e.g. "tableau-colorblind10" # If printing required - use less ink, avoid coloured backgrounds # If printing b&w, use grayscale style #Sharing visualisations with others fig, ax=plt.subplots() ax.bar=(medals.index, medals["Gold"]) ax.set_xticklabels(medals.index, rotation=90) ax.set_ylabel("Number of medals") fig.savefig("goldmedals.png") #Call to figure objects to save, provide file name. Won't appear on screen, but as a file ls #unix function gives list of files in working directory #png - lossless compression of image - image retains highquality, but takes up relatively large space/bandwidth #jpg - if part of website, uses lossycompression, takes up less diskspace/bandwidth, can control deg of loss of qual fig.savefig("godmedals.png", quality=50) #Controls degree of loss of quality. Avoid above 95, comp no longer affected fig.savefig("goldmedals.svg") #Vector graphics file. Diff elements can be edited in detail by advanced graphics software (good if need to edit later) fig.savefig("goldmedals.png", dpi=300) #dots per inch - higher number -> more densely rendered image. 300 rel high qual. Larger filesize fig.set_size_inches([5,3]) #Allows control of size of figure - width x height (determines aspect ratio) # Automating figures from data # Allows you to write programmes that automatically adjust what you are doing based on the input data " Why automate?" \ "- Ease and speed" \ "- Flexibility" \ "- Robustness" \ "- Reproducibility" # Column - panda series object sports = summer_2016_medals["Sport"].unique() #Creates a list of distinct sports fig ax=plt.subplots() for sport in sports: sport_df = summer_2016_medals[summer_2016_medals["Sport"] == sport] ax.bar(sport, sport_df["Height"].mean(), yerr=sport_df["Height"].std()) ax.set_ylabel("Height (cm)") ax.set_xticklabels(sports, rotation=90) plt.show() #Matplotlib gallery - lots of examples # Can also plot in 3D, e.g. parametric curve through 3D space # Visualising data from images, using pseudo colour - each value in image translated into a color # Animations - uses time to vary display through animation # Geospatial data - other packages e.g. catopy extends matplotlib using maps. Also seaborn # Pandas + Matplotlib = Seaborn
""" Data visualisation - Explore the dataset - Report insights • Matplotlib - Pyplot • Line plot - Plt.plot(year, pop) --> tells what to plot and how to plot - Plt.show() --> Displays plot • Scatter plot - Plt.scatter(year, pop, s=size, c=colour) • Putting into logarithmic scale - Plt.xscale('log') • Histogram - Explore dataset - Get idea about distribution - Divides dataset into bins - shows number of datapoint in bin - X = list of values want to build hist for - Bins - number of bins data is divided into - default = 10 - Plt.hist(values, bins=3) - Plt.clf() - allows multiple charts to be shown (???) • Data visualisation - Axis labels ○ Plt.xlabel('Year') ○ Plt.xlabel('Pop') ○ Must call before show function - Titles ○ Plt.title('XYZ') - Plt.yticks([0,2,4,6,8,10], [0, 2BN, 4BN, 6BN, 8BN, 10BN]) ○ Sets axis ticks ○ Second list - display names - Add more data ○ year = [x, y, z] + year ○ Pop = [x,y,z] + year - Plt.grid(True) • Dictionaries - Can use as a lookup - World = {"afghanistan" :30.55, "albania":2.77, "algeria":39.21} - World["albania"] - Very efficient - Keys must be immutable objects - cannot be changed after creation ○ Strings, booleans, integers and floats are immutable ○ Lists are mutable - Adding to dictionary ○ World["sealand"] = 0.00027 ○ Check: "sealand" in world - Deleting from dictionary ○ Del(world["sealand"]) - List vs. Dictionary ○ List - sequence of numbers, indexed by range of numbers - useful if order matters, with the ability to select entire subsets ○ Dictionary - Indexed by unique keys, lookup table with unique keys, quick to lookup • Pandas - Rectangular dataset - - Numpy an option - Pandas package ○ Data manipulation tool, built on numpy ○ Data stored in Dataframe - Can build dataframe manually from dictionary - Pd.DataFrame(dict) - Manually label index ○ Brics.index = ["BR", "RU",...] - Importing data ○ Brics.csv ○ Brics = pd.read_csv("path/to/brics.csv", index_col = 0) ○ To tell dataframe that row index is first column --> index_col = 0 • Pandas 2 - Column access ○ Brics["country"] ○ Series - 1D labelled array ○ Brics[["country"]] ○ Dataframe ○ Can extend to two columns - subdataframe - Row access ○ Brics[1:4] -> slice ○ End of slice exclusive ○ Index starts 0 - Loc ○ Select parts of table based on labels ○ Brics.loc["RU"] § Row as pandas series ○ Brics.loc[["RU", "IN", "CH"]] --> selected rows ○ Brics.loc[["RU","IN","CH"],["country","capital"]] --> subset ○ Brics.loc[:, ["country", "capital"]] --> returns all columns for two countries - Iloc ○ Based on position ○ Brics.iloc[[1,2,3]] ○ Brics.iloc[[1,2,3],[0,1] ○ Brics.iloc[:,[0,1]] • Logic, control flow and filtering - Comparison operators ○ Operators that can tell how too values relate and result in a boolean ○ Integer and string - not comparable - can't tell how objects of different types relate ○ Floats and ints are the exceptions ○ != --> not equal ○ == --> equal - Boolean operators ○ And § X>5 and x<15 --> True and True --> True ○ Or § Y=5 § Y < 7 or y>13 § True ○ Not § Negates the boolean value its used on § Not True = False § Not False = True - NumPy - doesn't want an array of booleans, array equivalents: § Logical_and() § Logical_or() § Logical_not() § Np.logical_and(bmi > 21, bmi < 22) § Operation is performed element-wise § To select the array: □ Bmi[np.logical_and(bmi>21,bmi<22)] - If, elif, else § Z=4 § If z % 2 == 0 : □ Print("z is even") § Elif z % 3 == 0 : □ Print("z is divisible by 3") § Else : □ Print("z is divisible by 2 nor 3") § If first condition satisfied, second condition is never reached - Filtering pandas dataframes § Get column --> brics["area"] --> want series § Is_huge = Brics["area"] > 8 --> Get a boolean § Brics[is_huge] --> selects countries with an area greater than 8 § Shorten: brics[brics["area"] > 8] ○ Boolean operators § Brics[np.logical_and(brics["area"] > 8, brics["area"] < 10)] """ # While loop = repeated if statement """ syntax: while condition: expression""" # Repeating an action until a condition is met error = 50.0 while error > 1: error = error / 4 print(error) """ For Loop for var in seq : expression""" # Simple for loop fam = [1,2,3,4] for height in fam : print(height) # Displays index for index, height in enumerate(fam) : print("index" + str(index) + ":" str(height)) # Could iterate over every character in a string for c in "family" : print(c.capitalize()) # Loop data structures - part 1 world = {"afghanistan" : 30.55, "albania" : 2.77, "algeria" : 39.21} for key, value in world.items() print(key + "--" + str(value)) # Dictionaries are inherently unordered # key and values are arbitrary names #2D numpy arrays import numpy as np np_height = np.array([1.73, 1.68, 1.71, 1.89, 1.79]) np_weight = np.array([65.4, 59.2, 63.6, 88.4, 68.7]) meas = np.array([np_height, np_weight]) for val in np.nditer(meas) : print(val) # Dictionary -- for key, val in my_dict.items() : # Numpy array -- for val in np.nditer(my_array) : # Loop datastructures part 2 - Pandas DF for val in brics : print(val) # Will only print column headers for lab, row in brics.iterrows(): print(lab) print(row) # Prints entire series for lab, row in brics.iterrows() : print(lab + ": " + row["capital"]) # To add additional column with length of country name for lab, row in brics.iterrows() : # Creating series on every iteration brics.loc[lab, "name length"] = len(row["country"]) # Can be inefficient as creating for each row # Apply is more efficient brics["name_length"] = brics["country"].apply(len) # --> creates new array print(brics) # Random numbers - import numpy # np.random.rand() ---> #Pseudo random numbers np.random.seed(123) np.random.rand() # Ensures 'reproduceability # Coin toss import numpy as np np.random.seed(123) coin = np.random.randint(0,2) # Randomly generates 0 or 1 print (coin) if coin == 0 : print("heads") else : print("tails") # Random walk - succession of random steps, e.g. path of molecules # Building list based on outcomes import numpy as np np.random.seed(123) outcomes = [] #Initialise an empty list for x in range(10) : coin = np.random.randint(0,2) # Random coin toss if coin == 0 : outcomes.append("heads") else : outcomes.append("tails") print(outcomes) # Generating a random walk import numpy as np np.random.seed(123) tails = [0] for x in range(10) : coin = np.random.randint(0,2) tails.append(tails[x] + coin) print(tails) # Distribution of random walks import numpy as np np.random.seed(123) tails = [0] for x in range(10): coin = np.random.randint(0, 2) tails.append(tails[x] + coin) #100 runs import numpy as np import matplotlib.pyplot as plt np.random.seed(123) final_tails = [] for x in range(100000) : tails = [0] for x in range(10) : coin = np.random.randint(0,2) tails.append(tails[x] + coin) final_tails.append(tails[-1]) plt.hist(final_tails,bins=10) plt.show()
import sys input_seq = sys.argv[1] def ReverseComplement(seq): newseq = seq[::-1] newseq = newseq.replace('A','%').replace('T', 'A').replace('%', 'T') newseq = newseq.replace('C', '%').replace('G', 'C').replace('%', 'G') newseq = newseq.replace('a', '%').replace('t', 'a').replace('%', 't') newseq = newseq.replace('c', '%').replace('g', 'c').replace('%', 'g') return newseq print 'The reverse complement DNA sequence is', ReverseComplement(input_seq)
st = True and True print("True and True is", st) st1 = False and True print("False and True is", st1) st2 = 1 == 1 and 2 == 1 print("1 == 1 and 2 == 1 is", st2) st3 = "test" == "test" print('"test" == "test" is', st3) st4 = 1 == 1 or 2 != 1 print("1 == 1 or 2 != 1 is", st4) st5 = True and 1 == 1 print("True and 1 == 1 is ", st5) st6 = False and 0 != 0 print("False and 0 != 0 is", st6) st7 = True or 1 == 1 print("True or 1 == 1 is", st7) st8 = "test" == "testing" print('"test" == "testing" is', st8) st9 = 1 != 0 and 2 == 1 print("1 != 0 and 2 == 1 is ",st9) st10 = "test" != "testing" print('"test" != "testing" is ', st10) st11 = "test" == 1 print('"test" == 1 is', st11)
from tkinter import * size_of_board = 600 number_of_dots = 6 symbol_size = (size_of_board / 3 - size_of_board / 8) / 2 symbol_thickness = 50 dot_color = '#7BC043' player1_color = '#0492CF' player1_color_light = '#67B0CF' player2_color = '#EE4035' player2_color_light = '#EE7E77' Green_color = '#7BC043' distance_between_dots = size_of_board / number_of_dots dot_width = 0.25 * distance_between_dots edge_width = 0.10 * distance_between_dots window = Tk() window.title("Dots and Line Game") window.mainloop(30) canvas = Canvas(window, width=size_of_board, height=size_of_board) canvas.pack() def draw_board(canvas): for l in range(50, 650,100): canvas.create_line(50,l,550, l, fill="blue", dash=(2,2)) canvas.create_line(l, 50, l, 550, fill='blue', dash=(2,2)) for i in range(6): for j in range(6): start_x = i * 100 + 50 end_x = j * 100 + 50 canvas.create_oval(start_x - dot_width/2, end_x - dot_width/2, start_x + dot_width/2, end_x + dot_width/2, fill=dot_color, outline=dot_color) def isEven(n): return n % 2 == 0 def get_logical_position(x, y): print(x,y) xlog = (x - 25) // 50 ylog = (y - 25) // 50 ptype = "" pos = [] if (isEven(ylog) and not isEven(xlog)): pos = [xlog, ylog] ptype = "row" elif (not(isEven(ylog) and isEven(xlog)): pos = [xlog, ylog] ptype = "col" return pos, ptype def handle_click(event): pos, ptype = get_logical_position(event.x, event.y) print(pos, ptype) draw_board(canvas) window.bind('<Button-1>', handle_click)
#!/usr/bin/env python3 # Created by: Brian Musembi # Created on: 06 May 2021 # This program tells the month of the year def main(): # this function tells the month of the year # input month = int(input("Enter the number of a month (ex 3 for March): ")) # process & output if (month == 1): print("January.") elif (month == 2): print("February.") elif (month == 3): print("March.") elif (month == 4): print("April.") elif (month == 5): print("May.") elif (month == 6): print("June.") elif (month == 7): print("July.") elif (month == 8): print("August.") elif (month == 9): print("September.") elif (month == 10): print("October.") elif (month == 11): print("November.") elif (month == 12): print("December.") else: print("") print("Please input a number from 1-12!") print("") print("Done.") if __name__ == "__main__": main()
import math from sympy.abc import d from sympy import sqrt from sympy.utilities.lambdify import lambdify EPS = 0.01 # погрешность def golden_ratio(f): # Метод золотого сечения """ Принимает: f - функция от одной переменной f(s), которая получилась после подстановки аргументов в иходную функцию Возвращает: answer (число) - средняя точка на интервале (a, b) """ f = lambdify(d, f) a = -3 # границы интервала поиска b = 3 PHI = (math.sqrt(5) - 1) / 2 i = 0 print('\nМетод золотого сечения:') while abs(b - a) > EPS: # основной цикл i += 1 alpha = PHI * a + (1 - PHI) * b beta = (1 - PHI) * a + PHI * b print('\tИтерация', str(i) + ':') print('\t\ta =', round(a, 4), '\t\tb =', round(b, 4)) if f(alpha) > f(beta): # сравниваем значение функции в точках alpha и beta a = alpha else: b = beta answer = (a + b) / 2 return answer el_a = 3 el_b = 4 f = 4 * (d + el_b * sqrt(1 - d ** 2 / el_a ** 2)) ans = golden_ratio(f) print('\nLoss function:', f.evalf(7), '\nd =', round(ans, 4), '\nh =', round(2000 / math.pi / ans ** 2, 4))