text
stringlengths
37
1.41M
''' Al igual que las condiciones se pueden anidar, los ciclos tambien, ejemplos clasicos son el trabajo con matrices datos en formato tabla, series de tiempo doble, dobles sumatorias, expresiones matematicas, etc. En este script se mostraran algunos ejemplos clasicos ''' #Imprimiendo un cuadrado de * filas = int(input("Ingrese el numero de filas ")) columnas = int(input("Ingrese el numero de columnas ")) for i in range(filas): fila_imprimir = "" for j in range(columnas): fila_imprimir+="*" print(fila_imprimir) #imprimiendo una piramide de * alto = int(input("Ingrese el alto de la piramide ")) for i in range(alto): row = "*" for j in range(i): row+="*" print(row)
#!/usr/bin/env python # -*- coding: utf-8 -*- #This program will evaluate the accuracy of the reorder code based on 2 criteria: #1 the sentence should have the same word order as the english sentence #2 the words in the sentence should be aligned as it would be in an english sentence import argparse from itertools import izip from difflib import SequenceMatcher import codecs from collections import defaultdict import openpyxl import sys import re import dictionary import translate sys.stdout = codecs.getwriter('utf-8')(sys.stdout) sys.stdin = codecs.getreader('utf-8')(sys.stdin) reload(sys) sys.setdefaultencoding('utf8') PARSER = argparse.ArgumentParser(description="evaluate the reorderings") PARSER.add_argument("-t", type=str, default="trial", help="file to be evaluated prefix") PARSER.add_argument("-es", type=str, default="es", help="spanish file") PARSER.add_argument("-en", type=str, default="en", help="english file") PARSER.add_argument("-o", type=str, default="output", help="output file") PARSER.add_argument("-p", type=str, default="pos.txt", help="output file") args = PARSER.parse_args() sys.stdout = codecs.getwriter('utf-8')(sys.stdout) sys.stdin = codecs.getreader('utf-8')(sys.stdin) def combine(a, b): return 'data/%s.%s' % (a, b) def utf8read(file): return codecs.open(file, 'r', 'utf-8') if __name__ == '__main__': if args.t: score = defaultdict(int) #Check for SVO wb = openpyxl.load_workbook("data/postags.xlsx") parsed = wb.get_sheet_by_name(args.t) sub = defaultdict(defaultdict) obj = defaultdict(defaultdict) ver = defaultdict(defaultdict) sentence_no = 0 subjects = ["SUBJ"] objects = ["DO","IO","OBLC"] verbs = ["v"] order = [] words = [] flags = [False, False, False] subject = "" object = "" verb = "" rows = parsed.get_highest_row() columns = parsed.get_highest_column() for i in range(1, int(rows+1)): if parsed.cell(column = 1, row = i).value == 1 : if i != 1: order = [] words = [] flags = [False, False, False] subject = "" object = "" verb = "" sentence_no +=1 if (parsed.cell(column = 8,row = i).value in subjects) & (flags[0]==False): flags[0] = True subject += parsed.cell(column = 2,row = i).value order.append("S") sub[sentence_no] = subject elif (parsed.cell(column = 8,row = i).value in objects) & (flags[1]==False): flags[1] = True object += parsed.cell(column = 2,row = i).value order.append("O") obj[sentence_no] = object elif (parsed.cell(column = 4,row = i).value in verbs) & (flags[2]==False): flags[2] = True verb += parsed.cell(column = 2,row = i).value order.append("V") ver[sentence_no] = verb total_possible_score = 100 * sentence_no sentence_no = 0 score = defaultdict(float) for output_sentences in izip(utf8read(combine(args.t,args.o))): sentence_no += 1 score[sentence_no] = 0 words = [] order = [] for word in output_sentences[0].rstrip().split(): if (word == sub[sentence_no]): order.append("S") elif(word == obj[sentence_no]): order.append("O") elif(word==ver[sentence_no]): order.append("V") else: words.append(word) try: if (order[0]=="S")&(order[1]=="V")&(order[2]=="O"): score[sentence_no] += 30 elif (order[0]=="S")&(order[1]=="O")&(order[2]=="V"): score[sentence_no] += 25 elif (order[0]=="O")&(order[1]=="S")&(order[2]=="V"): score[sentence_no] += 15 elif (order[0]=="O")&(order[1]=="V")&(order[2]=="S"): score[sentence_no] += 20 elif (order[0]=="V")&(order[1]=="S")&(order[2]=="O"): score[sentence_no] += 10 elif (order[0]=="V")&(order[1]=="O")&(order[2]=="S"): score[sentence_no] += 5 elif (order[0]=="S")&(order[1]=="O")|(order[0]=="O")&(order[1]=="V"): score[sentence_no] += 15 else: score[sentence_no] += 0 except: score[sentence_no]+= 0 #Check for correct word alignment dictionary = dictionary.create_dictionary() sent_no = 0 for es_sentences,en_sentences,o_sentence in zip(open(combine(args.t,args.es)),open(combine(args.t,args.en)),open(combine(args.t,args.o))): new_sentence = translate.translate(en_sentences,es_sentences,dictionary) sent_no+=1 difference = SequenceMatcher(None,new_sentence,o_sentence) score[sent_no] += difference.ratio() * 70 total_score = 0.0 for sents in score: total_score += score[sents] total_possible = 100.0 * float(sent_no) print "Accuracy of computation:",str(total_score/total_possible)
def countCase(str1): countUp=0 countLw=0 for i in str1: if(i.isupper()): countUp=countUp+1 if(i.islower()): countLw= countLw+1 print("No of uperCase letter is: ",countUp) print("No of lowerCase letter is: ",countLw) str = input("Enter string: ") countCase(str)
import logging logging.basicConfig(level=logging.DEBUG, format="%(asctime)s-->>%(levelname)s==>%(message)s", filename="log.txt") logging.info("program started") a=raw_input("Enter a value:") logging.info("Got the a value from the user") b=raw_input("Enter b value:") logging.info("Got the b value from the user") logging.debug("before conversion a=%s,b=%s"%(a,b)) try: a=float(a) logging.info("safely converted a") b=float(b) logging.info("safely converted b") logging.debug("after conversion a=%s,b=%s"%(a,b)) res=a/b logging.info("Result calculation completed") print "result=%s"%res logging.debug("result=%s"%res) except ZeroDivisionError as err: print "ERROR:%s"%err.message logging.error("ERROR:%s"%err.message) print "Enter b value not equal to zero" logging.error("Enter b value not equal to zero") except Exception as err: logging.error("ERROR:%s"%err.message) print "ERROR:%s"%err.message logging.error("some error") print "some error" print "other statements in program" print "program ended" print "main block" logging.info("COMPLETED!!!")
pi = 3.142 radius = float(input('what is the radius of your circle? ')) area = pi * ((radius) **2) print (area)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Michael Lockwood' __github__ = 'mlockwood' __email__ = '[email protected]' def levenshtein(a, b): """This function applies the levenshtein algorithm between an the object's gloss and a leipzig or gold tag. """ # Reset to calculate whereas b has greater length if len(a) < len(b): return levenshtein(b, a) # If b has length of 0 return length of a if len(b) == 0: return len(a) previous_row = range(len(b) + 1) for i, c1 in enumerate(a): current_row = [i + 1] for j, c2 in enumerate(b): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]
N = int(input("berapa angka = ")) ruang = [] for i in range(N): ruang.append(int(input("masukkan angka ke {} = ".format(i)))) print("Nilai Maksimal = {}".format(max(ruang))) print("Nilai Minimum = {}".format(min(ruang)))
n = int(input()) if n == 1 or n == 2: print(1) else: a, b, ans = 1, 1, 0 for i in range(2, n): ans = (a + b) % 10007 a, b = b, ans print(ans)
for num in range(1000, 10000): string = str(num) if string[0] == string[3] and string[1] == string[2]: print(num)
import os import string def get_valid_drives(): print("Getting valid drives...") valid_drives = [] for elem in string.ascii_lowercase: path = elem + ":\\" #if os.path.isdir(path): # print(path) if os.path.exists(path): valid_drives.append(path) #print(path) print("Got %s..." % (valid_drives)) return valid_drives import os def get_filepaths(directory, extension=""): print("Getting files with extension: [%s] for path %s..." % (extension, directory)) file_paths = [] # List which will store all of the full filepaths. # Walk the tree. for root, directories, files in os.walk(directory): for filename in files: # Join the two strings in order to form the full filepath. filepath = os.path.join(root, filename) if filepath.lower().endswith(extension): file_paths.append(filepath) # Add it to the list. print("Got %s files for path %s..." % (len(file_paths), directory)) return file_paths # Self-explanatory. # Run the above function and store its results in a variable. valid_drives = get_valid_drives() extensions_list2 = ".mp3" valid_mp3s = [] #valid_drives = ["d:\\games\\Counter-Strike1.6 v.42"] for drive in valid_drives: valid_mp3s.extend(get_filepaths(drive, extensions_list2)) f = open("all_mp3s.txt","wb") for file in valid_mp3s: f.write(file.encode()) f.write("\n".encode()) f.close()
def read_a_number(): nb = input('Choose a number: ') try: mode = int(nb) except ValueError: print("Not a number") mode = read_a_number() return mode def pag12_prog(): n = read_a_number() x = [] for a in range(n): x.append(read_a_number()) print(x) s=0 i=0 while(i<n): if x[i] > 0: s = s+x[i] else: s = s-x[i] i += 1 s = s / n print(s) #pag12_prog()
part_number = "42560353245833ab" def cardLuhnChecksumIsValid(card_number): """ checks to make sure that the card passes a luhn mod-10 checksum """ sum = 0 num_digits = len(card_number) oddeven = num_digits & 1 for count in range(0, num_digits): digit = int(card_number[count]) if not (( count & 1 ) ^ oddeven ): digit = digit * 2 if digit > 9: digit = digit - 9 sum = sum + digit return ( (sum % 10) == 0 ) def get_numbs(): for a in range(0,9): for b in range (0,9): s1 = part_number.replace("a", str(a)) s2 = s1.replace("b", str(b)) result = cardLuhnChecksumIsValid(s2) if result: print(s2) get_numbs()
__author__ = 'darakna' # python 2 # # Homework 3, Problem 3 # List comprehensions! # # Name: # # this gives us functions like sin and cos from math import * # two more functions (not in the math library above) def dbl(x): """ doubler! input: x, a number """ return 2*x def sq(x): """ squarer! input: x, a number """ return x**2 # examples for getting used to list comprehensions def lc_mult( N ): """ this example takes in an int N and returns a list of integers from 0 to N-1, **each multiplied by 2** """ return [ 2*x for x in range(N) ] def lc_idiv( N ): """ this example takes in an int N and returns a list of integers from 0 to N-1, **each divided by 2** WARNING: this is INTEGER division...! """ return [ x/2 for x in range(N) ] def lc_fdiv( N ): """ this example takes in an int N and returns a list of integers from 0 to N-1, **each divided by 2** NOTE: this is floating-point division...! """ return [ float(x)/2 for x in range(N) ] # Here is where your functions start for the homework: # Step 1, part 1 def unitfracs( N ): """ be sure to improve this docstring! """ pass # replace this line (pass is Python's empty statement) print(lc_mult( 10 ), # multiplication example lc_mult( 5 ), # a smaller example lc_idiv( 10 ) , # integer division lc_fdiv( 10 ) ) # floating-point division def dbl(x): """ input: a number x (int or float) output: twice the input """ return 2*x
import binascii import base64 req_n = "5203054907932715072219463010433671501242324999101031961778551414523203642794654633954122128718395475257091609045094294305282429283375416003959025668410070733743" resp_n = "131618988864947543213776229531634193412737234854212651796818129365118569829291789642298561838219946234914193882865537745361589944691738337361923969834323672753213" #req_n = "321682001638621484560335075095507393230746499319112395413345734508561395841716256209503480440122408356196694552170136827691509607517848131461840553581088359803526847604866029189" #resp_n = "129933656511779963167442542838852527261285746367852251381491658328954729449657923715297657634799729363497601683837417149328627845965213565543021934386297536927567961363693245472667" #req_n = "132752679009221621974424157119055405668892042595778428973751767008896088687960962058901693159841975248499249835571219034924880485719595053013906268929618431426022723233136913645060276155426395971" #resp_n = "121912844982339629176832774451185569235725668957286601326991833849575967441611698281396529582394583714754529674837173412218177687691781396442281828465865117438279845726846959841393955282492411534487" req_n = "4524534914863856075318572321251413488936046039067401564596991828706906852704171724928727799968714377343721934522283998377651546992172322004415314402246051761653738903416118187189" resp_n = "254239257533814359267852692761437331391922428319477921595965149711974391684634973376665789732855676833477979795253392954532649849776372456667217889116832653486841943556221436464217" #req_n = "1893337371170074321646616782232907752619374562068712860454591829671881387602079105829821458728608198515060273004738560920851587297336513881468192796945266862542950950920462165307" #resp_n = "158411637293917703298313128588223857349676152117948267465736224998959757611165578765169507656269526538265291767399699459739917837736937622125341974762215384448371978798789241515497" numb_req = int(req_n) numb_resp = int(resp_n) def is_3(big_n): if len(big_n) == 0: return 0 elif len(big_n) == 1: return int(big_n) else: return int(big_n[0]) + is_3(big_n[1:]) def findAllFactors(number): factors = list() for i in range(1, number): if number % i == 0: factors.append(i) return factors def isPrime(n): n = abs(int(n)) if n < 2: return 0 if n == 2: return 1 if not n & 1: return 0 for x in range(3, int(n ** 0.5) + 1, 2): if n % x == 0: return 0 return 1 def long_search(arg_num): factors = findAllFactors(arg_num) primeFactors = list() for f in factors: if isPrime(f) == 1: primeFactors.append(f) primeFactors.sort() print("%d" % (primeFactors[-1])) def short_search(arg_num): #F = factor(arg_num) arg_num.sagemath.factor() if __name__ == "__main__": print(len(req_n), len(resp_n)) for lenght in range(1, len(resp_n)): if int(numb_req % int(resp_n[0:lenght])) == 0: print("%s %s = %s" % (req_n, resp_n[0:lenght], numb_req % int(resp_n[0:lenght]))) print("%s" % int(numb_req / int(resp_n[0:lenght]) * int(resp_n[0:lenght]))) #print(binascii.hexlify((req_n.encode()))) #print(binascii.hexlify((resp_n.encode()))) #print(binascii.hexlify((str(numb_resp - numb_req).encode()))) #print(base64.b64encode(req_n.encode())) #print(base64.b64encode(resp_n.encode())) #print(base64.b64encode(str(numb_resp - numb_req).encode())) #print(bin(numb_req)) #print(bin(numb_resp)) #print(bin(numb_resp - numb_req)) #print(numb_resp) #print(numb_req) #print(numb_resp - numb_req) #print(numb_req / numb_resp) #print(numb_resp % numb_req)
"""The module encrypts a message using one key that is entered as an interger and it shifts the message letter by letter according to the key. This kind of encryption is called Substitution Encryption. - The module also decrypts the message given that we know the key value of the encryption.""" try: import random except ImportError: print("The import function did not work!!") class Suben: def __init__(self,text,key): self.text = text self.key = key class Encr(Suben): def __init__(self,text,key): try: Suben.__init__(self,text,key) self.e = '' for c in text : if ord(c) != 32: if ord(c) == 122 : self.e += 'a' else : self.e += chr(ord(c)+key) elif ord(c) == 32: self.e += ' ' except TypeError: print("Pass a string in the first argument!!") else: print("Successful!!!") def display(self): return self.e class Decr(Suben): def __init__(self,text,key): try: Suben.__init__(self,text,key) self.e = '' for c in text : if ord(c) != 32: if ord(c) == 122 : self.e += 'a' else : self.e += chr(ord(c)-key) elif ord(c) == 32: self.e += ' ' except TypeError: print("Pass a string in the first argument!!") else: print("Successful!!!") def display(self): return self.e
#!usr/bin/env python #list name = ['macel','zhangkai','zkorangesun'] #dist d = {"macel":95,"zhangkai":84,"zkorangesun":93} print d['macel'] print name[0] print d.get('zk') if 'zk' in d: print 'y' else: print 'n' print abs(-100) def my_abs(arg): return abs(arg) print my_abs(-101) print "hello"
# Project : Persistent Dictionary For Alien Civilization # Author : Syed Azam Hassan import json # Alien Language JSON Datafile def box(s): l = len(s) print("┌"+"─"*l+"┐") print("│"+s+"│") print("└"+"─"*l+"┘") print("\a") print(" ▄▄▄· ▄▄▌ ▪ ▄▄▄ . ▐ ▄ ·▄▄▄▄ ▪ ▄▄· ▄▄▄▄▄▪ ▐ ▄ ▄▄▄· ▄▄▄ ▄· ▄▌") print("▐█ ▀█ ██• ██ ▀▄.▀·•█▌▐█ ██▪ ██ ██ ▐█ ▌▪•██ ██ ▪ •█▌▐█▐█ ▀█ ▀▄ █·▐█▪██▌") print("▄█▀▀█ ██▪ ▐█·▐▀▀▪▄▐█▐▐▌ ▐█· ▐█▌▐█·██ ▄▄ ▐█.▪▐█· ▄█▀▄ ▐█▐▐▌▄█▀▀█ ▐▀▀▄ ▐█▌▐█▪") print("▐█ ▪▐▌▐█▌▐▌▐█▌▐█▄▄▌██▐█▌ ██. ██ ▐█▌▐███▌ ▐█▌·▐█▌▐█▌.▐▌██▐█▌▐█ ▪▐▌▐█•█▌ ▐█▀·.") print(" ▀ ▀ .▀▀▀ ▀▀▀ ▀▀▀ ▀▀ █▪ ▀▀▀▀▀• ▀▀▀·▀▀▀ ▀▀▀ ▀▀▀ ▀█▄▀▪▀▀ █▪ ▀ ▀ .▀ ▀ ▀ • ") print("....ℭ𝔬𝔪𝔪𝔲𝔫𝔦𝔠𝔞𝔱𝔦𝔬𝔫 𝔴𝔦𝔱𝔥 𝔢𝔵𝔱𝔯𝔞𝔱𝔢𝔯𝔯𝔢𝔰𝔱𝔯𝔦𝔞𝔩 𝔦𝔫𝔱𝔢𝔩𝔩𝔦𝔤𝔢𝔫𝔠𝔢....") while True: print(" ●───────┐ ┌───────● ") print(" │ │ ") print("╔══════════╧════════════╧══════════╗") print("║ ◄██► M A I N M E N U ◄██► ║") print("╠══════════════════════════════════╣") print('║ [1] English to Alien Translation ║') print('║ [2] Alien to English Translation ║') print('║ [3] Display Dictionary ║') print('║ [4] Edit Dictionary ║') print('║ [5] Exit ║') print("╚══════════════(◄██►)══════════════╝") ch = input(" Enter Choice [1/5] : ") print() if ch == "5": box("What are you gonna do, talk the alien to death?") box("Good Bye") print("\a") break if ch == "1": box("English to Alien Translation") p = input("Type a phrase in English Language: ") p = p.lower() with open("alien_dict.json") as ad: d = json.load(ad) d = {k.lower():v.lower() for k,v in d.items()} ap = "Alien Phrase : " for w in p.split(): if w in d: ap = ap + " " + d[w] else: ap = ap + " " + w box(ap.capitalize()) input() continue elif ch == "2": box("Alien to English Translation") p = input("Type a phrase in Alien Language: ") p = p.lower() with open("alien_dict.json") as ad: d = json.load(ad) d = {k.lower():v.lower() for k,v in d.items()} ap = "English Phrase : " for w in p.split(): if w in d.values(): l = [k for (k, v) in d.items() if v == w] ap = ap + " " + ' '.join(l) else: ap = ap + " " + w box(ap.capitalize()) input() continue elif ch == "3": box("Display Dictionary") with open("alien_dict.json") as ad: d = json.load(ad) print(json.dumps(d, indent = 4, sort_keys=True)) input() continue elif ch == "4": box("Edit Alien Dictionary") try: with open("alien_dict.json") as ad: d = json.load(ad) e = input("Enter English Translation: ") a = input("Enter a Alien Word: ") if a.strip() == "" or e.strip() == "": print("Blank Words Can't Add") else: d[e] = a with open("alien_dict.json", "w") as ad: json.dump(d, ad) print("Word added in Alien Dictioanry") except FileNotFoundError: with open("alien_dict.json", 'w') as ad: json.dump({}, ad) print("New Alien Dictionary Created") input() continue
# https://towardsdatascience.com/common-loss-functions-in-machine-learning-46af0ffc4d23 import numpy as np y_hat = np.array([0.000, 0.166, 0.333]) #Prediction for training example y_true = np.array([0.000, 0.254, 0.998]) #actual result #Regression Losses #mean square error def rmse(predictions, targets): differences = predictions - targets differences_squared = differences ** 2 mean_of_differences_squared = differences_squared.mean() rmse_val = np.sqrt(mean_of_differences_squared) return rmse_val #absolute error def mae(predictions, targets): differences = predictions - targets absolute_differences = np.absolute(differences) mean_absolute_differences = absolute_differences.mean() return mean_absolute_differences #Classification Losses #Cross Entropy Loss/Negative Log Likelihood predictions = np.array([[0.25,0.25,0.25,0.25], [0.01,0.01,0.01,0.96]]) targets = np.array([[0,0,0,1], [0,0,0,1]]) def cross_entropy(predictions, targets, epsilon=1e-10): predictions = np.clip(predictions, epsilon, 1. - epsilon) N = predictions.shape[0] ce_loss = -np.sum(np.sum(targets * np.log(predictions + 1e-5)))/N return ce_loss cross_entropy_loss = cross_entropy(predictions, targets) print ("Cross entropy loss is: " + str(cross_entropy_loss)) #main print("d is: " + str(["%.8f" % elem for elem in y_hat])) print("p is: " + str(["%.8f" % elem for elem in y_true])) rmse_val = rmse(y_hat, y_true) print("rms error is: " + str(rmse_val)) mae_val = mae(y_hat, y_true) print ("mae error is: " + str(mae_val))
class nguoi: def __init__(self,ten=None): self.ten=ten def nhap(self): self.ten=input("Ten: ") def xuat(self): print(self.ten,"la nguoi") class hocsinh(nguoi): def __init__(self,masv=None,ten=None,lop=None): super().__init__(ten) self.masv=masv self.lop=lop def nhap(self): super().nhap() self.masv=input("Ma sv: ") self.lop=input("Lop: ") def xuat(): print(self.ten,"la hoc sinh lop",self.lop,"va masv la",self.masv) a=hocsinh() a.nhap() a.xuat()
# def tieneRepetidos(arr): # repetido = False # for i in arr: # if arr.count(i) > 1: repetido = True # print(repetido) # x = list(input('Ingrese una lista: ').split(', ')) # tieneRepetidos(x) # def esPalidrome(arr): # if arr[::-1] == arr: print('Es palídrome') # else: print('No es palídrome') # x = list(input('Ingrese una lista: ').split(', ')) # esPalidrome(x) # def contienePalidrome(arr): # existe = False # for i in arr: # if i[::-1] == i: existe = i # if not existe: print('No existe') # else: print(existe) # x = list(input('Ingrese una lista: ').split(', ')) # contienePalidrome(x) # def contieneVocalRepetida(arr): # existe = [] # for i in arr: # if i.count('a') > 1 : existe.append(i) # if i.count('e') > 1 : existe.append(i) # if i.count('i') > 1 : existe.append(i) # if i.count('o') > 1 : existe.append(i) # if i.count('u') > 1 : existe.append(i) # if not existe: print('No existe') # else: print(', '.join(existe)) # x = list(input('Ingrese una lista: ').split(', ')) # contieneVocalRepetida(x) # def contieneVocalRepetida(arr1, arr2): # resultado = [] # for i in arr1: # if i in arr2: resultado.append(i) # if not resultado: print('Son iguales') # print(resultado) # x = list(input('Ingrese la primera lista: ').split(', ')) # y = list(input('Ingrese la segunda lista: ').split(', ')) # contieneVocalRepetida(x, y) # def promedio_arreglo(arr): # mappedList = list(map(int, arr)) # sum = 0 # for i in mappedList: # sum += i # return sum / len(mappedList) # x = list(input('Ingrese el arreglo: ').split(', ')) # print(promedio_arreglo(x)) def calcular_producto_matriz(x): resultado = [] for i in range(len(x[0])): resultado.append(x[0][i] * x[1][i]) print(resultado) x = [int(x) for x in input('Ingrese el primer elemento de la matriz: ').split(', ')] y = [int(y) for y in input('Ingrese el segundo elemento de la matriz: ').split(', ')] z = [x, y] calcular_producto_matriz(z)
# map(int, input().split(' ')) def promedio_arreglo(arr): mappedList = list(map(int, arr)) sum = 0 for i in mappedList: sum += i return sum / len(mappedList) x = list(input('Ingrese el arreglo: ').split(', ')) print(promedio_arreglo(x))
# lista1 = [0, 1, 2, 3] # lista2 = ['A', 'B', 'C'] # lista3 = [lista1, lista2] # print(lista3) # print(lista3[0]) # print(lista3[1]) # print(lista3[1][0]) # lista1 = ["A", "B", "C", "E"] # lista2 = [1, 2, 3, 4, 5] # lista3 = lista1 + lista2 # aqui se presenta un pequeño error # print(lista3) # nombres = ['Antonio', 'María', 'Mabel'] # otros_nombres = ['Barry', 'John', 'Guttag'] # nombres.extend(otros_nombres) # print(nombres) # print(otros_nombres) # lista1 = [1, 2, 3, 4, 5] # lista2 = lista1 * 3 # print(lista2) # lista3 = ['Abc', 'Bcd'] # lista4 = lista3 * 2 # print(lista4) # print(['Rojas', 123] < ['Rosas', 123]) # print(['Rosas', 123] == ['rosas', 123]) # print(['Rosas', 123] > ['Rosas', 23]) # print(['Rosas', '123'] > ['Rosas', '23']) # avengers = ['Ironman', 'Thor', 'Ant-man', 'Hulk'] # print(avengers[0]) # print(avengers[3]) # print(avengers[-1]) # print(avengers[-3]) # text = ['cien', 'años', 'de', 'soledad'] # if 'años' in text: print('Si está') # else: print('No está') # s = ['hola', 'amigos', 'mios'] # for palabra in s: # print(palabra, end = ', ') # d = 10 # desplaza = [d + x for x in range(5)] # print(desplaza) # potencias = [3 ** x for x in range(2, 6)] # print(potencias) # lista = [1, -2, 3] # a, b, c = lista # print('a =', a) # print('b =', b) # print('c =', c) # lista = [11, 9, -2, 3, 8, 5] # var1, var2, var3 = [lista[i] for i in (1, 3, 5)] # print('var1 =', var1, 'var2 =', var2, 'var3 =', var3) # var1, var2, var3 = [lista[i] for i in range(0, 6, 2)] # print('var1 =', var1, 'var2 =', var2, 'var3 =', var3) # def minmax(a, b): # if a < b: return [a, b] # else: return [b, a] # x, y = minmax(5, 13) # print('min =', x,',', 'max =', y) # x, y = minmax(12, -4) # print('min =', x,',', 'max =', y) # lista = ['E', 'l', 'm', 'e', 'j', 'o', 'r'] # lista[0] = 'e' # print(lista) # lista[4] = 'l' # print(lista) # lista[-1] = 's' # print(lista) # print(list('hola')) # nombres = ['Antonio', 'Johan'] # nombres.append('Mónica') # print(nombres) # nombres.append('María') # print(nombres) # nombres.append('Mabel') # print(nombres) # nombres = ['Antonio', 'Johan', 'María'] # nombres.insert(0, 'Mónica') # print(nombres) # nombres.insert(2, 'Peter') # print(nombres) # nombres.insert(len(nombres) // 2, '10') # print(nombres) # nombres = ['a', 'e', 'i', 'o', 'u', 'i', 'x'] # nombres.remove('x') # print(nombres) # nombres.remove('i') # print(nombres) # nombres.remove('i') # print(nombres) # avengers = ['Ironman', 'Thor', 'Ant-man', 'Hulk'] # print(avengers[:2]) # print(avengers[1:3]) # print(avengers[3:3]) # print(avengers[::-1]) # lista = [4, 3, 8, 8, 2, 5, 4, 6, 8, 9] # print(lista.count(2)) # print(lista.count(8)) # print(lista.count(5)) # print(lista.count(7)) # print(min(lista)) # print(max(lista)) # lista = [4, 3, 8, 8, 2, 5, 4, 6, 8, 9] # print(lista.index(2)) # print(lista.index(8)) # print(lista.index(5)) # lista = [4, 5, -1, 6, 7] # lista.sort # print(lista) # lista.sort(reverse = True) # print(lista) # lista = ['a', 'b', 'c', 'd', 'f'] # lista.sort # print(lista) # lista.sort(reverse = True) # print(lista) nombres = ['Antonio', 'Johan', 'Mónica', 'Mabel'] nombres.pop(1) print(nombres) nombre_borrado = nombres.pop() print(nombre_borrado, 'Ha sido eliminada de la lista.') print(nombres)
# Examples of Python lists # A list is defined using the [] (Square) brackets. # Individual items are seperated by commas. my_shopping_list = ["Apples","Oranges","Milk", "Bread"] print("="*20) print("The list: ") print("="*20) print(my_shopping_list) raw_input("\nPress Enter to advance...") # We can add items to the list using the .append method my_shopping_list.append("Butter") print("="*20) print("Added Butter: ") print("="*20) print(my_shopping_list) # And we can remove items too - defaults to last item in list. my_shopping_list.pop() raw_input("\nPress Enter to advance...") print("="*20) print("Removed Butter: ") print("="*20) print(my_shopping_list) # Let's sort the items into alphabetical order my_shopping_list.sort() raw_input("\nPress Enter to advance...") print("="*20) print("Sorted the list: ") print("="*20) print(my_shopping_list)
# -*- coding: UTF-8 -*- #지하철 카드는 어떻게 돌아갈까? #구성 : 사람, 리더기, 기계, 문 #고려사항 : 나이, 환승횟수 #card 세팅 : 연령, 가진 돈, 환승횟수, 거리 usercard_age = 0 #(청소년 = 0, 일반인 = 1) usercard_money = 0 usercard_transfer = 0 transfer = 1 #카드 충전 및 카드 상태설정 usercard_money = input("얼마를 충전하시겠습니까? : ") usercard_age = input("당신의 연령은 ?(청소년 = 0, 어른 =1) : ") #연령설정에 따른 기본료, 환승료 def age(): if usercard_age ==0: basic_cost = 800 transfer_cost = 50 else: basic_cost = 1000 transfer_cost = 100 while transfer == 1: if usercard_transfer == 0: if usercard_age == 0: usercard_money = usercard_money - 800 usercard_transfer = usercard_transfer + 1 print(usercard_money) else: usercard_money = usercard_money - 1000 usercard_transfer = usercard_transfer + 1 print(usercard_money) else: if usercard_age == 0: usercard_money = usercard_money - 50 usercard_transfer = usercard_transfer + 1 print(usercard_money) else: usercard_money = usercard_money - 100 usercard_transfer = usercard_transfer + 1 print(usercard_money) transfer = input("환승하시겠습니까? Yes=1 , No=0 :") print("이용해주셔서 감사합니다") #기능추가 # 5회 이상일 경우 다시 초기값 설정 & 중단 # 거리값에 따라 가중치 부가 # 함수로 만들
from tkinter import * # For some reason, importing tkinter doesn't import messagebox in Python 3.6+ from tkinter import messagebox from tkinter import simpledialog guessList = [] class GuessNumber(Frame): '''represents a board of guess your number''' def __init__(self,master,lowerRange,upperRange): '''GuessNumber(lowerRange,upperRange) creates a guessing number button board''' Frame.__init__(self,master) self.grid() self.lowerRange = lowerRange self.upperRange = upperRange self.computerGuess = (self.lowerRange + self.upperRange)//2 self.endgame = None Label(self,text="My Guess").grid(row=0,column=0) Label(self,text=self.computerGuess).grid(row=2,column=0) Label(self,text="Result").grid(row=0,column=1) self.tooHighButton = Button(self,text="Too High",command=self.too_high).grid(row=1,column=1) self.tooLowButton = Button(self,text="Too Low",command=self.too_low).grid(row=3,column=1) self.correctButton = Button(self,text="Correct!",command=self.correct).grid(row=2,column=1) def too_high(self): '''if answer is too high''' guessList.append(self.computerGuess) self.upperRange = self.computerGuess return GuessNumber(root,self.lowerRange,self.computerGuess) def too_low(self): '''if answer is too low''' guessList.append(self.computerGuess) self.lowerRange = self.computerGuess return GuessNumber(root,self.computerGuess,self.upperRange) def correct(self): '''if the answer is correct''' guessList.append(self.computerGuess) if messagebox.showinfo('Thinking of your number',"Yay -- I got it! It took me " + str(len(guessList)) + " tries. Here's my full list of guesses: " + str(guessList) + ". YAY",parent=self): self.destroy() self.quit() root = Tk() def play(): lowerRange = int(simpledialog.askstring(title="Lower Bound", prompt="Lower Bound:")) upperRange = int(simpledialog.askstring(title="Upper Bound", prompt="Upper Bound:")) root.title('Guess') guess = GuessNumber(root,lowerRange,upperRange) guess.mainloop() play()
#!/usr/bin/env python # coding: utf-8 # In[1]: class NumberPattern(object): def __init__(self,start,end = 0,step = -1): self.start = start self.end = end self.step = step def pattern(self): numbers = [i for i in range(self.start,self.end,self.step)] for iter_ in range(len(numbers)*2): if iter_ < len(numbers): length = 0 for num in numbers[iter_:]: print('',num,end='') length += 1 if length == len(numbers[iter_:]): print('\n') else: length = 0 for num in numbers[-(iter_- (len(numbers) - 1)):]: print('',num,end='') length += 1 if length == len(numbers[-(iter_- (len(numbers) - 1)):]): print('\n') # In[8]: num_pattern = NumberPattern(10) num_pattern.pattern()
def inches_to_cm(inches): return inches * 2.54 def lbs_to_Kg(lbs): return lbs * 0.453592 name = 'Zed A. Shaw' age = 35 # not a lie height = 74 # inches weight = 180 # lbs eyes = 'Blue' teeth = 'White' hair = 'Brown' height_in_cm = inches_to_cm(height) #cm weight_in_kg = lbs_to_Kg(weight) # Kg print(f"Let's talk about {name}.") print(f"He's {height} inches tall ({height_in_cm} cm).") print(f"He's {weight} pounds heavy ({weight_in_kg} kg). ") print("Actually that's not too heavy.") print(f"He's got {eyes} eyes and {hair} hair.") print(f"His teeth are usually {teeth} depending on the coffee.") # this line is tricky, try to get it exactly right total = age + height + weight print(f"If I add {age} years, {height} height, and {weight} lbs I get {total}.")
import argparse import json import sys class PasswdFieldEnum(object): USERNAME = 0 UID = 2 GECOS = 4 TOTAL_FIELDS = 7 class GroupFieldEnum(object): GROUPNAME = 0 USERS = 3 TOTAL_FIELDS = 4 class FileFormatError(Exception): pass def validate_passwd_format(user_data, line_num, users_encountered): """ Check whether a row of the passwd file has a valid format by - counting the number of fields - ensuring that there are no duplicate users :param user_data: a list containing the fields of an entry in the passwd file :param line_num: the line number of the entry being checked :param users_encountered: a set of users already parsed in the passwd file """ if len(user_data) != PasswdFieldEnum.TOTAL_FIELDS: raise FileFormatError( "Couldn't parse line {} of '{}': expected {} values but found {}".format(line_num, passwd_path, PasswdFieldEnum.TOTAL_FIELDS, len(user_data))) if user_data[PasswdFieldEnum.USERNAME] in users_encountered: raise FileFormatError( "Couldn't parse line {} of '{}': duplicate user '{}' found".format(line_num, passwd_path, user_data[PasswdFieldEnum.USERNAME])) def validate_group_format(group_data, line_num, groups_encountered): """ Check whether a row of the group file has a valid format by - counting the number of fields - ensuring that there are no duplicate groups :param group_data: a list containing the fields of an entry in the group file :param line_num: the line number of the entry being checked :param groups_encountered: a set of groups already parsed in the group file :raise FileFormatError """ if len(group_data) != GroupFieldEnum.TOTAL_FIELDS: raise FileFormatError( "Couldn't parse line {} of '{}': expected {} values but found {}".format(line_num, passwd_path, GroupFieldEnum.TOTAL_FIELDS, len(group_data))) if group_data[GroupFieldEnum.GROUPNAME] in groups_encountered: raise FileFormatError( "Couldn't parse line {} of '{}': duplicate group '{}' found".format(line_num, group_path, group_data[GroupFieldEnum.GROUPNAME])) def parse_passwd_file(passwd_file, user2groups): """ Create a dictionary that contains all the user information we need :param passwd_file: path (string) to the passwd file :param user2groups: a dictionary that maps usernames to groups :return: a dictionary containing user and group information :raise FileFormatError """ parsed_data = {} users_encountered = set() with passwd_file: for index, user_data in enumerate(passwd_file.read().splitlines()): user_data = user_data.split(":") try: validate_passwd_format(user_data, index + 1, users_encountered) except Exception as e: sys.exit(str(e)) username = user_data[PasswdFieldEnum.USERNAME] users_encountered.add(username) uid = user_data[PasswdFieldEnum.UID] gecos = user_data[PasswdFieldEnum.GECOS] fullname = gecos.split(",")[0] groups = user2groups[username] if username in user2groups else [] parsed_data[username] = { "uid": uid, "full_name": fullname, "groups": groups } return parsed_data def parse_group_file(group_file): """ Create a mapping from users to groups :param group_file: path (string) to the group file :return: a dictionary with usernames as keys and lists of groups as values """ user2groups = {} groups_encountered = set() with group_file: for index, group_data in enumerate(group_file.read().splitlines()): group_data = group_data.split(":") try: validate_group_format(group_data, index + 1, groups_encountered) except Exception as e: sys.exit(str(e)) group_name = group_data[GroupFieldEnum.GROUPNAME] groups_encountered.add(group_name) users = group_data[GroupFieldEnum.USERS] if users == '': continue for user in users.split(","): if user not in user2groups: user2groups[user] = [] user2groups[user].append(group_name) return user2groups parser = argparse.ArgumentParser( description='Parse the UNIX passwd and group files and combine the data into a single JSON output.') parser.add_argument("-p", "--passwd", default='/etc/passwd', help='Path to the passwd file. Defaults to /etc/passwd if not provided.') parser.add_argument("-g", "--group", default='/etc/group', help='Path to the group file. Defaults to /etc/group if not provided.') parser.add_argument("-s", "--sorted", action='store_true', help='Sort keys of the JSON string alphabetically.') parser.add_argument("-c", "--compact", action='store_true', help='Print the JSON string in a compact form. The default setting is to pretty-print the JSON.') parser.add_argument("-o", "--outfile", help='Specifies a file path to which the JSON string should be written. If omitted or an error occurs, the output is printed to STDOUT.') args = parser.parse_args() passwd_path = args.passwd group_path = args.group try: passwd_file = open(passwd_path) group_file = open(group_path) except Exception as e: sys.exit(str(e)) user2groups = parse_group_file(group_file) parsed_data = parse_passwd_file(passwd_file, user2groups) parsed_json = json.dumps(parsed_data, indent=None if args.compact else 4, sort_keys=args.sorted) if args.outfile: try: with open(args.outfile, "w") as outfile: outfile.write(parsed_json) except Exception as e: print("Couldn't write to output file: {}".format(str(e))) print(parsed_json) else: print(parsed_json)
#!/usr/bin/env python3.8 # -*- coding: utf-8 -*- #数据类型 #1.整数 -精确运算 print("整数:") print(1,-1,0) #十进制 print(0xff,0x00) #十六进制 0x开头 print("\n") #2.浮点数 -四舍五入存储 print("浮点数:") print(1.23e10) #科学计数法:1.11 -> 0.111e1 print(1.11e-3) print("\n") #3.字符串 -’.‘或者“.”或者’‘’.''' print("字符串:") print('I\'m OK!') # 转义 \' print('I\'m \"OK\"!') # 转义 \" print("I'm 'ok' \\") # 转义 \\ print('\\\t\\') print(r'\\\t\\') #r'' 引号内的内容不转义 print('''hello world!''') #多行打印 print(r'''hello \n world''') #r'''多行打印 print("\n") #4.布尔值 -True 和 False print("布尔值:") print(True) print(False) print(True and True) print(True and False) print(True or True) print(True or False) print(not True) print("\n") #5.空值 -None print("空值:") print(None) print(type(None)) print("\n") #变量 print("变量:") x='abc' y='bcd' z=x print(z) x=y print(x) y=z print(y) print("\n") #常量 print("常量:") PI=3.1415926 print(PI) print("\n") #除法,整除,取余 print("除法,整除,取余:") print(10/3) print(10//3) print(10%3)
#!/usr/bin/env python3.8 # -*- coding: utf-8 -*- #高阶函数,返回函数,匿名函数,装饰器,偏函数 #1.高阶函数 Higher-order function #函数名也是变量,指向函数代码 fabs=abs print("1.",fabs(-12),type(fabs),fabs.__name__) #函数作为变量,传入某个函数当做参数,即是高阶函数 #函数的参数,是变量,这个变量是另一个函数 def abs_add(x,y,f=abs): return f(x)+f(y) print("2.",abs_add(-10,-28,abs),abs_add(19,-11)) #内置函数:map/reduce,filter,sorted from collections.abc import Iterator def f(x): return x*x r=map(f,[1,2,3]) #传入函数f和一个Iterabble, # 将f作用于Iterable对象的每一个元素, #并返回一个Iterator 对象 print("3.",list(r),isinstance(r,Iterator)) from functools import reduce DIGIT={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'0':0} def char2num(s): return DIGIT[s] def str2int(s): return reduce(lambda x,y:x*10+y,map(char2num,s)) print("4.",str2int('12588'),type(str2int('1')),type(int(1))) #用filter()函数求素数 #计算素数的一个方法是埃氏筛法 def odd_iter():#构建奇数数列,除了2,其他偶数都不是素数 n=1 while True: n=n+2 yield n def not_divisible(n): return lambda x:x % n > 0 def primes(): yield 2 it=odd_iter() while True: n=next(it) yield n it=filter(not_divisible(n),it) print("5.",end=' ') for n in primes(): if n <50: print(n,end=' ') else: break print() #sorted函数 #sorted(Iterable,key=,reverse=)->List print("6.",sorted([3,5,-4,-9])) print("7.",sorted([3,5,-4,-9],key=abs)) print("8.",sorted(['bob', 'about', 'Zoo', 'Credit'])) print("9.",sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower)) print("9.",sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower,reverse=True)) #2.返回函数 #闭包closure #生成并返回函数,类似函数生成式,动态变化的函数体 def lazy_sum(*args): def sum(): ax=0 for n in args: ax=ax+n return ax return sum f=lazy_sum(1,2,3,4,5) f1=lazy_sum(1,2,3,4,5) print("10.",f(),f,f==f1) def count(): fs=[] for i in range(1,4): def f(): return i*i fs.append(f) #只传入函数,函数内部的代码并未执行 return fs c1,c2,c3=count() #三个返回函数的调用结果值都为9,因为fs.append(f)的f中引用了i #当调用函数时,i都已经变为3,所以调用结果都为9 #所以,返回函数不要引用任何循环变量,或者后续会发生变化的变量 print("11.",c1(),c2(),c3()) #改进版本 def count1(): def f(j): def g(): return j*j return g fs=[] for i in range(1,4): fs.append(f(i)) #传入时,i已经确定,被传入函数中 return fs cc1,cc2,cc3=count1() print("12.",cc1(),cc2(),cc3()) #3.匿名函数 lambda #不常使用的函数,可以使用匿名函数,一次行执行的函数代码 print("13.",list(map(lambda x:x*x,[1,2,3,4,5]))) f=lambda x:x*x #匿名函数赋值于某个变量 print("14.",f(6),f) def func(x,y): return lambda z: x*x+y*y+z #返回匿名函数 print("15.",func(3,5)(1)) #4.装饰器 decorator: 可用于函数和类 #在原函数的功能不改变的前提下,增加新的功能和代码,又不影响原函数 #在代码运行期间动态增加功能的方式--装饰器Decorator import functools def log(text): def decorator(func): @functools.wraps(func) def wrapper(*args,**kw): print("%s %s():"%(text,func.__name__)) return func(*args,**kw) return wrapper return decorator @log('execute') def now(): print("2020-03-27") print("16.",now) now() #5.偏函数 partial-function #把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数 import functools int2=functools.partial(int,base=2) #相当于 def int2(s,base=2): return int(s,base) print("17.",int2) print("18.",int2('1000'),int2('1000',base=8))
sum_num = 1 for i in range(1, int(input()) + 1): sum_num = (sum_num * i) % (10**9 + 7) print(sum_num)
a, b = map(int, input().split()) if a == 1: a = 14 if b == 1: b = 14 def calc(a, b): if a > b: return 'Alice' elif a < b: return 'Bob' else: return 'Draw' print(calc(a, b))
# 'a' + str + 'b' # 'c' + str + 'a' # 'b' + str + 'b' n = int(input()) ans = input() count = 0 turn = 0 s = 'b' while True: if len(s) > n: print(-1) break elif ans == 'b': print(0) break else: if turn == 0: s = 'a' + s + 'c' turn += 1 count += 1 elif turn == 1: s = 'c' + s + 'a' turn += 1 count += 1 elif turn == 2: s = 'b' + s + 'b' turn = 0 count += 1 if s == ans: print(count) break
x = float (input ("введите число: ")) if -2.4 <= x <= 5.7: print (x ** 2) else: print(4) else: ("введите число!:")
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self, root): self.root = Node(root) self._print_tree_selector = { 'preorder': self._preorder_print, 'inorder': self._inorder_print, 'postorder': self._postorder_print } def insert(self, new_val): pass def search(self, find_val): """Return True if the value is in the tree, return False otherwise.""" return self.__preorder_search(self.root, find_val) def print_tree(self, traversal_mode='inorder'): """Print out all tree nodes as they are visited in a pre-order traversal.""" print_tree_method = self._print_tree_selector[traversal_mode] return print_tree_method(self.root, "") def __preorder_search(self, start, find_val): """Helper method - use this to create a recursive search solution.""" if start is not None: if start.value == find_val: return True left_search = self.__preorder_search(start.left, find_val) if left_search: return True else: return self.__preorder_search(start.right, find_val) ## Alternative # if start: # if start.value == find_val: # return True # else: # return self.preorder_search(start.left, find_val) or self.preorder_search(start.right, find_val) return False @staticmethod def __populate_traversal(traversal, value): if not traversal: # first item being added to traversal traversal += str(value) else: traversal += '-' + str(value) return traversal @classmethod def _preorder_print(cls, start, traversal): """Helper method - use this to create a recursive print solution.""" if start is not None: traversal = cls.__populate_traversal(traversal, start.value) traversal = cls._preorder_print(start.left, traversal) traversal = cls._preorder_print(start.right, traversal) return traversal @classmethod def _inorder_print(cls, start, traversal): if start is not None: traversal = cls._inorder_print(start.left, traversal) traversal = cls.__populate_traversal(traversal, start.value) traversal = cls._inorder_print(start.right, traversal) return traversal @classmethod def _postorder_print(cls, start, traversal): if start is not None: traversal = cls._postorder_print(start.left, traversal) traversal = cls._postorder_print(start.right, traversal) traversal = cls.__populate_traversal(traversal, start.value) return traversal class BST(BinaryTree): def __init__(self, root): super().__init__(root) def insert(self, new_val): current_node = self.root while current_node is not None: if new_val < current_node.value and current_node.left is None: current_node.left = Node(new_val) return if new_val >= current_node.value and current_node.right is None: current_node.right = Node(new_val) return if new_val < current_node.value: current_node = current_node.left else: current_node = current_node.right ## Alternative # def insert(self, new_val): # self.insert_helper(self.root, new_val) # # def insert_helper(self, current, new_val): # if current.value < new_val: # if current.right: # self.insert_helper(current.right, new_val) # else: # current.right = Node(new_val) # else: # if current.left: # self.insert_helper(current.left, new_val) # else: # current.left = Node(new_val) def search(self, find_val): current_node = self.root while current_node is not None: if current_node.value == find_val: return True if find_val < current_node.value: current_node = current_node.left else: current_node = current_node.right return False ## Alternative # def search(self, find_val): # return self.search_helper(self.root, find_val) # # def search_helper(self, current, find_val): # if current: # if current.value == find_val: # return True # elif current.value < find_val: # return self.search_helper(current.right, find_val) # else: # return self.search_helper(current.left, find_val) # return False if __name__ == '__main__': # Set up tree tree = BinaryTree(4) tree.root.left = Node(2) tree.root.right = Node(5) tree.root.left.left = Node(1) tree.root.left.right = Node(3) # Test search # Should be True print(tree.search(4)) # Should be False print(tree.search(6)) # Test print_tree # Should be 1-2-4-5-3 print('preorder traversal', tree.print_tree('preorder')) print('inorder traversal', tree.print_tree('inorder')) print('postorder traversal', tree.print_tree('postorder')) # Set up BST tree = BST(4) # Insert elements tree.insert(2) tree.insert(1) tree.insert(3) tree.insert(3) tree.insert(5) # Check search # Should be True print(tree.search(4)) # Should be False print(tree.search(6)) # def test(start): # if start is not None: # print(start.value) # print('left') # test(start.left) # print(start.value) # print('right') # test(start.right) # test(tree.root) # Test print_tree # Should be 1-2-4-5-3 print('preorder traversal', tree.print_tree('preorder')) print('inorder traversal', tree.print_tree('inorder')) print('postorder traversal', tree.print_tree('postorder'))
import numpy as np import random def swap_mutate(chromosome,mutate_percent): ## flip coin to see if chromosome gets mutated if random.uniform(0,1) < mutate_percent: ## select 2 random genes of the chromosome gene1 = random.randint(0, len(chromosome)-1) gene2 = random.randint(0, len(chromosome)-1) while gene2 == gene1: gene2 == random.randint(0, len(chromosome)-1) ## swap the selected genes chromosome[gene1],chromosome[gene2]=chromosome[gene2],chromosome[gene1] return chromosome def ordered_crossover(parent1,parent2): ## ordered_crossover() takes in two parent chromosomes as input ## and returns a child chromosome ## ## ordered_crossover() takes a random subarray from the first parent and ## copies that subarray over to the child (note: the subarray can ## wrap across the ends of the array) ## the remaining genes of the child are filled in the order that ## they appear in the second parent ## set n to the chromosome length n = len(parent1) ## initialize child with an array of zeros child = np.zeros(n, dtype=int) ## select a random subarray of parent1 by first randomly selecting ## the start and end points of the subarray start_point = random.randint(0,n-1) ## restrict the length of the subarray to between 1 and n - 2 end_point = (start_point + random.randint(0,n-1 - 2)) % n print("start_point = ",start_point) print("end_point = ",end_point) ## copy the subarray from parent1 into the child if start_point <= end_point: child[start_point:end_point+1] = parent1[start_point:end_point+1] else: ## if start_point is greater than end_point, the subarray ## wraps around the ends of the array child[start_point:] = parent1[start_point:] child[:end_point+1] = parent1[:end_point+1] ## fill the remaining genes of the child in the order they appear ## in parent2 pointer = 0 for i in range(n): if parent2[i] not in child: while child[pointer] != 0: pointer += 1 child[pointer] = parent2[i] return child def generate_permutation(n): ## create a random permutation of the sequence from 1 to n ## initialize the permutation with an array of zeros permutation = np.zeros(n, dtype=int) for i in range(n): ## randomly select an integer between 1 and n choice = random.randint(1,n) ## check if the chosen integer has already been ## added to the permutation. ## if it has, keep choosing numbers until a new one ## is chosen while choice in permutation: choice = random.randint(1,n) ## add the new number to the permutation permutation[i] = choice return permutation if __name__ == "__main__": A = generate_permutation(6) B = generate_permutation(6) print("A = ",A) print("B = ",B) child = ordered_crossover(A, B) print("child = ",child) swap_mutate(child, 1) print("mutated = ",child)
# This function is an implementation of the autokey Vigenere cipher algorithm. def decryptVigenere(ciphertext, key): ciphertextbreak = [] ciphertextbreakextra = [] Letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' smallLetters = 'abcdefghijklmnopqrstuvwxyz' keylength = len(key) ciphertextlength = len(ciphertext) diff = ciphertextlength - keylength finalplaintext = list('.' * ciphertextlength) ciphertextbreak.append(ciphertext[0 : keylength]) ciphertextbreakextra.append(ciphertext[-diff:]) for i in range(0, len(ciphertextbreak)): for j in range(0, keylength): indkey = smallLetters.index(key[j]) indcipher = Letters.index(ciphertextbreak[i][j]) newindcipher = indcipher - indkey modindcipher = newindcipher % 26 finalplaintext[j] = smallLetters[modindcipher] for i in range(0, diff): indkey = smallLetters.index(finalplaintext[i]) indcipher = Letters.index(ciphertextbreakextra[0][i]) newindcipher = indcipher - indkey modindcipher = newindcipher % 26 finalplaintext[keylength + i] = smallLetters[modindcipher] plaintext = "".join(finalplaintext) plaintext = plaintext.upper() print(plaintext)
#!/usr/bin/python3 print("Stoisz przed kamienną bramą podczas pełni księżyca. ") password = input("Podaj hasło: ") if password.lower() == "melon": print("Możesz wejść, brama została otwarta!") else: print("Hasło nie zadziałało")
# STEP 4 # Create a checking account class that is a subclass of the abstract account class. It should have the # following member methods: # makeWithdraw: Before the super class method is called, this method will determine if a # withdrawal (a check written) will cause the balance to go below $0. If the # balance goes below $0, a service charge of $15 will be taken from the account. # # The withdrawal will not be made due to insufficient funds. If there isn’t enough # in the account to pay the service charge, the balance will become negative and # the customer will owe the negative amount to the bank. # doMonthlyReport: Before the super class method is called, this method adds the monthly fee of $5 # plus $0.10 per withdrawal to the monthly service charge in the data fields. # Exercise with a Checking account, multiple transactions (Withdrawals and Monthly Report) import datetime from BankEntities.CheckingAccount import CheckingAccount account2 = CheckingAccount("0002", "Bassel Kotaish", 100, True) trans_number = 0 trans_flag = True trans_withdrawals = 0 trans_deposits = 0 trans_list = [] trans_type = "" v_amount = "" v_service_charge = 0 v_balance = 0 WITHDRAWAL_FEE = 0.10 MONTHLY_WITHDRAWALS_FEE = 5.00 monthly_fee_now = "" v_boolean_bank_menu = True v_boolean_account_menu = True while v_boolean_bank_menu: # Bank Menu This leads to # another menu (account menu) print("BANK MENU") # print("A: Savings") print("B: Checking") print("C: Exit") menu_bank = input("Enter a valid choice - uppercase and lowercase, invalid --> Main Menu > ") if menu_bank == "B" or menu_bank == "b": if monthly_fee_now.upper() == "Y": # initialize account and variables account2 = CheckingAccount("0002", "Bassel Kotaish", 100, True) trans_number = 0 trans_flag = True trans_withdrawals = 0 trans_deposits = 0 trans_list = [] trans_type = "" v_amount = "" v_service_charge = 0 v_balance = 0 v_account_type = "Checking" account2.account_type = "Checking" elif menu_bank == "C" or menu_bank == "c": print("Exiting program") break else: continue # Working with account type now while v_boolean_account_menu: print(v_account_type.upper() + " MENU") # print("A: Deposit") print("B: Withdrawals") print("C: Report") print("D: Go back to BANK MENU") menu_account = input("Enter a valid choice - uppercase and lowercase, invalid --> Bank Menu > ") if menu_account.upper() == "B": print("Working with " + v_account_type.upper() + " MENU - B: Withdrawals") v_amount = input("Operation amount, please > ") # validate the operation amount if not v_amount.isnumeric() or v_amount == str(0): print("Operation amount is not numeric or equal zero") else: trans_type = "w" v_operation_date = datetime.datetime.now() account2.withdraw(amount=float(v_amount)) trans_number += 1 trans_flag = account2.checking_flag if not account2.checking_flag: print("Checking account balance below 0.00 $, no withdrawals allowed and $ 15 Penalty") v_balance = account2.balance v_service_charge = account2.withdrawal_penalty elif account2.checking_flag: trans_withdrawals += 1 account2.num_withdrawals = trans_withdrawals # WITHDRAWAL_FEE # $ 0.10 v_service_charge = WITHDRAWAL_FEE account2.monthly_service_charge = account2.monthly_service_charge + v_service_charge account2.balance = account2.balance - v_service_charge v_balance = account2.balance trans_list.append( [trans_number, trans_type, v_amount, v_service_charge, v_operation_date, v_balance, trans_flag]) # list first position is zero (0) transaction # and transaction amount for each element on the list elif menu_account.upper() == "C": print("Working with " + v_account_type.upper() + " MENU - C: Report") if len(trans_list) >= 1: while True: monthly_fee_now = input("Report with Monthly Fee now (Y/N)? - " "uppercase and lowercase, otherwise invalid > ") if monthly_fee_now.upper() == "Y" or monthly_fee_now.upper() == "N": break else: continue # At least 1 withdrawal to apply MONTHLY_WITHDRAWALS_FEE for the Monthly Report # MONTHLY_WITHDRAWALS_FEE => $ 5.00 if len(trans_list) >= 1 and monthly_fee_now.upper() == "Y": account2.balance = v_balance - MONTHLY_WITHDRAWALS_FEE account2.monthly_service_charge = account2.monthly_service_charge + MONTHLY_WITHDRAWALS_FEE account2.account_type = v_account_type account2.monthly_report() for t in trans_list: print("{0:8}".format(t[0]) + "|", end="") if t[1] == "d": if t[6]: print("{:16,.2f} $".format(float(t[2])) + "|", end="") print("{0:17}".format(" ") + "|", end="") else: print("{:16,.2f} $".format(float(t[2])) + "|", end="") # deposit too low, balance below $ 25 print("<--Cannot deposit" + "|", end="") elif t[1] == "w": if t[6]: print("{0:18}".format(" ") + "|", end="") print("{:15,.2f} $".format(float(t[2])) + "|", end="") else: print("Penalty withdraw->" + "|", end="") # Cannot withdraw print("{:15,.2f} $".format(float(t[2])) + "|", end="") print("{:15,.2f} $".format(float(t[3])) + "|", end="") print("{}".format(t[4].strftime("%c")) + " |", end="") print("{:15,.2f} $".format(float(t[5]))) print("-" * 109) account2.balance = v_balance if monthly_fee_now.upper() == "Y": break else: monthly_fee_now = "" continue elif menu_account.upper == "D": print("Go to previous menu") break else: break
#practice working with dates and time from datetime import date from datetime import time from datetime import datetime def main(): print("Today's date = ", date.today()) print("Current time = ", datetime.now()) print("The current year =", date.today().year) print("The current month =", date.today().month) if __name__ == "__main__": main()
#task1 def binarysearch(arr, l, r, x): if r >= l: mid = l + (r - l) // 2 if arr[mid] == x: return mid elif arr[mid] > x: return binarysearch(arr, l, mid - 1, x) else: return binarysearch(arr, mid + 1, r, x) else: return -1 #task2 def fibonaccisearch(lst, target): size = len(lst) start = -1 f0 = 0 f1 = 1 f2 = 1 while (f2 < size): f0 = f1 f1 = f2 f2 = f1 + f0 while (f2 > 1): index = min(start + f0, size - 1) if lst[index] < target: f2 = f1 f1 = f0 f0 = f2 - f1 start = index elif lst[index] > target: f2 = f0 f1 = f1 - f0 f0 = f2 - f1 else: return index if (f1) and (lst[size - 1] == target): return size - 1 return None #task3 class HashTable: def __init__(self): self.size = 11 self.slots = [None] * self.size self.data = [None] * self.size def put(self, key, data): hashvalue = self.hashfunction(key,len(self.slots)) if self.slots[hashvalue] == None: self.slots[hashvalue] = key self.data[hashvalue] = data else: if self.slots[hashvalue] == key: self.data[hashvalue] = data else: nextslot = self.rehash(hashvalue, len(self.slots)) while self.slots[nextslot] != None and \ self.slots[nextslot] != key: nextslot = self.rehash(nextslot, len(self.slots)) if self.slots[nextslot] == None: self.slots[nextslot] = key self.data[nextslot] = data else: self.data[nextslot] = data def hashfunction(self, key, size): return key%size def rehash(self, oldhash, size): return (oldhash+1)%size def get(self, key): startslot = self.hashfunction(key, len(self.slots)) data = None stop = False found = False position = startslot while self.slots[position] != None and \ not found and not stop: if self.slots[position] == key: found = True data = self.data[position] else: position = self.rehash(position, len(self.slots)) if position == startslot: stop = True return data def __getitem__(self, key): return self.get(key) def __setitem__(self, key, data): self.put(key, data) def __len__(self): count = 0 for value in self.slots: if value != None: count += 1 return count def __contains__(self, key): return self.get(key) != None
#Questao 1 # 1. Escreva um programa em Python que leia uma tupla contendo 3 números inteiros, (n1, n2, n3) e os imprima em ordem crescente. print("Digite 3 números conforme exemplo: (n1, n2, n3)") numeros = tuple(str(input("Informe os 3 numeros ")).split(",")) numeros = [int(i) for i in numeros] numeros.sort(reverse=False) print(f"Os numeros informados são {tuple(numeros)}")
# Questao 9 # 9. Usando o código anterior, escreva um novo programa que, quando as teclas ‘w’, ‘a’, ‘s’ e ‘d’ forem pressionadas, # ele movimente o círculo com o texto “clique” nas direções corretas. # Caso colida com algum retângulo, o retângulo que participou da colisão deve desaparecer. import pygame from pygame.locals import * from escrever import escreve_texto from random import randint import time pygame.init() largura_tela, altura_tela = 800, 800 tela = pygame.display.set_mode((largura_tela, altura_tela)) BRANCO, PRETO = (255, 255, 255), (0, 0, 0) AZUL, AMARELO = (0, 0, 255), (255, 151, 26) x_circulo, y_circulo, diametro_circulo = largura_tela/2, 80, 60 fonte = pygame.font.Font(None, 24) clock = pygame.time.Clock() def desenha_circulo(x_circulo, y_circulo): pygame.draw.circle(tela, AZUL, (x_circulo, y_circulo), diametro_circulo) text = fonte.render(f"Clique aqui", 1, BRANCO) tela.blit(text, (x_circulo-44, y_circulo - 10)) class Teclas: def __init__(self, w, a, s, d): self.w = w self.a = a self.s = s self.d = d teclas = Teclas(False, False, False, False) def move_circulo(teclas, x_circulo, y_circulo): if teclas.w and y_circulo > diametro_circulo: y_circulo -= 1 elif teclas.s and y_circulo < altura_tela-diametro_circulo: y_circulo += 1 if teclas.a and x_circulo > diametro_circulo: x_circulo -= 1 elif teclas.d and x_circulo < largura_tela-diametro_circulo: x_circulo += 1 if x_circulo == diametro_circulo: x_circulo = largura_tela-diametro_circulo elif x_circulo == largura_tela-diametro_circulo: x_circulo = diametro_circulo elif y_circulo == diametro_circulo: y_circulo = altura_tela-diametro_circulo elif y_circulo == altura_tela-diametro_circulo: y_circulo = diametro_circulo return x_circulo, y_circulo class Retangulo(): def __init__(self): self.largura_retangulo = 160 self.altura_retangulo = 130 self.x = randint(0, largura_tela-self.largura_retangulo) self.y = randint(0, altura_tela-self.altura_retangulo) self.area = pygame.Rect(self.x, self.y, self.largura_retangulo, self.altura_retangulo) self.cor = AMARELO def desenha_retangulo(self, tela): pygame.draw.rect(tela, self.cor, self.area) lista_retangulos = [] def validar_lista_retangulos(retangulo): lista_retangulos.append(retangulo) if len(lista_retangulos) > 0: for rct in lista_retangulos: if rct != retangulo: index = pygame.Rect.collidepoint(retangulo.area, rct.x, rct.y) if index == 1: lista_retangulos.remove(rct) terminou = False while not terminou: tela.fill(PRETO) for retangulo_desenhado in lista_retangulos: retangulo_desenhado.desenha_retangulo(tela) escreve_texto("Q9", tela, BRANCO, fonte) for event in pygame.event.get(): if event.type == pygame.QUIT: terminou = True # Enquanto estiver pressionado, o coelho vai se mexer if event.type == pygame.KEYDOWN: if event.key == K_w or event.key == K_UP: teclas.w = True elif event.key == K_a or event.key == K_LEFT: teclas.a = True elif event.key == K_s or event.key == K_DOWN: teclas.s = True elif event.key == K_d or event.key == K_RIGHT: teclas.d = True # No momento que parou de pressionar a tecla if event.type == pygame.KEYUP: if event.key == pygame.K_w or event.key == pygame.K_UP: teclas.w = False elif event.key == pygame.K_a or event.key == pygame.K_LEFT: teclas.a = False elif event.key == pygame.K_s or event.key == pygame.K_DOWN: teclas.s = False elif event.key == pygame.K_d or event.key == pygame.K_RIGHT: teclas.d = False if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: pos = pygame.mouse.get_pos() x_mouse, y_mouse = pos # clique dentro do circulo if x_mouse >= x_circulo - diametro_circulo and x_mouse <= x_circulo + diametro_circulo and y_mouse >= y_circulo - diametro_circulo and y_mouse <= y_circulo + diametro_circulo: retangulo = Retangulo() validar_lista_retangulos(retangulo) x_circulo, y_circulo = move_circulo(teclas, x_circulo, y_circulo) desenha_circulo(x_circulo, y_circulo) pygame.display.update() pygame.display.quit() pygame.quit()
a = 10 b = 5 print('a =', a, '\tb = ', b) a = a ^ b b = a ^ b a = a ^ b print('a =', a, '\tb =', b)
a = 8 b = 2 print('Addition:\t' , a, '+', b, '=', a+b) print('Subtraction:\t' , a, '-', b, '=', a-b) print('Multiplication:\t' , a, '*', b, '=', a*b) print('Floor Division:\t' , a, '/', b, '=', a//b) print('Modulo:\t\t' , a, '%', b, '=', a%b) print('Exponent:\t' , a, '^2=', b, '=', a**b)
#queremos usar multiprocessamento sempre que for para acelerar significativamente nosso programa, #agora a aceleração vem de diferentes tarefas executadas em paralelo import concurrent.futures import time #inicio marcador do tempo start = time.perf_counter() #função responsável pelo delay def do_something(seconds): print(f'Sleeping {seconds} second(s)...') time.sleep(seconds) return f'Done Sleeping...{seconds}' #responsável por criar uma pilha de executor de processos, para utilizar a função map with concurrent.futures.ProcessPoolExecutor() as executor: secs = [5, 4, 3, 2, 1] results = executor.map(do_something, secs) #explicado no exercício de threads for result in results: print(result) #fim marcador do tempo finish = time.perf_counter() print(f'Finished in {round(finish - start, 2)} second(s)')
#dicionarios student = {'name': 'Guilherme', 'age': 21, 'courses': ['Math', 'CompSci']} print(student['name']) student['phone'] = '111-111' print(student.get('phone','not found')) print(student.items()) print('\n') for key, value in student.items(): print(key, value)
""" Contains exceptions that can be thrown during the course of executing this client """ class NetworkError(IOError, RuntimeError): """ Thrown if the client is unable to connect to the server, or recieves an unexpected response from the server. """ pass class ValidationError(ValueError): """ Thrown if a JSON object does not conform to a required JSON schema. This exception takes in the message and context from the API. :var str message: The message that the API returns from validating the schema :var [str] context: The context in which the error occurred """ def __init__(self, message, context, *args, **kwargs): """ Instantiates the variables described above """ ValueError.__init__(self, *args, **kwargs) self.message = message self.context = context def __str__(self): """ Returns a string representation of the exception """ return 'ValueError: message=%s, context=%s' % ( self.message, self.context) class ProcessingError(RuntimeError): """ Thrown if an error occurs while executing :meth:`run` in a processing thread """ pass class ServiceNotFoundError(KeyError, NetworkError): """ Thrown if the client attempts to locate a service, but that service does not exist """ pass
import unittest from populace import find_users class TestFindUsers(unittest.TestCase): def test_valid_city_with_results(self): """ Test method returns correct number of users for a valid city """ users = find_users("London") self.assertEqual(len(users), 9) def test_valid_city_with_no_results(self): """ Test method returns no users for a valid city with noone nearby """ users = find_users("Newcastle") self.assertEqual(len(users), 0) def test_invalid_city(self): """ Test method returns no users for an invalid city """ users = find_users("foo") self.assertEqual(len(users), 0) def test_valid_city_with_bigger_radius(self): """ Test method returns more users if radius is increased """ users = find_users("London", radius=150) self.assertEqual(len(users), 13) def test_valid_city_with_smaller_radius(self): """ Test method returns more users if radius is increased """ users = find_users("London", radius=25) self.assertEqual(len(users), 8) def test_invalid_radius(self): """ Test method throws an error if invalid radius is supplied """ with self.assertRaises(TypeError): find_users("London", radius="bar")
from Student import Student from Dorm import Dorm from matrix import Matrix import random dorms = [] students = [] NUMDORMS = 2 NUMSINGLES = 3 NUMDOUBLES = 3 ROOMSPERDORM = NUMSINGLES + NUMDOUBLES NUMSTUDENTS = NUMDORMS * (NUMSINGLES + NUMDOUBLES * 2) def initDorms(): for dorm in range(NUMDORMS): dorms.append(Dorm(NUMSINGLES, NUMDOUBLES, dorm*" ")) def initStudents(): for student in range(NUMDORMS * NUMSINGLES - 1): weights = {} for dorm in dorms: weights[dorm.name()] = random.random() stud = Student(1, None, weights) students.append(stud) assignedDorm = dorms[random.randrange(0,len(dorms))] while (assignedDorm.existsEmptyRoom(1) == False): assignedDorm = dorms[random.randrange(0,len(dorms))] listRooms = assignedDorm.getListRooms() room = listRooms[random.randrange(0,NUMSINGLES)] while room.full() == True: room = listRooms[random.randrange(0,NUMSINGLES)] #room.addStudent(stud) for student in range(NUMDORMS * NUMDOUBLES): weights = {} for dorm in dorms: weights[dorm.name()] = random.random() stud = Student(2, None, weights) students.append(stud) assignedDorm = dorms[random.randrange(0,len(dorms))] while (assignedDorm.existsEmptyRoom(2) == False): assignedDorm = dorms[random.randrange(0,len(dorms))] listRooms = assignedDorm.getListRooms() room = listRooms[random.randrange(NUMSINGLES,len(listRooms))] while room.full() == True: room = listRooms[random.randrange(NUMSINGLES, len(listRooms))] #room.addStudent(stud) if __name__ == '__main__': initDorms() initStudents() for dorm in dorms: print dorm.totalUtil() singles = [student for student in students if student.getRoomType() == 1] #m = Matrix(singles, dorms)
A = float(input()) B = float(input()) C = float(input()) PESO_A = 2 PESO_B = 3 PESO_C = 5 A_POND = PESO_A * A B_POND = PESO_B * B C_POND = PESO_C * C MEDIA = (A_POND + B_POND + C_POND) / (PESO_A + PESO_B + PESO_C) print("MEDIA = %.1f" % MEDIA)
number_1 = input('enter 1-st number: ') number_2 = input('enter 2-nd number: ') if number_1.isdigit(): if number_2.isdigit(): sum = int(number_2) + int(number_1) print(number_1,"+",number_2,"=",sum) else: print(number_2," is'nt a digit") else: print(number_1," is'nt a digit") print("Good")
#!usr/bin/env python def hora_minuto(horas=0): if horas < 1 or horas > 100: print("Error no puede ingresar numeros menores a 0 o mayores a 100") else: print("Existen {result} minutos en {hora} hora(s).".format( result=horas * 60, hora=horas)) def main(): try: horas = int(input("Ingrese una cantidad de horas: ")) except: print("Solo números enteros") else: hora_minuto(horas) if __name__ == "__main__": main()
def fibonacci(n): """ Metodo recursivo # para 34 toma 5 seg """ if n == 1 or n == 2 or n < 1: return 1 else: result = fibonacci(n - 1) + fibonacci(n - 2) return result def fibonacci_2(n): """ Funcion fibonacci usando el metodo de menor a mayor mejor rendimiento, en 34 el resultado es instantaneo """ if n == 1 or n == 2 or n < 1: return 1 seq = [None] * (n+1) seq[1] = 1 seq[2] = 1 for i in range(3, n + 1): seq[i] = seq[i-1] + seq[i-2] return seq[n] print(fibonacci(34))
from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenize ps=PorterStemmer() example_words=['python','pythoner','pythoning','pythoned','pythonly'] for w in example_words: print(ps.stem(w)) new_text='it is very important to be pythonly while you are pythoning with python. All pythoners have pythoned poorly at least once' words=word_tokenize(new_text) for w in words: print(ps.stem(w))
#calculate the number of students in this classroom total = 0 student = int( input("Enter value: ") ) while student != -1: total += student student = int( input("Enter value: ") ) print( "total=" , total )
#1. Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big".Example: biggie_size([-1, 3, 5, -5]) returns that same list, but whose values are now [-1, "big", "big", -5] arr = [-1, 34, -3, 37, 16, -25, -5, 87] def newArr(arr): for i in range(0, len(arr), 1): if (arr[i] > 0): arr[i] = "big" return arr print(newArr(arr)) #2. Count Positives - Given a list of numbers, create a function to replace the last value with the number of positive values. (Note that zero is not considered to be a positive number).Example: count_positives([-1,1,1,1]) changes the original list to [-1,1,1,3] and returns it Example: count_positives([1,6,-4,-2,-7,-2]) changes the list to [1,6,-4,-2,-7,2] and returns it arr = [1, 6, -4, -2, -7, -2] def countPos(arr): arr[-1] = abs(arr[-1]) arr.append(arr[-1]) arr.pop() return(arr) print(countPos(arr)) #3. Sum Total - Create a function that takes a list and returns the sum of all the values in the list. Example: sum_total([1,2,3,4]) should return 10 Example: sum_total([6,3,-2]) should return 7 arr = [11,-2,34,48, 37, -21] def arrSum(arr): sum = 0 for i in range (0, len(arr)): sum = sum + arr[i] return sum print(arrSum(arr)) #4. Average - Create a function that takes a list and returns the average of all the values.x Example: average([1,2,3,4]) should return 2.5 arr = [10, 54, 37, 21, 28, 2] def arrAvg(arr): sum = 0 for i in range(0, len(arr)): sum = sum + arr[i] return sum/len(arr) print(arrAvg(arr)) #5. Length - Create a function that takes a list and returns the length of the list. Example: length([37,2,1,-9]) should return 4 Example: length([]) should return 0 arr = ["Danielle", 34, "Christopher", 37, 2010, 11] def lenList(arr): index = 0 for i in range (0, len(arr)): index = i # print(i) # print(index) return index + 1 print(lenList(arr)) arr = [37, 2, 1, -9] def lenList(arr): index = 0 for i in range (0, len(arr)): index = index + i return index-2 print(lenList(arr)) #6. Minimum - Create a function that takes a list of numbers and returns the minimum value in the list. If the list is empty, have the function return False. Example: minimum([37,2,1,-9]) should return -9 Example: minimum([]) should return False arr = [37, 2, 1, -9] arr2 = [] def minValue(arr): for i in range (0, len(arr)): if (arr[i] < 0): print(arr[i]) x = noMinValue(arr) print(x) def noMinValue(arr): for i in range (0, len(arr)): if (len(arr2) == 0): return False print(minValue(arr)) #7. Maximum - Create a function that takes a list and returns the maximum value in the list. If the list is empty, have the function return False. Example: maximum([37,2,1,-9]) should return 37 Example: maximum([]) should return False arr = [37, 2, 1, -9] arr2 = [] def maxValue(arr): max = 0 tempNum = 0 for i in range (0, len(arr)): if (arr[i] > 0): tempNum = arr[i] if (tempNum > max): max = tempNum print(max) x = noMaxValue(arr) print(x) def noMaxValue(arr): for i in range (0, len(arr)): if (len(arr2) == 0): return False print(maxValue(arr)) #8. Ultimate Analysis - Create a function that takes a list and returns a dictionary that has the sumTotal, average, minimum, maximum and length of the list. Example: ultimate_analysis([37,2,1,-9]) should return {'sumTotal': 31, 'average': 7.75, 'minimum': -9, 'maximum': 37, 'length': 4 } arr = [37, 2, 1, -9, -12] def ultimateArr(arr): sum = 0 avg = 0 maximum = 0 length = 0 for i in range (0, len(arr)): if(arr[i] > 0): if (maximum < arr[i]): maximum = arr[i] sum = sum + arr[i] avg = avg + arr[i] arr[i] < 0 length = length + i return (f"Sum : {sum}, Average : {avg/len(arr)}, Minmum : {arr[i]}, Maximum : {maximum}, Length : {length + 2}") print(ultimateArr(arr)) #9. Reverse List - Create a function that takes a list and return that list with values reversed. Do this without creating a second list. (This challenge is known to appear during basic technical interviews.) Example: reverse_list([37,2,1,-9]) should return [-9,1,2,37] arr_list = [37, 2, 1, -9, -12, 5, 34, 37] def reverseList(arr_list): print(list(reversed(arr_list))) print(reverseList(arr_list))
#import modules/requests import requests import bokeh import pandas as pd import csv import numpy as np import json api1="https://maps.googleapis.com/maps/api/geocode/json" csvfile=open('data.csv','w') csvwriter=csv.writer(csvfile, delimiter=',') #the while loop allows the user to enter the desired amount of inputs number=0 city = [] temp = [] while number<10: #put together url address=input("address:") if address=='quit': break # url=api1+urllib.parse.urlencode({"address":address}) # print(url) #get data from api json_data=requests.get(api1, params={'address':address}).json() json_status=json_data["status"] print("API Status:"+json_status) #access sub-dictoionary of results to get easy to read, formatted address if json_status == 'OK': for each in json_data ["results"][0] ["address_components"]: print(each["long_name"]) simple_address=json_data["results"][0]["formatted_address"] print(simple_address) number+=1 lat=str(json_data["results"][0]["geometry"]["bounds"]["northeast"]["lat"]) print(lat) lng=str(json_data["results"][0]["geometry"]["bounds"]["northeast"]["lng"]) print(lng) #Use the latitude and longitude from the previous api for the coordinates of Dark sky to get the temperature. #create url for dark sky api endpoint='https://api.darksky.net/forecast/' key='804c033fb6e3278059f4195775533fae' payload={'units':'us'} url2=endpoint+key+'/'+lat+','+lng json_data2=requests.get(url2,params=payload) data=json_data2.json() temperature=data['currently']['temperature'] print(temperature) city.append(address) temp.append(temperature) #import bokeh and create x and y axises from bokeh.charts import Bar, output_file, show from bokeh.charts import Bar, output_file, save print('cities', city) df = pd.DataFrame({'city':city, 'temperature':temp}) print(df) output_file("Temp of cities") bar1=Bar(df,"city",values="temperature",title="Temperature of various locations") save(bar1)
class Casting: def to_int(s): if type(s) == str: return int(s.strip()) else: return s class 사각형: name = "사각형" def __init__(self): print("사각형 created") def input_data(self): datum = input(self.msg) # 5, 3 data = datum.split(',') # ['5', '3'] x, y = Casting.to_int(data[0]), Casting.to_int(data[1]) self.__새넓이(x, y) def __새넓이(self, x, y): r = x * y print("{}의 넓이는 {}입니다".format(self.name, r)) class 직사각형(사각형): name = "직사각형" msg = "가로와 세로는?? (usage: 가로,세로)" class 평행사변형(사각형): name = "평행사변형" msg = "밑변와 높이는?? (usage: 밑변, 높이)" all_rects = [직사각형(), 평행사변형()] while True: print() rect_type = input("사각형의 종류는?\n 1) 직사각형\n 2)평행사변형\n (quit:q) >> ") if (rect_type == 'q'): break rect_index = Casting.to_int(rect_type) - 1 rect = all_rects[rect_index] rect.input_data() #input_data() 이렇게 되면 안되는 이유는?
import math A=float(input("Digite o valor do coeficiente A: ")) B=float(input("Digite o valor do coeficiente B: ")) C=float(input("Digite o valor do coeficiente C: ")) Delta=B**2-4*A*C if Delta<0: print(f"Seu delta vale {Delta} , portanto a equação não possui raízes reais.") if (Delta >=0): x1=(-B+math.sqrt(Delta))/(2*A) x2=(-B-math.sqrt(Delta))/(2*A) if (Delta>0): print(f"Seu delta vale {Delta} , portanto a equação possui 2 raízes {x1} e {x2} reais e distintas.") elif (Delta==0): print(f"Seu delta vale {Delta} , portanto a equação possui raízes {x1} e {x2} reais iguais.")
c=0 s=0 maiors=0 menors=float(input("Digite o valor do salário: ")) while(c<4): s=float(input("Digite o valor do salário: ")) c+=1 if maiors<s: maiors=s if menors>s: menors=s print(f"O maior salário foi de R${maiors:.2f} e o menor foi de R${menors:.2f}")
import os import pygame from random import choice chanse = [0] * 8 + [1] * 2 # вероятность появления (2/10) class Board: # класс поля def __init__(self, board_size): self.board_size = list(board_size) self.board = [[0] * board_size[0] for _ in range(board_size[1])] # само поле self.left = 10 self.top = 10 self.cell_size = 30 def set_view(self, board_configs): self.left = board_configs[0] self.top = board_configs[1] self.cell_size = board_configs[2] def render(self): for y in range(self.board_size[1]): for x in range(self.board_size[0]): w = self.left + self.cell_size * x h = self.top + self.cell_size * y if self.setka: pygame.draw.rect(self.screen, (100, 100, 100), (w, h, self.cell_size, self.cell_size), 1) if self.krug: if self.board[y][x]: pygame.draw.circle(self.screen, pygame.Color('green'), (w + self.cell_size // 2, h + self.cell_size // 2), self.cell_size // 2 - 2) else: if self.board[y][x]: pygame.draw.rect(self.screen, pygame.Color('green'), (w, h, self.cell_size, self.cell_size)) def get_cell(self, mouse_pos): for y in range(self.board_size[1]): for x in range(self.board_size[0]): w = self.left + self.cell_size * x h = self.top + self.cell_size * y if w + self.cell_size >= mouse_pos[0] > w and \ h + self.cell_size >= mouse_pos[1] > h: return x, y return None def on_click(self, cell_coords): i = 1 if self.board[cell_coords[1]][cell_coords[0]]: i = 0 self.board[cell_coords[1]][cell_coords[0]] = i def get_click(self, mouse_pos): cell_coords = self.get_cell(mouse_pos) if cell_coords is not None: self.on_click(cell_coords) def __str__(self): return self.board class Life(Board): def __init__(self, board_size, v=20): Board.__init__(self, board_size) self.setka = self.krug = True self.v = v self.stop = True self.clock = pygame.time.Clock() self.bg = True def set_viev(self, board_configs=(0, 0, 20)): Board.set_view(self, board_configs) self.screen = pygame.display.set_mode(( self.board_size[0] * self.cell_size + self.left * 2, self.board_size[1] * self.cell_size + self.top * 2)) self.board = [[0] * self.board_size[0] for _ in range(self.board_size[1])] # импорт заднего фона fullname = os.path.join('data', 'stars_bg.jpg') image = pygame.image.load(fullname).convert() self.bg = pygame.transform.scale(image, (self.cell_size * self.board_size[0], self.cell_size * (self.board_size[1]))) def start_life(self): # начало жизни pygame.init() running = True while running: self.screen.fill((50, 50, 50)) if self.bg: # отрисовка заднего фона self.screen.blit(self.bg, self.bg.get_rect()) for event in pygame.event.get(): flag = True # релизуем управление if event.type == pygame.QUIT: # выключение running = False if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: # нажтие на ЛКМ self.get_click(event.pos) if event.button == 2: # нажатие на СКМ self.v = 10 # скорость равна 10 if event.button == 3: # нажатие на ПКМ self.stop = False # запуск "жизни" if event.button == 4: # прокрутка колёсика мыши вверх self.v += 1 # увеличение скорости if event.button == 5: # прокрутка колёсика мыши вниз if self.v > 1: self.v -= 1 # уменьшение скорости if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: # выключение running = False if event.key == pygame.K_r: # нажатие клавиши "R" # очистка поля self.board = [ [0] * self.board_size[0] for _ in range(self.board_size[1])] if event.key == pygame.K_b: # нажатие клавиши "B" # включить/выключить задний фон if self.bg: self.bg = False else: self.bg = True if event.key == pygame.K_t: # нажатие клавиши "T" # поставить живые клетки случайным образом self.randomize() if event.key == pygame.K_w: # нажатие клавиши "W" self.full_all() # заставить поле полностью if event.key == pygame.K_s: # нажатие клавиши "S" if self.setka: # включить или отключить сетку self.setka = False else: self.setka = True flag = False if event.key == pygame.K_q: # нажатие клавиши "Q" # выбор клетки в форме квадрата или же круга if self.krug: self.krug = False else: self.krug = True flag = False if event.key == pygame.K_UP: # нажатие стрелки вверх if self.board_size[1] > 3: self.board_size[1] -= 1 self.set_viev((self.left, self.top, self.cell_size)) if event.key == pygame.K_DOWN: # нажатие стрелки вниз self.board_size[1] += 1 self.set_viev((self.left, self.top, self.cell_size)) if event.key == pygame.K_RIGHT: # нажатие стрелки вправо self.board_size[0] += 1 self.set_viev((self.left, self.top, self.cell_size)) if event.key == pygame.K_LEFT: # нажатие стрелки влево if self.board_size[0] > 3: self.board_size[0] -= 1 self.set_viev((self.left, self.top, self.cell_size)) if event.key == pygame.K_EQUALS: # нажатие клавиши "=" self.cell_size += 1 self.set_viev((self.left, self.top, self.cell_size)) if event.key == pygame.K_MINUS: # нажатие клавиши "-" if self.cell_size > 5: self.cell_size -= 1 self.set_viev((self.left, self.top, self.cell_size)) if event.key == pygame.K_m: # нажатие клавиши "M" self.v = 0 flag = False if event.key == pygame.K_SPACE: # нажатие клавиши "Space" if self.stop: # запуск и остановка "жизни" self.stop = False else: self.stop = True elif not self.stop and flag: self.stop = True self.render() if not self.stop: self.living() self.clock.tick(self.v) '''if pygame.mouse.get_focused() and self.stop: pos = pygame.mouse.get_pos() pygame.draw.circle(self.screen, pygame.Color('red'), (pos[0], pos[1]), 5)''' pygame.display.flip() pygame.quit() def on_click(self, cell_coords): if self.stop: Board.on_click(self, cell_coords) def living(self): boardI = [] for y in range(self.board_size[1]): boardI.append(self.board[y][:]) for y in range(self.board_size[1]): for x in range(self.board_size[0]): klet = self.near((x, y)) if self.board[y][x] == 1 and not (klet == 3 or klet == 2): boardI[y][x] = 0 elif self.board[y][x] == 0 and klet == 3: boardI[y][x] = 1 self.board = boardI def randomize(self): for y in range(self.board_size[1]): for x in range(self.board_size[0]): self.board[y][x] = choice(chanse) def full_all(self): for y in range(self.board_size[1]): for x in range(self.board_size[0]): self.board[y][x] = 1 def near(self, cell_coords): klet = 0 a = [cell_coords[1] - 1, cell_coords[1], cell_coords[1] + 1] if cell_coords[1] == 0: a = [self.board_size[1] - 1, 0, 1] elif cell_coords[1] == self.board_size[1] - 1: a = [self.board_size[1] - 2, self.board_size[1] - 1, 0] for y in a: b = [cell_coords[0] - 1, cell_coords[0], cell_coords[0] + 1] if cell_coords[0] == 0: b = [self.board_size[0] - 1, 0, 1] elif cell_coords[0] == self.board_size[0] - 1: b = [self.board_size[0] - 2, self.board_size[0] - 1, 0] for x in b: if self.board[y][x] == 1 and not (cell_coords[0] == x and cell_coords[1] == y): klet += 1 return klet # тест игры if __name__ == '__main__': v = 20 # первоначальная скорость board_size = (20, 20) # размер поля board_configs = (0, 0, 30) # отступ слева (и справа), # отступ сверху (и снизу), размер клетки l = Life(board_size, v) l.set_viev(board_configs) l.start_life()
def AnoPangalanMo(): PangalanMoPo = input("What's your name?: ") return PangalanMoPo def AnongEdadMoNa(): WhatsYourAge = input("What is your Age?: ") return WhatsYourAge def SaanKaPoNakatira(): WhereDoYouLive = input("What's your Address?: ") return WhereDoYouLive def GaanoKaKatangkad(): AnoPoHeightMoMeters = float(input("How tall are you?: ")) return AnoPoHeightMoMeters def GaanoKaKabigat(): AnoNamanWeightMoKg = int(input("What is your weight?: ")) return AnoNamanWeightMoKg def WhatIsYourBMI(): YourBMI = WeightInKg / (HeightInMeters ** 2) print("BMI: ") print(YourBMI) if YourBMI < 25: return "normal" else: return "overweight" def BioSummary(): print(f"Hi, my name is {PangalanMo}. I am {EdadMo} and I live in {SaanKaNakatira}.") def BMIResult(): print(f"I am {HeightInMeters}m tall, I weigh {WeightInKg}kg and my classfication is {BMIMo}.") # The first step is the program asking for your name. PangalanMo = AnoPangalanMo() # The second step is for you to provide your age. EdadMo = AnongEdadMoNa() # The third step now is providing your address. SaanKaNakatira = SaanKaPoNakatira() # Now for the next step is providing your height in meters. HeightInMeters = GaanoKaKatangkad() # Then for the 5th step is you provide your weight in kg. WeightInKg = GaanoKaKabigat() # And then in orderly fashion the program will provide you your BMI results. BMIMo = WhatIsYourBMI() # This will summarize all the information you provided the program. PakitaNaAngSummary = BioSummary() # The program will also provide you with your BMI classification. Results = BMIResult() # I tried this program initially on my youngest brother since we are trying to lower his weight so # we needed to know his BMI classification as a start. # We found out that he is overweight hahahahaha lol. # When I was revising this program I could not push the changes through git bash so I got frustrated a little # I found out that changing the name of the file and pushing it again is a mistake but I was too late since # I deleted the file on account of my frustration so I reverted my commits and recovered the file then # learned to use git reset --mixed origin/master so I could upload my file sucessfully.
#https://adventofcode.com/2016/day/6 from collections import defaultdict def part1(input_file): with open(input_file, "r") as f: lines = f.read().strip().split("\n") letter_counts = [defaultdict(int) for i in range(len(lines[0]))] for line in lines: for i in range(len(line)): letter_counts[i][line[i]] += 1 result = "" for i in range(len(letter_counts)): most = 0 for key in letter_counts[i]: if letter_counts[i][key] > most: letter = key most = letter_counts[i][key] result += letter return result def main(): input_file = "day06-input.txt" print(part1(input_file)) if __name__ == "__main__": main()
#https://adventofcode.com/2016/day/7 def is_abba(string): return ((string[0] != string[1]) and (string[2] == string[1]) and (string[3] == string[0])) def part1(input_file): with open(input_file, "r") as f: ips = f.read().strip().split("\n") valid_count = 0 for ip in ips: has_abba = False inside_brackets = False for i in range(len(ip) - 3): if ip[i-1] == "[": inside_brackets = True elif ip[i-1] == "]": inside_brackets = False sub_str = ip[i:i+4] if inside_brackets: if is_abba(sub_str): has_abba = False break elif not has_abba: if is_abba(sub_str): has_abba = True if has_abba: valid_count += 1 return valid_count def main(): input_file = "day07-input.txt" print(part1(input_file)) if __name__ == "__main__": main()
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ zero_index = 0 curr_index = 0 two_index = len(input_list)-1 while curr_index <= two_index: curr_val = input_list[curr_index] # 0 if curr_val < 1: # swap zero to the left if zero_index < curr_index: input_list[curr_index], input_list[zero_index] = input_list[zero_index], input_list[curr_index] zero_index += 1 curr_index += 1 continue # 2 if curr_val > 1: if input_list[two_index] > 1: two_index -= 1 continue else: # swap two to the right input_list[curr_index], input_list[two_index] = input_list[two_index], input_list[curr_index] two_index -= 1 continue # 1 else: # just move curr_index += 1 return input_list def test_function(test_case): sorted_array = sort_012(test_case) if sorted_array == sorted(test_case): print("Pass") else: print("Fail") # empty and edge case test_function([]) test_function([0, 0]) test_function([1, 1]) test_function([2, 2]) test_function([2, 1]) # random cases test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2]) test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1]) # sorted and reverse cases test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) test_function([2, 2, 2, 1, 1, 1, 0, 0, 0])
class PizzaStorage: def __init__(self): self.count = 10 def minus(self, count): self.count = self.count - count class Customer: def __init__(self, name, storage): self.name = name self.storage = storage def eat(self): self.storage.minus(1) class FatCustomer(Customer): def __init__(self, name, storage, logger): super().__init__(name, storage) self.logger = logger def eat(self): self.storage.minus(1) self.logger.write_to_log('fat eat') def sayThanks(self): print('thanks!') class Logger: def write_to_log(self, text): print('LOG: ', text) pizzaStorage = PizzaStorage() customer = Customer('bill', pizzaStorage) fatCustomer = FatCustomer('bob', pizzaStorage, Logger()) customer.eat() print(pizzaStorage.count) fatCustomer.eat() print(pizzaStorage.count)
import random def gen_func(): while True: yield random.random() generator = gen_func() print('generator function', gen_func) # генераторная функция print('generator', generator) # генератор print('value: ', generator.__next__()) print('value: ', generator.__next__()) print('value: ', generator.__next__()) # OUTPUT: # value: 0.5982845385357144 # value: 0.3308434359315522 # value: 0.3165169253705432
#!/usr/bin/env python3 class A(object): def foo1(self,x): print("executing foo1(%s,%s)" % (self,x) ) self.foo2() def foo2(self): print('method foo2 ' + str(self.__class__)) @classmethod def class_foo(cls,x): print("executing class_foo(%s,%s)" % (cls,x) ) cls.class_foo2() @classmethod def class_foo2(cls): print('method class_foo2') @staticmethod def static_foo(x): print("executing static_foo(%s)" % x) a = A() # при вызове метода экземпляра класс первым аргументом всегда неявно передаётся ссылка на экземпляр класса. # её можно использовать для вызова других методов этого экземпляра(foo2) # при этом из экземпляра класса можно добраться до самого класса self.__class__ a.foo1(1) a.foo2() # при вызове метода класса первым аргументом неявно передаётся ссылка на класс # её можно использовать для запуска других методов класса(class_foo2) a.class_foo(2) A.class_foo2() # это просто метод класса никак не связанный с классом. ему не нужно передавать self/cls A.static_foo(100) # можно вызвать метод через класс. для этого первым аргументом нужно передать объект, который вызывается A.foo1(a, 1) ================================== два способа выполнить метод экземпляра: class A(): def __init__(self, x): self.x = x def out(self): print(self.x) a = A(2) a.out() # 2 A.out(a) # 2 ================================== если переменная или метод не находится в экземпляре, то он ищется в классе: class A(object): x = 10 @classmethod def out(cls): cls.more() @classmethod def more(cls): print('more' + str(cls.x)) A.more() # more10 A.out() # more10 a = A() a.out() # more10 print(a.x) # 10 ================================== переменная сначала ищется в экземпляре, затем в классе, затем в вышестоящих классах: class B: y = 100 class A(B): # y = 10 # def __init__(self): # self.y = 20 def str(self): pass a = A() print(a.y) # 100 то же самое касается методов class B: y = 100 @classmethod def pr(self): print('pr') class A(B): # y = 10 # def __init__(self): # self.y = 20 def str(self): pass a = A() a.pr() # pr ================================== ================================== ================================== ================================== #!/usr/bin/env python3 class Person(object): type = 'man' def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name def who(self): return self.type def change(self): self.type = 'woman' def who2(self): return self.type def delete(self): del self.type def who3(self): return self.type p = Person('qqq', 'www') print(p.who()) p.change() print(p.who2()) p.delete() print(p.who3()) # type из класса наследуется экземплярами. но экземпляр может переопределить type. # однако экземпляр не может изменить переменную класса. поэтому после удаления переменной из экземплляра, опять берётся переменная класса ================================== при вызове класс выполняет __new__, __init__ и возвращает экземпляр. при вызове экземпляр выполняет __call__, если она определена ================================== объект можно представить как строку при помощи: __str__, __repr__. если определены обе функции, то преимущество у __str__ разница между ними только в назначении. первый формат нужен для пользователя, второй для отладки. кроме того в print выводится __str__ ================================== от object наследуются все остальные объекты. в том числе наследуются стандартные методы типа __eq__. их множно переопределять. ================================== class Manager(Person): # Наследование def giveRaise(self, ...): # Адаптация(тоже можно адаптировать конструктор). по сути вызывается метод родителя, но пеердаются другие аргументы class Person: def giveRaise(self, percent): print(percent) class Manager(Person): def giveRaise(self, percent): Person.giveRaise(self, percent + 10) p = Person() p.giveRaise(1) # 1 m = Manager() m.giveRaise(1) # 11 def someThingElse(self, ...): # Расширение. это просто добавление в наследника метода, которого нет в родителе ---------------------- следует различать перегрузку и переопределение методов. пример переопределения. class A: def go(self): print('A!') class B(A): def go(self): print('B!') в классе B go() должна была выводить A!, но благодаря переопределению выводит B! важно то, что изменять свойства родителя из наследника нельзя, можно только переорпеделять при переопределении можно изменять количество аргументов: class A(): def publ(self, a): print('publ', a) class B(A): def publ(self, a, b): print('publb', a, b) a = A() print(a.publ(123)) # 123 b = B() print(b.publ(123, 456)) # 123 456 пример переорпеделения переменной. важно то, что невозможно переопределить перееменную родителя: class A(): def __init__(self, q): self.q = q class B(A): def __init__(self, q, w): super().__init__(q) self.w = w self.q = 444 a = A(111) print(a.q) # 111 b = B(222, 333) print(b.q, b.w) # 444 333 print(a.q) # 111 вот пример перегрузки(наследование не обязательно): class A(): def meth(self, q, w=None): if w is not None: print(q, w) else: print(q) a = A() print(a.meth(222)) # 222 print(a.meth(222, 333)) # 222 333 ---------------------- Инкапсуляция — ограничение доступа к составляющим объект компонентам. инкапсуляция действует только на уровне соглашений. знак подчёркивания перед переменной говорит, что она псевдоприватная. то есть может изменяться только методами этого класса. ---------------------- наследование связывает классы. при этом потомок содержит все методы и свойства родителя. самый верхний объект для классов это object. из него наследуются методы типа __init__() ---------------------- полиморфизм это когда в различных классах методы с одинаковыми названиями выполняют различноые действия. эти классы не обязательно должны быть связаны наследованием. перегрузка операторов это частный случай полиморфизма. при перегрузке может меняться количество аргументов. тип не имеет значения потому что в питоне динамическая типизация например по умолчанию метод __str__() выводит содержимое объекта в специфическом формате. потому что этого метод определён в object. но если перегрузить этот метода так: class qwert: def __str__(self): return 'hello' , то print(qwert()) выведет hello. мы перегрузили __str__() переопределение метода используется когда имеет место наследование. когда наследования нет, то скорее всего используется ветвление внутри метода. вот классический случай полиморфизма: print(len("geeks")) print(len([10, 20, 30])) # здесь используется один и тот же метод len, но внутри него есть ветвление, которое на основе типа применяет соответствующий алгоритм вот ещё случай(на основе паттерна Стратегия): class Product: def __init__(self, title, logger): self.title = title self.logger = logger def setPrice(self, price): try: if price <= 0: raise Exception('wrong price!') self.price = price except Exception as e: self.logger.makeLog(e) class LoggerFill: def __init__(self): self.log = [] def makeLog(self, message): self.log.append(message) class LoggerPrint: def makeLog(self, message): print('error: ', message) product = Product('phone', LoggerFill()) product.setPrice(-10) product = Product('phone', LoggerPrint()) product.setPrice(-10) ================================== композиция это когда один объект становится частью другого. class A: def meth(self): print('go') class B(): def __init__(self): self.a = A() b = B() b.a.meth() ================================== множественное наследование: поиск идентификаторов производится вначале в производном классе, затем в базовом классе, расположенном первым в списке, далее просматриваются все базовые классы базового класса. Только после этого просматривается базовый класс, расположенный в списке правее, и все его базовые классы. ================================== модификаторы доступа реализованы только на основе соглашений об именовании: class A(): qqq = 4 def __init__(self, name, age, gender): self.name = name self._gender = gender self.__age = age self.field =33 def publ(self): return 'publ' def _protect(self): return '_protect' def __privat(self): return '__privat' a = A('tom', 20, 'male') print(a.publ()) print(a._protect()) print(a.__privat()) # AttributeError: 'A' object has no attribute '__privat' print(a.name) print(a._gender) print(a.__age) # AttributeError: 'A' object has no attribute '__age' print(a._A__age) ================================== можно метод сделать свойством: class A(): def __init__(self, a): self.a = a @property def pro(self): return self.a def meth(self): return self.a a = A(123) print(a.pro) # 123 print(a.meth()) # 123 ================================== мелкая копия объекта(копируются только ссылки на объекты): a = [[1, 2], [3, 4], [[22, 33], [44, 55]]] s = a a[2][1][0] = 9 print(a) print(s) # [[1, 2], [3, 4], [[22, 33], [9, 55]]] # [[1, 2], [3, 4], [[22, 33], [9, 55]]] --------- глубокая копия объекта(копируются объкты): import copy a = [[1, 2], [3, 4], [[22, 33], [44, 55]]] s = copy.deepcopy(a) a[2][1][0] = 9 print(a) print(s) # [[1, 2], [3, 4], [[22, 33], [9, 55]]] # [[1, 2], [3, 4], [[22, 33], [44, 55]]] суть в том, что в s лежит совсем другой объект ================================== ================================== sum = x + y означает, что sum = x.__add__(y) res = x[4] означает, что res = x.__getitem__(4) for item in X: означает, что к каждому элементу из X будет применяться __getitem__() ==================================== class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return "repr Point, x={}, y={}".format(self.x, self.y) def __str__(self): return "str Point, x={}, y={}".format(self.x, self.y) point = Point(1, 2) print(repr(point)) # repr .... print(str(point)) # str .... print(point) # str ... only in cli: >>>point >>> repr ... при выводе объекта через print сначала будет попытка вывести его в виде строки, которую возвращает str, если он не будет найден, то в виде repr. если и он не будет найден, то поиск будет производиться в родителе. также можно использовать эти методы явно: str(obj), repr(obj) в скрипте можно выывести __repr__() так: print(f'{point!r}') # на старье ниже 3.6 можно так: print('%r' % point) то есть в функции форматирования ==================================== __getitem__() class Indexer: def __getitem__(self, index): return index ** 2 X = Indexer() print(X[2]) # 4 ================================== obj - x, эквивалентна obj.__sub__(x) возможно перегрузить метод вычитания: class Number: def __init__(self, start): self.data = start def __sub__(self, other): return Number(self.data - other) X = Number(5) Y = X - 2 print(Y.data) ================================== ================================== ================================== ================================== ================================== ================================== ==================================
# oprator haye condition < > >= <= == != # int * int = int # str * int = str # int * float = float num_2 = 20 num_1 = 10 result = num_1 > num_2 print(result) num = 50 start = 0 stop = 100 res_1 = num > start res_2 = num < stop print (res_1,"\n", res_2) # "\n" baraye new line # mitavan shart haro to ye khat tarkib kard
import pandas import turtle screen = turtle.Screen() screen.title("U.S. States Game") image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) # A writing "turtle" that will write in the names of correctly guessed states: writer = turtle.Turtle() writer.hideturtle() writer.penup() # Converting "50_states.csv" file to a Pandas dataframe to work with. 2 columns (x and y coord.), rows with state names: data = pandas.read_csv("50_states.csv") # Saving all the states in a list: states = [state for state in data.state] # A list to keep track of correctly guessed names: correct_guesses = [] # A list of states not guessed: missing_states = [] # Check if the guess is among the 50 states. If it is, the state name is printed onto its location on the map # The value is appended to the correct_guesses list: while len(correct_guesses) < 50: guess_state = screen.textinput(title=f"{len(correct_guesses)}/50 States Correct", prompt="Enter a state name!").title() if guess_state == "Exit": # populating a list of states not guessed by the player: missing_states = [st for st in states if st not in correct_guesses] break else: for st in states: if guess_state == st: correct_guesses.append(st) x_coor = int(data[data.state == st]['x']) y_coor = int(data[data.state == st]['y']) writer.goto(x_coor, y_coor) writer.write(st) # Creating "states to learn" .csv file so the user can learn the names of all the states: new_data = pandas.DataFrame(missing_states) new_data.to_csv("states_to_learn.csv")
def main(): baseWord = getMainWord() baseWordSplat = list(baseWord) wordList = [] getWords(wordList) compTotalResultList = engine(wordList, baseWordSplat) print('\nDifferences from', baseWord, 'based on ASCII values per character (somewhat pointless): \n') for each in range (0, len(compTotalResultList)): if compTotalResultList[each] < 0: print(wordList[each], ' - ', -1*compTotalResultList[each] ) else: print(wordList[each], ' - ', compTotalResultList[each] ) ending() def ending(): yn = input('\nWould you like to try again? Y/N\n') if yn == 'y' or yn == 'Y': main() elif yn == 'n' or yn == 'N': exit() else: print('Please type Y to continue or N to exit\n') ending() def engine(wordList, baseWordSplat): compTotalResultList = [] baseTotal = 0 for letter in baseWordSplat: baseTotal += ord(letter) for word in wordList: compTotalResult = 0 wordSplat = list(word) for letter in wordSplat: compTotalResult += ord(letter) compTotalResultList.append(baseTotal - compTotalResult) return(compTotalResultList) def getMainWord(): baseWord = input('Please type the main word you wish to compare against.\n') if baseWord.isalpha() == False: print('Only letters. No numbers.') getMainWord() return(baseWord) def getWords(wordList): currentWord = input('Please type the words you wish to compare to the main word. Type nothing and Press enter when finished.\n') if currentWord == '': return(wordList) elif currentWord not in wordList: wordList.append(currentWord) getWords(wordList) else: print('Word already registered\n') getWords(wordList) main()
import streamlit as st import numpy as np import pandas as pd # Add a title st.title('My first app_') # Add some text st.text('Streamlit is great') st.dataframe(pd.DataFrame({ 'first column': [1, 2, 3, 4], 'second column': [10, 20, 30, 40] })) # lineplot chart_data = pd.DataFrame( np.random.randn(20, 3), columns=['a', 'b', 'c']) st.line_chart(chart_data) # map map_data = pd.DataFrame( np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], columns=['lat', 'lon']) st.map(map_data) # checkbox if st.checkbox('Show dataframe'): st.dataframe(pd.DataFrame({ 'first column': [1, 2, 3, 4], 'second column': [10, 20, 30, 40] })) chart_data = pd.DataFrame( np.random.randn(20, 3), columns=['a', 'b', 'c']) st.line_chart(chart_data) map_data = pd.DataFrame( np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], columns=['lat', 'lon']) st.map(map_data) # select box df = pd.DataFrame( np.random.randn(20, 3), columns=['a', 'b', 'c']) column = st.selectbox( 'What column to you want to display', df.columns) st.line_chart(df[column]) # multi-select df = pd.DataFrame( np.random.randn(20, 3), columns=['a', 'b', 'c']) columns = st.multiselect( label='What column to you want to display', options=df.columns) st.line_chart(df[columns]) # slider x = st.slider('Select a value') st.write(x, 'squared is', x * x) ## slider-range x = st.slider( 'Select a range of values', 0.0, 100.0, (25.0, 75.0)) st.write('Range values:', x) #
number=int(input()) sum_int=0 while number>0 : sum_int += number%10 number //= 10 print(sum_int)
hours = [False] * 4 minutes = [False] * 6 def clock(n, hours, minutes, h, m, posh, posm): if(posm > 5 or posh > 3): return if(n == 0): if(h < 12 and m < 60): print(str(h) + ":" +str(m)) return for pos in range(posh, len(hours)): if not hours[pos]: hours[pos] = True clock(n-1, hours, minutes, h + (2**pos), m, pos+1, posm) hours[pos] = False for pos in range(posm, len(minutes)): if not minutes[pos]: minutes[pos] = True clock(n-1, hours, minutes, h, m + (2**pos), posh, pos+1) minutes[pos] = False clock(2, hours, minutes, 0, 0, 0, 0)
import numpy as np from PIL import ImageFont, Image, ImageDraw, ImageEnhance from colour import Color from math import floor SAMPLE_LETTER = "x" # Used to determine the typical width and height of an ASCII character BRIGHTNESS_FACTOR = 1.5 # How much to brighten image by GRAYSCALE_LVLS = "#&B9@?sri:,. " # GRAYSCALE_LVLS = ' .,:irs?@9B&#' For inverted brightness def get_width_height(numpy_obj): """Returns the width and height of any numpy array""" h, w = numpy_obj.shape[0], numpy_obj.shape[1] return w, h def avg_tile_brightness(img_tile): """img_tile parameter is a 2 dimensional array representing a tile in a given image; the image should be represented using grayscale values rather than rgb values; returns the average grayscale value of the image tile""" tile_width, tile_height = get_width_height(img_tile) grayscale_vals = img_tile.reshape(tile_height * tile_width) # Reshape 2D array into 1D array avg_grayscale = np.average(grayscale_vals) return avg_grayscale def get_num_tiles(img): """Determines how many ASCII characters are needed for each row/column in the image""" font = ImageFont.load_default() # Load in default font letter_width, letter_height = font.getsize(SAMPLE_LETTER)[0], font.getsize(SAMPLE_LETTER)[1] # Get width and height of an ASCII character img_width, img_height, = get_width_height(img) num_letters_per_col = img_height // letter_height num_letters_per_row = img_width // letter_width return num_letters_per_row, num_letters_per_col, letter_width, letter_height def get_tile(img, w_start, h_start, w_end, h_end): """ :param img: a 2D array storing image values represented as tuples :param w_start: starting width index :param h_start: starting height index :param w_end: ending width index :param h_end: ending height index :return: a tile of the image from starting width index to ending width index and starting height index to ending height index; returned as a numpy array """ tile = [] i = 0 for row in range(h_start, h_end): tile.append([]) for col in range(w_start, w_end): tile[i].append(img[row][col]) i += 1 return np.array(tile) def brighten(img): """Brightens an image object and returns the brightened version as a numpy array""" enhancer = ImageEnhance.Brightness(img) img = enhancer.enhance(BRIGHTNESS_FACTOR) return np.array(img) def create_gradients(start_color, end_color, num_lines): """ :param start_color: starting color of the gradient represented as a string :param end_color: ending color of the gradient represented as a string :param num_lines: the number of colored lines between the starting color and ending color :return: an array storing color values that start at start_color and gradually become closer and closer to end_color """ start = Color(start_color) end = Color(end_color) return list(start.range_to(end, num_lines)) def draw_to_image(img, letters_per_row, letters_per_col, letter_width, letter_height, grayscale, color_gradients, draw): """ draws to the new image line by line :param img: an image represented as 3-dimensional numpy as grayscale values :param letters_per_row: the number of ASCII characters that it takes to represent the original image horizontally :param letters_per_col: the number of ASCII characters it takes to represent the original image vertically :param letter_width: estimated width of an ASCII character :param letter_height: estimated height of an ASCII character :param grayscale: A list of ASCII characters representing the different possible levels of grayscale from darkest to lightest :param color_gradients: A list of colors where the first color in the list gradually becomes more like the last color in the list :param draw: An ImageDraw.draw object used to draw to the new image :return: nothing; the function simply draws to the new image """ line_index = 0 # First line of the image y = 0 # The current distance from the very top of the image, starts at 0 col_pixel_count = 0 # The number of pixels processed vertically col_end_count = 0 # Used to determine the value of the last pixel for each given tile, vertically for row in range(0, letters_per_col): col_end_count += letter_height row_pixel_count = 0 # The number of pixels processed horizontally row_end_count = 0 # Used to determine the value of the last pixel for each given tile, horizontally line = "" # Begin a new line for col in range(0, letters_per_row): row_end_count += letter_width tile = get_tile(img, row_pixel_count, col_pixel_count, row_end_count, col_end_count) # Get image tile avg_brightness = avg_tile_brightness(tile) # Determine average brightness of the tile i = floor((((len(grayscale) - 1) * avg_brightness) // 255)) # Convert grayscale value as an index line += grayscale[i] # Add one of the ASCII characters in grayscale to the current line of the image row_pixel_count += letter_width # Update the number of pixels processed col = color_gradients[line_index] # Determine the current color gradient draw.text((0, y), line, col.hex) # Draw the line to the image in color col y += letter_height # Update y; next line should be letter_height distance from previous line line_index += 1 # Update line index for color_gradients list col_pixel_count += letter_height def check_color(col1, col2, col3): """If colors are left blank in the GUI, set them to black and white by default""" if col1 == "": col1 = "black" if col2 == "": col2 = "black" if col3 == "": col3 = "white" return col1, col2, col3 def execute_infile(old_name, new_name, start_color, end_color, bgcolor): img = Image.open(old_name).convert("L") # Open the image as grayscale values np_img = brighten(img) # Brighten and convert to numpy array w, h = get_width_height(np_img) # Width and height of current image lvls_grayscale = list(GRAYSCALE_LVLS) # Turn grayscale lvls into a list letters_per_row, letters_per_col, letter_width, letter_height = get_num_tiles(np_img) num_lines = h//letter_height # Calculate number of lines in the image (same as # of rows) color_gradients = create_gradients(start_color, end_color, num_lines) # Create a list of colors new_img = Image.new("RGBA", (w, h), bgcolor) # Create a new image draw = ImageDraw.Draw(new_img) # Create an object that'll allow us to draw to new_img draw_to_image(np_img, letters_per_row, letters_per_col, letter_width, letter_height, lvls_grayscale, color_gradients, draw) new_img.save(new_name) print("Image created successfully") def ascii_art(label, path, start_color, end_color, bgcolor): start_color, end_color, bgcolor = check_color(start_color, end_color, bgcolor) img = Image.open(path).convert("L") # Open the image as grayscale values np_img = brighten(img) # Brighten and convert to numpy array w, h = get_width_height(np_img) # Width and height of current image lvls_grayscale = list(GRAYSCALE_LVLS) # Turn grayscale lvls into a list letters_per_row, letters_per_col, letter_width, letter_height = get_num_tiles(np_img) num_lines = h // letter_height # Calculate number of lines in the image (same as # of rows) color_gradients = create_gradients(start_color, end_color, num_lines) # Create a list of colors new_img = Image.new("RGBA", (w, h), bgcolor) # Create a new image draw = ImageDraw.Draw(new_img) # Create an object that'll allow us to draw to new_img draw_to_image(np_img, letters_per_row, letters_per_col, letter_width, letter_height, lvls_grayscale, color_gradients, draw) # Draw to the image return new_img, label if __name__ == "__main__": execute_infile("imgs/abraham.jpeg", "lol.pnp", "blue", "red", "white")
def restaurant(cruzer1): menu = [] foods = cruzer1["sells"] cocacola = foods[0]["name"] cocacola_price = foods[0]["price"] pizza = foods[1]["name"] pizza_price = foods[1]["price"] hamburguesa = foods[2]["name"] hamburguesa_price = foods[2]["price"] hamburguesa_refresco = foods[3]["name"] hamburguesa_refresco_price = foods[3]["price"] ron = foods[4]["name"] ron_price = foods[4]["price"] name = input("Ingrese su nombre: ") dni = int(input("Ingrese su dni: ")) add_more = "SI" while add_more == "SI": options = input(f''' ¿Qué desea comprar? Alimentos: 1. {pizza} --> ${pizza_price} 2. {hamburguesa} --> ${hamburguesa_price} Bebidas: 3. {cocacola} --> ${cocacola_price} 4. {ron} --> ${ron_price} Menú de Combos: 5. {hamburguesa_refresco} --> ${hamburguesa_refresco_price} >>> ''') menu.append(options) add_more = input("¿Desea añadir algo más a su compra? ").upper() return f''' Su pedido fue de los alimentos {menu}. Gracias por su compra.'''
def fibo(n): a = 0 b = 1 sum = 0 series =[] series.append(a) series.append(b) while(sum < n): sum = a + b series.append(sum) a = b b = sum print(series) limit = int(input("enter the number till where u want your fib series : ")) fibo(limit)
from cs50 import SQL import csv from sys import argv # Open Db db = SQL("sqlite:///students.db") # Read parameters if len(argv) != 2: print("Usage : python roster.py <house name>") exit(1) query = db.execute("SELECT first, middle, last, birth FROM students WHERE house = ? ORDER BY last, first", argv[1]) listnames = [] for q in query: # query is a list of dictionaries listnames = [] listnames.append(q['first']) if q['middle'] == None: listnames.append(q['last']) else: listnames.append(q['middle']) listnames.append(q['last']) print(f"{' '.join(listnames)}, born {q['birth']}")
year = int(input()) while True: year += 1 string = str(year) if len(set(string)) == len(string): print(string) break
from re import findall pattern = r"([@|#])([A-Za-z]{3,})\1\1([A-Za-z]{3,})\1" data = input() matches = findall(pattern, data) mirror_words = [] for match in matches: if match[1] == match[2][::-1]: mirror_words.append(match[1] + " <=> " + match[2]) if not matches: print("No word pairs found!") else: print(f"{len(matches)} word pairs found!") if not mirror_words: print("No mirror words!") else: print("The mirror words are:") print(", ".join(mirror_words))
start_index = int(input()) stop_index = int(input()) for index in range(start_index, stop_index + 1): print(chr(index), end=' ')
goal_height = int(input()) current_height = goal_height - 30 total_attempts = 0 success = False while not success: for _ in range(3): attempt_height = int(input()) total_attempts += 1 if goal_height <= current_height < attempt_height: success = True break if attempt_height > current_height: current_height += 5 break else: break if success: print(f"Tihomir succeeded, he jumped over {current_height}cm after {total_attempts} jumps.") else: print(f"Tihomir failed at {current_height}cm after {total_attempts} jumps.")
guests_count = int(input()) price_per_guest = float(input()) budget = float(input()) discount = {10 <= guests_count <= 15: 0.15 * price_per_guest * guests_count, 15 < guests_count <= 20: 0.2 * price_per_guest * guests_count, guests_count > 20: 0.25 * price_per_guest * guests_count, guests_count < 10: 0} cake_price = 0.1 * budget total = guests_count * price_per_guest - discount[True] + cake_price money_difference = budget - total if money_difference < 0: print(f"No party! {abs(money_difference):.2f} leva needed.") else: print(f"It is party time! {money_difference:.2f} leva left.")
tournaments_count = int(input()) starting_points = int(input()) points = {"W": 2000, "F": 1200, "SF": 720} final_points = 0 won_tournaments = 0 for _ in range(tournaments_count): stage_reached = input() final_points += points[stage_reached] if stage_reached == "W": won_tournaments += 1 avrg_points = int(final_points / tournaments_count) won_perc = won_tournaments / tournaments_count final_points += starting_points print(f"Final points: {final_points}") print(f"Average points: {avrg_points}") print(f"{won_perc:.2%}")
from re import compile pattern = compile(r"(w{3}.[A-Za-z0-9-]+(\.[a-z]+)+)") data = input() while data: match = pattern.findall(data) if match: print(match[0][0]) data = input()
import string READ_PATH = 'text.txt' WRITE_PATH = 'output.txt' def count_symbols(line, validation): return len([ch for ch in line if ch in validation]) with open(READ_PATH, 'r') as r_file: with open(WRITE_PATH, 'w') as w_file: reader = r_file.readlines() for index, line in enumerate(reader): char_count = count_symbols(line, string.ascii_letters) p_count = count_symbols(line, string.punctuation) print(f'Line {index+1}: {line.strip()} ({char_count})({p_count})', file=w_file)
sweets_prices = {"cookies": 1.50, "cakes": 7.80, "waffles": 2.30} sweets_count_total = {"cookies": 0, "cakes": 0, "waffles": 0} bakers_count = int(input()) for _ in range(bakers_count): baker_name = input() sweets_type = input() sweets_per_baker = {"cookies": 0, "cakes": 0, "waffles": 0} while sweets_type != "Stop baking!": sweets_count = int(input()) sweets_per_baker[sweets_type] += sweets_count sweets_count_total[sweets_type] += sweets_count sweets_type = input() print(f'{baker_name} baked ' f'{sweets_per_baker["cookies"]} cookies, ' f'{sweets_per_baker["cakes"]} cakes and ' f'{sweets_per_baker["waffles"]} waffles.') total_sold = sweets_count_total["cookies"] + \ sweets_count_total["cakes"] + \ sweets_count_total["waffles"] total_sum = sweets_count_total["cookies"] * sweets_prices["cookies"] + \ sweets_count_total["cakes"] * sweets_prices["cakes"] + \ sweets_count_total["waffles"] * sweets_prices["waffles"] print(f"All bakery sold: {total_sold}") print(f"Total sum for charity: {total_sum:.2f} lv.")
"""Search for element's COORDINATES until element is found from given POSITION in SQUARE matrix""" QUEEN = 'Q' KING = 'K' SIZE_OF_MATRIX = 8 DELTAS = [ (0, -1), # left (-1, -1), # up left (1, 0), # up (-1, 1), # up right (0, 1), # right (1, 1), # down right (-1, 0), # down (1, -1), # down left ] def is_valid(value, max_value): return 0 <= value < max_value def search_for_delta(mat, x, y, delta): delta_x, delta_y = delta while True: if not is_valid(x, SIZE_OF_MATRIX) or not is_valid(y, SIZE_OF_MATRIX): return None if mat[x][y] == QUEEN: return x, y x += delta_x y += delta_y def search_for_cell_from_given_position(mat, x, y): results = [search_for_delta(mat, x, y, delta) for delta in DELTAS] return list(filter(lambda q: q, results))
width = int(input()) height = int(input()) depth = int(input()) priority = input() volume = width * height * depth taxes = {"true": {50 < volume <= 100: 0, 100 < volume <= 200: 10, 200 < volume <= 300: 20}, "false": {50 < volume <= 100: 25, 100 < volume <= 200: 50, 200 < volume <= 300: 100}} tax = 0 if volume > 50: tax = taxes[priority][True] print(f"Luggage tax: {tax:.2f}")
sold_count = int(input()) hearthstone_count = 0 fornite_count = 0 overwatch_count = 0 others_count = 0 for s in range(sold_count): game_name = input() if game_name == "Hearthstone": hearthstone_count += 1 elif game_name == "Fornite": fornite_count += 1 elif game_name == "Overwatch": overwatch_count += 1 else: others_count += 1 hearthstone_share = hearthstone_count / sold_count fornite_share = fornite_count / sold_count overwatch_share = overwatch_count / sold_count others_share = others_count / sold_count print(f"Hearthstone - {hearthstone_share:.2%}") print(f"Fornite - {fornite_share:.2%}") print(f"Overwatch - {overwatch_share:.2%}") print(f"Others - {others_share:.2%}")
x = int(input()) y = int(input()) for number in range(x, y + 1): even_sum = 0 odd_sum = 0 counter = 1 num = number while num > 0: last = num % 10 if counter % 2 == 0: even_sum += last else: odd_sum += last num = num // 10 counter += 1 if even_sum == odd_sum: print(number, end=" ")
#!/usr/bin/env python3 def print_line(n): ll = [] for i in range(1, n+1): ll.append(i) print(' '.join(map(str, ll))) def print_triangle(size): for row in range(1, size + 2): print_line(row) for row in range(size, 0, -1): print_line(row)
n = int(input()) even_sum = 0 odd_sum = 0 for index, _ in enumerate(range(n), 1): number = int(input()) if index % 2 == 0: even_sum += number else: odd_sum += number difference = abs(even_sum - odd_sum) if difference == 0: print(f"Yes\nSum = {even_sum}") else: print(f"No\nDiff = {difference}")
def draw_battle_field(n_raws): """You will be given a number n representing the number of rows of the field. On the next n lines you will receive each row of the field as a string with numbers separated by a space. Each number greater than zero represents a ship with a health equal to the number value.""" field = [] for row_num in range(n_raws): # first row = 0 raw_values_list = [int(value) for value in input().split()] # list of integer values for current row field.append(raw_values_list) # append list of values for columns in the raws_list - lists in list return field def attack(field, i_raw, i_col, destroyed): """Each time a square is being attacked, if there is a ship there (number greater than 0) you should reduce its value.""" if not field[i_raw][i_col] == 0: # if there is a ship in the spot field[i_raw][i_col] -= 1 # reduce it's value if field[i_raw][i_col] == 0: # if the ship is destroyed destroyed += 1 # increase the count of destroyed ships return destroyed def main(): destroyed_ships = 0 number_of_rows = int(input()) battle_field = draw_battle_field(number_of_rows) all_attacks = input().split() for current_attack in all_attacks: # current attack = "{str}-{str}" attack_indexes = current_attack.split("-") # attack_indexes = ["str", "str"] raw_index = int(attack_indexes[0]) column_index = int(attack_indexes[1]) destroyed_ships = attack(battle_field, raw_index, column_index, destroyed_ships) print(destroyed_ships) if __name__ == '__main__': main()
budget = float(input()) category = input() people_count = int(input()) prices = {"VIP": 499.99, "Normal": 249.99} transport_price = {1 <= people_count <= 4: 0.75 * budget, 5 <= people_count <= 9: 0.6 * budget, 10 <= people_count <= 24: 0.5 * budget, 25 <= people_count <= 49: 0.4 * budget, people_count >= 50: 0.25 * budget} money_left = budget - transport_price[True] price = prices[category] * people_count difference = money_left - price if difference >= 0: print(f"Yes! You have {difference:.2f} leva left.") else: print(f"Not enough money! You need {abs(difference):.2f} leva.")
city = input() sales = float(input()) commission = 'error' commissions = {'Sofia': {0 <= sales <= 500: 0.05, 500 < sales <= 1000: 0.07, 1000 < sales <= 10000: 0.08, sales > 10000: 0.12}, 'Varna': {0 <= sales <= 500: 0.045, 500 < sales <= 1000: 0.075, 1000 < sales <= 10000: 0.10, sales > 10000: 0.13}, 'Plovdiv': {0 <= sales <= 500: 0.055, 500 < sales <= 1000: 0.08, 1000 < sales <= 10000: 0.12, sales > 10000: 0.145}} if sales >= 0 and city in commissions.keys(): commission = f"{commissions[city][True] * sales:.2f}" print(commission)
data = input() resources = {} all_input_list = [] while not data == "stop": all_input_list.append(data) data = input() for index in range(0, len(all_input_list), 2): key = all_input_list[index] value = all_input_list[index + 1] if key not in resources.keys(): resources[key] = int(value) else: resources[key] += int(value) for item in resources.items(): key, value = item print(f"{key} -> {value}")
class Customer: __id = 0 def __init__(self, name: str, address: str, email: str): self.name = name self.address = address self.email = email self.id = self.set_id() def __repr__(self): return f"Customer <{self.id}> {self.name}; Address: {self.address}; Email: {self.email}" @classmethod def set_id(cls): cls.__id = cls.get_next_id() return cls.__id @staticmethod # should be class method but that's how it is described in problem description def get_next_id(): return Customer.__id + 1
money_vacation = float(input()) money_available = float(input()) total_days = 0 spend_days = 0 while money_available < money_vacation: total_days += 1 action = input() action_money = float(input()) if action == 'save': money_available += action_money spend_days = 0 elif action == 'spend': money_available -= action_money spend_days += 1 if money_available < 0: money_available = 0 if spend_days == 5: print("You can't save the money.") print(f"{total_days}") break else: print(f"You saved the money for {total_days} days.")