text
stringlengths
37
1.41M
import math, random def isPrimeTrialDiv(num): if num < 2: return False for i in range(2, int(math.sqrt(num)) + 1): if num % i == 0: return False return True def primeSieve(sieveSize): sieve = [True] * sieveSize sieve[0] = False sieve[1] = False for i in range...
dia = input('Digite o dia que estamos: ') if (dia == '1'): print ('Domingo') elif (dia == '2'): print ('Segunda') elif (dia == '3'): print ('Terça') elif (dia == '4'): print ('Quarta') elif (dia == '5'): print ('Quinta') elif (dia == '6'): print ('Sexta') elif (dia == '7'): print ('Sabádo')...
import socket #创建一个socket链接 server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #绑定ip和端口 server.bind(('127.0.0.1',8080)) #监听 server.listen(5) print("启动成功") #等待连接 clientSocket, clientAddress = server.accept() print("%s -- %s 连接成功" % (str(clientAddress),clientAddress)) while True: #接收数据 data = clientSocket....
#浅拷贝 import copy will = ["Will", 28, ["Python", "C#", "JavaScript"]] wilber = copy.copy(will) print(id(will)) print(will) print([id(ele) for ele in will]) print("浅拷贝后的id",id(wilber)) print("浅拷贝后的元素",wilber) print("浅拷贝后的元素id",[id(ele) for ele in wilber]) will[0] = "Wilber" will[2].append("CSS") print("修改后的id",id(will)...
#__author: Administrator #date: 2020/3/12 #在分布式中最常见 #python 内置了map() 和 reduce()函数 #map 分散到各个储存中 # reduce 将分散出的数据整合并重新计算 from functools import reduce #map() #原型 map(fn,lsd) #参数1是函数 #参数2是序列 #功能:将传入的函数依次作用在序列中的每一个元素,并把结果作为新的Iterator返回 #将单个字符转成对应的字面量整数 def cha2int(chr): return {"0":0,"1":1,"2":2...
def city_country(city_name="zhangbei",country_name="zhangbei",person=""): if person: a = city_name + ',' + person + " " + country_name else: a = city_name + ',' + country_name return a.title() c = city_country(person="sunwenbo") #b = city_country("beijing","zhongguo","sunwenbo") print(c)
from typing import List def _get_comb_indexes(num_options_list: List[int], n=None) -> List[List[int]]: """ Given a list with the number of possible options per place, returns a list of numbers representing combinations. The combinations are created via additions to a multi-radix number, from left to right...
#__author: Administrator #date: 2019/12/22 ''' 多态:一种事物的多种形态 最终目标:人可以喂任何一种动物 ''' from cat import Cat from mouse import Mouse from person import Person from animal import Animal tom = Cat("tom") jerry = Mouse("jerry") tom.eat() jerry.eat() #思考:在添加100种动物,也都有name属性和eat方法 #定义了一个有name属性和eat方法的Animal类,让...
#__author: Administrator #date: 2019/12/8 ''' 重写:将函数重新定义写一遍 __str__():在调用print打印对象是自动调用,是给用户用的,是一个描述对象的方法 __repr__():是给机器用的,在python解释器里面直接敲对象名在回车后调用的方法 注意:在没有str时,且有repr时, str=repr ''' class Person(object): def __init__(self, name, age, height, weight): #print(name, age, height, weight) ...
# -*- encoding:Utf-8 -*- #-----------------------------------------------------------------------------# # Author : VERNIZEAU Aurélien # # File : server.py # # ...
# debes definir la metaclase 'Meta' a continuacion def crear_property(tipo, valor): def setter(self, valor): pass def getter(self): return self.value return property(getter, setter) class Meta(type): def __new__(meta, clase, base, dic): return super().__new__(meta, clase, bas...
import threading import time import random __author__ = 'Jm' class Godzilla(threading.Thread): def __init__(self, hp): super().__init__() self.hp = hp self.vivo = True self.lista = list() def run(self): while self.vivo: time.sleep(8) if self....
from enum import Enum __author__ = ['belen_saldias', 'patricio_lopez'] class Direccion(Enum): """ Una enumeración es como "números con nombre" Se utiliza así: dir = Direccion.arriba """ izquierda = 1 arriba = 2 derecha = 3 abajo = 4 class Estacion: def __init__(self, numero): ...
from threading import ( BoundedSemaphore, Condition, Event, Lock, RLock, Semaphore, Thread, ) lock = Lock() g = 0 def add_one(): global g lock.acquire() print "Adding 1" g += 1 lock.release() def add_two(): global g lock.acquire() print "Adding 2" g ...
# inspiration from http://paulmouzas.github.io/2014/12/31/implementing-a-hash-table.html class HashMap: def __init__(self, length, hash_function): self.length = length self.map = [[] for _ in range(length)] self.hash_function = lambda key: hash_function(length, key) def insert(self, k...
def insert_sort_single(ar, n): i = n - 1 e = ar[i] while i > 0: if ar[i - 1] > e: ar[i] = ar[i - 1] i -= 1 else: ar[i] = e return ar ar[0] = e return ar def insert_sort(ar, n): for i in range(1, n): ar = insert_sort_singl...
import statistics # the filter() method filters the given # iterable with the help of a function that tests # each element against the condition passed into that # filter(function, iterable my_list = [7, 5, 2, 8, 10, 73, 92] def func(elem): if elem % 2 == 0: return True else: return False ...
from PIL import Image, ImageDraw import face_recognition image = face_recognition.load_image_file("image/photo1.jpg") face_landmarks_list = face_recognition.face_landmarks(image) pil_image = Image.fromarray(image) d = ImageDraw.Draw(pil_image) for face_landmarks in face_landmarks_list: for facial_feature in fac...
a=[1,2,3,4,5,6,7,8] b=[2,3,4] print b in a 'abcd' in 'abcdefg' my_list = [ 'a' , 'b' , 'c'] print list(enumerate ( my_list ))
#The method index() returns the lowest index in list that obj appears. #Following is the syntax for index() method list.index(obj) #l=["sai","krishna",123,567] #print l.index("krishna") str = "this is string example....wow!!!" str1 = "exam" print str.index(str1) print str.index(str1, 14) print str.index(str1, 1...
from random import randint nPrisoners = int(input('How many prisoners do you have? ')) print('There are ' + str(nPrisoners) + ' prisoners. How many day will it take to rejoin freedom?') dictPrisoners = {} for n in range(nPrisoners): dictPrisoners[n] = False light = False counter = 0 ...
#! /E:/Anaconda3 python #Code adpated from Denny Britz's guide in CNN for Text Classification via TensorFlow #https://github.com/dennybritz/cnn-text-classification-tf #imports import numpy import re def cleanString(string): """ Cleans data sets by removing noisy data, Also ensures that specific punctuati...
""" @Author : P.Gnanender Reddy @Since : Dec'2019 @Description:This code is about Temperature Conversion. """ from com.bridgelabz.FunctionalPrograms.Utility import TemperatureConversion try: n=int(input("enter celsius value")) #user input TemperatureConversion(n) #calling temperature conversion function here...
""" @Author : P.Gnanender Reddy @Since : Dec'2019 @Description:This code is for Calendar. """ import calendar try: #using try block for different inputs yy = int(input("please enter the year")) #Asking the user to provide year mm = int(input("please enter the month in number format")) #Aski...
from com.bridgelabz.AlgorithmPrograms.util import prime try: n=int(input("enter starting value")) #asking user to provide starting parameter value n1=int(input("enter end value")) #asking user to provide end value prime(n,n1) #calling prime function here except ValueError: print("Enter valid data")#ask...
""" @Author : P.Gnanender Reddy @Since : Dec'2019 @Description:This code is for finding quadratic. """ from com.bridgelabz.FunctionalPrograms.Utility import quadratic try: a=int(input("enter first value")) #user input b=int(input("enter second value")) c=int(input("enter third value")) quadratic(a,b...
""" @Author : P.Gnanender Reddy @Since : Dec'2019 @Description:This code is for hashing. """ from com.bridgelabz.DataStructures.Utility1 import LinkedList def hashfunction(): try: file = open("texttt.txt", 'r') # here input data is reading ro the file # here input data is reading ro the file text = f...
number = input("Please enter a series of number, using any separators: ") separators = "" for char in number: if not char.isnumeric(): separators = separators + char #print(separators)
''' 2.1. Разработать функцию, возвращающую список чисел ряда Фибоначчи с использованием бесконечных итераторов (модуль itertools). ''' import itertools def fib_numbers(n): fib_list = [0, 1] for i in itertools.count(0): if i > 1: fib_list += [fib_list[-2] + fib_list[-1]] if i >= n -...
#3.2 remove命令 numbers = ['0', '1', '2', '3', '13'] print(numbers) dislike_number = '13' numbers.remove(dislike_number)#remove将不清楚元素位置但是知道其内容的元素删除,与pop命令一样,将其从列表中删除时还可继续使用它的值,remove将只删除第一个指定的值,如果要删除的值有多个,将要使用循环。 print(numbers) print("\nI realy dont like the number that is " + dislike_number + ".") #对列表进行排序 table = ['A...
from survey import AnonymousSurvey quetion = "What is your favorite language?" my_survey = AnonymousSurvey(quetion) my_survey.shoe_question() print("Enter 'q' at any time to quit.\n") while True: respone = input("Language: ") if respone == 'q': break my_survey.store_respone(respone) print("\nThan...
def make_album(name, album, num = ' '):#为函数增加一个可选的形参 if num:#当num不为空时bool值为True,执行if语句 m_a = {'singer_name': name, 'album_name': album}#返回一个字典 else: m_a = {'singer_name': name, 'album_name': album, 'num_1': num} return m_a A_1 = make_album(name = '1', album = '2') A_2 = make_album('3', '4',...
''' 比较、逻辑和身份运算符的使用 ''' flag0 = 1 == 1 flag1 = 3 > 2 flag2 = not (1 != 2) print('flag0 =', flag0) print('flag1 =', flag1) print('flag2 =', flag2) ''' 使用input()函数获取键盘的输入(字符串) 使用int()函数将输入的字符串转换为整数 使用print()函数输入带占位符的字符串 ''' ''' 分段函数求值 3x - 5 (x > 1) f(x) = x + 2 (-1 <= x <= 1) 5x + 3 (x < -1) ''...
#PythonDraw(蟒蛇绘制).py import turtle as t #将引用的库的名称更换以达到防止函数重名的情况发生 t.setup(650,350,200,200) #设定初始海龟的位置及窗体的长宽,(宽度,高度,起始点坐标x,y) t.penup() #空笔命令,此时海龟不在画布上留下痕迹 t.fd(-250) #走直线,d为距离 t.pendown() #着笔命令,与空笔命令成对出现,效果相反 t.pensize(25) #将海龟的腰围设置为25个像素 t.pencolor("purple") t.seth(-40) #方向控制函数,改变行进方向(绝对角度) for i in range(4):#循环语句,ran...
def make_great(names1, Great_name): while names1: current_name = names1.pop() current = 'the Great ' + current_name Great_name.append(current) ''' 使用该函数打印列表中的元素 ''' def show_magition_name(names): for name in names: print("\nThere is one magition name's " + name) magitions ...
##元组(使用圆括号()来定义元组,元组中的元素是不能被修改的),访问修改元组中元素值的语法不变 dim = (200,40) print(dim[0]) print(dim[1]) for number in dim: print(number) print("Original dim:") for number in dim: print(number) dim = (240,80) print("\nModified dim:") for number in dim: print(number)
import abc import numpy as np import math import collections # ===== helper classes and functions ==== # DO NOT EDIT this section -- see below # ======================================= class LanguageModel(metaclass=abc.ABCMeta): """ Abstract class for a language model Args: docs: the texts. Shou...
x = float(input('Enter the coordinate of the point x ')) y = float(input('Enter the coordinate of the point y ')) if -4 < x < 4 and -4 < y < 4: print('Point in a circle') else: print('The point is not in a circle')
# Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. # In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: # Example 1: # Input: rowIndex = 3 # Output: [1,3,3,1] # Example 2: # Input: rowIndex = 0 # Output: [1] # Example 3: # Input: rowInd...
# Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length. # Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. # Example 1: # Given nums = [1,1,1,2,2,3], # Your functio...
#Write your function here def odd_indices(lst): odd_lst = [] for x in range(len(lst)): if x % 2 != 0: odd_lst.append(lst[x]) return odd_lst #Uncomment the line below when your function is done print(odd_indices([4, 3, 7, 10, 11, -2]))
""" This program is a classifier for sentences. Given a dataset of sentences, the program trains a neural network to say if the sentence is a good or a bad feedback. """ import pandas as pd #used to manipulate files from sklearn.feature_extraction.text import CountVectorizer # used to vectorize the sent...
# 练习使用 filter() 内置函数 # filter(function, iterable) def filter_nums(nums): res = list(filter(lambda x: x >= 0, nums)) return res if __name__ == "__main__": nums = list(range(-5, 5)) print("before filter:", nums) res = filter_nums(nums) print("after filter:", res)
# 练习使用 reduce() 内置函数 # 当需要对一个列表进行一些计算并返回结果时,Reduce 是个非常有用的函数, 避免使用了 for 循环 # reduce(function, sequence) from functools import reduce def all_product(nums): res = reduce(lambda x, y: x * y, nums) return res if __name__ == "__main__": nums = [1, 2, 3, 4] res = all_product(nums) print(res)
import random inner = 0 outer = 0 for times in range(100000): x = random.random() * 2 - 1 y = random.random() * 2 - 1 print(x, y) if x ** 2 + y ** 2 <= 1: inner = inner + 1 print("圓內") else: outer = outer + 1 print("圓外") print("面積:", 4 * inner / (inner + outer))
from decimal import Decimal print(Decimal("3.14")) a = "hello python" print(a[0]) print(a[len(a) - 1]) print(a[-1]) print(a[1:7]) #1~6 print(a[2:]) print(a[::2]) print(a[2::2]) print(a[::-1]) print("hello" in a) #布林 a = True a = a and 5 >= 7 - 2 * 3 print(a)
import random def trans(card): transcolor = ["\u2663", "\u2666", "\u2665", "\u2660"] transnumber = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] return transcolor[card[0]] + transnumber[card[1]] def score(number): return (number - 1) % 13 deck = [] for c in r...
import random low = 1 high = 1000 ans = random.randint(low, high) times = 0 while True: msg = "Please input[" + str(low) + "-" + str(high) + "]:" guess = int(input(msg)) times = times + 1 if guess == ans: print("Bingo") break elif guess < ans: low = guess elif guess > a...
class Solution: # @param A : list of integers # @param B : list of integers # @return A modified after the merge def merge(self, A, B): size = len(A) + len(B) M = [0] * size i, j = len(A) - 1, len(B) - 1 k = size - 1 while i >= 0 and j >= 0: if A[i] ...
import math class Solution: # @param A : integer # @return a list of integers def allFactors(self, A): if A < 2: return [1] res = [] sqrt = int(math.sqrt(A)) for i in range(1, sqrt + 1): if A % i == 0: res.append(i) co...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def makeLinkList(L): prev = None for v in L: node = ListNode(v) if prev: prev.next = node else: head = node prev = node retu...
class Solution: # @param A : string # @return a strings def reverseString(self, A): S = [] for c in A: S.append(c) rev = [] while (len(S) > 0): rev.append(S.pop()) return ''.join(rev) string="abcfoo" print(string[::-1]) print(string[-1::-1])...
import os import csv # setup path to data resource csvpath = os.path.join('Resources', 'budget_data.csv') # create the working lists and some variables periods = [] deltas = [] total_months = 0 total_dollars = 0 delta_avg = 0 last = 0 curr_chng = 0 max_incr = 0 max_decr = 0 # read from resource file with open(csvpath...
# Write your code here class CoffeeMachine: def __init__(self, cwater, cmilk, cbeans, ccups, cmoney): self.cwater = cwater self.cmilk = cmilk self.cbeans = cbeans self.ccups = ccups self.cmoney = cmoney self.process_method() def UI_method(self): return in...
from sys import exit from random import randint from textwrap import dedent class Scene(object): def enter (self): print("This scene is not yet configured.") print("Subclass it and implement enter().") exit(1) class Engine(object): def __init__(self, scene_map): ...
print("Hello! Would you like me to sing a song for you?") choice = input() if choice == 'Yes': print(song) elif choice == 'No': print("Goodbye") else: quit() class song(object): def __init__(self, lyrics): self.lyrics = lyrics def sing_me_a_song(self): for...
a = 'global' class Fred: a = 'class' # in class scope b = (a for i in range(10)) # function scope c = [a for i in range(10)] # function scope d = a # class scope e = lambda: a # function scope f = lambda a=a: a # class scope @staticmethod #or @classmethod def g(): return a pr...
astring = 'Hello on Swamp Cinema' print(astring.index('e')) # 1 print(astring.rindex('e')) # 18 print(astring.find('e')) # 1 print(astring.rfind('e')) # 18 print('---------------') alist = [10,16,26,5,2,19,105,26] print(alist.index(16)) # 1 print(alist[1]) #second element in list : 16
def add(x, y): return x + y def sub(x, y): return x - y def mult(x, y): return x * y def div(x, y): return x / y print("Select operation.") print("1.add") print("2.sub") print("3.mult") print("4.div") choice = input("Enter choice(1,2,3,4):") num1 = int(input("Enter first num")) num2 = int(input("Enter second ...
import keyword print(keyword.kwlist) a,b,c = 1,2,3 print(a,b,c) a = b = c = 1 print(a,b,c) x = y = [7, 8, 9] x = [13,8,9] print("here is x : ",x) print("here is y : ",y) x[0] = 111 x[1] = 222 x[2] = 333 print('Here is x : ',x)
class Parrot: species = "bird" def __init__(self,name,age): self.name = name self.age = age def sing(self, song): return "{} sings {}".format(self.name, song) def dance(self): return "{} is now dancing".format(self.name) blu = Parrot("Blu",10) woo = Parrot("Woo",15) print("Blu is a {}".format(blu.__cla...
import math class Vector(object): def __init__(self,x,y): self.x = x self.y = y def __neg__(self): return Vector(-self.x, -self.y) def __add__(self,other): return Vector(self.x + other.x, self.y + other.y) def __sub__(self,other): return self + (-other) def __eq__(self,other): return self.x == other.x ...
import hashlib def hash_file(filename): """This function returns the SHA-1 hash""" h = hashlib.sha1() with open(filename,'rb') as file: chunk = 0 while chunk != b'': #read only 1024 bytes at a time chunk = file.read(1024) h.update(chunk) #return the hex representationof digest return h.hexdigest() mes...
class operation(): lis=[] def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def alloperation(self): resulta = self.num1 + self.num2 results = self.num1 - self.num2 resultm = self.num1 * self.num2 try: resultd = self.num1 / self...
from math_operator_operation import operation as op print("20-05-2019") while (True): num1 = input("Enter The First Number: ") num2 = input("Enter The Second Number: ") num1 = float(num1) num2 = float(num2) obj = op(num1, num2) re = obj.alloperation() for i in range(0, len(re)): ...
from datetime import date,datetime from main import daysbetween def calc(): print("You have",int(input("Enter amount of dining dollars you have remaining: "))/daysbetween(date.today(),"2021-12-17"),"dining dollars per day for the rest of the semester.") def main(): calc() if __name__=="__main__": main()
# 02.12.2019 Dasha import datetime print("Numerical derivative.\n" + str(datetime.datetime.now()) + "\n") step = 0.5 num_points_equals_5 = False #y_{-2} y_m2 = 0. #y_{-1} y_m1 = 0.25 #y_{0} y_0 = 75. #y_{+1} y_p1 = 1. #y_{+2} y_p2 = 4. # 5 points dev = 1/(12. * step) * (y_m2 - 8. * y_m1 + 8. * y_p1 - y_p2) print("Fr...
""" La librairie calc permet de faire les opérations basiques de calcul entre deux entiers. """ def add(arg1,arg2): try: return int(arg1)+int(arg2) except ValueError: print("Un des arguments n'est pas un entier.") def sous(arg1,arg2): try: return int(arg1)-int(arg2) except Va...
from typing import NamedTuple from typing import Dict GLOBAL_SCOPE = "GLOBAL" class Symbol(NamedTuple): name: str scope: str index: int class SymbolTable: """This class stores a dict representing all the variables in Monkey""" store: Dict[str, Symbol] num_definitions: int def __init__(se...
import time import math def receive(reader:callable)->(int,bytes): """ Receive a serial message :param reader: a function which reads data from serial :return: a tuple of the data """ protocol_num = b'' c = reader(1) if c == b'\xff': return 255, None while c != b'\n': ...
print("TRIANGLE BUILDER") print("================") num_rows = int(input("Enter the number of rows> ")) row = 1 while row <= num_rows: print("#" * row) row = row + 1 print() print("Triangle complete.")
#UPDATES# #adjacent arrays now update for both bs and us each time a space is clicked (still needs a bit of work) #updated to agree with rest of world: the (row, column) standard has been adopted from Square import * from GridVisualizer import * from pseudocode import * import random import time class MineSweeper(): ...
import math T=int(raw_input()) while T>0: N=int(raw_input()) print math.factorial(N) T-=1
def multipleOfThree(): n = int(input("Enter a number: ")) i = 0 if n % 3 == 0: print("This number is a multiple of 3.") for i in range(0, n//3): print(n, n-1, n-2) n-=3 else: print("This number isn't a multiple of 3.") for i in range(0, n/3): ...
#Gabriel Harrison #9/21/2018 #Change sorter #change 1 def change(): #1 get input from the user how much change raw_change=int(input("How much change do you have? ")) #2 calculate total for quarters, dimes, nickels, and penies quarters=raw_change//25 whats_left=raw_change % 25 dimes=whats_left//...
low = int(input("Enter the lower value : ")) up = int(input("Enter the upper value : ")) for i in range(low,up+1): if(i%2 == 0): print(i)
n = int(input("Enter a number: ")) if n>100000: print("false") elif(n%2==0): print("This Number is Even") else: print("This Number is Odd")
import copy def removeDups(L1, L2): for e1 in copy.deepcopy(L1): #for e1 in L1[:]: if e1 in L2: L1.remove(e1) L1 = [1,2,3,4] L2 = [1,2,5,6] removeDups(L1, L2) print('L1 =', L1)
from Person import Person import datetime me = Person('Michael Guttag') him = Person('Barack Hussein Obama') her = Person('Madonna') print(him.getLastName()) print(her.getLastName()) him.setBirthday(datetime.date(1961, 8, 4)) her.setBirthday(datetime.date(1958, 8, 16)) print(him.getName(), 'is', him.getAge(), 'days ol...
import sqlite3 from random import randint #Делаем переменные глобальными. global data global cur #Создаем базу данных. base - название. data = sqlite3.connect("base.data") #Создаем курсор. cur = data.cursor() #Создание таблицы. #CREATE TABLE IF NOT EXISTS users - создать столбец если такого нет. cur.ex...
# -*- coding:utf-8 -*- # @Time :2019/11/12 0012 15:03 # @Author :Lemon_huahua #@File :acculate.py #M与N的数学运算:用户输入两个数 M 和 N,其中 N 是整数,计算M 和 N 的5种数学运算结果,并依次输出,(编程题) # M=int(input ("M=")) # N=int(input("N=")) # print(M+N) # print(M-N) # print(M*N) # print(M/N) # print(M**N) #用户输入矩形的长和宽,计算其面积并输出 # chang=float(i...
import string from collections import defaultdict class SuffixTree(object): class Node(object): def __init__(self, label): self.label = label # label on path leading to this node self.out = {} # outgoing edges; maps characters to nodes self.leaf = defaultdict(list) #...
# -*- coding: utf-8 -*- """ ==================IMDB MOVIE REVIEW SENTIMENT ANALYSIS======================== ROLES OF EACH TEAM MEMBER FOR THIS PROGRAM: AVNEET - Splitting the input file into train and test - Implementing the bag of words - Implementing and finding results of random forest model PARAS ...
#命令行输入端口名称,得出IP地址 import re import sys f = open('1.txt') if len(sys.argv) < 2: sys.exit('输入错误') port = sys.argv[1] #print(port) while True: data = '' if sys.argv[1] in data: pattern = r'\d+\.?\d+\.\d+\.+\d+/?\d+' l = re.findall(pattern,data) print(l) if data == '\n': ...
ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher. Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special characters included in the string, they sh...
This question was asked by ContextLogic. Implement division of two positive integers without using the division, multiplication, or modulus operators. Return the quotient as an integer, ignoring the remainder. def division(x,y): toplam = 0 count = 0 while toplam != x: toplam += y count += 1 return coun...
``` Given an array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock once. Note that you must buy before you can sell it. For example, given [9, 11, 8, 5, 7, 10], you should return 5...
username = "kevser" while name != username: name=input("Enter your username: ") if name == username: print(f"Hello, {username}! The password is : W@12") else: print(f"Hello! try again.")
import turtle import random ''' n=0 0==>2 e=1 1==>0 w=2 2==>3 s=3 3==>1 ''' turtle.colormode(255) t1=turtle.Turtle() t1.speed(100) t1.hideturtle() t1.pensize(4) segmentLength=20 prev=[] current=[] def north(): t1.pencolor(random.randint(100,240), random.randint(100,240), random.randint(100,240)) t1.setheadin...
"""Define classes related to quizzes. ASSUMPTIONS: Names of quizes are unique. Quizzes are created by one teacher. There are always 4 choices in the questions, and 1 correct answer. When take a quiz, student can answer questions in order.Can not take a quiz again if it is finished. Question is...
def ohm_law(U, I, R): if ',' in list(U): U = U.replace(',', '.') if ',' in list(I): I = I.replace(',', '.') if ',' in list(R): R = R.replace(',', '.') if U is '' and I is '' or R is '' and U is '' or I is '' and R is '': return "Can't use the formula, need two parameters!" else: if U...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 1 22:28:22 2019 Line plots using the fill_between command @author: alberto """ import numpy as np import matplotlib.pyplot as plt n = 256 X = np.linspace(-np.pi, np.pi, n, endpoint=True) Y = np.sin(2 * X) plt.plot(X, Y + 1, color='blue', alpha=...
import numpy as np import matplotlib.pyplot as plt import random def meanshiftcode(image): # load image in "original_image" K= plt.imread('image') row=K.shape[0] col=K.shape[1] J= row * col Size = row,col,3 R = np.zeros(Size, dtype= np.uint8) D=np.zeros((J,5)) ...
# Working hour(s) for each day of the week for Suddeth mo = 8 tu = 7 we = 8 th = 8 fr = 6 hr_wage_suddeth = 8 total_hr = mo + tu + we + th + fr # print(total_hr) total_wage_suddeth = total_hr * hr_wage_suddeth print('Suddeth made $ %d for the week' %total_wage_suddeth) ## Bartol's goal for this week is $342 ## ho...
# H5_sung.py # set var score for user input(12:42PM) score = int(input('Please Enter the test scores: ')) def point_to_grade(score): """ From the user's, input numeric value, conversion happens here Return: grade, that contains numeric value converted to letter """ if score >= 800...
# wt = pounds # ht = inches # msg = optimal/over/under #18.5 - 25: optimal #below 18.5: under #over 25: over wt = int(input("Enter your current Body Weight in pounds: ")) ht = int(input("Enter your current Body Height in inches: ")) bmi = wt * (703/ht**2) print("Your BMI is: ", bmi) if bmi < 18.5: print("Under...
type_number = int(input('Enter any integer: ')) if type_number % 2 == 0: print(type_number, "'s EVEN number") else: print(type_number, "'s ODD number")
# file: bird.py # this module contains the class from OOP s2 t5 UCU 2019. class Bird: """ A class for representing birds. """ def __init__(self, name, can_fly=True, eggs=0): """ A method for initialisation Bird object. :param name: str :param can_fly: bool """ self.name = name self.can_fly = can_fly ...
def subarraysWithKDistinct( A, K): left = 0 right = 0 rtn_cnt = 0 temp = set() while left <=right and right <len(A) and left <= len(A)-K: if len(temp) <= K: temp.add(A[right]) if len(temp) == K: rtn_cnt +=1 right+=1 if right >=l...
class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.capacity = capacity self.num_dict = {} self.lru = [] def get(self, key): """ :type key: int :rtype: int """ if key in self.num_dict: ...