text
stringlengths
37
1.41M
# num=int(input("enter the year")) # if num%4==0: # print("leap year") # else: # print(" It is not leap year")
# # calculator # num1=int(input("enter the num1 ")) # num2=int(input("enter the num2 ")) # operator=input("enter the operator") # if operator == "+": # print(num1+num2) # elif operator == "-": # print(num1-num2) # elif operator == '/': # print(num1/num2) # elif operator == '*': # print(num1*num2) # e...
# ***isosceles,equirlateral,scalence*** # n=input("enter the degrees ") # a=int(input("a: ")); # b=int(input("b: ")) # c=int(input("c: ")); # if a==b and b==c: # print("is equirlateral triangle") # elif a==b or b==c or c==a: # print("is isosceles triangle") # # elif a!=b or b!=a or b!=c: # else: # print(...
# *** creates 9x9 board (valid input for _main_file.solve()) from some of data below (below the getch() method) def create_sudoku(inp): row = 0; col = 0; outp = [[0] * 9 for _ in range(9)] for letter in inp.replace('.', '0'): a = ord(letter) if a >= 48 and a <= 57: # if letter is in between '0' ...
from tkinter import * import math from random import randint,choice #Подготовка окна root = Tk() fr = Frame(root) root.title("easySpace") root.geometry("1366x768") canv = Canvas(root, bg='black') canv.pack(fill = BOTH, expand = 1) #Интерфейс пользователя class UI(): def __init__(self): self #""" Здесь ...
# Status: Probably works. Demo. # After you put an image with some shapes in image.jpg, it will find # contours and display their outlines and centers. Pretty much just # http://www.pyimagesearch.com/2016/02/01/opencv-center-of-contour/ import imutils import cv2 image = cv2.imread('image.jpg') gray = cv2.cvtColor(i...
# Unnar Sigurðsson # Movement function def movement(a_str): return a_str # Movement_input function def movement_input(): a_str = str(input("Direction: ")) return a_str # Tiles def tiletraveller(blabla): #Tiles a = "nN" b = "nN" c = "nN" d = "nNsSeE" e = "sSwW" f = "nNs...
import unittest # 求和 def add(x, y): return x + y class TestAdd(unittest.TestCase): def test_add_01(self): result = add(1, 1) self.assertEqual(result, 2) def test_add_02(self): result = add(1, 0) self.assertEqual(result, 1) def test_add_03(self): result = add(0, 0)...
def multiply(x, y): result = x * y return result answer = multiply(10.5, 4) print(answer) forty_two = multiply(6, 7) print(forty_two) print('-' * 80) for val in range(1, 5): two_times = multiply(2, val) print(two_times) print('-' * 80)
import time # Interview question at Radband October 2018 # Problem description (aproximately): design a scheduler that receive at init time several event and their frequencies. # When started, the scheduler begin triggering the events respecting their frequencies class Node: def __init__(self, val, freq): ...
# input: 13 -> 1101 -> {11}{01} -> 1110 -> output: 14 # input: 74 -> 01001010 -> {01}{00}{10}{10} -> 10000101 -> output: 133 def swapAdjacentBits(n): return int("".join(["".join(i) for i in zip("{0:032b}".format(n)[1::2], "{0:032b}".format(n)[::2])]), 2) def swapAdjacentBits2(n): return ((n & 0xaaaaaaaa) >>...
from collections import deque """ de = collections.deque([1,2,3]) de.append(4) de.appendleft(6) de.pop() de.popleft() de.index(4,2,5) # The number 4 first occurs at a position ? from 2 to 5 de.insert(4,3) # insert the value 3 at 5th position de.count(3) # The count of 3 in deque is ... de.remove(3) # remove ...
class Item: """ This is a class to represent an online sold item. Attributes ---------- category: str Item's category. name: str Item's name. code: str Item's unique code. price: str Item's price in brazilian currency (BRL). details: str Item's lo...
import random #import the random function in order to randomly select a number, which is used later on in the function import pygame #This game sets the size of the pygame display, and titles the name of the pygame window as Magnet Monopoly pygame.init() display_width= 880 display_height= 600 gameDisplay = pygame.disp...
#########################Done######################### #First Aproach def IsSame(s1,s2): l1=len(s1) l2 = len(s2) if l1!=l2: return False if l1<1 and l2<1: return True if l1<1 or l2<1: return False #We can sort then and compare character by character #Second Approach def ...
# def convertIntoBinary(num,b): # res=0 # i=0 # while num>0 and i<=b: # res=res+(num%10)*(2**i) # num=num/10 # i=i+1 # return res # def binaryToDecimal(binary): # binary1 = binary # decimal, i, n = 0, 0, 0 # while (binary != 0): # dec = binary % 10 # decim...
import math def checkPrime(n): if n<2: return False if n==2: return False if n%2==0: return False for i in range(3,int(math.sqrt(n))): if n%i==0: return False return True n=input("Enter the number:") for i in range(1,n+1): if n%i==0: if checkP...
n=input("Enter the number") li=[x for x in range(1,n+1)] print sum(li)
class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None if __name__=='__main__': llist=LinkedList() llist.head=Node(10) second=Node(20) third=Node(30) second.next=third llist.head.next=second
n=int(raw_input("Enter the number:")) rev=0 while n>0: rev=rev*10+n%10 n=n/10 print rev
''' n=input("Enter the number: ") dict={} dict2={} for i in range(1,n+1): dict[i]=i*i dict2.update({i:i*i}) print dict print dict2 ''' print "-----------------Staring completely new session-----------------" #Creating a empty dictionary data1={} data2={} data3={} data4={} data5={} #Creating a dictionary with in...
count=0 high=100 low=0 print("Please think of a number between 0 and 100!") while input != 'c': newnum=int((high+low)/2) print("Is your secret number "+str( newnum)+"?") x = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") if x ...
print ('Merhaba, Django Girls!') if 3>2: print('calisiyor') if 5>2 : print("5 gercekten de 2'den buyuktur") else: print("5 2'den buyuk degildir") name = "Zeynep" if name == "Ayse": print("Selam Ayse!") elif name == "Zeynep": print("Selam Zeynep!") else: print("Selam yabanci") volume = 57 if vol...
n = int(input("Ingrese numero de filas: ")) for i in range(1, n+1): print((str(i)+ " ")*i)
# ex15 reading files # import argv module from sys import argv # unpack the argv script, filename = argv # open the file txt = open(filename) # print the file name print "Here's your file %s:" % filename # print the file content print txt.read() # reread the file print "Type the filename again:" file_again = raw_i...
# Definition for a undirected graph node # class UndirectedGraphNode: # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution: # @param node, a undirected graph node # @return a undirected graph node def __init__(self): self.Map = {} #store nodes in copied...
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: # @param intervals, a list of Interval # @return a list of Interval def merge(self, intervals): if not intervals: return [] interva...
class Solution: # @return a list of integers def getRow(self, rowIndex): values = [1 for i in range(0, rowIndex+1)] #we only need the bottom row for row in range(1, rowIndex+1): values[row] = 1 for col in range(row-1, 0, -1): values[col] = values[col-1] + values[col] return values
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree node # @return nothing def connect(self, root): if root is None: ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param a list of ListNode # @return a ListNode def mergeKLists(self, lists): if not lists: return None if len(lists) == 1: ...
__author__ = 'Justin' """ Question: Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320 """ num = int(input("Enter numbe...
from tkinter import * root = Tk() root.geometry('400x400') root.config(bg = 'magenta') root.resizable(0,0) root.title('PhoneBook App') contactlist = [ ['Jane Doe', '123456'], ['John Doe', '78910'], ] Name = StringVar() Number = StringVar() frame = Frame(root) frame.pack(side = RIGHT) #scro...
def create_multiplication_table(width, height): output = "" num_chars = len(str(width*height)) + 1 for a in range(1, height+1): for b in range(1, width+1): product = a * b product_str = str(product) product_str = product_str.rjust(num_chars, ' ') output += product_str output += "\n\n" return o...
#--- ALUNO - WALSAN JADSON --- #------- IMPORTANDO BIBLIOTECAS ------- import sys import timeit #------- DEFININDO FUNCOES ------- #-- 1 def countingSort(lista): a = lista print(a) b = [0] for i in range(0, len(a)): b.append(a[i]) k = buscaMaior(a) print "maior numero da l...
def get_length(dna): ''' (str) -> int Return the length of the DNA sequence dna. >>> get_length('ATCGAT') 6 >>> get_length('ATCG') 4 ''' return (len (dna)) def is_longer(dna1, dna2): ''' (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA seque...
import string import itertools import math class MyCrossword: __doc__ = "helper to solve crossword puzzles" def __init__(self): return def GeneratePermutation(self,A=None,B=None,C=None,D=None,E=None,F=None,G=None,H=None,I=None,J=None,K=None): if K is not None: ...
#Find wearther string is having Uniq Charectors are not from collections import Counter def isHavingUniq(s): C = Counter(s) for key in C: if C[key] != 1: return False return True s= 'abcde' print(isHavingUniq(s)) def uni_Char2(s): return len(set(s)) == len(s) s= 'abcdaf' print(un...
# Reverce the words in the sentence def revSentence(s): s1 = s.strip() print(s1) rString = '' sWords = s.split(' ') for word in reversed(sWords): rString = rString + " " + word.strip() return rString s = " This is the Best " def revSentence1(s): i = 0 lenght = len(s) ...
s = 'azcbobobegghakl' b = 0 if 'bob' in s: print('\'bob\' in string \'s\'') i = 0 for char in s: print('char ' + str(i) + ' in string \'s\': ' + char) if char == 'b': i += 1 for char in s[i]: print('Found letter \'b\', checking for \'o\'') ...
#-*-encoding=utf-8-*- class Kiyafetler(): def __init__(self): self.adi="Mızrak" self.ozellik="+8 Atak Gücü" def ozellikGoster(self): print("{} adlı eşyanın özelliği {}".format(self.adi,self.ozellik)) def kiyafetGiy(self,oyuncu): oyuncu.saldırıGucu += 8 oy...
#-*-encoding=utf-8-*- import random class Karakterler(): def __init__(self): self.kasa=[] self.saldırıGucu=12 self.savunmaGucu=15 self.can=150 self.adi="Ana Karakter" self.ustundekiler=[] def saldir(self,rakip): self.savasSimilasyonu(rakip) ...
In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: The town judge trusts nobody. Everybody (except for the town judge) trusts the town judge. There is exactly one person that satisfies properties 1 and 2. You are g...
import random from menu import * from time import sleep from typing import * # passphrase generator randomly generates passphrase # from words found in textfile paramater # until min char count acheived # returns passphrase and wordcount of passphrase def Passphrase_Generator(): text_files = Menu() text_file...
# IoT program by MicroPython # https://github.com/rnsk/micropython-iot # # MIT License # Copyright (c) 2021 Yoshika Takada (@rnsk) """CdS library""" from machine import Pin, ADC class CdS: def __init__(self, pin_id): """Initialize Args: pin_id (int): センサーのPIN番号 """ se...
# -*- coding: utf-8 -*- """ Created on Sun Apr 5 16:46:21 2020 @author: Shivam Sekra """ import numpy as np import cv2 # We point OpenCV's CascadeClassifier function to where our # classifier (XML file format) is stored face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') #...
dict1 = {0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five"} ans = "y" while ans == "y" or ans == "Y" : val = input("Enter value: ") print("Value", val, end = " ") for k in dict1: if dict1[k] == val: print("Exists at", k) break else: print("Not found") ans = input("Want to check...
#!/usr/bin/python ''' There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). nums1 = [1, 3] nums2 = [2] The median is 2.0 nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 ''' class Soluti...
import numpy as np class Collection: def __init__(self, values): self.values = values def get(self): if len(self.values) == 0: return None return np.random.choice(self.values) def all(self): return set(self.values) def c(values=list()): """ Creates ...
import numpy as np import string from .collection import c, Collection from typing import List ''' Generators should be classes that have at least two public methods with the following signatures generate_formula([String]) vocabulary(config) The first one should generate a random and valid mathematical expression in l...
from PIL import Image from k_means import k_means if __name__ == '__main__': print("Coloque el nombre de la imagen a comprimir:") imageName = input() #imageName = "stardewValley.png" # Se carga la imagen y se obtienen los valores de sus pixeles # (requiere pillow en python3, PIL en python2) image = Image.open...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Apr 17 11:16:22 2020 @author: ivan """ #bilo je python3 #PART 1 - BUILDING A CNN from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense ...
s = int(input("อัตราเร็วของการเคลื่อนที่ :")) t = int(input("เวลาที่วัตถุใช้เคลื่อนที่จริง :")) v = int(s/t) print (v, "km/h")
from math import sqrt, pow def length(a, b): return sqrt(pow(b.x - a.x, 2) + pow(b.y - a.y, 2)) def triangle_area(t): a, b, c = (length(t.a, t.b), length(t.b, t.c), length(t.c, t.a)) s = (a + b + c) / 2 return sqrt(s * (s - a) * (s - b) * (s - c))
class Patient(object): def __init__(self, id_number, name, allergies=[], bed_number='none'): self.id_number = id_number self.name = name self.allergies = allergies self.bed_number = bed_number class Hospital(object): def __init__(self, name, capacity, patients=[]): sel...
## TODO: define the convolutional neural network architecture import torch import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): """ Neural networ...
for _ in range(int(input())): N=int(input()) while N!=1: print(int(N),end=' ') if N%2==0: N=N/2 else: N=(N*3)+1 print(int(N))
import math print("ievadi garumu centimetros") g = int(input()) print("ievadi svaru kilogramos") s = int(input()) print(s / g**2 * 100)
# Python program to display all the prime numbers within an interval lower = 900 #lower limit upper = 950 # upper limit print("Prime numbers between", lower, "and", upper, "are:") for num in range(lower, upper + 1): # all prime numbers are greater than 1 if num > 1: for i in range(2, num): ...
#Escribe un programa que permita leer un arreglo de n datos enteros, luego imprime de manera invertida. Guarde el archivo como Arreglo.py import random import numpy as np # a = np.array([ # [1, 2, 3], # [4, 5, 6] # ]) # b = np.array([ # [0, 0, 0], # ...
import time # Funcion menu def menu(): print("================================= Menu de Opciones =================================") print("0. Salir") print("1. Saludar") print("2. Calcular si un número es par") print("3. Calcular el promedio de 5 notas") print("4. Calcular el porcentaje") ...
# Crear una lista y almacenar 10 enteros pedidos por teclado. Eliminar todos los elementos que sean iguales al número entero 5. # listaenteros = list() # counter = 0 # while counter < 10: # numero = input("Escriba el numero para agregar a la lista: ") # listaenteros.append(numero) # counter += 1 # ...
# -*- coding: utf-8 -*- """ Created on Fri Mar 19 13:45:23 2021 @author: epits """ from ps6.py import Message import string class CiphertextMessage(Message): def __init__(self, text): ''' Initializes a CiphertextMessage object text (string): the message's text a Ci...
""" Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements. For example: unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] unique_in_order('ABBCcA...
from node import Node # inserir na fila # remover na fila # observar o topo da fila class Fila: def __init__(self): self._size = 0 self.first = None self.last = None def __len__(self): return self._size def push(self, elemento): node = Node(elemento) ...
def approach1(): global a, b a = [1, 2, 3, 4, 5] b = [5, 6, 7, 8, 9] for vala in a: for valb in b: if vala == valb: print("common values present") def approach2(): [print("common values present") for vala in a if vala in b] def approach3(): c = set(a) ...
# myDict = { # 1: "mani", # 2: "suresh" # } #print(myDict) import random import string random_invalid_alnums = lambda s="rand12", exclude=[]: [ str(s) + c for c in string.punctuation if c not in exclude ] random_invalid_alphas = lambda s="rand", exclude=[]: [ str(s) + c for c in string.punctuation + st...
class parent: def __init__(self, fname, lname): self.fname = fname self.lname = lname def printName(self): print(self.fname, self.lname) class child(parent): def __init__(self, fname, lname, year): super().__init__(fname, lname) self.grad_year = year def print...
import numpy as np import matplotlib.pyplot as plt x = 4 theta = 90 sin = np.sin(theta) cos = np.cos(theta) print("theta is", theta) print("sinus is", sin) print("cosinus is",cos) print("It is Radian") meshPoints = np.linspace(-1,1,500) value53 = meshPoints[52] print("53th element of meshpoint is",value53) ...
# Factors numbers into Primes! # Anders Kouru 30 juni 2014, last modified 19 dec 2018 import math def introFunction(): print("This function Factors numbers into Primes!") return 0 def prime_Factor(prime_numb): divisor = 2.0 prime_save = prime_numb end = pow(prime_save,0.5) end_save =...
# Solution 1 num = 1 while num < 11: print(' 😄 ' * num) num += 1 # Solution 2 for num in range(1, 11): print(' 😄 ' * num) # Solution 3 for num in range(1, 11): emoji = '' count = 1 while count <= num: emoji += ' 😄 ' count += 1 print(emoji)
print('How many kilometers did you cycle today?') kms = float(input()) # input always returns a str miles = round(kms / 1.6934, 2) print(f'Ok you said {miles} miles.') # age = input('How are you?\n') # if age and not(age != str): # int_age = int(age) # if int_age >= 10 and int_age < 21: # print('You...
# There're built-in functions and methods in python names = ["Bianca", "Luca", "Philippe", "Pedro"] print(names) names.append("Ana") print(names) names.pop() names.pop() names.pop() print(names) names.append("Bianca") print(names.count("Bianca")) # number of ocurrances in list names.extend(["Philippe", "Pedro"]) ...
from random import randint print('Rock...') print('Paper...') print('Scissor...') options = ['rock', 'paper', 'scissor'] rand_idx = randint(0, 2) player_1 = input('Player 1, make your move: ') player_2 = options[rand_idx] print(f'Computer players {player_2}') if player_1 == player_2: print('It\'s a tie!') elif p...
user_info = {} user_info['first_name'] = input('Enter your first name: ') user_info['last_name'] = input('Enter your last name: ') print(user_info)
# https://leetcode.com/problems/missing-number/description/ # Time: O(n) # Space: O(1) # # Given an array containing n distinct numbers taken from # 0, 1, 2, ..., n, find the one that is missing from the array. # # For example, # Given nums = [0, 1, 3] return 2. # # Note: # Your algorithm should run in linear runtime ...
""" Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. Example 1: Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]] 0 3 | | 1 --- 2 4 Output: ...
# V0 # IDEA : MATRIX IN ORDER + BRUTE FORCE # Space: O(1) # Time: O(m+n) # worst case class Solution: def searchMatrix(self, matrix, target): if len(matrix) == 0: return False row, col = 0, len(matrix[0]) - 1 while row < len(matrix) and col >= 0: if matrix[r...
# Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. # Now you want to find out who the celebrity is or verify that there is not one. The on...
# V0 # IDEA : brute force + check subset of set # LOGIC : start from the given time, then "add 1 minute" in every loop, # if all the elements in the upddated time are also the subset of the original time set -> return True (find the answer) # CONCEPT : subset in python # https://stackoverflow.com/questions/16579085/...
# V0 class Solution(object): def reconstructQueue(self, people): people.sort(key = lambda x : (-x[0], x[1])) res = [] for p in people: res.insert(p[1], p) return res # V1 # https://blog.csdn.net/fuxuemingzhu/article/details/68486884 # IDEA : MAKE THE ARRAY IN DESCENDING...
# V0 # IDEA : MATH class Solution(object): def complexNumberMultiply(self, a, b): def split(s): tmp = s[:-1].split("+") return int(tmp[0]), int(tmp[1]) m, n = split(a) p, q = split(b) return '{}+{}i'.format((m*p - n*q),(m*q + n*p)) # V1 # http://bookshadow.c...
# Evaluate the value of an arithmetic expression in Reverse Polish Notation. # # Valid operators are +, -, *, /. Each operand may be an integer or another expression. # # Some examples: # ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 # ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 # V0 # IDEA : STACK # DEMO...
# V0 # IDEA : REVERSE WHOLE STRING -> REVERSE EACH WORD class Solution(object): def reverseWords(self, s): s_ = s[::-1] s_list = s_.split(" ") return " ".join([ i[::-1] for i in s_list]) # V1 # http://www.voidcn.com/article/p-eggrnnob-zo.html class Solution(object): def reverseWord...
""" Given the head of a singly linked list, reverse the list, and return the reversed list. Example 1: Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: Input: head = [1,2] Output: [2,1] Example 3: Input: head = [] Output: [] Constraints: The number of nodes in the list is the range [0, 5000]. -5000 <=...
# 295. Find Median from Data Stream # Hard # # Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. # # For example, # [2,3,4], the median is 3 # # [2,3], the median is (2 + 3) / 2 = 2.5 # # Design a data str...
# Time: O(n) # Space: O(1) # # The API: int read4(char *buf) reads 4 characters at a time from a file. # # The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. # # By using the read4 API, implement the function int read(char *buf, int n) th...
# V0 class Solution: def tree2str(self, t): if not t: return '' if not t.left and not t.right: return str(t.val) ### NOTICE HERE if not t.left: return str(t.val) + '()' + '(' + self.tree2str(t.right) + ')' ### NOTICE HERE if not t.r...
# V0 # IDEA :RECURSION, BST # IDEA : USE BST'S PROPERTY : # -> FOR EVERY NODE : right > node > left # -> USE ABOVE PROPERTY FOR BST TRIMMING class Solution: def trimBST(self, root, L, R): if not root: return # NOTICE HERE # SINCE IT'S BST # SO if root.val < L, THE ro...
# ################################################################# # # DATA STRUCTURE DEMO : Tree # ################################################################# # # build a tree # # https://github.com/OmkarPathak/Data-Structures-using-Python/blob/master/Trees/Tree.py # ######################################...
# Follow up for problem “Populating Next Right Pointers in Each Node”. # # What if the given tree could be any binary tree? Would your previous solution still work? # # Note: # # You may only use constant extra space. # # For example, # # Given the following binary tree, # # 1 # / \ # 2 3 # ...
""" Represent the input m as a vector with (k − 1) components over Zp, where p is prime: m = (ak−1,...,a1); • Choose the polynomial P(x) = ak−1xk−1 +···+a1x (remark that P(0) = 0 - this property will be used for decoding); • Encode m as the vector y = (P(1), P(2),...,P(n)), where n = k + 2s, y = (y1,...,yn). "...
import sys sys.stdin = open("input.txt") def be_upper(words): return words.upper() phrase = input() print(be_upper(phrase)) #The_headline_is_the_text_indicating_the_nature_of_the_article_below_it.
numbers = [3,9,4,7,5,0,1,2,6,8] def quick_sort(numbers): N = len(numbers) if N <= 1: return numbers else: pivot = numbers[0] # 우선 첫번째 값을 둠 left, right = [], [] # 빈 리트를 만들어줌 # 지금 numbers[0]인 3보다 작은애들은 left에, 큰 애들은 right에 넣어줌. for idx in range(1,N): # numbers[0]이 피봇의 ...
from affine import Affine from alberti import Alberti from atbash import Atbash from caesar import Caesar import os def clear(): """Clears text off the console screen""" os.system('cls' if os.name == 'nt' else 'clear') def print_underlined(text): """Prints the text underlined with ='s""" print(text)...
class Car: color = "" def description(self): description_string = "This is a %s car." % self.color # we'll explain self parameter later in task 4 return description_string car1 = Car() car2 = Car() car1.color = "blue" car2.color = "red" print(car1.description()) print(car2.description())...
# ask for age # 18-21 wristband # 21+ normal entry # too young import sys try: age = int(input("How old are ya lad?")) except: print("Valid numbers please!") sys.exit() print(age) if age >= 21: print('cul') elif age >= 18: print('cul') else: print('get lost lad')
class ContactList(list): def search(self, name): """Return all contacts that contain the search value in their name.""" matching_contacts = [] for contact in self: if name in contact.name: matching_contacts.append(contact) return matching_contacts ...
name = "John" age = 17 print(name == "John" or age == 17) # checks that either name equals to "John" OR age equals to 17 print(name == 'John' and age != 23)
class MyClass: variable = 'hi' def foo(self): # we'll explain self parameter later in task 4 print("Hello from function foo") my_object = MyClass() # variable "my_object" holds an object of the class "MyClass" that contains the variable and the "foo" function
print('ur age pls') age = input() print('how tall r u') heigh = input() print(''' Aha you,re %r age old and %r heavy.Nice to know ''' % (age, heigh))