text
stringlengths
37
1.41M
# Double-base palindromes Q36 # Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. def isPalindrome(n) : num = str(n) numLen = len(num) if numLen == 1: return True numTest = False for i in range(0, int(numLen/2)): # range half the number if num[i] != num[(numLen-1)-i]: # test the first half to last half numTest = False break else: numTest = True return numTest sum = 0 for n in range(1,1000000): n_bin = bin(n)[2:] if isPalindrome(n) and isPalindrome(n_bin): sum += n print("{} {}".format(n, n_bin)) print("Palindrome sum is {}.".format(sum))
def helloWorld(x): text ='. Hello World' count = 1 for i in range (x): print (f"{count}{text}") count = count + 1 helloWorld(7)
DAYS_OF_WEEK = { 1: "MON", 2: "TUE", 3: "WED", 4: "THU", 5: "FRI", 6: "SAT", 7: "SUN" } # The functions must all take a datetime object and they must all # return a string def week_number(date_time): return "{week_number}".format(week_number=date_time.strftime("%V")) def week_day(date_time): return DAYS_OF_WEEK[date_time.isoweekday()] def week_day_in_isoformat(date_time): return str(date_time.isoweekday()) def iso_format(date_time): return date_time.isoformat() # Regular expression matched as a list of optionals # will always match the first one they find in the list, # so if your function names start with the same characters, # then always put the longer ones at the top of the list # so they are matched first. In this case we have put # 'wdi' in front of 'wd'. If you don't then the wrong # function might get matched by mistake. DATE_FORMATTERS_MAP = { "wdi": week_day_in_isoformat, "wn": week_number, "wd": week_day, "!": week_number, "iso": iso_format }
import sqlite3 def getdb(): conn = sqlite3.connect('../data/purchasing.db') return(conn) def printdb(): with open('file.txt.', 'w') as f: c = getdb().cursor() c.execute('''select * from items where br10qty > 0''') towrite = c.fetchall() for num, supp, prod, code, name, br, x, y, z, a, b in towrite: print(num, supp, prod, code, name, br, x, y, z, a, b) f.write(str(num) + supp.rstrip() + prod.rstrip() + code.rstrip() + name.rstrip() + str(br) + str(x) + str(y) + str(z) + str(a) + str(b) + '\n')
#Lárus Ármann Kjartansson #5.11.2020 import random #### KLASAR #### #### TRAPEZOID CLASS ### class Trapisa: numer = 1 def __init__(self,a=0.0,b=0.0,c=0.0,d=0.0,h=0.0): self.a = a self.b = b self.c = c self.d = d self.h = h self.nafn = "NN" self.numer=Trapisa.numer Trapisa.numer +=1 def get_a (self): return self.a def set_a (self,hlid): self.a = hlid def get_b (self): return self.b def set_b (self,hlid): self.b = hlid def get_c (self): return self.c def set_c (self,hlid): self.c = hlid def get_d (self): return self.d def set_d(self,hlid): self.d = hlid def get_h (self): return self.h def set_h(self,hlid): self.h = hlid ### GETTER OG SETTER ### def get_nafn (self): return self.nafn def set_nafn (self,nafn=""): self.nafn = nafn ### adferdina ### def ummal_trapisa(self): return self.a + self.b + self.c + self.d def flatarmal_trapisa1(self): s=(self.a+self.b+self.c+self.d)/2 #return (self.a + self.c)/(self.a + self.c)*math.sqrt((s-self.c)*(s-self.a)* def flatarmal_trapisa2(self): return self.h*((self.a+self.c)/2) def trapisa_jafnarma(self): if self.d==self.b: return True else: return False def __str__(self): return "Ég er númer"+str(self.numer)+"og heiti ",self.nafn+"Trapisa eða hálfsamsíðungur er ferhyrningur þar sem tvær mótlægar hliðar eru samsíða." #### FROG CLASS #### class Frog: numer = 1 def __init__(self,kyn): self.kyn = kyn self.numer = Frog.numer Frog.numer +=1 def __str__(self): return "I am frog number "+str(self.numer)+" and i am "+self.kyn #### CAR CLASS #### class Car: def __init__(self,tegund="",argerd="",hradi=0,bensin=0,eydsla=0): self.tegund = tegund self.argerd = argerd self.hradi = hradi self.bensin = bensin self.eydsla = eydsla def stada(self,sek): kominn_metrar=self.hradi*sek return kominn_metrar def eftir_bensin(self,sek): eftir_bensin = (self.bensin-(self.eydsla*self.hradi*sek)/100) return eftir_bensin def __str__(self): return self.tegund+" argerd " +str(self.argerd) #### Class #### class Boydem(): ### klasi fyrir Idrottamenn def __init__(self,nafn="",aldur=0,kyn="hk"): self.nafn = nafn self.aldur = aldur self.kyn = kyn self.gildi=5 def kraftur(self): return self.gildi def __str__(self): if self.kyn.lower() =="kk": return self.nafn+" er "+str(self.aldur)+" ara gamall" else: return self.nafn+" er "+str(self.aldur)+" ara gomul" class Runner(Boydem): # Klasi fyrir Hlaupara def __init__(self,nafn,aldur,kyn,hradi): Boydem.__init__(self,nafn,aldur,kyn) self.hradi = hradi def kraftur(self): return self.gildi*self.hradi def __str__(self): if self.kyn.lower() =="kk": return self.nafn+" "+str(self.aldur)+" ara gamall og hradinn er "+str(self.hradi) else: return self.nafn+" "+str(self.aldur)+" ara gomul og hradinn er "+str(self.hradi) on = True while on == True: print("1.Trapisa") print("2.Frog") print("3.Car") print("4.Erfdir") print("5.Haetta") val = int(input("Veldu?")) if val == 1: #### TRAPISA OUTPUT #### konni = Trapisa(1,2,3,4,5) print(konni.get_a())#1 konni.set_a(222) print(konni.get_a())#222 konni.set_nafn(input("Nafn? ")) print(konni.get_nafn()) elif val == 2: #### FROG OUTPUT #### dude = Frog("KK") print(dude) kerling = Frog("KVK") print(kerling) Frogs_KK =[] Frogs_KK.append(dude) Frogs_KVK =[] Frogs_KVK.append(kerling) dagur = 0 kyn="" while (len(Frogs_KVK)+len(Frogs_KK)) < 10000: for x in range(len(Frogs_KVK)): tala=random.randint(0,1) if tala==1: kyn="KK" froskur = Frog(kyn) Frogs_KK.append(froskur) else: kyn="KVK" froskur = Frog(kyn) Frogs_KVK.append(Frog) dagur+=2 print("Dagur numer", dagur) print("Fjoldi karlfroska er kominn upp i ", len(Frogs_KK)) print("Fjoldi kvennfroska er kominn upp i ", len(Frogs_KVK)) print("Detta eru allir karlfroskarnir") for Frog in Frogs_KK: print(froskur) elif val == 3: #### CAR OUTPUT #### hradi = random.randint(5,15) bensin = random.randint(50,200) eydsla = random.randint(2,8) bill1=Car("Pegassi Zentorno","2016",hradi,bensin,eydsla) print(bill1) hradi = random.randint(4,14) bensin = random.randint(50,200) eydsla = random.randint(2,8) bill2=Car("Maybach","2012",hradi,bensin,eydsla) print(bill2) hradi = random.randint(6,16) bensin = random.randint(5,200) eydsla = random.randint(3,8) bill3=Car("Toyota Yaris","2007",hradi,bensin,eydsla) print(bill3) # BEGIN sek = 0 while (bill1.stada(sek)<1000 and bill1.eftir_bensin(sek) >=0): sek+=1 print (bill1.tegund,"er kominn",bill1.stada(sek)) print (bill1.tegund,"a eftir af bensini",round(bill1.eftir_bensin(sek),2)) sek=0 while (bill2.stada(sek)<1000 and bill2.eftir_bensin(sek) >=0): sek+=1 print (bill2.tegund,"er kominn",bill2.stada(sek)) print (bill2.tegund,"a eftir af bensini",round(bill2.eftir_bensin(sek),2)) sek=0 while (bill3.stada(sek)<1000 and bill3.eftir_bensin(sek) >=0): sek+=1 print (bill3.tegund,"er kominn",bill3.stada(sek)) print (bill3.tegund,"a eftir af bensini",round(bill3.eftir_bensin(sek),2)) sek=0 elif val == 4: ob1 = Boydem("Karl",17,"kk") print(ob1) print(ob1.__doc__) ob2 = Runner("Gellan",17,"kvk","5") print(ob2) print(ob2.__doc__) print(ob2.kraftur()) elif val == 5: print("Bless bless") break else: break
#!/usr/bin/python3 def read_lines(filename="", nb_lines=0): """Function that reads n lines of a text file (UTF8) and prints it to stdout""" line_number = 0 with open(filename, encoding='utf-8') as f: for line in f: line_number += 1 if (nb_lines <= 0) or (nb_lines >= line_number): print(line, end="")
#!/usr/bin/python3 """Unittest for max_integer """ import unittest max_integer = __import__('6-max_integer').max_integer class TestMaxInteger(unittest.TestCase): """unittests for the function def max_integer(list=[])""" def test_max_integer(self): self.assertEqual(max_integer([1, 2, 3]), 3) self.assertEqual(max_integer([7, -2, 5]), 7) self.assertEqual(max_integer([7, 10, 5]), 10) self.assertEqual(max_integer([-1, -5, -7]), -1) self.assertEqual(max_integer([7]), 7) self.assertEqual(max_integer([]), None)
#!/usr/bin/python3 def is_kind_of_class(obj, a_class): """ check if an object is an instance of a class that inherited from the class""" if isinstance(obj, a_class): return True return False
""" Un telefono depende del estado del telefono/linea -Si suena lo puedes coger Se trata de un patron donde el comportamiento de un determinado estado está determinado por su propio estado. Hay un disparado de un estado a otro => state machine """ #LIGHT SWITCH from abc import ABC class Switch: def __init__(self) -> None: self.state = OffState() def on(self): self.state.on(self) def off(self): self.state.off(self) class State(ABC): def on(self, switch): print("Light is already on") def off(self, switch): print("Light is already off") class OnState(State): def __init__(self): print("Ligth turned on") def off(self, switch): print("Turning light off...") switch.state = OffState() class OffState(State): def __init__(self) -> None: print("Light turned off") def on(self, switch): print("Turning light on...") switch.state = OnState() if __name__ == "__main__": sw = Switch() sw.on() sw.off() sw.off()
#Un adaptador es una pieza que permite adaptar una interfaz existente para #que funcione de acuerdo a lo requerido por una interfaz Y class Point: def __init__(self, x, y) -> None: self.x = x self.y = y def draw_point(p): print(".", end= "") #Tenemos al API anterior #Tenemos la siguiente necesidad: Tenemos que pintar, pero no podemos pintar porque la función #para pintar necesita puntos, y nosotros tenemos lineas: class Line: def __init__(self, start, end) -> None: self.start = start self.end = end class Rectangle(list): def __init__(self, x, y, width, height): super().__init__() self.append(Line(Point(x, y), Point(x + width, y))) self.append(Line(Point(x + width, y), Point(x + width, y + height))) self.append(Line(Point(x, y), Point(x, y + height))) self.append(Line(Point(x, y), Point(x + width, y + height))) class LineToPointAdapter(): cache = {} def __init__(self, line): self.h = hash(line) if self.h in self.cache: return super().__init__() print(f'Generating points for line ' f'[{line.start.x},{line.start.y}]→' f'[{line.end.x},{line.end.y}]') left = min(line.start.x, line.end.x) right = max(line.start.x, line.end.x) top = min(line.start.y, line.end.y) bottom = min(line.start.y, line.end.y) points = [] if right - left == 0: for y in range(top, bottom): points.append(Point(left, y)) elif line.end.y - line.start.y == 0: for x in range(left, right): points.append(Point(x, top)) self.cache[self.h] = points #Para que el objeto pueda usarse como un iterable def __iter__(self): return iter(self.cache[self.h]) def draw(rcs): print("\n\n-- Drawing some stuff --\n") for rc in rcs: for line in rc: adapter = LineToPointAdapter(line) for p in adapter: draw_point(p) if __name__ == "__main__": rcs = [ Rectangle(1,1,10,10), Rectangle(3,3,6,6) ] draw(rcs)
#Motivacion: """ clickas a un elemento en el form => quien gestiona el click - el boton -el group box -underlaying window Esencialmente, encadenar componenetes para que todos tengan la oportunidad de realizar algún procesamiento. Opcionalmente con la capacidad de terminar la cadena """ class Creature: def __init__(self, name, attack, defense) -> None: self.name = name self.attack = attack self.defense = defense def __str__(self) -> str: return f"{self.name} ({self.attack}/{self.defense})" class CreatureModifier: def __init__(self, creature) -> None: self.creature = creature #esto va a apuntar a la siguiente funcion que se va a ejecutar self.next_modifier = None def add_modifier(self, modifier): if self.next_modifier: self.next_modifier.add_modifier(modifier) else: self.next_modifier = modifier def handle(self): if self.next_modifier: self.next_modifier.handle() class DoubleAttackModifier(CreatureModifier): def handle(self): print(f"Doubling {self.creature.name}'s attack") self.creature.attack *= 2 super().handle() class IncreaseDefenseModifier(CreatureModifier): def handle(self): if self.creature.attack <= 2: print(f"Increasing {self.creature.name} defense") self.creature.defense += 1 else: print("Not possible to increase defense") super().handle() class NoBonusesModifier(CreatureModifier): def handle(self): print("No bonuses for you") if __name__ == "__main__": goblin = Creature("Gobline", 1,1) print(goblin) root = CreatureModifier(goblin) root.add_modifier(NoBonusesModifier(goblin)) root.add_modifier(DoubleAttackModifier(goblin)) root.add_modifier(DoubleAttackModifier(goblin)) root.add_modifier(IncreaseDefenseModifier(goblin)) root.handle() print(goblin) root.handle() print(goblin) """ Command query separation: command = asking for an action or change (eg: please set your attack value to 2) query = asking for information (eg please give me your attack value) CQS = having separate means of sending commands and queries to """
class Company(object): def __init__(self, company_id, company_name, company_type, company_email): self.Company_id = company_id self.Company_name = company_name self.company_type = company_type self.company_email = company_email def __str__(self): return "Company Name = {0}\nCompany Email = {1}".format(self.Company_name, self.company_email) class Employee(Company): def __init__(self, company_id, company_name, company_type, company_email, emp_id, emp_name, emp_salary, emp_desg, emp_email): self.emp_id = emp_id self.emp_name = emp_name self.emp_salary = emp_salary self.emp_desg = emp_desg self.emp_email = emp_email Company.__init__(self,company_name,company_type,company_email,company_email) def __str__(self): return "\nEmployee ID = {}\nEmployee Name ={}\nEmployee email ={}".format(self.emp_id, self.emp_name, self.emp_email) comp = Employee(102, "Facebook", "Social networking site", "facebook.com",102,"stepahn",23000, "dev", "[email protected]") print(comp)
class programming(): count=0 def __init__(self,interpreter): self.interpreter=interpreter programming.count+=1 def print_progarm(self): print(self.interpreter) class python(programming): count=0 def __init__(self,name,interpreter): self.name=name super().__init__(interpreter) python.count+=1 def print_lang(self): print(self.name) def print_progarm(self): print('from python',self.interpreter) class java(programming): count=0 def __init__(self,name,interpreter): self.name=name super().__init__(interpreter) java.count+=1 def print_lang(self, greeting): print(greeting, self.name) # if __name__ == '__main__': # py1=python("python1","c#") # jv1=java("java","c") import datetime a=datetime.datetime(2014,12,23)+datetime.timedelta(days=2) class Programmer(object): def __init__(self): self.plang=self.plang def p_print(self): print(self.plang) class Tester(object): def __init__(self): self.tlang=self.tlang class Employee(Programmer,Tester): def __init__(self,name,plang,tlang): self.name=name self.plang=plang self.tlang = tlang super(Programmer,self).__init__() super(Tester,self).__init__() def p_print(self): print(self.name) super().p_print() emp=Employee("employe","java","selenium") print(Employee.__mro__)
def load_file(): try: f = open('input.txt', 'r+')#open file except NoSuchFile: return "No Such File" for lines in f.readlines():#for loop to read through txt file data = lines[0:4]#splice txt file from 0 to 3 data2 = lines[4:]#splice txt file index 4 to end data3 = data2.split(',')#split at , data4 = [int(i) for i in data3] #cast string to integer if data == "min:":#if statement when data is equal to min print("The min of [" + data2 + "] is: " + str(min(data4))) elif data == "max:":#if statement when data is equal to max print("The max of [" + data2 + "] is: " + str(max(data4))) elif data == "avg:": print("The avg of [" + data2 + "] is: " + str(sum(data4)/len(data4))) else: print("No Such operation") f.close()#close file
#비밀번호 찾기 from sys import stdin,stdout rd = lambda:stdin.readline() wr = stdout.write N,M = map(int, rd().split()) account = dict() for i in range(0, N): id, pw = rd().split() account[id] = pw for i in range(0, M): id = rd().rstrip() #끝의 개행문자 제거 print(f"{account[id]}")
driving = input('你有沒有開過車?') if driving != ('有') and driving != ('沒有'): print('只能回答"有"或"沒有"') raise SystemExit age = input('請輸入年齡: ') age = int(age) if driving == '有': if age > 18: print('恭喜你!通過測驗了!') else: print('未滿18歲怎麼會開過車呢?') elif driving == '沒有': if age > 18: print('成年了可以考駕照了') else: print('再過幾年就可以考駕照了')
def fatorial(n): produto = n for i in range (1, n): produto = produto * (n-1) return produto def main(): for i in range (10): print (fatorial(i)) main()
# Possible_inputs = ['Scissor', 'Rock', 'Paper'] def whowin(human, cpu): if human == cpu: return 0 elif human == 'Scissor' and cpu == 'Rock': return -1 elif human == 'Scissor' and cpu == 'Paper': return +1 elif human == 'Rock' and cpu == 'Scissor': return +1 elif human == 'Rock' and cpu == 'Paper': return -1 elif human == 'Paper' and cpu == 'Scissor': return -1 elif human == 'Paper' and cpu == 'Rock': return +1 else: return 0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import glob import re def count_key_words(key_words): contents = [] for file_name in glob.glob('*.txt'): with open(file_name, 'r') as file: contents.append(file.read()) str = ''.join(contents).lower() return dict(map(lambda x:(x, len(re.findall(x, str))), key_words)) if __name__ == '__main__': print(count_key_words(['byte', 'type']))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import ast import xlwt def read_city(path): with open(path, 'r') as file: content = file.read() return ast.literal_eval(content) def write_city2xls(dic): wb = xlwt.Workbook() ws = wb.add_sheet('City') for key, value in dic.items(): row = int(key) - 1 ws.write(row, 0, key) ws.write(row, 1, value) wb.save('city.xls') if __name__ == '__main__': dic = read_city(r'.\city.txt') write_city2xls(dic)
def input_info(): name=str(input("enter your name: ")) age=float(input("enter your age: ")) weight=float(input("enter your weight: ")) system=str(input("enter your desired metrics: ")) return (name,age,weight,system) def calculate_bmi(weight,age,system='metrics'): if system.startswith('m'): bmi=(weight*age) else: bmi=(weight*age)/2 return bmi while True: (name_inputted,age_inputted,weight_inputted,system_inputted)=input_info() print(f"your name give is ----> {name_inputted}") print(f"your age given is ---> {age_inputted}") print(f"your weight given is ---> {weight_inputted}") print("\n") if name_inputted == 'chintu': break bmi_returned_value=calculate_bmi(weight=weight_inputted,age=age_inputted,system=system_inputted) print(f" bmi value given is ---->{bmi_returned_value}")
'''def calc(num): try: if num > 9: print(f"you provided num as ---->{num}") except: print("you provided not an int type") a=calc(10) b=calc('this') ''' '''import json import os a=float(input("enter no")) print(a) with open('test_pra','w') as f: json.dump(a,f) path_of_file=os.path.abspath("test_pra") print(path_of_file) with open('test_pra','r') as j: m=j.read() print(f"you supplied data is {m}") ''' #num=int(input("enter your desired number")) """try: raise ValueError('x should not be less than 10!') except ValueError: print('There was an exception.') """ x=int(input("enter number")) if x < 10: raise ValueError('x should not be less than 10!')
class testing: "This is for testing class concepts" a=3 def __init__(self,firstname,lastname): ############# These is main class deinfition. Here, i am declaring two params to be needed and then will make use of those params self.name_given_firstname=firstname ################ You can re-use these params anywhere in ur code self.name_given_lastname=lastname ################### You can re-use these params anywhere in ur code testing.a += 1 def fun_a(self,number=12): print(f"fistname is ----> {self.name_given_firstname} and lastname is ---> {self.name_given_lastname}") #return number*number def fun_b(self,c,d): return c*d test=testing('chintu','reddy') test.fun_a() #z=test.fun_a(10) #print(z) y=test.fun_b(25,25) print(y) print(f"value of value is ---> {testing.a}") test1=testing('chintu','reddy') print(f"value of value is ---> {testing.a}")
number = float(input("Please Enter any number : ")) if number > 0: print("{0} is a positive number".format(number)) elif number == 0: print("{0} is zero".format(number)) else: print("{0} is a negative number".format(number))
list = [21, 54, 75, "JON", 30, "Nishit", 9] print("list[1] : ", list[1]) print("list[2,5] : ", list[2, 5]) print("list[3:] : ", list[3:])
for x in range(15): if x % 2 == 0: continue print("value is : ", x)
import prime import randomnumber import sys if __name__ == '__main__': arg = sys.argv[len(sys.argv)-1] n = 0 is_prime = False if arg == '--fermat': while not is_prime: n = randomnumber.multiply_with_carry() is_prime = prime.fermat(n) print('Random number generated with MWC: {}'.format(n)) print('Is prime by fermat? {}'.format(is_prime)) elif arg == '--miller': while not is_prime: n = randomnumber.multiply_with_carry() is_prime = prime.miller_rabin(n) print('Random number generated with MWC: {}'.format(n)) print('Is prime by miller? {}'.format(is_prime))
ip = '10.1.1.1' mask = 4 print(f'IP: {ip} mask {mask}') # Same with .format # print("IP: {ip}, mask: {mask}".format(ip=ip, mask=mask)) '''Очень важное отличие f-строк от format: f-строки это выражение, которое выполняется, а не просто строка. То есть, в случае с ipython, как только мы написали выражение и нажали Enter, оно выполнилось и вместо выражений {ip} и {mask} подставились значения переменных. Поэтому, например, нельзя сначала написать шаблон, а затем определить переменные, ''' # Можно писать выражения octets = ['10', '1', '1', '1'] mask = 24 # Кроме подстановки значений переменных, в фигурных скобках можно писать выражения: print(f"IP: {'.'.join(octets)}, mask: {mask}") print(type('.'.join(octets))) # После двоеточия в f-строках можно указывать те же значения, что и при использовании format: oct1, oct2, oct3, oct4 = [10, 1, 1, 1] print(f''' IP address: {oct1:<8} {oct2:<8} {oct3:<8} {oct4:<8} {oct1:08b} {oct1:08b} {oct1:08b} {oct1:08b} ''') ip_list = ['10.1.1.1/24', '10.2.2.2/24', '10.3.3.3/24'] for ip_address in ip_list: ip, mask = ip_address.split('/') print(f"IP: {ip}, mask: {mask}") intf_type = 'Gi' intf_name = '0/3' print(f'\ninterface {intf_type}/{intf_name}') # Выравнивание столбцами topology = [['sw1', 'Gi0/1', 'r1', 'Gi0/2'], ['sw1', 'Gi0/2', 'r2', 'Gi0/1'], ['sw1', 'Gi0/3', 'r3', 'Gi0/0'], ['sw1', 'Gi0/5', 'sw4', 'Gi0/2']] width = 8 for connection in topology: l_device, l_port, r_device, r_port = connection print(f'{l_device:{width}} {l_port:{width}} {r_device:{width}} {r_port:{width}}') # print(l_device[:width], r_device[:width]) session_stats = {'done': 10, 'todo': 0} if session_stats['todo']: print(f"Pomodoros done: {session_stats['done']}, TODO: {session_stats['todo']}") else: print(f"Good job! All {session_stats['done']} pomodoros done!") print(f'Количество подключений в топологии: {len(topology)}') # 0 после двоеточия - заменяет нулями все пробелы для строки меньше 8 символов, b - переводит в двоичную систему print(f'{int(oct1):08b} {int(oct2):08b} {int(oct3):08b} {int(oct4):08b}')
# for num in range(5): # print(num) # else: # print("Числа закончились") for num in range(5): if num == 3: break else: print(num) else: print("Числа закончились")
# ip = input("Введите ip-адрес: ") # # for octet in ip: # print(octet) # if ip == '': # ip = '192.168.120.1' # print("IP по умолчанию: " + ip) """ „unicast“ - если первый байт в диапазоне 1-223 „multicast“ - если первый байт в диапазоне 224-239 „local broadcast“ - если IP-адрес равен 255.255.255.255 „unassigned“ - если IP-адрес равен 0.0.0.0 „unused“ - во всех остальных случаях """ def check_ip(ip): check_status = True octet = ip.split('.') if len(octet) == 4: for num in octet: # print(num) if int(num) not in range(0, 256): check_status = False break if check_status: return True else: return False def network_type(ip): octet = ip.split('.') # print(octet[0]) if ip == '0.0.0.0': print(ip + " unassigned") elif octet[0] in str(range(1, 223)): print(ip + " unicast") elif octet[0] in str(range(224, 239)): print(ip + " multicast") elif ip == '255.255.255.255': print(ip + " local broadcast") else: print(ip + " unused") def test(): print("Проверка для unicast") network_type('1.0.0.0') network_type('223.0.0.0') print("Проверка для multicast") network_type('224.0.0.0') network_type('239.0.0.0') print("Проверка для local broadcast") network_type('255.255.255.255') print("Проверка для unassigned") network_type('0.0.0.0') print("Проверка на unused") network_type('test') network_type('0.1.1.1') # test() while True: ip = input("Введите IP-адрес: ") if check_ip(ip): print("Адрес введен верно") print(ip) break else: print("Адрес введен неверно")
# ZeroDivisionError: division by zero # print(2/0) # TypeError: can only concatenate str (not "int") to str # print('test' + 2) # try: # 2 / 0 # # except: # print("You can't divide by zero") # try: print("Let's divide some numbers") #Всё выполниться до этого выражения 2/0 print("Cool!") except ZeroDivisionError: print("You can't divide by zero") except ValueError: print("Неверное значение") finally: print("Выполняется всегда")
""" What is the largest prime factor of the number 600851475143 ? """ def main(): num = 600851475143 for x in range(2, num): if(num % x == 0): num /= x; print(num) main()
from unittest import TestCase, skip from unittest.mock import Mock from collections import defaultdict, OrderedDict, Counter suits = ['s', 'c', 'd', 'h'] def parse_cards(cards): rank = { '1': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14 } return sorted([(int(rank.get(c[0], (c[0]))), c[-1]) for c in cards], key=lambda x: -x[0]) def create_card(rank, suit): int2rank = { 11: 'J', 12: 'Q', 13: 'K', 14: 'A' } return int2rank.get(rank, str(rank)) + suit def parse_and_count_cards(cards): pc = parse_cards(cards) count = OrderedDict() for c in pc: try: count[c[0]] += 1 except KeyError: count[c[0]] = 1 return pc, count def find_high_card(cards): """Return the ranks of the (up to) five highest cards, sorted in descending order.""" return [card[0] for card in parse_cards(cards)][:5] def find_n_of_a_kind(n, cards): """Check if *cards* contain (at least) *n* cards of the same rank. n will be either 2, 3, or 4. If several n-of-a-kinds are found, consider only the one with the highest rank. To correctly resolve ties, return a list of the rank of the n-of-a-kind and then ranks of the highest other cards in descending orders. For example: [2, 11, 8, 7] where 2 is the rank of the n-of-a-kind, and [11, 8, 7] are the ranks of the highest other cards. The whole list must not consider more than five cards (so this example would be correct for n=2). """ pc, count = parse_and_count_cards(cards) for key in count: if count[key] >= n: return [key] + [card[0] for card in pc if card[0] != key][:(5 - n)] return None def find_two_pairs(cards): """If *cards* contain (at least) two pairs, return a triple (rank of highest pair, rank of second highest pair, rank of the highest other card) If there is no other card, because len(cards) == 4, then just return the pairs' ranks. If no two pairs are found, return None. """ pc, count = parse_and_count_cards(cards) pairs = [] for rank in count: if count[rank] == 2: pairs.append(rank) if len(pairs) == 2: break if len(pairs) < 2: return None return pairs + [card[0] for card in pc if card[0] not in pairs][:1] def find_straight(cards): """If *cards* contain a straight, return the rank of its highest card. Otherwise return None. A straight consists of five cards of sequential rank, e.g. ['2h', '3c', '4d', '5d', '6h']. As a special rule, aces may be used with rank 1, so ['Ac', '2h', '3c', '4d', '5d'] also forms a (lower) straight. """ ranks = list(OrderedDict.fromkeys([rank for rank, suit in parse_cards(cards)])) if ranks[0] == 14: ranks.append(1) if len(ranks) < 5: return None for i in range(len(ranks)): cmp = ranks[i:i+5] if len(cmp) < 5: continue if cmp == list(range(cmp[0], cmp[0]-5, -1)): return cmp[0] return None def find_flush(cards): """If *cards* contain a flush (five cards of the same suit), return the ranks of its cards, sorted in descending order. Otherwise return None.""" pc = parse_cards(cards) count = defaultdict(int) for c in pc: count[c[1]] += 1 for s in suits: if count[s] >= 5: return [card[0] for card in pc if card[1] == s][:5] return None def find_full_house(cards): """If *cards* contain a full house (a triple and a pair), return a tuple (rank of triple, rank of pair) of the cards in the full house. Otherwise return None. """ pc, count = parse_and_count_cards(cards) triple = pair = None for rank in count: if count[rank] == 2 and pair is None: pair = rank if count[rank] == 3: if triple is None: triple = rank elif pair is None: pair = rank if triple and pair: return [triple, pair] return None def find_straight_flush(cards): """If *cards* contain a straight flush (a straight, where all cards are of the same suit), return the rank of its highest card. Otherwise return None. """ suitcount = Counter([suit for rank, suit in parse_cards(cards)]) for suit, count in suitcount.items(): if count >= 5: return find_straight([c for c in cards if c[-1] == suit]) return None def rank_function(cards): functions = [ find_straight_flush, lambda x: find_n_of_a_kind(4, x), find_full_house, find_flush, find_straight, lambda x: find_n_of_a_kind(3, x), find_two_pairs, lambda x : find_n_of_a_kind(2, x), find_high_card, ] for i, f in enumerate(functions): rank = f(cards) if rank: return 9 - i, rank class TestFindHighCard(TestCase): def test_empty(self): self.assertEqual([], find_high_card([])) def test_less_than_five(self): cards = parse_cards(['5d', 'Jh', 'As']) self.assertEqual([14, 11, 5], find_high_card(cards)) def test_more_than_five(self): cards = parse_cards(['5d', 'Jh', 'As', '10c', '2c', '2d', '4d']) self.assertEqual([14, 11, 10, 5, 4], find_high_card(cards)) class TestNOfAKind(TestCase): def test_not_found(self): cards = parse_cards(['5d', 'Jh', 'As', '10c', '2c', '3d', '4d']) self.assertIsNone(find_n_of_a_kind(2, cards)) def test_one_result(self): cards = parse_cards(['5d', 'Jh', 'As', '10c', '2c', '2d', '4d']) self.assertEqual([2, 14, 11, 10], find_n_of_a_kind(2, cards)) def test_two_results(self): cards = parse_cards(['5d', '5c', '5h', '2s', '2c', '2d', 'As']) self.assertEqual([5, 14, 2], find_n_of_a_kind(3, cards)) def test_bigger_n(self): cards = parse_cards(['5d', 'Jh', 'As', '10c', '5c', '5d', '5d']) self.assertEqual([5, 14], find_n_of_a_kind(4, cards)) class TestFindTwoPairs(TestCase): def test_not_found(self): cards = parse_cards(['5d', 'Jh', 'As', '5c', '2c', '3d', '4d']) self.assertIsNone(find_two_pairs(cards)) def test_found(self): cards = parse_cards(['5d', 'Jh', 'As', '5c', '2c', '2d', '4d']) self.assertEqual([5, 2, 14], find_two_pairs(cards)) def test_only_four_cards(self): cards = parse_cards(['5d', '5c', '2c', '2d']) self.assertEqual([5, 2], find_two_pairs(cards)) def test_three_pairs(self): cards = parse_cards(['5d', '2h', 'As', '5c', '2c', 'Jd', 'Jd']) self.assertEqual([11, 5, 14], find_two_pairs(cards)) class TestFindStraight(TestCase): def test_not_found(self): cards = parse_cards(['4d', '7h', '2s', '5c', '7c', '6d', 'Qd']) self.assertIsNone(find_straight(cards)) def test_with_double(self): cards = parse_cards(['4d', '7h', '8s', '5c', '7c', '6d', 'Qd']) self.assertEqual(8, find_straight(cards)) def test_straight_with_six_cards(self): cards = parse_cards(['4d', '8h', '3s', '5c', '7c', '6d', 'Qd']) self.assertEqual(8, find_straight(cards)) def test_find_straight_low_ace(self): cards = parse_cards(['4d', '8h', '3s', '5c', '2c', '7d', 'Ad']) self.assertEqual(5, find_straight(cards)) def test_dont_use_low_ace_if_better_straight_possible(self): cards = parse_cards(['4d', '8h', '3s', '5c', '2c', '6d', 'Ad']) self.assertEqual(6, find_straight(cards)) def test_no_low_king(self): cards = parse_cards(['Kd', '8h', '3s', '4c', '2c', '7d', 'Ad']) self.assertIsNone(find_straight(cards)) class TestFindFlush(TestCase): def test_not_found(self): cards = parse_cards(['10d', '8d', '3c', '5h', 'Qd', '7d', 'As']) self.assertIsNone(find_flush(cards)) def test_find_flush(self): cards = parse_cards(['10d', '8d', '3d', '5d', 'Qd', 'As']) self.assertEqual([12, 10, 8, 5, 3], find_flush(cards)) def test_more_than_five_cards(self): cards = parse_cards(['10d', '8d', '3d', '5d', 'Qd', '7d', 'As']) self.assertEqual([12, 10, 8, 7, 5], find_flush(cards)) class TestFindFullHouse(TestCase): def test_no_triple(self): cards = parse_cards(['10d', '10s', '3c', '3h', 'Qd', '7d', 'As']) self.assertIsNone(find_full_house(cards)) def test_no_pair(self): cards = parse_cards(['10d', '10s', '3c', '10h', 'Qd', '7d', 'As']) self.assertIsNone(find_full_house(cards)) def test_find_full_house(self): cards = parse_cards(['10d', '10s', '3d', '5d', '3h', '3c', 'As']) self.assertEqual([3, 10], find_full_house(cards)) def test_choose_best(self): cards = parse_cards(['10d', '10s', '3d', 'Qd', '3h', '3c', 'Qs']) self.assertEqual([3, 12], find_full_house(cards)) def two_triples(self): cards = parse_cards(['10d', '10s', '10h', '3d', '3h', 'Qc', '3s']) self.assertEqual([3, 12], find_full_house(cards)) class TestFindStraightFlush(TestCase): def test_no_flush(self): cards = parse_cards(['2d', '3d', '4s', '5c', '6d', '7d', '8d']) self.assertIsNone(find_straight_flush(cards)) def test_no_straight(self): cards = parse_cards(['10d', '10d', '3d', '3d', 'Qd', '7d', 'Ad']) self.assertIsNone(find_straight_flush(cards)) def test_find_straight_flush(self): cards = parse_cards(['2d', '3d', '4d', '5d', '6d', '7d', '8c']) self.assertEqual(7, find_straight_flush(cards)) def test_with_low_ace(self): cards = parse_cards(['2d', '3d', '4d', '5d', '6c', '7c', 'Ad']) self.assertEqual(5, find_straight_flush(cards)) class TestRanking(TestCase): def test_ranking(self): # In particular check cases where two rankings apply (e.g. Full House and Flush) card_sets = [ # Straight Flush ['As', 'Ks', 'Qs', 'Js', '10s', '2c', '3c'], ['Ks', 'Qs', 'Js', '10s', '9s', '2c', '3c'], # 4 of a kind ['10s', '10d', '10c', '10h', 'As', '2c', '2d'], ['10s', '10d', '10c', '10h', 'Ks', '2c', '2d'], # Full House ['As', 'Ad', 'Ah', 'Kh', 'Ks', '2c', '2d'], ['3s', '3d', '3h', 'Kh', 'Ks', '2c', '2d'], # Flush ['3s', 'Ks', '4s', '10s', '7s', '2c', '2d'], ['3s', 'Qs', '4s', '10s', '7s', '2c', '2d'], # Straight ['3s', '4d', '5h', '6d', '7c', '2c', '2d'], ['As', '2c', '3s', '4d', '5h', '7c', '2d'], # 3 of a kind ['10s', '10d', '10c', 'Ah', 'Ks', '3c', '2d'], ['10s', '10d', '10c', 'Ah', 'Qs', '3c', '2d'], # Two Pairs ['10s', '10d', 'Kh', '4c', '4c', '2h', '6d'], ['10s', '10d', 'Ah', '3c', '3c', '2h', '6d'], ['10s', '10d', '4h', '3c', '3c', '2h', '6d'], # 2 of a kind ['10s', '10d', 'Ah', '4c', '5c', '2h', '6d'], ['10s', '10d', 'Kh', '3c', '5c', '2h', '6d'], # High card ['Qs', '10d', 'Ah', '3c', '5c', '2h', '6d'], ['Qs', '10d', 'Kh', '3c', '5c', '2h', '6d'], ] ranks = [rank_function(c) for c in card_sets] for rank, card_set in zip(ranks, card_sets): print(rank, card_set) sorted_card_sets = sorted(card_sets, key=rank_function, reverse=True) self.assertListEqual(card_sets, sorted_card_sets)
''' Created on Sep 16, 2018 @author: rachelk4 ''' import unittest from geeksforgeeks.algorithm import isTriplet class isTripletTest(unittest.TestCase): def test(self): ar = [3, 1, 4, 6, 5] ar_size = len(ar) self.assertEqual(isTriplet(ar, ar_size), True) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
while True: dice_to_filter = [5, 2, 3, 1, 4] drop_lowest_number = 100000000; for eachNumber in dice_to_filter: print(eachNumber) def drop_lowest_number(dice_to_filter): drop_lowest_number = eachNumber print("lowest number to drop: ", drop_lowest_number) if dice_to_filter == 5: break
while True: answer1 = input ("Which direction do you want to go? (R for right and L for left) ") if answer1 == "r" or answer1 == "R": print("You go right and encounter a person") print("") print("You talk to the person and they give you a free sword. ") print("") username = input ("Before giving you the sword they ask you for your name: ") print("") print("Hello there young traveler " + username) print("") print("You ask the person for their name. They tell you not to worry about it, as you walk away from them you turn around to see they have dissapeard") print("") answer2 = input("You enter a big room and encounter a monster. What do you do? (F to fight and R to run.) ") if answer2 == "f" or answer2 == "F": print("") print("you fought the monster and after a hard battle you killed it.") print("") answer5 = input("You find a giant monkey and it speaks to you, do you respond? (T to talk and I to ignore) ") if answer5 == "T" or answer5 == "t": print("") print("You talk to the monkey and it gives you banana, you win the game. GG") print("") print("<3 Monkey") print("") username = input("what was your name? ") print("") print("thank you for playing " + username) break else: print("You didnt talk to the monkey, the monkey ripped off your head for not being polite. GG ") break elif answer2 == "r" or answer2 == "R": print("") print("You ran and got killed by the monster.") elif answer1 == "l" or answer1 == "L": print("You go left and encounter a monster") answer3 = input("What do you do with the monster? (F to fight and R to run) ") if answer3 == "f" or answer3 == "F": print("") print("You died trying to fight the monster") elif answer3 == "r" or answer3 == "R": print("") print("You run away but the monster chases you.") print("") answer4 = input ("As you run from the monster you find a place to hide, do you take the chance or do you keep running (H to hide and R to run) ") if answer4 == "H" or answer4 == "h": print("") print("You hid and the monster ran past you.") print("") print("You run back to where you encountered the monster and are able to traverse through it layer.") print("") answer6 = input ("You find a giant monkey and it speaks to you, do you respond? (T to talk and I to ignore) ") if answer6 == "T" or answer6 == "t": print("") print("You talk to the monkey and it gives you banana, you win the game. GG") print("") print("<3 Monkey") print("") username = input("what was your name? ") print("") print("thank you for playing " + username) break else: print("You didnt talk to the monkey, the monkey ripped your head off for not being polite. GG ") print("") username = input("what was your name? ") print("thank you for playing " + username) break elif answer4 == "R" or answer4 == "r": print("") print("You keep running but the monster catches you and eats you.") break else: answer7 = input("Incorrect input. Do you want to try again? (Y to try again N to give up) ") if answer7 == "Y" or answer7 == "y": continue elif answer7 == "N" or answer7 == "n": break
n=input() n1,n2 = "", "" for i in range(0,len(n),2): n1=n1+n[i] for i in range(1,len(n),2): n2=n2+n[i] print(n1,n2)
k=int(input()) while(k%2==0): k=k//2 print(k)
import numpy as np import random n_strain = 2 #starting off with 2 strains max_strain = 10 #ASSUMPTION: we are assuming a disease with mutation that happens when more than one strain is in the same person's body at the same time (which is totally not necessarily the case) a = np.random.rand(max_strain) #infection rate of each strain, take a random probability from 0 to 1 b = np.random.rand(max_strain) * 14 #randomly generated average healing time print(str(a)+"\n"+str(b)) #NOTE: two lines below are random numbers we set, change to the two lines above for random instead of deterministic model (there are other random function used in the program because they were necessary for simulation) # a = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] #infection rate # b = [7, 7, 5, 7, 9, 4, 5, 6, 3, 8] #mean date it takes to recover5 infected = np.zeros(max_strain) #an 1D array to record how many people are currently infected, basically the I variable but for each strain for each strain, we use this to ramp up new infection rate based on how many people are currently infected N = 20 #number of people in population m = 0.1 #1-probability of mutation, in this case probability of mutation is 0.05 med_rec = np.zeros((N, max_strain)) #A 2D array listing the state of each person (column) in pretains to each strain (row), where -1 is immune, 0 is susceptible, and 1 and above is infected and recording the number of days of infection #########INITIALIZING ARRAYS WE WANT TO PLOT############### P_mutation = np.zeros(max_strain) #when does each mutation happen #########END OF INITIALIZING ARRAYS WE WANT TO PLOT######## #ASSUMPTION: we are not taking death into consideration #ASSUMPTION: randomly select one person to be infected with each strain that we start with (leftmost n_strain strains on the med_rec array) for s in range(n_strain): med_rec[random.randint(0,N-1),s] = 1 infected[s] = 1 #record first infection for the strain P_mutation[s] = 0 #we have it from time 0 without mutation t_range = 100 #change this to simulate time period I_mean = 0.2 #neutral in terms of infected or not infected, can change this, used in gaussian distribution of infection for t in range(t_range-1): print(str(med_rec)) #print("infection arr: "+str(infected)) print("t = " + str(t)) for p in range(N): #for ever person ill = 0 #keep track of whether the person is infected with more than one disease, if so they are eligible for mutation (ASSUMPTION: not counting for infection this iteration) #print("person "+str(p)) #ASSUMPTION: no one dies from the disease (so far) for s in range(n_strain): #for every current existing strain if med_rec[p,s] == -1: #this person is immune to this strain continue elif med_rec[p,s] == 0: #potentially be infected by exisiting virus if random.gauss(I_mean-infected[s]/N,1) < a[s]: #gets sick for a probability, more people infected with the strain more likely it is for others to catch it #ASSUMPTION: we are using a gaussian distribution with mean around the middle (0.5) and standard deviation of infected/population of that desease to simulate encounterance #instead of pre-calculating new infections which is I_new = I_old * e^(-bt) in notes, we are simulting the chances of infection #ASSUMPTION: everyone have the same chance of encountering each other in the community med_rec[p,s] = 1 infected[s]+=1 else: #potentially heal or make a mutate strain if already ill if med_rec[p,s] > random.gauss(b[s],1): #healed #ASSUMPTION: we are using gaussian function to simulate normal distribution of recovery around b[s] which is the mean rate we decided, and we're using 1 as standard deviation med_rec[p,s] = -1 infected[s]-=1 continue #move on to the next strain for this person else: med_rec[p,s]+=1 #increment number of days being ill ill+=1 if n_strain >= max_strain: #we can't mutate because our data structures only support so many strains continue if ill > 1: #if infected with more than one strain if random.uniform(0,1) > 1-m: #mutate print("mutation @ time "+str(t)+" on strain "+str(n_strain)+" person "+str(p)) P_mutation[n_strain] = t n_strain+=1 med_rec[p] = 0 #reset entire row to 0 when we have multiple infections med_rec[p,n_strain-1] = 1 #-1 because we are using index print("Mutation times: "+str(P_mutation)) #TODO: need to go through array and tally up results (and pre-store them before plotting)
print(""" **************************************** *** PROGRAMACIÓN ORIENTADA A OBJETOS *** ****************************************\n""") #POLIMORFISMO class auto(): def desplazamiento(self): print("Un auto se desplaza utilizando 4 ruedas") class moto(): def desplazamiento(self): print("Una moto se desplaza utilizando 2 ruedas") class camion(): def desplazamiento(self): print("Un camión se desplaza utilizando 6 ruedas") def desplazamientovehiculos(vehiculo): #Con esto podemos utilizar polimorfismo vehiculo.desplazamiento() mivehiculo=moto() desplazamientovehiculos(mivehiculo)
print(""" **************************************** *** PROGRAMACIÓN ORIENTADA A OBJETOS *** ****************************************\n""") #Con funciones print("SEGUNDA PARTE:\n") class persona1(): def __init__(self,nombre,edad,residencia): self.nombre=nombre self.edad=edad self.resindencia=residencia def descripcion(self): print("Nombre:",self.nombre,"\nEdad:",self.edad,"\nLugar de residencia:",self.resindencia) class empleado1(persona1): def __init__(self,salario,antigüedad,nombre_empleado,edad_empleado,residencia_empleado): super().__init__(nombre_empleado,edad_empleado,residencia_empleado) #Sirve para poder heredar de una clse self.salario=salario self.antigüedad=antigüedad def descripcion(self): super().descripcion() print("Salario Anual:",self.salario,"\nAntigüedad:",self.antigüedad,"años") Eusebio=empleado1(150000,9,"Eusebio",45,"Portugal") Eusebio.descripcion() print(isinstance(Eusebio,empleado1)) #Esto sirve para saber si un objeto pertenece a una clase o no.
#Decoradores I def fun_decoradora(funcion_parametro): def fun_interna(): print("Vamos a ralizar un cálculo:") funcion_parametro() print("Hemos terminado el cálculo") return fun_interna @fun_decoradora #Con esto ("@ejemplofuncion") llamamos a nuestra función decoradora, en este caso se le añade.. def suma():#..aquí a la suma print(15+20) @fun_decoradora def resta():#...y luego a la resta print(30-10) suma() print("") resta()
from io import open archivo_texto=open("#29_archivo2.txt","r") archivo_texto.seek(6) print(archivo_texto.read()) #Vamos a ver como desplazar el puntero y escribir en donde nosotros queramos con el método "seek(posición_deseada)" archivo_texto.seek(len(archivo_texto.read())/2) #Esto sirve para posicionar el cursor en la mitad del texto.... #...sin importar cuando grande o largo sea print(archivo_texto.read()) archivo_texto.seek(len(archivo_texto.readline())) #También se puede leer linea a linea print(archivo_texto.read()) archivo_texto.seek(0) print(archivo_texto.read(5)) #Al utilizar el read para leer, lo que hacemos es que se lea hasta la posición especificada print(archivo_texto.read()) #Después de utilizar la función read y poner de vuelta el print, continua la lectura desde... #...donde dejo de leer el print anterior
print(""" **************************************** *** PROGRAMACIÓN ORIENTADA A OBJETOS *** ****************************************\n""") #Encapsulamiento en chequeo interno class Automovil(): def __init__ (self): self.__largoChasis=250 self.__anchoChasis=120 self.__ruedas=4 self.__enmarcha=False def arrancar(self,arrancamos): self.__enmarcha=arrancamos if(self.__enmarcha): chequear=self.__chequeoInterno() if(self.__enmarcha and chequear): return "El coche está en marcha" elif(self.__enmarcha and chequear==False): return "Algo anda mal. No podemos arrancar el coche." else: return "El coche está parado" def estado(self): print("El coche tiene",self.__ruedas,"ruedas. Un ancho de",self.__anchoChasis,"y un largo de",self.__largoChasis) def __chequeoInterno(self): #Vamos a agregar un chequeo antes de que arranque el auto print("Realizando chequeo interno") self.gasolina="ok" self.aceite="ok" self.puertas="cerradas" if(self.gasolina=="ok" and self.aceite=="ok" and self.puertas=="cerradas"): return True else: return False miCoche=Automovil() print(miCoche.arrancar(True)) miCoche.estado() print("\nPOO parte 2:\n") miCoche2=Automovil() print(miCoche2.arrancar(False)) miCoche2.estado()
print("************************") print("*** CLASE OPERADORES ***") print("************************\n") print("PROGRAMA DE BECAS") print("") distancia=int(input("A que distancia vive de la escuela en km? ")) print(distancia) num_herm=int(input("Cuántos hermanos tiene? ")) print(num_herm) sala_fam=int(input("Cúal es el salario anual familiar? ")) print(sala_fam) print("") if distancia>20 and num_herm>2 and sala_fam<=350000: print("Con derecho a beca completa") else: print("Sin derecho a beca completa") print("\nREEVALUACION DE BECAS\n") distancia1=int(input("A que distancia vive de la escuela en km? ")) print(distancia1) num_herm1=int(input("Cuántos hermanos tiene? ")) print(num_herm1) sala_fam1=int(input("Cúal es el salario anual familiar? ")) print(sala_fam1) print("") if distancia1>20 or num_herm1>2 or sala_fam1<=350000: print("Con derecho a beca parcial") else: print("Sin derecho a beca parcial") print("\nOPERADOR IN\n") print("ASIGNATURAS ELECTIVAS\n") print(""" ASIGNATURAS DISPONIBLES: -Negocios Bursátiles -Turismo -Industria Pesada """) materia=input("Qué asignatura eliges?: ") opc=materia.lower() #Para poner el input en minusculas evitar problemas if opc in ("negocios bursatiles","negocios bursátiles","turismo","industria pesada"): print("Asignatura elegida: "+opc) else: print("Opción erronea.") print("") print("PROGRAMA FINALIZADO.")
print(""" *********************************** *** BUCLE WHILE (Indeterminado) *** ***********************************\n""") a=1 while a<=10: print("Ejecución "+str(a)) a+=1 #Es muy necesario agregarle algo que impida que sea un bucle infinito, sino el uso de recursos de la pc causaría un desastre print("Ejecución finalizada.") edad=int(input("Introduce tu edad por favor: ")) while edad<18 or edad>100: print("Has introducido una edad restringida. Vuelve a intentarlo") edad=int(input("Introduce tu edad por favor: ")) print("Gracias por colaborar, puedes pasar") print("Edad del aspirante:",edad) print("\nCOMO EVITAR QUE UN BUCLE SEA INFINITO:\n") import math #Sirve para importar una clase con todos sus métodos y/o funciones. Siempre se pone al ppio del código. Es necesario para poder hacer algunas cosas print("Programa de cálculo de raíz cuadrada") num=int(input("Introduce un número: ")) intentos=0 while num<0: print("Error. No existe la raíz cuadrada de un número negativo.") if intentos==4: print("Has agotado tus intentos. El programa se cerrara.") break; #Esta instrucción termina el bucle num=int(input("Introduce un número: ")) if num<0: intentos+=1 if intentos<2: solucion=math.sqrt(num) #Introdujimos la clase "math" y "sqrt"(square root/raíz cuadrada) print("La raíz cuadrada de ",num,"es",solucion)
import numpy as np data = np.load('monthdata.npz') #Each column in a month Jan-Dec of a particular year totals = data['totals'] #total precipitation in a year, jan-dec counts = data['counts'] #number of oberservations recorded in a given month # #print(totals) # print(counts) # 1) Which city had the lowest total precipitation over the year? sumtotal = np.sum(totals, axis=1) #print(sumtotal) minimum = np.argmin(sumtotal) print("Row with lowest total precipitation:\n", minimum) # 2) Determine the average precipitation in these locations for each month avg = np.divide(np.sum(totals, axis=0), np.sum(counts, axis=0)) print("Average precipitation in each month:") print(avg) # # 3) Average precipitation for each city avg = np.divide(np.sum(totals, axis=1), np.sum(counts, axis=1)) print("Average precipitation in each city:") print(avg) # # 4) Calculate the total precipitation for each quarter in each city totals_reshape_size = int((totals.size / 12) * 4) #print(totals_reshape_size) quarterly_totals = np.reshape(np.sum(np.reshape(np.ravel(totals), (totals_reshape_size,3)), axis=1), (int(totals_reshape_size / 4), 4)) print("Quarterly precipitation totals") print(quarterly_totals)
fname = input("Enter file name: ") count = 0 if len(fname) < 1 : fname = "mbox-short.txt" fn = open(fname) for line in fn: line = line.rstrip() if line.startswith('From:'):continue if line.startswith('From'): count+=1 spl = line.split() print(spl[1]) print("There were", count, "lines in the file with From as the first word")
while True: line = input('>') if line[0] == '#': continue #Возвращает обратнов начало if line == 'done': break #Если done то срабатывает брейк и работает последний принт print (line) print('Done!')
# -*- coding: utf-8 -*- """ Created on Wed May 5 20:34:59 2021 @author: siddh """ #https://www.techgig.com/codegladiators/dashboard problem 1 def comp(V,S): i,j=0,0 m=len(S) n=len(V) while j<m and i<n: if S[j]==V[i]: j=j+1 i=i+1 return j==m def main(): V=input() fi=[] for i in range(int(input())): s=input() if comp(V,s): fi.append("POSITIVE") else: fi.append("NEGATIVE") for k in fi: print(k) main()
# -*- coding: utf-8 -*- """ Created on Fri May 21 19:33:22 2021 @author: siddh """ #https://www.codechef.com/problems/LETSC001 def sieve(n): l=[True for _ in range(n+1)] l[0],l[1]=False,False for i in range(2,int(n**.5)+1): for j in range(2*i,n+1,i): l[j]=False return l.count(True) n=int(input()) print(sieve(n))
from typing import List class Index: def __init__(self, table, num_columns, primary_key_index: int): """ Args: num_columns: number of columns for users primary_key_index: which column is primary key Attributes: map_list: List of Dict Dict: key -> List[Rids] int to list mapping index created: boolean values for index that are created """ self.table = table self.num_features = num_columns self.index_created = [] for i in range(self.num_features): self.index_created.append(False) # Index is created for primary keys by default self.index_created[primary_key_index] = True self.map_list = [] self.primary_key_index = primary_key_index for i in range(self.num_features): self.map_list.append({}) return def map_insert(self, new_record): """ Args: new_record: new records we insert """ if len(new_record.columns) != self.num_features: raise ValueError('Index Error: "{}"'.format("Map Insert incompatible num columns")) base_rid = new_record.rid for feature_index in range(len(new_record.columns)): if self.index_created[feature_index] == False: continue new_key = new_record.columns[feature_index] if feature_index == self.primary_key_index: # if we're updating the primary key in our map if new_key in self.map_list[feature_index]: # And if new primary key is already in the primary key map raise ValueError("Cannot update to primary key", new_key, "that already exists!") else: # if new primary key isn't in primary key map at all self.map_list[feature_index][new_key] = [base_rid] else: # if we're not updating the primary key at all # first remove old key from rid list if new_key in self.map_list[feature_index]: # if in map, append new key to the rids list self.map_list[feature_index][new_key].append(base_rid) else: # initialize a list of rid(s) to current map and store the base rid self.map_list[feature_index][new_key] = [base_rid] return def map_change(self, base_rid, old_feature: List, new_feature: List): """ Args: old_feature: old_feature we query select before query update new_feature: new_feature we want to do query update to the table """ if len(old_feature) != self.num_features or len(new_feature) != self.num_features: print('Index Error: "{}"'.format("Map Insert incompatible num columns")) for feature_index in range(self.num_features): if self.index_created[feature_index] == False: continue old_key = old_feature[feature_index] new_key = new_feature[feature_index] if old_key not in self.map_list[feature_index]: raise ValueError('Index Error: old key not exist', old_key, 'new feature:', new_feature) if new_key is None or new_key == old_key: continue if feature_index == self.primary_key_index: # if we're updating the primary key in our map if new_key in self.map_list[feature_index]: # And if new primary key is already in the primary key map raise ValueError("Cannot update to primary key", new_key, "that already exists!") else: # if new primary key isn't in primary key map at all del self.map_list[feature_index][old_key] self.map_list[feature_index][new_key] = [base_rid] else: # if we're not updating the primary key at all # first remove old key from rid list self.map_list[feature_index][old_key].remove(base_rid) if new_key in self.map_list[feature_index]: # if in map, append new key to the rids list self.map_list[feature_index][new_key].append(base_rid) else: # initialize a list of rid(s) to current map and store the base rid self.map_list[feature_index][new_key] = [base_rid] return def map_delete(self, old_key): del self.map_list[self.primary_key_index][old_key] def locate(self, key: int, feature_index: int): if self.index_created[feature_index] == False: raise ValueError("Index hasn't been built for this column yet!") if key not in self.map_list[feature_index]: return None ans = self.map_list[feature_index][key] if len(ans) == 0: return None else: return ans def create_index(self, column_number): self.table.table_create_index(column_number) def drop_index(self, column_number): self.index_created[column_number] = False # Empty it out self.map_list[column_number] = {} return
class Rectangle: def __init__(self,length,width): self.L = length self.W = width def area(self): area = self.L * self.W return (area) def isSquare(self): if self.L == self.W: return True else: return False def main(): Squareish = Rectangle(200,20) print("The area of Squareish is",Squareish.area()) print("Squareish Length:",Squareish.L, "Squareish Width:", Squareish.W) if Squareish.isSquare() == True: print("Squareish is a Square") else: print("Squareish is not a Square") if __name__ == '__main__': main()
# -*- coding:utf-8 -*- """ @Author:gaopan @Time:2019/9/16-10:30 @Project:learn_test_develop @Purpose: 1.对phonebook_1改造 融合手机号查找和姓名查找 增加简单确认选择 对手机号非数字做容错 支持简单的模糊查找 """ class PhoneBook: def __init__(self): # self.phonebook = [{'name': 'a', 'phone': '1'}, {'name': 'b', 'phone': '1'}, {'name': 'a', 'phone': '2'}] self.phonebook = [] pass # 对于输入手机号提供一个容错 def input_phone(self, msg): phone = input(msg) try: int(phone) return phone except ValueError: print("输入的手机号含非数字") return None # 输入函数 def input_data(self): name = input("输入姓名:") phone = self.input_phone(msg="输入电话:") # 用dict来存储单条数据 if name and phone: data = {'name': name, 'phone': phone} return data else: return None # 实现添加联系人 def add_data(self): data = self.input_data() if data is None: print("数据有误") else: self.phonebook.append(data) print("数据存储成功") # 通过姓名或手机号查找信息 def query_data(self): query_list = [] query = input("输入姓名或手机号:") for info in self.phonebook: # in支持简单的模糊查询,==不支持 if query == info['name'] or query == info['phone']: # if query in info['name'] or query in info['phone']: query_list.append(info) print(info) if len(query_list) == 0: print("不好意思,没有数据") return query, None return query, query_list # 姓名或手机号维度删除用户 def delete_data(self): query, data = self.query_data() if data is None: print("通讯录没有数据:%s" % query) return for info in data: option = input("是否确认删除,Y or N:") if option == 'Y': self.phonebook.remove(info) print("成功删除信息:%s" % str(info)) elif option == 'N': print("不删除这条信息:%s" % str(info)) else: print("输入有误,跳过这条信息") # 修改姓名或手机号 def modify_data(self): query, data = self.query_data() if data is None: print("通讯录没有数据:%s" % query) return for info in data: if query == info['name']: print("用户%s的原有手机号:" % query + info['phone']) phone_modify = self.input_phone(msg="输入修改后的手机号:") if phone_modify is None: continue data_modify = {'name': query, 'phone': phone_modify} option = input("是否确认修改,Y or N:") if option == 'Y': self.phonebook.remove(info) self.phonebook.append(data_modify) print("修改后的数据是:" + str(data_modify)) elif option == 'N': print("不修改这条信息:%s" % str(info)) else: print("输入有误,跳过这条信息") elif query == info['phone']: print("手机号%s原有姓名:" % query + info['name']) name_modify = input("输入修改后名字:") data_modify = {'name': name_modify, 'phone': query} option = input("是否确认修改,Y or N:") if option == 'Y': self.phonebook.remove(info) self.phonebook.append(data_modify) print("修改后的数据是:" + str(data_modify)) elif option == 'N': print("不修改这条信息:%s" % str(info)) else: print("输入有误,跳过这条信息") if __name__ == '__main__': """ 实现通讯录功能,包含增删改查. 1.增加 2.删除 3.修改 4.查找 5.退出 """ book = PhoneBook() while True: print("1.增加;2.删除;3.修改;4.查找;5.退出") number = input("请输入需要的操作代号:") if number == '1': print("增加操作") book.add_data() elif number == '2': print("删除操作") book.delete_data() elif number == '3': print("修改操作") book.modify_data() elif number == '4': print("查找操作") book.query_data() elif number == '5': print("退出程序") exit() else: print("输入错误")
a=int(input("sizze?")) b=1 for i in range(a): for j in range(b): print("*", end =" ") print("\n") if b<=a: b=b+1
numbers = [1, 5, 3, -1, 2] def max(numbers): nowmax=numbers[0] for i in range(len(numbers)): if nowmax<numbers[i]: nowmax=numbers[i] index=i return nowmax,i max_number = max(numbers) print(max_number) numbers = [123, 100, 345, 200, 5, 500] def num(numbers): new=list(range(len(numbers))) print(new) for i in range(len(new)): new[i]=0 nulls=0 for i in range(len(numbers)): if numbers[i]%100==0: new[i]=numbers[i] else: nulls=nulls+1 for i in range(nulls): new.remove(0) return new print(num(numbers)) numbers = [1, 5, 3, -1, 2] print(numbers[0]) print(numbers[2]) print(numbers[-1]) numbers = [1, 0, 3, 5, 0, 2] numbers.remove(numbers[1]) numbers.remove(numbers[3]) print(numbers) """Код, за премахване на нулите""" def nozeros(numbers): nulls=0 for i in range(len(numbers)): if numbers[i]==0: nulls=nulls+1; for i in range(nulls): numbers.remove(o) return numbers text = 'ab m' def has_spaces(text): if ' ' in text: print(True) else: print(False) has_spaces(text) n = 5 def make_dashed_sttring(n): print(n * "-") make_dashed_sttring(n) text = "xyz1pq2" c = '0123456789' def digits_count(text,c ): a=0 for item in text: if item in c: a = a + 1 return print(a) digits_count(text,c) text='my text' vowels='eyuioa' def first_vowel_index(text,vowels): for i in range(len(text)): for j in range(len(vowels)): if text[i]==vowels[j]: return i print(first_vowel_index(text,vowels)) def word_count(text): spaces=0 for i in range(len(text)): if text[i]== ' ': spaces=spaces+1 return spaces+1 print(word_count(text)) def vowels_to_upper(text,vowels): new=list(range(len(text))) for i in range(len(text)): new[i]=0 for i in range(len(new)): for j in range(len(vowels)): if text[i]==vowels[j]: new[i]=1 for i in range(len(new)): if new[i]!=1: new[i]=text[i] else: new[i]=text[i].upper() new="".join(new) return new print(vowels_to_upper(text,vowels)) num=[[1, 2, 3],[3, 2, 1]] def ones_count(numbers): ones=0 for i in range(len(num)): for j in range(len(num[i])): if num[i][j]==1: ones=ones+1 return ones print(ones_count(num)) def same_case(letter1, letter2): if letter1.upper==letter1 and letter2.upper==letter2: return print(True) elif letter1.upper!=letter1 and letter2.upper!=letter2: return(print(True)) else: return print(False) same_case("A", "B") not same_case("A", "a") def equal_no_case(letter1, letter2): if letter1.upper()==letter2.upper(): print(True) else: print(False) equal_no_case("A", "a") not equal_no_case("A", "B")
import re class IgnoreList: def ignoreDict(il): with open(r"ignoreList.txt", "r", encoding="utf-8") as fp: contain = fp.readline() while contain: qwe = contain.replace('_'," ") b = re.findall(r"\w+", qwe) il.extend(b) contain = fp.readline() fp.close() finalIL = [] for x in il: y = x.lower() finalIL.append(y) return finalIL def ignoreWord(word, finalIL): if (not(word in finalIL)): return word ''' To be put in main.py if we want to use ignoreList: Matthew while True: try: response = int(input("\nDo you want to ignore any word?:\n (Yes/1, No/2)\n")) if response == 1: fp = open(r"ignoreList.txt", "w", encoding="utf-8") fp.write(input("\nPlease input words you don't want\nPut a space between each word.\n")) fp.close() break elif response == 2: fp = open(r"ignoreList.txt", "w", encoding="utf-8") fp.write("") fp.close() break else: print("\nPlease input 1 or 2 for the ignore list.") except ValueError: print("\nPlease input 1 or 2 for the ignore list.") '''
# N disk are placed on tower A in decesing order from bottom and we have to move all these disk to Tower C in same oder as in A. def TowerOfHanoi(n , from_rod, to_rod, aux_rod): if n == 1: print "Move disk 1 from rod",from_rod,"to rod",to_rod return TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) print "Move disk",n,"from rod",from_rod,"to rod",to_rod TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) n = 4 TowerOfHanoi(n, "A","B","C")
list2 =[1,2,5,7,9,11,25,67,77,89,94,101] num = int(input("Enter the number to be searched:")) n = len(list2) min =0 max =n-1 for i in range(n): avg = (min + max)//2 if num == list2[max] : print("Number found at : ",max) break elif num == list2[min] : print("Number found ",min) break elif num == list2[avg]: print("number found ",avg) break elif num > list2[avg] : min = avg elif num <list2[avg] : max = avg else : print("Nmuber not found ")
class node : def __init__(self,key): self.data = key self.left = None self.right = None def insert(self,key): if self.data : if key < self.data : if self.left is None: self.left = node(key) else: self.left.insert(key) elif key > self.data : if self.right is None: self.right= node(key) else : self.right.insert(key) else : self.data = key def inorder(self): if self.left : self.left.inorder() print(self.data) if self.right : self.right.inorder() def preorder(self): print(self.data) if self.left : self.left.preorder() if self.right: self.right.preorder() def postorder(self): if self.left : self.left.postorder() if self.right : self.right.postorder() print(self.data) def find(self , key ): if key == self.data : return True elif key < self.data : if self.left is None: return False return self.left.find(key) elif key > self.data : if self.right is None: return False else : return self.right.find(key) def levelorder(self): h =self.height(root) for i in range(1,h+1 ): self.levelorderatthatlevel(root, i) def levelorderatthatlevel(self,root,level): if root is None: return elif level ==1 : print(root.data) else : self.levelorderatthatlevel(root.left,level-1) self.levelorderatthatlevel(root.right,level-1) def height(self,node): if node is None: return 0 else : lheight =self.height(node.left) rheight =self.height(node.right) if lheight > rheight: return lheight + 1 else : return rheight + 1 def levelorderusingqueue(self,node ): if node is None: return queue=[] queue.append(node) while (len(queue) > 0 ): print(queue[0].data) temp_node = queue[0] if temp_node.left is not None: queue.append(temp_node.left) if temp_node.right is not None: queue.append(temp_node.right) temp_node = queue.pop(0) def count(self): if self is None: return 0 else : return 1 + self.left.count() + self.rigth.count() def maxval(self,root): if root is None: return -1 else : return max (root.data , max(self.maxval(root.left),self.maxval(root.right))) def childrensum(self,root): if root is None : return True if root is not None and root.left is None and root.right is None : return True sum = 0 if root.left : sum = sum + root.left.data if root.right : sum = sum + root.right.data return (sum == root.data and childrensum(root.left) and childrensum(root.right)) def findpath(self,root,key,path): if root is None : return False path.append(root) if root.data == key : return True if self.findpath(root.left,key,path) or self.findpath(root.right,key,path): return True path.pop() return False def LCA(self,root,n1 ,n2 ): path1 =[] path2 =[] if self.findpath(root,n1,path1) or self.findpath(root,n2,path2): return None i =0 while i < len(path1) or i < len(path2): if path1[i+1] != path2[i+1]: return path1[i] return None def minval(self,root): current = root while current.left is not None: current = current.left return current def deletenode(self,root,val): if root is None: return root # to find the root to be deleted if val > root.data : self.deletenode(root.right,val) return root elif val < root.data : self.deletenode(root.left,val) return root #after we found the node else : # if node has only 1 child if root.left is None: temp = root.right del root return temp elif root.right is None : temp = root.left del root return temp # if node has 2 child temp = self.minval(root.right) root.data = temp.data root.right = self.deletenode(root.right , temp.data) return root root = node(12) root.insert(6) root.insert(14) root.insert(3) root.insert(5) root.insert(4) #root.preorder() ''' print('preorder') root.preorder() print('postorder ') root.postorder() print('inorder') root.inorder() print(root.find(12)) print(root.find(42)) print(root.find(14)) print(root.find(3))''' #root.levelorder() #root.levelorderusingqueue(root) print(root.count()) #print(root.maxval(root)) #print(root.height(root)) #print(root.childrensum(root)) #Not applicable for this type of tree . so always false . change insertion operation for this to work # print(root.LCA(root,3,4)) # something's wrong #root.deletenode(root,5) #not working againnnnnnnnnnn #root.levelorderusingqueue(root)
balance = float(input("Enter your balance")) withdrawal = 500 class MyError(Exception): def __init__(self,val): self.val = val try: if balance > withdrawal: print(balance - withdrawal) else : #raise NameError raise MyError("bad") except NameError: print("Insuffecient Balance") finally: print("ALWAYS INPUT WITHDRAW MONEY LESS THAN CURRENT BALANCE ")
#mouse click events ...left click , right click and middle click all will trigger different events from tkinter import * root = Tk(className='click window ') def leftclick(event): print("LEFT ") def rightclick(event): print("RIGHT ") def click(event): print("CENTER ") frame = Frame(root,width =300,height = 250 ) frame.bind("<Button-1>",leftclick) frame.bind("<Button-2>",rightclick) frame.bind("<Button-3>",click) frame.pack() #button1 = Button(root,text = "CLICK") root.mainloop()
from tkinter import * root = Tk(className='click window ') one = Label(root,text ="Enter your name" , bg = 'red',fg = 'white') #one.pack() one.grid(row =0 ,column = 0) one = Label(root,text ="HELLO UNKNOWN" , bg = 'red',fg = 'white') #one.pack() one.grid(row =1 ,column = 1) #lets create entry box Tk() name = StringVar() user_entry = Entry(root,width = 24,textvariable = name) user_entry.grid(row =0 ,column = 1) #user_entry.pack(side = LEFT) name = Tk.StringVar() root.mainloop()
#we have to find the number of distinct common element between 2 arrays assuming the first array has larger length a = [10,5,20,15,30,30,5] b=[30,5,80,15,30] count = 0 for i in range(len(a)): flag =True for j in range(i-1,-1,-1): if a[j] == a[i]: flag = False break if flag == True: for j in range(len(b)): if a[i] == b[j]: count = count + 1 break print(count)
# codes from practice on trees on geeks for geeks #Determine if Two Trees are Identical Method 1 - compare inorder/preorder/postorder/level order of both trees if same both trees are identical def inorder(root,queue): if root is None : return else : inorder(root.left,queue) queue.append(root.data) inorder(root.right,queue) return queue def isIdentical(root1, root2): # Code here if root1 is None and root2 is None : return True q1 =[ ] q1 = inorder(root1,q1) q2 = [ ] q2 = inorder(root2, q2 ) n =len(q1) count = 0 if len(q1) == len(q2): for i in range(0,n): if q1[i] == q2[i] : count = count + 1 if count == n : return True else : return False else : return False #method 2 def isIdentical(root1, root2): if (root1==None and root2==None): return True elif (root1!=None and root2!=None): return (root1.data==root2.data and isIdentical(root1.left,root2.left) and isIdentical(root1.right,root2.right)) else: return False # to count numbers of leaf node in a tree def countLeaves(root): # Code here if root is None : return q =[] count = 0 q.append(root) while len(q) > 0: temp = q[0] if temp.left is None and temp.right is None: count = count + 1 if temp.left is not None : q.append(temp.left) if temp.right is not None : q.append(temp.right) q.pop(0) return count # to find if a tree is balanced or not def height(root): if root is None : return 0 else : lh = height(root.left) rh = height(root.right) if lh > rh : return 1 + lh else : return 1 + rh def isBalanced(root): #add code here if root is None : return True l= height(root.left) r = height(root.right) return (abs(l-r) <= 1) and isBalanced(root.left ) and isBalanced(root.right) # diameter of binary tree - efficient method def height(root, ans): if (root == None): return 0 left_height = height(root.left, ans) right_height = height(root.right, ans) # update the answer, because diameter # of a tree is nothing but maximum # value of (left_height + right_height + 1) # for each node ans[0] = max(ans[0], 1 + left_height + right_height) return 1 + max(left_height, right_height) def diameter(root): # Code here if (root == None): return 0 ans =[0] # This will store # the final answer height_of_tree = height(root, ans) return ans[0] # sum of leaf node def sumLeaf(root): ''' :param root: root of given tree. :return: sum of leaf nodes ''' # code here if root is None: return 0 if (root.left is None and root.right is None): return root.data return sumLeaf(root.left)+ sumLeaf(root.right)
#left rotate by 1 def rotateby1(arr): temp = arr[0] for i in range(1,len(arr)): arr[i-1] = arr[i] arr[len(arr) -1 ] = temp return arr l1 = [1,2,3,4,5] #print(rotateby1(l1)) # rotate by d using rotate by 1 def rotatebyd(arr,d): for i in range(0,d): rotateby1(arr) return arr # print(rotatebyd(l1,3)) # rotate by d - METHOD 2 ,her we copy first d elements in array and move elements of the array by d position def rotatebyd2(arr,d): l2 = [] index = 0 for i in range(0,d): l2.append(arr[i]) for i in range(d, len(arr)): arr[i-d] = arr[i] for i in range(len(arr)- d , len(arr)): arr[i] = l2[index] index = index +1 return arr #print(rotatebyd2(l1,3)) #METHOD 3 using reversal algo def rotateleft(arr,n,d): reverse(arr,0,d-1) reverse(arr,d,n-1) reverse(arr,0,n-1) return arr def reverse(arr,low,high): while(low < high ): arr[low],arr[high] = arr[high],arr[low] low = low + 1 high = high +1 print(rotateleft(l1,len(l1),3))
#try except finallly a = int(input("Enter the 1st number:")) b = int(input("Enter the 2nd number:")) try : print(a/b) except Exception as e : print("Error --" ,e) finally: print("Job done ")
#!/bin/python3 import math import os import random import re import sys # Complete the minimumNumber function below. def minimumNumber(n, password): # Return the minimum number of characters to make the password strong numbers = "0123456789" lower_case = "abcdefghijklmnopqrstuvwxyz" upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" special_characters = "!@#$%^&*()-+" special=0 lower=0 upper=0 num=0 for i in password: if i in lower_case: lower+=1 elif i in upper_case: upper+=1 elif i in special_characters: special+=1 elif i in numbers: num+=1 strong=[special,lower,upper,num] present=0 for j in strong: if j>0: present+=1 if n>=6: if present==4: ans=0 else: ans=4-present else: if present==4: ans=6-n else: ans=max(4-present,6-n) return ans if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) password = input() answer = minimumNumber(n, password) fptr.write(str(answer) + '\n') fptr.close()
#!/bin/python3 import math import os import random import re import sys # # Complete the 'equalStacks' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER_ARRAY h1 # 2. INTEGER_ARRAY h2 # 3. INTEGER_ARRAY h3 # def equalStacks(h1, h2, h3): # Write your code here sum1=sum(h1) sum2=sum(h2) sum3=sum(h3) while True: if not h1 or not h2 or not h3: return 0 if sum1==sum2 and sum2==sum3: return sum1 if sum1>=sum2 and sum1>=sum3: sum1-=h1.pop(0) elif sum2>=sum1 and sum2>=sum3: sum2-=h2.pop(0) elif sum3>=sum1 and sum3>=sum2: sum3-=h3.pop(0) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') first_multiple_input = input().rstrip().split() n1 = int(first_multiple_input[0]) n2 = int(first_multiple_input[1]) n3 = int(first_multiple_input[2]) h1 = list(map(int, input().rstrip().split())) h2 = list(map(int, input().rstrip().split())) h3 = list(map(int, input().rstrip().split())) result = equalStacks(h1, h2, h3) fptr.write(str(result) + '\n') fptr.close()
#!/bin/python3 import math import os import random import re import sys # # Complete the 'decentNumber' function below. # # The function accepts INTEGER n as parameter. # def decentNumber(n): # Write your code here if n%3==0: print('5'*n) else: a=0 while a<n+1: if (n-a)%3==0 and a%5==0: break else: a+=1 if (n-a)%3==0 and a%5==0: print('5'*(n-a)+'3'*a) else: print(-1) if __name__ == '__main__': t = int(input().strip()) for t_itr in range(t): n = int(input().strip()) decentNumber(n)
#!/bin/python3 import os import sys # Complete the solve function below. def solve(n): #we need to check if n=(m(m+1))//2 --> m^2 + m - 2n = 0 for some natural no. m # m = (-b+-(D^0.5))/2a D=1+(8*n) m=(-1+(D**0.5))/2 ans='Better Luck Next Time' if m==int(m): ans='Go On Bob '+str(int(m)) return ans if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): n = int(input()) result = solve(n) fptr.write(result + '\n') fptr.close()
#!/bin/python3 import math import os import random import re import sys # # Complete the 'extraLongFactorials' function below. # # The function accepts INTEGER n as parameter. # def extraLongFactorials(n): # Write your code here ans=1 for i in range(2,n+1): ans*=i print(ans) if __name__ == '__main__': n = int(input().strip()) extraLongFactorials(n)
# Enter your code here. Read input from STDIN. Print output to STDOUT t=int(input()) a=[] for i in range(t): b=[] b=list(map(str, input().split())) a.append(b) for x in range(len(a)): try: print(int(a[x][0])//int(a[x][1])) except ZeroDivisionError: print ("Error Code: integer division or modulo by zero") except ValueError as e: print ("Error Code:", e)
#!/bin/python3 import math import os import random import re import sys from collections import Counter # # Complete the 'pickingNumbers' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY a as parameter. # def pickingNumbers(a): # Write your code here ans=0 freqDict=Counter(a) item=freqDict.items() for key,value in item: if key-1 in freqDict: ans=max(ans,value+freqDict[key-1]) else: ans=max(ans,value) return ans if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) a = list(map(int, input().rstrip().split())) result = pickingNumbers(a) fptr.write(str(result) + '\n') fptr.close()
# Enter your code here. Read input from STDIN. Print output to STDOUT n=int(input()) ans=0 for i in range(n): ans+=int(input()) print(str(ans)[:10])
#!/bin/python3 import math import os import random import re import sys # # Complete the 'funnyString' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # def funnyString(s): # Write your code here normal=[ord(i) for i in s] diff=[abs(normal[j]-normal[j-1]) for j in range(1,len(normal))] if diff==diff[::-1]: return 'Funny' else: return 'Not Funny' if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') q = int(input().strip()) for q_itr in range(q): s = input() result = funnyString(s) fptr.write(result + '\n') fptr.close()
#!/bin/python3 import math import os import random import re import sys # # Complete the 'encryption' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # def encryption(s): # Write your code here s=s.replace(' ','') row=math.floor(len(s)**0.5) col=math.ceil(len(s)**0.5) ans='' for i in range(col): a='' for j in range(i,len(s),col): a+=s[j] ans+=a+' ' return ans if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = encryption(s) fptr.write(result + '\n') fptr.close()
#!/bin/python3 import math import os import random import re import sys # Complete the miniMaxSum function below. def miniMaxSum(arr): arr.sort() minimum=sum(arr[0:4]) maximum=sum(arr[1:5]) ans=[] ans.append(str(minimum)) ans.append(str(maximum)) print(' '.join(ans)) if __name__ == '__main__': arr = list(map(int, input().rstrip().split())) miniMaxSum(arr)
# Enter your code here. Read input from STDIN. Print output to STDOUT n=int(input()) arr=list(map(int,input().split())) if all(i>0 for i in arr): if any(str(i)==str(i)[::-1] for i in arr): print('True') else: print('False') else: print('False')
#Variables and data types i = 20 print(type(i)) j="Hello" print(type(j)) x,y,z = 8, 12.4 , 'hello' print(type(x),type(y),type(z)) a = b = c = "Orange" print(a) print(b) print(c) x = "awesome" print("Python is " + x) #A variable name must start with a letter or the underscore character #A variable name cannot start with a number #A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) #Variable names are case-sensitive (age, Age and AGE are three different variables)
#Loops #FOR #Includes 2, excludes 6 for x in range(2, 6): print(x) #Step value for x in range(2, 10, 2): print(x) #Looping through each letter of a string for x in "banana": print(x) #Break fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break #Continue fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) #WHILE i = 1 while i < 6: print(i) i += 1 #break and continue in while too
#1. Dadas as variáveis: Planeta = "Terra" Diametro = 12742 #Use format() para printar a seguinte frase: #O diâmetro da terra é de 12742 kilômetros. print('O diâmetro da {} é de {} kilômetros. '.format(Planeta, Diametro))
""" Find The Percentage The provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a list of students. Print the average of the marks array for the student name provided, showing 2 places after the decimal. """ if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): line = input().split() name, scores = line[0], line[1:] scores = map(float, scores) student_marks[name] = scores query_name = input() mark=list(student_marks[query_name]) c=0 s=0 for i in mark: c+=1 s=s+i avg=s/c print("{:.2f}".format(avg))
print("hello") print("Saya sedang belajar python") a = 8 b = 6 print("variable a = ", a) print("variable b = ", b) print("Hasil penjumlahan a+b = ", a+b) a = (input("masukan nilai a : ")) b = (input("masukan nilai b : ")) print("variable a = ", a) print("variable b = ", b) print("Hasil penggabungan {0}&{1}=%s".format(a, b) % (a+b)) # konversi nilai variable a = int(a) b = int(b) print("hasil penjumlahan {0}+{1}=%d".format(a, b) % (a+b)) print("hasil pembagian {0}/{1}=%f".format(a, b) % (a/b))
from itertools import count from functools import reduce def trees_on_slope(tree_map, slope): height, width = len(tree_map), len(tree_map[0]) x_coord_cnt, y_coords = count(0, slope[0]), range(0, height, slope[1]) xy_coords = map(lambda y: (next(x_coord_cnt) % width, y), y_coords) return sum(map(lambda xy: tree_map[xy[1]][xy[0]] == '#', xy_coords)) def main(): with open('input') as f: lines = f.read().splitlines() tree_map = lines slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] part_one = trees_on_slope(tree_map, slopes[1]) part_two = map(lambda s: trees_on_slope(tree_map, s), slopes) part_two = reduce(lambda x, y: x*y, part_two) print("--- Part One ---", part_one, sep='\n') print("--- Part Two ---", part_two, sep='\n') if __name__ == "__main__": main()
a = input('Введите массив\n') squares = set() # Функция form из исходной строки с числами заданного массива # формирует матрицу смежности являющуюся входными данными # для задачи поиска гамильтонова пути def form(stroka): b = list() for i in stroka.split(): b.append(int(i)) b.sort() # squares = list() squares = {i ** 2 for i in range(1, int((2 * b[len(b) - 1] - 1) ** 0.5) + 1)} matr = [[1 if i + j in squares and i != j else 0 for j in b] for i in b] print(b) print(squares) print(len(b)) for i in range(len(b)): print(matr[i]) return matr form(a)
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: objvar.py class Person: '''Represents a person.''' # 这是类的变量 print "gexing class set" population = 0 # 构造函数 def __init__(self, name): '''Initializes the person's data.''' #类的文档字符串 import ipdb; ipdb.set_trace() print "gexing, init set" # 这里是self.name,所以这个name是对象的变量 self.name = name print '(Initializing %s)' % self.name # 构造函数使得类的变量population+1 Person.population += 1 # 析构函数 def __del__(self): import ipdb; ipdb.set_trace() '''I am dying.''' #方法的文档字符串 print "gexing, del set" print '%s says bye.' % self.name Person.population -= 1 if Person.population == 0: print 'I am the last one.' else: print 'There are still %d people left.' % Person.population def sayHi(self): import ipdb; ipdb.set_trace() '''Greeting by the person. Really, that's all it does.''' print 'Hi, my name is %s.' % self.name def howMany(self):#如果这个函数要调用本类的sayHi(self),需要操作self.sayHi() import ipdb; ipdb.set_trace() '''Prints the current population.''' if Person.population == 1: print 'I am the only person here.' else: print 'We have %d persons here.' % Person.population # 我们可以在运行时使用Person.__doc__和Person.sayHi.__doc__来分别访问类与方法的文档字符串。 import ipdb; ipdb.set_trace() swaroop = Person('Swaroop') swaroop.sayHi() swaroop.howMany() kalam = Person('Abdul Kalam') kalam.sayHi() kalam.howMany() swaroop.sayHi() swaroop.howMany()
'''Given a sqlite database file, will convert the database to a CSV file. Takes two command line arguments: 1) The path to the database file (Mandatory argument). 2) The path or name of a CSV file (optional). ''' # Standard modules import sys import sqlite3 # Non-standard modules import pandas.io.sql as sql __author__ = "Andrew Moore" __email__ = "[email protected]" # Reference: # http://stackoverflow.com/questions/17556450/sqlite3-python-export-from-sqlite-to-csv-text-file-does-not-exceed-20k if (len(sys.argv) != 2 and len(sys.argv) != 3): exception = """ The script takes 2 or 3 arguments:\n 1) The path to the database file (Mandatory argument)\n 2) The path or name of a CSV file (optional) """ raise Exception(exception) database_name = sys.argv[1] csv_file = sys.argv[2] if len(sys.argv) > 2 else 'output.csv' con = sqlite3.connect(database_name) table = sql.read_sql('select * from output', con) # make sure it is a CSV file csv_file_name = csv_file.split(".")[0] csv_file = csv_file_name + ".csv" table.to_csv(csv_file) con.close()
def spiralMatrixPrint(endRowIndex,endColIndex,matrix) : startRowIndex = 0 startColIndex = 0 while (startRowIndex < endRowIndex and startColIndex < endColIndex): for i in range (startColIndex,endColIndex+1): print(matrix[startRowIndex][i],end =' ') #print(" ") startRowIndex= startRowIndex +1 for i in range (startRowIndex,endRowIndex+1): print (matrix[i][endColIndex],end = ' ') #print (" ") endColIndex= endColIndex -1 for i in range (endColIndex,startColIndex-1,-1): print(matrix[endRowIndex][i],end =' ') endRowIndex= endRowIndex-1 for i in range (endRowIndex,startRowIndex-1,-1): print(matrix[i][startColIndex],end =' ') startColIndex+=1 matrix = [['a','b','c','d','e'],['f','g','h','i','j'],['k','l','m','n','o'],['p','q','r','s','t']] spiralMatrixPrint(3,4,matrix)
# A:Apple, Avocado # B : Banana, Berry def countElements(inpFruits): dict = {} maxCount=0 for ele in inpFruits: firstChar = ele[0:1] if firstChar in dict: dict[firstChar].append(ele) currentListCount= len(dict[firstChar]) if(currentListCount> maxCount): maxCount=currentListCount else: maxCount=1 dict[firstChar] = [ele] print(dict,maxCount) values = ["Apple", "Banana", "Berry"] countElements(values) def findElement(inpParameter,elementToBeSearched) : found = {} for element in inpParameter : found.setdefault(element,0) if elementToBeSearched in found.keys(): print (elementToBeSearched,"is present in given array",inpParameter) return True else : print(elementToBeSearched , "is not present in given array",inpParameter) return False value = 12,23,45 returnedValue=findElement(value,112) print("value returned by the function is:",returnedValue) returnedValue=findElement(value,12) print("value returned by the function is:",returnedValue) returnedValue=findElement(value,45) print("value returned by the function is:",returnedValue)
from histogram import * from sample import random_sentence from sentence_generator import markov, random_word def random_walk_sentence(): word_list = read_word_file('poemtest.txt') histogram = make_histogram(word_list) starting_word = random_word_frequency(histogram) markovv = markov(word_list) sentence_list = [] word = random_word(markovv, starting_word) sentence_list.append(word) for _ in range(7): word = random_word(markovv, word) sentence_list.append(word) sentence = [] s = ' '.join(sentence_list) s = s.capitalize() s += '.' return s if __name__ == "__main__": random_walk_sentence()
# shekhar r vanjarapu # # Program for an time counter # This program is an example for recurssion # n = input("Enter the no. of seconds you would like to countdown") def count_down(n): if n == 0: print "Blast Off!!!" else: print n count_down(n-1)
def problem3_3(month, day, year): """ Takes date of form mm/dd/yyyy and writes it in form June 17, 2016 Example3_3: problem3_3(6, 17, 2016) gives June 17, 2016 """ month_list=("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") month_input=int(month)-1 print(month_list[month_input], str(day) + ",", year)
import sqlite3 # DB 연결하기 dbpath = "test2.sqlite" conn = sqlite3.connect(dbpath) # 테이블 생성하기 cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS items") cur.execute("""CREATE TABLE items ( item_id INTEGER PRIMARY KEY, name TEXT, price INTEGER)""") conn.commit() # 데이터 넣기 cur = conn.cursor() cur.execute( "INSERT INTO items (name, price) VALUES (?, ?)", ("Orange", 5200)) conn.commit() # 데이터 연속으로 넣기 cur = conn.cursor() data = [("Mango", 7700), ("Kiwi", 4000), ("Grape", 8000), ("Peach", 9400), ("Persimon", 7000), ("Strawberry", 4000)] cur.executemany( "INSERT INTO items (name, price) VALUES (?, ?)", data ) conn.commit() # 4000~7000 사이의 데이터만 추출하기 cur = conn.cursor() price_range = (4000, 7000) cur.execute( "SELECT * FROM items WHERE price>=? AND price<=?", price_range) item_list = cur.fetchall() for item in item_list: print(item)
# cs212 ; Unit 2 ; 41 # -------------- # User Instructions # # Write a function, compile_word(word), that compiles a word # of UPPERCASE letters as numeric digits. For example: # compile_word('YOU') => '(1*U + 10*O +100*Y)' # Non-uppercase words should remain unchaged. def compile_word(word): """Compile a word of uppercase letters as numeric digits. E.g., compile_word('YOU') => '(1*U+10*O+100*Y)' Non-uppercase words unchanged: compile_word('+') => '+'""" # Your code here.
# cs215 ; Final Exam ; 5 # # Design and implement an algorithm that can preprocess a # graph and then answer the question "is x connected to y in the # graph" for any x and y in constant time Theta(1). # # # `process_graph` will be called only once on each graph. If you want, # you can store whatever information you need for `is_connected` in # global variables # def process_graph(G): # your code here pass # # When being graded, `is_connected` will be called # many times so this routine needs to be quick # def is_connected(i, j): # your code here pass ####### # Testing # def test(): G = {1:{2:1}, 2:{1:1}, 3:{4:1}, 4:{3:1}, 5:{}} process_graph(G) assert is_connected(1, 2) == True assert is_connected(1, 3) == False G = {1:{2:1, 3:1}, 2:{1:1}, 3:{4:1, 1:1}, 4:{3:1}, 5:{}} process_graph(G) assert is_connected(1, 2) == True assert is_connected(1, 3) == True assert is_connected(1, 5) == False
# cs215 ; Unit 1: A Social Network Magic Trick ; 15 # counting steps in naive as a function of a def naive(a, b): x = a y = b z = 0 while x > 0: z = z + y x = x - 1 return z def time(a): # The number of steps it takes to execute naive(a, b) # as a function of a steps = 0 # your code here return steps
# cs215 ; Unit 1: A Social Network Magic Trick ; 14 import math def time(n): """ Return the number of steps necessary to calculate `print countdown(n)`""" steps = 0 # YOUR CODE HERE return steps def countdown(x): y = 0 while x > 0: x = x - 5 y = y + 1 print y print countdown(50)
#!/usr/bin/env python3 import turtle import math def raute(size, winkel): turtle.right(winkel / 2.0) for w in [winkel, 180 - winkel, winkel, 180 - winkel / 2.0]: turtle.forward(size) turtle.left(w) def timmer_raute(n, size, winkel): for i in range(n): raute(size, winkel) turtle.right(winkel / 2.0) turtle.forward(size) turtle.left((180 + winkel) / 2.0) size *= math.tan(math.pi / 360 * winkel) turtle.speed(0) timmer_raute(40, 200, 87) turtle.done()
import definitions import random #api example sine = definitions.trig["functions"]["sine"]["name"] def triviaChoice(triv): ''' Randomly generates and returns a random piece of data. :type triv: string :param triv: key used to access data interface subject of choice ''' subject = definitions.trig[triv] fieldList = subject["fieldList"] subFieldList = subject["subFieldList"] #Offset the length by 3 to make intended fields inaccessible optNum = len(subject) - 3 fieldPick = random.randint(0,optNum) field = subject[ fieldList[ fieldPick ]] if len(subFieldList) > 1: subNum = len(subFieldList) - 1 else: subNum = 0 subNum = random.randint(0,subNum) #rNum = random.randint(0,optNum) print(subNum) #print(subFieldList) #print(field) subFieldPick = subNum subField = field[ subFieldList[ subFieldPick ]] return subField def main(): choice = triviaChoice("angles") #choice = definitions.trig["angles"] print(choice) return if __name__ == "__main__": main()