text
stringlengths
5
121k
def ugly_qsort(seq): if not seq: return [] pivot = seq[0] lesser = ugly_qsort([x for x in seq[1:] if x < pivot]) greater = ugly_qsort([x for x in seq[1:] if x >= pivot]) return lesser + [pivot] + greater
class Solution(object): def fractionToDecimal(self, numerator, denominator): """ :type numerator: int :type denominator: int :rtype: str """ string_buffer = [] if numerator == 0: return "0" if (numerator < 0) ^ (denominator < 0): ...
import json class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if not root: ...
class Solution(object): def addOneRow(self, root, val, depth): """ :type root: TreeNode :type val: int :type depth: int :rtype: TreeNode """ if depth == 1: return TreeNode(val, left=root) queue = [root] while depth > 2: ...
from operator import attrgetter class Solution(object): def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ intervals.sort(key=attrgetter('start')) res = [] if not intervals: return res res.appen...
def findwidth(n,h): sum1=0 i=0 while i<len(n): if(n[i]>h): sum1 = sum1+2 else: sum1 = sum1+1 i=i+1 return sum1 t = input() t = list(map(int ,t.split(" "))) li = input() li = list(map(int,li.split(" "))) print(findwidth(li,t[1]))...
def spell(n): return sum(list(map(int,n))) n = (input()) count=0 while len((n))!=1: count =count+1 n=str(spell(n)) print(count)
from tensorflow.examples.tutorials.mnist import input_data from scipy.io import loadmat import numpy as np trainfile = "datasets/housenumbers/train_32x32.mat" trainset = loadmat(trainfile) X = trainset['X'] y = trainset['y'] print(X.shape) print(y.shape) yvec = np.zeros((y.shape[0], len(np.unique(y)))) yvec[np.ar...
__author__ = 'wangzhenhao' class List: def __init__(self): self.l = [] def append(self, x): self.l.append(x) def insert(self, i, x): self.l.insert(i, x) def pop(self): return self.l.pop() def __str__(self): return str(self.l) def empty(self): ...
__author__ = 'wangzhenhao' def hanoi(a='A', b='B', c='C', n=1): if n < 1: pass elif n == 1: print(a + ' -> ' + c) else: hanoi(a, c, b, n - 1) print(a + ' -> ' + c) hanoi(b, a, c, n - 1)
tasa = 0.05 saldo = 500000 pagoMensual = 2684.11 totalPagado = 0.0 mes = 0 pagoExtra = 1000 while mes < 12: saldo = saldo * (1+ tasa/12) - pagoMensual -pagoExtra totalPagado = pagoMensual + totalPagado + pagoExtra mes = mes + 1 print(f'Total Pagado: ${round(totalPagado, 2)} en el mes: {...
cadena = "Ejemplo con for" for c in cadena: f= cadena.split() a= f[-1:] print('caracter:', c, a)
data=""" 1.Forward indexing --->0 1 2 3 4 5 length 2.backward indexing(or)negative indexing -1 -2 -3 -4 -5 -6 length of the string a="good afternoon all" """ '''l=[1,22,36,25,663,265,145,2567,36] output=[] count=0 for i in l: if len(str(i))==2: output.append(i) count+=1 avg=sum(output)/count ...
fruits=["banana","apple","peach","pear"] print(fruits[0]) print(fruits[3]) print("now reprinting all fruits") for fruit in fruits: print(fruit) print("now reprinting all fruits in reverse") fruits.reverse() for fruit in fruits: print(fruit) print("now printing fruits in alphabetical order") fruits.sort() ...
print("How old are you ?", end =' ') age = input() print("How tall are you?", end =' ') height = input() print("What do you like?", end=' ') like = input() print(f'you are {age} years old, {height} cm tall and you like {like} ')
def pos_neg(n): """Prints whether int n is positive, negative, or zero.""" if n < 0: print("Your number is Negative... But you already knew that.") elif n > 0: print("Your number is super positive! How nice.") else: print("Zero? Really? How boring.") my_num = int(input("Ente...
for x in range(1,11): for y in range(1,11): z = x * y print(z, end="\t") print()
def IsPalindrome(s): for k in range(len(s) // 2): if (s[k] != s[-k -1]): return False return True Suma = 0 for n in range(1, 1000000): b = str(bin(n))[2:] if IsPalindrome(b) and IsPalindrome(str(n)): Suma += n print(n, b) print('ANSWER: ', Suma)
def Fib(): f0 = 1 yield f0 f1 = 1 yield f1 while True: f0, f1 = f1, f1 + f0 yield f1 def IsPandigital(s): return set(s) == set('123456789') n = 0 for f in Fib(): n += 1 s = str(f) if IsPandigital(s[-9:]): print...
import math def IsPrime(n): for k in range(2, int(math.sqrt(n)) + 1): if n % k == 0: return False return True Count = 0 for n in range(2, 1000000): s = str(n) AllPrimes = True for k in range(len(s)): if not IsPrime(int(s)): AllPrimes = False ...
import math def IsPrime(n): if (n == 1): return False for k in range(2, int(math.sqrt(n)) + 1): if n % k == 0: return False return True Acum = 0 limit = 11 n = 11 while True: s = str(n) AllPrimes = True for k in range(len(s)): r = s[k:] l...
import math from itertools import permutations as p def IsPrime(n): for k in range(2, int(math.sqrt(n)) + 1): if n % k == 0: return False return True Ans = 0 for k in range(9, 2, -1): l = [(x + 1) for x in range(k)] P = p(l) ll = list(P) ll.sort(reverse=True) ...
""" Created on Mon Apr 8 15:53:04 2019 @author: ttc """ try: items = ['a', 'b'] third = items[2] print("This won't print") except IndexError: print("Index out of bound") print("continuing") try: x = 5 y = x/0 print("This won't print, either") except IndexError: print("Division ...
import time def fibo(num): if num ==1 or num ==2: return 1 else: return fibo(num-1) + fibo(num-2) def iterfibo(num): if num == 0: return 0 elif num == 1: return 1 else: a,b = 1,1 for i in range(num-1): a,b = b,a+b return a nbr...
import pygame from pygame.sprite import Sprite class Bullet(Sprite): def __init__(self, game): """Class for single bullet.""" super().__init__() self.screen = game.screen self.settings = game.settings self.color = self.settings.bullet_color self.speed =...
import json class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead. """ nums1_copy = nums1[:...
import json class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ max_area = 0 iterations = 0 i = 0 j = len(height)-1 while i != j: iterations +=1 print("---") print...
class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """ result = [] if len(s) == None: return result def backtrack(s,temp ,start): def palindrome(s,l,r): if l ==r: ...
import turtle t = turtle.Turtle() t.shape('classic') n1 = int(turtle.textinput('입력창', '변1: ')) n2 = int(turtle.textinput('입력창', '변2: ')) n3 = int(turtle.textinput('입력창', '변3: ')) if (n3*n3) == (n2*n2) + (n1 * n1): t.forward(n1*100) t.left(90) t.forward(n2*100) t.home() else: t.write('...
from tkinter import * top = Tk() top.title("Oval을 이용한 그림판") penc = "blue" def paint(event): x1, y1 = (event.x - 1 ), (event.y -1) x2, y2 = (event.x + 1), (event.y + 1) cnvs.create_oval( x1, y1, x2,y2, outline=penc, fill=penc) def redColor(): global penc penc = "red" def greenColor(): global ...
from tkinter import * top = Tk() top.title("체크박스") def result(): result = "" if int(chk1c.get()): result += "체크박스1 " if int(chk2c.get()): result += "체크박스2 " if int(chk3c.get()): result += "체크박스3 " print(result) lb1['text'] = result chk1c = IntVar() chk2c = IntVar() chk...
import os import csv poll_csv = os.path.join('Resources', 'election_data.csv') votes = [] candidates = [] occurance = [] percentage =[] with open(poll_csv, 'r') as csvfile: poll_txt = os.path.join('election_results.txt') with open(poll_txt, 'w') as datafile: csvreader = csv.reader(csvfile, de...
class priority_queue: def __init__(self, priority='cost'): self.queue = [] self.__size = 0 self.priority = priority def __sorting_agl(self, item): return item[self.priority] def __sort(self): self.queue.sort(key=self.__sorting_agl) def __change_size(self, beta)...
from utils.Node import infinity from utils.Tree import tree_for_adv_search def alpha_beta_pruning(tree): v = max_value(tree, -infinity, infinity) return v def max_value(node, alpha, beta): if node.is_leaf(): return node.value v = - infinity for child in node.children: v = max(...
from ciphers import Cipher class Keyword(Cipher): def __init__(self): self.plaintext = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 ' def encrypt(self, text, cipher_pad): """ Accepts an alphanumerical string object (text) and an alphanumerical string object (cipher_pad) as arguments...
from math import log2 EPS = 0.000001 ITN = int(log2(1 / EPS) / log2(3 / 2)) def h(v_p, v_f, a, x): return (((1 - a) ** 2 + x ** 2) ** (1/2)) / v_p + (((1 - x) ** 2 + a ** 2) ** (1 / 2)) / v_f def ternary_search(left, right, v_p, v_f, a, bound): for i in range(bound): middle_1 = (2 * left + right) / ...
T = int(input()) for t in range(T): linha = input().split(" ") somatoria = int(linha[0]) + int(linha[1]) if somatoria <= int(linha[2]): print ('CABE!', end="" if t == T - 1 else "\n") elif somatoria >= int(linha[2]): print ('NAO CABE!', end="" if t == T - 1 else "\n")
""" Created on Mon Jan 28 16:44:45 2019 @author: kyouma """ from scipy.stats import poisson poisson.pmf(3, 2) ''' a = 0 numeros = range(4) for k in numeros: a += poisson.pmf(k,2) print (a) mesma coisa que: ''' poisson.cdf(3,2) poisson.pmf(12,10)
import csv with open("data.csv", newline='') as f: data = csv.reader(f) list_data = list(data) list_data.pop(0) print(list_data) total = 0 for h in range(len(list_data)): height = list_data[h][1] total = total+float(height) mean = total/len(list_data) print(mean)
course_Room = {'CS101': 3004, 'CS102': 4501, 'CS103': 6755, 'NT110': 1244, 'CM241': 1411} course_Instructor = {'CS101': 'Haynes', 'CS102': 'Alvarado', 'CS103': 'Rich', 'NT110': 'Burke', 'CM241': 'Lee'} course_Meeting_Time = {'CS101': '8:00 AM', 'CS102': '9:00 AM', 'CS103': '10:00 AM', 'NT110': '11:00 AM', 'CM241': '1:0...
insurance_Factor = 0.80 def insurance_Calculator(cost): insuranceCost = cost * insurance_Factor return insuranceCost print("What is the replacement cost of the building?") replacementCost = float(input()) print("Minimum amount of insurance to buy:", insurance_Calculator(replacementCost))
class Person: def __init__(self, name, address, telephone_number): self.__name = name self.__address = address self.__telephone_number = telephone_number class Customer(Person): def __init__(self, name, address, telephone_number, customer_number, trueorfalse): super().__init__(...
import PyPDF2 import tkinter from tkinter import filedialog as fd tkinter.Tk().withdraw() filename = fd.askopenfilenames(initialdir = "/",title = "Select files",filetypes = (("PDF files","*.pdf"),("all files","*.*"))) filename = list(filename) print(filename) pdfOutputFile = fd.asksaveasfile(mode='wb', defaultexte...
import numpy as np from random import randint def password(n, sets): passw = '' num_sets = len(sets) for i in range(n): if i < num_sets: set1 = sets[i] k = set1[randint(0, len(set1)-1)] else: rand_set = sets[randint(0, len(sets)-1)] k = rand_...
def fibonacci(N): if N < 1: return 0 fib = [0] * (N + 1) fib[1] = 1 for i in range(2, len(fib)): fib[i] = fib[i-1] + fib[i-2] return fib[N] def ladder(A, B): sequence = [] for i, v in enumerate(A): sequence.append(fibonacci(v+1)) for i, v in enumerate(B): sequence[i] =...
def push(val, stack, size): stack[size] = val size += 1 return size def pop(stack, size): size -= 1 stack[size] = 0 return size def brackets(S): if not len(S): return 1 size = 0 stack = [0] * len(S) size = push(S[0], stack, size) for i in range(1, len(S)): ...
import math def divide2(dividend, divisor): positive = (dividend < 0) is (divisor < 0) dividend, divisor = abs(dividend), abs(divisor) res = 0 while dividend >= divisor: temp, i = divisor, 1 while dividend >= temp: dividend -= temp res += i i <<= 1 ...
import math def find_next_square(sq): root = math.sqrt(sq) if root - math.floor(root)==0: x = root+1 square = x*x return int(square) else: return -1
tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def printTable(table): colWidth = [0] * len(table) for x in range(0,len(table)): lengthOfString = [] for y in range(0,len(table[x])): ...
'''import re print('You can strip some characters by strip method,\n just put the characters you want to strip in the parenthese\n followed function strip') print('Please input the text you wanna strip.') text = input() print('Please use the strip function.') def strip(string): preWhiteSpace = re.compile(r'^\s+...
import PyPDF2,os from pathlib import Path os.makedirs('encryptedPdfs',exist_ok=True) def encrypt(folder): absPath = os.path.abspath(folder) for folderName,subfolders,filenames in os.walk(absPath): for filename in filenames: if filename.endswith('.pdf'): try: ...
n, m = map(int, input().strip().split()) def gcd(a, b): while b > 0: a, b = b, a % b return a def lcm(a, b): return a * b // gcd(a, b) print(gcd(n, m), lcm(n, m))
def print_with_word_decorator(word, decorator): print("-----------------------------\n") for sign in word: print(sign, end=decorator) print("\n\n-----------------------------") def fill_breaks(list, sign): print("not implemented yet") def index_of_set(set, index): try: sorted_lis...
""" Class representing one card: value, color and file with image """ class Card: VALUES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'As'] COLORS = ['♥', '♦', '♣', '♠'] def __init__(self, value, color): """Init card - value and color.""" self._value = value ...
def read_file_in_lines(reading_file): for line in reading_file.readlines(): print(line.strip()) def write_line_in_file(file_to_writing, new_line, encoding): with open(file_to_writing, "a", encoding=encoding) as file_oject: file_oject.write(new_line + "\n") def fill_and_split_line(first_word,...
def df(original): def wrapper(*args,**kwargs): print('a',*args) print('k', **kwargs) return original(*args,**kwargs) return wrapper @df def display(x): print(x) response = ['Go get Jason a cup of water','Go massage for Jason','Go keep your toys',"Go wash Jason's plate",'Go clean...
from sklearn import datasets iris = datasets.load_iris() iris.data[:5] from sklearn.metrics import accuracy_score from sklearn.naive_bayes import GaussianNB gnb = GaussianNB() y_pred = gnb.fit(iris.data, iris.target).predict(iris.data) right_num = (iris.target == y_pred).sum() print("Total testing num :%d ...
from tkinter import * def to_delete(): res = txt.get() cartList.remove(res) lbl1.configure(text=cartList) txt.delete(0, END) def to_buy(): destroy_object = [lbl, lbl1, lbl2, lbl3, btn, btn2, txt] for object_name in destroy_object: if object_name.winfo_viewable(): object_...
name = input("What is yur name ? ") job = input("what job do you wanna aply for ? ") time = input("How much time woud you take for obtaining this job ? ") steps = input("what are the steps that you need to follow in order to get to get this job ? ") first_Day = input("when would you like to start ? ") print("Candidatul...
stopwords = ''' i a an are as at be by for from how in is it of on or that the this to was what when where '''.split() def strip_stopwords(sentence): """Removes stopwords - also normalizes whitespace""" words = sentence.split() sentence = [] for word in words: if word.lower() not in stopwords: ...
import random HIT_MARKER = 'X' MISS_MARKER = 'O' INIT_MARKER = '#' PLAYER_MARKER = 'P' rowSize = 5 colSize = 5 isEnemyAlive = True enemy_row = random.randint(0,rowSize - 1) enemy_col = random.randint(0,colSize - 1) isPlayerAlive = True playerShip_row = random.randint(0,rowSize - 1) playerShip_co...
import json table = json.load(open('./periodic_table.json')) mode = input('Wybierz tryb (liczba atomowa - 1, symbol - 2): ') if (mode == '1'): number = input('Podaj liczbę atomową: ') for atom in table['elements']: if (atom['number'] == int(number)): foundAtom = atom ...
def intersection(arrays): hash ={} for x in arrays[0]: hash[x] = 0 for x in range(1, len(arrays)): for y in arrays[x]: if y in hash: hash[y] += 1 todrop = [] for item in hash: if hash[item] == 0: todrop.append(item)...
graph=[] union_array=[] def initialize_union_array(N): global union_array for i in range(N): union_array.append(i) def union(u,v): global union_array value = union_array[v] replace_value = union_array[u] for i,ele in enumerate(union_array): if ele == replace_value: u...
n = int(input()) cond = n&1 if cond == 1: print("Odd number") else: print("Even number")
import prompt def greet(): print('Welcome to the Brain Games!') def welcome_user(rules): print(rules) print() name = prompt.string('May I have your name? ') print('Hello, {}!'.format(name)) print() return name def request_answer(question): print(f'Question: {question}') user_an...
def alphabet_position(letter): lwr_let = letter.lower() pos = ord(lwr_let) - 97 return pos def rotate_character(char, rot): if not char.isalpha(): return char else: rotated = chr(alphabet_position(char) + rot + 97) if not rotated.isalpha(): rotated = chr(ord(rota...
from random import random from utils import clear_term def guess_game(): resume = True while resume: clear_term() hidden_num = int(random() * 100) while True: guess_num = input('Guess the hidden num [0-99]: ').strip() if not guess_num.isnumeric(): ...
from random import random from utils import get_item_by_index, is_numeric, clear_term def rps_game(): elements = { 'rock': 'scissor', 'paper': 'rock', 'scissor': 'paper' } while True: clear_term() pc_choice = get_item_by_index(elements, int(random() * 3)) pr...
def printLinkedList(head): node = head while node != None: print(node.data) node = node.next
def reversePrint(head): if head is None: return else: out = [] node = head while node != None: out.append(node.data) node = node.next print("\n".join(map(str, out[::-1])))
""" Module for image utilities. """ import numpy as np import cv2 def crop(img: np.array, size): """ Take a numpy array and crop it to size """ y, x, z = img.shape cx = (x // 2) - (size // 2) cy = (y // 2) - (size // 2) return img[cy:cy+size, cx:cx+size, :] def northwest(img, size): """ Ta...
from sys import argv script, first, second = argv print("The script is called:", script) print("Your first variable is:", first) print("Your second variavle is:", second) first = input() second = input() print("是这样?", first, second)
""" Exemplo de Entrada Exemplo de Saída 1.0 7.0 5.0 9.0 4.4721 -2.5 0.4 12.1 7.3 16.1484 2.5 -0.4 -12.2 7.0 16.4575 """ import math p1 = input().split(" ") p2 = input().split(" ") x1, y1 = p1 x2, y2 = p2 res = format(math.sqrt((float(x2) - float(x1))**2 + (float(y2) - float(y1))**2), '.4f') print(res)
securityCode = {} matrixList = [] encodedMatrix = [] pattern = [ [1,2,3], [1,1,2], [0,1,2] ] def initializeCode(): code = 1 for i in range(65,91): securityCode[chr(i)] = code code += 1 def findChar(value): for key in securityCode: if securityCode[key] is value: ...
for i in range(5): try: print(i / 0) except ZeroDivisionError as e: print(e, "---> division by 0 is not allowed") for i in range(5): try: print(i / 0) except NameError: print("---> division by 0 is not allowed") for i in range(5): try: print(i / 1) ex...
from itertools import * list1 = [1, 2, 3, 'a', 'b', 'c'] list2 = [101,102, 103, 'X', 'Y'] a = chain(list1, list2) for i in chain(list1, list2): print(i) list(chain(list1, list2)) count(10, 2.5) for i in count(10, 2.5): if i <= 50: print(i) else: break a = range(11, 16) for i in cy...
""" Assignment 1-A ============== Write fuction that generates the text below; use at least variables and f-strings. For those who are already familiar with Python – write the best code you can to conform to the Zen of Python. """ def poem(): result = '' base = [["the house that Jack built", "lay in"], ...
from time import clock print("enter your name:", end="") start_time =clock() name = input() print("nhập name") elapsed = clock() - start_time print(name, "it took you", elapsed ,"second to repond")
""" A clock class. """ class Time(): """ A class to represent time """ def __init__(self, __hour=0, __min=0, __sec=0): """Constructs the time class. Keyword Arguments: __hour {int} -- hours of the time (default: {0}) __min {int} -- minutes of the time...
ROD = 5.0292 FURLONG = 40 MILE = 1609.34 FOOT = 0.3048 WALKING_SPEED = 3.1 rods = float(input("Input rods: ")) print("You input", rods, "rods.\n") meters = rods * ROD feet = meters / FOOT miles = meters / MILE furlongs = rods / FURLONG walking_hours = miles / WALKING_SPEED walking = walking_hour...
import unittest class Point: def __init__(self, a=0, b=0): self.x = a self.y = b class Solution: def maxPoints(self, points): """ :type points: List[Point] :rtype: int """ result, n = 0, len(points) for i in range(n): d...
class Solution: def validMountainArray(self, A): """ :type A: List[int] :rtype: bool """ if not A or len(A) < 3: return False if A[0] > A[1] or A[-2] < A[-1]: return False peak = False for i in range(0, len(A) ...
from collections import Counter class Solution: def removeDuplicateLetters(self, s): """ :type s: str :rtype: str """ freq = Counter(s) visited, stack = set(), [] for c in s: freq[c] -= 1 if c not in visited: ...
class Node: def __init__(self, val, left, right): self.val = val self.left = left self.right = right class Solution: def __init__(self): self.cur = None def treeToDoublyList(self, root: 'Node') -> 'Node': if not root: return None ...
class Solution: def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ result = [[0] * n for _ in range(n)] nowWidth = n nowHeight = n x = 0 y = 0 num = 1 while nowWidth > 0 and nowHeight > 0: if n...
import unittest class Solution: def accountsMerge(self, accounts): """ :type accounts: List[List[str]] :rtype: List[List[str]] """ def find(s, root): return s if root[s] == s else find(root[s], root) result = [] root = {} own...
import string import random class Codec: def __init__(self): self.shortToLong = {} self.longToShort = {} def randomString(self): return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(6)) def encode(self, longUrl): """Encodes a URL to a shortened...
class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ red, blue = 0, len(nums) - 1 i = 0 while i <= blue: if nums[i] == 0: nums[red], nums[i] = n...
class MaxStack: def __init__(self): """ initialize your data structure here. """ self.stack = [] self.stackMax = [] def push(self, x): """ :type x: int :rtype: void """ if not self.stackMax or self.stackMax[-1] <= x:...
import unittest class Solution: def licenseKeyFormatting(self, S, K): """ :type S: str :type K: int :rtype: str """ S = S.replace("-", "").upper() rem = len(S) % K return "-".join([S[:rem]] + [S[i:i+K] for i in range(rem, len(S), K)]).str...
import unittest class Solution(object): def kEmptySlots(self, flowers, k): """ :type flowers: List[int] :type k: int :rtype: int """ ga...
import unittest class Solution: def findMin(self, nums): """ :type nums: List[int] :rtype: int """ left, right = 0, len(nums) - 1 if nums[left] > nums[right]: while left != right - 1: mid = (left + right) // 2 ...
import unittest class Master: def __init__(self, secretWord): self.secretWord = secretWord def guess(self, word): """ :type word: str :rtype int """ if word == self.secretWord: return 6 else: return sum(c1 == c2 for c1, c2 in zip(...
""" Created on Tue Dec 17 17:48:08 2019 @author: jline """ class Car: wheels = 4 def __init__(self): self.mil = 10 self.com = "BMW" c1 = Car() c2 = Car() c1.mil = 8 print(c1.com, c1.mil, c1.wheels) print(c2.com, c2.mil, c2.wheels) Car.whe...
class Animal: def __init__(self, age, name): self.age = age self.name = name def saluda(self, saludo='Hola', receptor = 'nuevo amigo'): print(saludo + " " + receptor) @staticmethod def add(a, b): if isinstance(a, int) and isinstance(b, int): return a + b ...
x = 8 if x <= 25: print(str(x) + " is between 0 and 25") elif x > 75 and x < 100: print(str(x) + " is between 75 and 100")
username = input("Enter your name: ") Age = int(input("Enter your age: ")) print("your name is: " + username) year = str( (2021-Age) + 100) print(username + " will be 100 years old in the year " + year)
number_to_guess = 5 a = int(input("dime un numero?")) b = int(input("dame otro numero?")) c = int(input("solo uno mas")) if a == number_to_guess: print("acertaste") if b == number_to_guess: print("acertaste") if c == number_to_guess: print("acertaste") else: print("no has acertado :(")
n=input() y=input() l="ABCDEFGHIJKLMNOPQRSTUVWXYZ" if(sorted(l)==sorted(n+y)): print("complementary") else: print("non-complementary")