text
stringlengths
37
1.41M
# Input: An integer k and a string Text. # Output: DeBruijnk(Text), in the form of an adjacency list. from collections import defaultdict def DeBruijn(Text, k): deBruijn = defaultdict(list) t = len(Text) for i in range(0, t - k + 1): kmer = Text[i:i+k-1] deBruijn[kmer].append(Text[i+1:i+k])...
# Input: A DNA string Genome # Output: A list containing all integers i minimizing Skew(Prefix_i(Text)) over all values of i (from 0 to |Genome|) def MinimumSkew(Genome): positions = [] # output variable array = SkewArray(Genome) print('array, ', array) minimum = min(array) print('minimum', minimum...
import unittest MS = __import__('02_MedianString') class MedianStringCase(unittest.TestCase): # there is actually two solutions for sample dataset def test_sample(self): Dna = ['AAATTGACGCAT','GACGACCACGTT','CGTCAGCGCCTG','GCTGAGCACCGG','AGTACGGGACAG'] expected = 'ACG' expected2= 'GAC' ...
def main(): Reverse("ATAG") Complement("ATGC") def Complement(Pattern): result = "" for num in range(0,len(Pattern)): if (Pattern[num] == 'A'): result+='T' elif (Pattern[num] == 'T'): result+='A' elif (Pattern[num] == 'G'): result+='C' elif (Pattern[num] == 'C'): result+='G' print(result) def...
fname=input("Enter a file name : ") f=open(fname,"r") chr=0 words=0 lines=0 for l in f: lines+=1 wordlist=l.split() words+=len(wordlist) chr+=len(l) print("characters :",chr) print("Words : ",words) print("Lines : ",lines)
def func(str): newstr='' for s in str: if s not in "!()-[]{};:''',\,<>/?@#$%^&*_~": newstr+=s return newstr str=input("Enter input : ") print(func(str))
import random def print_mat(n): for i in range(n): for j in range(n): print(random.randint(0,1),end=' ') print() n=int(input("Enter n")) print_mat(n)
def isconsecutive(l): for i in range(len(l)-3): c=[l[i] for j in range(4)] #print(c) if(l[i:i+4]==c[0:4]): return True return False listitem=input("Enter list element") li=listitem.split() print(isconsecutive(li))
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ checker = -1 for cur in range(len(nums)): if checker < 0 and nums[cur] == 0: checker = cur...
class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ path = path.split('/') result = '' pass_dir = ['', '.'] stack = [] for dir in path: if dir not in pass_dir: if dir == '..':...
class Solution(object): def countSegments(self, s): """ :type s: str :rtype: int """ return len(s.split(' ')) input_str = "Hello, my name is John" obj = Solution() print(obj.countSegments(input_str))
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: int """ odd_flag = False length = 0 frequency = [0] * 52 for char in s: if ord(char) >= ord('a'): idx = ord(char) - ord('a') + 26 ...
# iterative solution # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def helper(self, node, target, before_sum, dict): if node is None: return complement = before_sum + no...
# max heap implementation practice import math class MaxHeap(object): def __init__(self): self.data = [] def get_size(self): return len(self.data) # find parent index of last leaf (parent of last leaf = last parent) # compute by length of array (length) @staticmeth...
class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ if num < 10: return num result = num % 9 if result == 0: return 9 else: return result num = 23 obj = Solution() print(obj.addDig...
class Solution(object): def pattern_checker(self, arr): check_hash = {} cur = 0 result = [] for ch in arr: if ch in check_hash: result.append(check_hash[ch]) else: cur += 1 check_hash[ch] = cur re...
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.data = [] self.min_stack = [] self.min_value = 0 def push(self, x): """ :type x: int :rtype: void """ if len(self.data) <= 0 or ...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def path_by_dfs(self, node, result, path): if node is None: return if node.left is None and node.right...
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: void Do not return anything, modify nums1 in-place instead. """ if n == 0: return num1...
from pathlib import Path from exceptions import InputRowLengthException, InputColumnLengthException, SolutionFailedException class Helpers: def get_puzzle(self, puzzle_name, directory='puzzles'): """ Inputs: - puzzle_name: 'puzzle1.txt' - directory: 'puzzles' path_...
class Point: def __init__(self, x = 0, y = 0): self.__x = x; self.__y = y def __checkValue(x): if isinstance(x, int) or isinstance(x, float): return True return False def setCoords(self, x, y): if Point.__checkValue(x) and Point.__checkValue(y) : ...
message = input() alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' h1 = message[:int(len(message)/2)] h2 = message[int(len(message)/2):] decrypted = '' r1, r2 = 0, 0 for i in range(len(h1)): r1 += alphabet.index(h1[i]) r2 += alphabet.index(h2[i]) for i in range(len(h1)): decrypted += alphabet[((alphabet.index(h1[...
date = input() if date == 'OCT 31' or date == 'DEC 25': print('yup') else: print('nope')
import numpy as np ## Abstract class for Activation : class Activation(): def forward(self,x): raise NotImplementedError def gradient(self,x): raise NotImplementedError ## Real class for activation : class Identity(Activation): def forward(self,x): return x def gradient(sel...
from tkinter import * import tkinter.ttk as ttk import tkinter.messagebox class Screen: '''Game Vars''' # These variables are the basis of the game, and will not be changed by # settings # Screen proportions MAIN_SPLIT = 0.15 # split between Top and Bottom frames BOTTOM_SPLIT = 0.75 # Split...
#!/usr/bin/python # -*- coding: utf-8 -*- ### Joc de 3 en ratlla. ### Creat per David Noguera contacta@noguerad.es ### Sou lliures de copiar o modificar el codi, ### però siusplau citeu a l'autor. import os import random import time #-----Variables #-----Constants tirs = ['5'] # Començem amb la casel...
from csv import Error, DictReader, QUOTE_NONE from typing import Generator, Union from common import MetadataRecord from .exceptions import ExtractionError from .file_extractor import file_extractor def _sanitize_key(column_name: str) -> str: """ Sanitize a column_name read from a CSV file, by removing lead...
class Question: def __init__(self, prompt, answer): self.prompt = prompt self.answer = answer question_prompts = [ # List of Questions "\nWhich of these is not a core data type in Python? \n (a) List (b) Dictionary \n (c) Tuple (d) Class\n\n" , "\nWhat data type is th...
## A Watermelon 🍉 # Mubashir is eating a watermelon. # He spits out all watermelon seeds if seeds are more than five. # He can swallow all watermelon seeds if seeds are less than five. # He can eat 1/4 of watermelon each time. # Given a 2D array of watermelon where 0 is representing juicy watermelon while 1 is represe...
"""Test module hangman.""" from hangman import check_format_answer, generate_random_word, \ get_wrong_message, get_correct_message, check_answer def test_check_format_answer(): """Test check_format_answer.""" assert check_format_answer("a"), \ "Check format answer don't see one char like correct a...
"""TimeSpecification""" from __future__ import absolute_import import types from species import Species from six.moves import range def floatRange(start, stop, step, epsilon=0.001): """Like range, but for floats. The last step is adjusted to fall into stop, all the while avoiding a step smaller than eps...
"""Algebraic Operations with List of FLoats.""" import math import numpy as npy from operator import __and__ as AND from operator import add as addition from operator import mul as multiplication from types import ListType,TupleType def toList(x): """ Direkt von der ZauberFloete returns a list type ...
import random value = random.randint(1,100) count = 0 print('Proposer un nombre entre 1 et 100!') guess = input("Votre valeur: ") while guess != value: count += 1 if guess.isnumeric(): guess = int(guess) else: print("Ce n'est pas un nombre entier, veuillez entrer un nombre entier...
import pandas as pd import sys import os from datetime import date # fileloc = sys.argv[1] locinput = input("Paste the directory of the xlsx file ") # read the excel file df = pd.read_excel(locinput) # strip unecessary columns and leaving whats needed df = df[['DSM', 'Util %']] # remove NaN's df = df.dropna() ...
print("********************************") print("Star Pattern") print("********************************") print("Number of Stars you want to see in galaxy") num = int(input()) + 1 print("You want to print reverse or straight (0(Yes)/1(NO))") optionReverse = int(input()) if optionReverse == 0: Reverse = True elif op...
#Taking cost of 1 Tile cost = int(input("Enter the cost of 1 Tile:" )) print(f"Cost of 1 Tile is {cost}Rs") #floor height and width f_width = 11 f_height = 10 print('Floor width is 11 Feet and height is 10 Feet ') #Tile Height and width t_width = 60 t_height = 60 print('Tile width is 60 cm and height is 60 cm ') #T...
#!/usr/bin/python from ingredient import Ingredient class Meal: """The Meal class contains the name of the meal as well as a list of required Ingredients. """ def __init__(self, options): self.ingredients = [] self.hydrate(options) def hydrate(self, options): self.name =...
# 숨겨진 카드의 수를 맞추는 게임입니다. 1-100까지의 임의의 수를 가진 카드를 한 장 숨기고 이 카드의 수를 맞추는 게임입니다. # 아래의 화면과 같이 카드 속의 수가 57인 경우를 보면 수를 맞추는 사람이 40이라고 입력하면 "더 높게", # 다시 75이라고 입력하면 "더 낮게" 라는 식으로 범위를 좁혀가며 수를 맞추고 있습니다. 게임을 반복하기 위해 y/n이라고 묻고 n인 경우 종료됩니다. import random min, max = 1, 100 while True: randomnum = random.randrange(max) + min ...
#!/usr/bin/python3 matriz = [ [1,2,3], [4,5,6], [7,8,9] ] for x in range(0,len(matriz),1): for y in range(0,len(matriz),1): print(matriz[x][y])
# O mesmo professor do desafio 19 quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada. # import random from random import shuffle import os import time listaOrdemAlunos = list(range(4)) i = 0 while i < len(listaOrdemAlunos): lis...
""" Leia um numero inteiro e mostre na tela o seu sucessor e antecessor """ numero = int(input('Entre com um numero inteiro: ')) print('O antecessor de {} é : {}'.format(numero, (numero-1))) print(' e o sucessor é {} '.format(numero+1))
# Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo. # import math from math import tan, sin,cos, radians angulo = int(input('Entre com ângulo: ')) print('O seno de {} é {:.2f},\nO Cosseno de {} é {:.2f},\nA tangente de {} é {:.2f}'.format(angulo, sin(radian...
# Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido. # import random from random import choice import os import time lista = list(range(4)) i = 0 while i < len(lista): lista[i] = str(input('En...
def levenstein_dist(str1, str2): dist = [i for i in range((len(str1) + 1))] for idx2 in range(1, len(str2)+1): next_dist = [0] * (len(str1) + 1) next_dist[0] = idx2 for idx1 in range(1, len(str1)+1): if str1[idx1-1] == str2[idx2-1]: substitution_cost = 0 ...
# 两个栈实现一个队列 def stacktoqueue(size): stack1 = [] stack2 = [] for i in range(size): inqueue(i) def inqueue(data): pass def outqueue(): pass def transdata(stack1, stack2): pass
nums = [23,2,4,6,2,5,1,6,13,54,8] def select_sort(nums): # 时间复杂度O(n^2) if not nums: return [] for i in range(len(nums)-1): smallest = i for j in range(i, len(nums)): if nums[j] < nums[smallest]: smallest = j nums[i], nums[smallest] = nums[sma...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def preordertraversal(self, root): res = [] def dfs(root): if not root: return res.append(root.val) dfs(root.left) ...
from operator import itemgetter def check(string , checksum): dic = {} numbers = '' for i in string : if i.isalpha() : if i in dic : dic[i] += 1 else : dic[i] = 1 elif i.isdigit() : numbers += i temp = sorted(dic....
import csv # with open('names.csv', 'w') as file: # fieldnames = ['question', 'title'] # writer = csv.DictWriter(file, fieldnames=fieldnames) # writer.writeheader() questionid = 100000 with open('01_01_2014-12_31_2014_1_.csv') as csvfile: spamreader = csv.DictReader(csvfile) for row in spamr...
# pylint: disable-msg=anomalous-backslash-in-string """ Clock object ============ The :class:`Clock` object allows you to schedule a function call in the future; once or repeatedly at specified intervals. It's heavily based on Kivy's Clock object. (Almost 100% identical.) An instance of the clock is available in MPF s...
#Graph BFS traversal def dfs(G,n,V): queue = [n] while queue: e = queue.pop(0) print "{0}->".format(e), for item in G[e]: if not V.get(item,False): queue.append(item) V[item] = True def main(): G = { 1:...
import time import picamera import os import datetime def nameProject(cam): name = str(input("\n\nEnter project name: ")) date = datetime.datetime.now() now = date.strftime("%Y-%m-%d") mypath = "/home/pi/camera/"+now+"-"+name if not os.path.isdir(mypath): os.makedirs(mypath) ...
n = input('請輸入西元年') n = int(n) def is_leap(n): if n%4 != 0: print('平年') return False elif n%100 == 0 and n%400 != 0: print('閏年') return True elif n%100 == 0 and n%400 != 0: print('平年') return False elif n%400 == 0 and n%3200 !=0 : print('閏年') return True else : print('MD') is_leap(n)
import numpy as np import matplotlib.pyplot as plt def cross(set_list): '''Given a list of sets, return the cross product.''' # By associativity of cross product, cross the first two sets together # then cross that with the rest. The big conditional in the list # comprehension is just to make sure tha...
n1 = 15 n2 = 25 print "maximum of "+ n1 +"and " + n2 +"is " +max(n1,n2) #maximum of 15 and 25 is 25 print "maximum of {0} and {1} is {2}".format(n1,n2,max(n1,n2)) #maximum of 15 and 25 is 25 print "maximum of %i and %i is %d" % (n1,n2,max(n1,n2)) #maximum of 15 and 25 is 25 """ where %i and %d are placeholders for in...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- '''对象的引用''' ''' import sys print(sys.getrefcount('aa')) print(sys.version) print(sys.version_info) import platform print(platform.version()) print(platform.python_version()) ''' '''OOP面向对象编程''' ''' class Person(): def __init__(self,name): self.Name=name ...
#!/usr/bin/env python # -*- coding:utf-8 -*- from cryptography.fernet import Fernet class Crypto(object): def __init__(self): self.c_key = b'YrrndDCGiZjuYaIKtDq0bt1cNRqOMgtbcCGQBwtNwuo=' # 生成带密钥的实例对象 self.fernet_obj = Fernet(self.c_key) def encryption(self, text): # 调用实例对象的加密方...
a = 1, 2.3, 4.1, "sadas" print(a) print(a[1]) for x in a: print(x) x, y = divmod(15, 2) # 商,余数 print(x, y) # 元组是不可变类型,这意味着你不能在元组内删除或添加或编辑任何值。 # a[1] = 1 # TypeError: 'tuple' object does not support item assignment # 要创建只含有一个元素的元组,在值后面跟一个逗号。 b = (12,) print(type(b)) # <class 'tuple'>
# 在 python 中 我们不需要为变量指定数据类型。所以你可以直接写出 abc = 1 ,这样变量 abc 就是整数类型。如果你写出 abc = 1.0 ,那么变量 abc 就是浮点类型。 # python 也能操作字符串,它们用单引号或双引号括起来,就像下面这样。 abc = 1 b = 1.3 c = 'a' e = "da" 的 = 'ada' h = 'dadasdasdasdsadas' print(type(e)) number = 5 # int(input("请输入一个整数:")) if number < 200: print("%d < 200" % number) else: prin...
import logging ''' try: r = 10/int('a') print('result:',r) #上面有错,这句不会执行 except ValueError as e: print('ValueError:',e) logging.exception(e) except ZeroDivisionError as e: print('ZeroDivisionError:',e) else: print('no error') # 此外,如果没有错误发生,可以在except语句块后面加一个else,当没有错误发生时,会自动执行else语句: finally: # fi...
# 只要有任意一个操作数是浮点数,结果就会是浮点数。 a = 1 + 2 b = 1.0 + a print(type(a)) # <class 'int'> print(type(b)) # <class 'float'> # 进行除法运算时若是除不尽,结果将会是小数 这很自然?自然个毛啊,C语言可不是这样的 c = 14 / 3 print(c) # 4.666666666666667 # 整除 d = 14 // 3 print(d) # 4 # 取余 % # 小栗子 days = 265 ''' # divmod(num1, num2) 返回一个元组,这个元组包含两个值,第一个是 num1 和 num2 ...
# ASCII编码是1个字节,而Unicode编码通常是2个字节 # 本着节约的精神,又出现了把Unicode编码转化为“可变长编码”的UTF-8编码。UTF-8编码把一个Unicode字符根据不同的数字大小编码成1-6个字节,常用的英文字母被编码成1个字节,汉字通常是3个字节,只有很生僻的字符才会被编码成4-6个字节。如果你要传输的文本包含大量英文字符,用UTF-8编码就能节省空间: a = 'aaa' # 字符串 str Unicode编码 a = b'aaa' # bytes 每个字符都只占用一个字节 # 如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用d...
# 如果要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__,在Python中,实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问 class Student(object): def __init__(self, name, score): self._name = name self.__score = score # 这个self参数必须有,调用时不用传 def print_score(self): print("%s: %s" % (self.__name, self.__score)) ...
# for..in 循环 names = ['dada', '小米', '小明'] for name in names: print(name) # 计算1+2+3+4 # 方式1 sum = 0 for x in [1, 2, 3, 4]: sum += x print(sum) # 方式2 # range()函数,可以生成一个整数序列,再通过list()函数可以转换为list。比如range(5)生成的序列是从0开始小于5的整数(0,1,2,3,4): sum = 0 for x in range(101): sum += x print(sum) # while # 计算100以内所有...
''' Becoming a black belt with dictionaries ''' from pprint import pprint # How to make a dictionary ######################### d = {} # dictionary literal d = dict() # dict contructor # Five ways to prepopulate a dictionary ############# d = { ...
n_fizz = int(input("Hello!\nPlease input fizz number: ")) n_buzz = int(input("Hello!\nPlease input buzz number: ")) n_main_number = int(input("Hello!\nPlease input main number: ")) main_str="" i=1 while i<=n_main_number: if i % n_fizz == 0 and i % n_buzz == 0: main_str+='FB' elif i % n_fizz == 0: main_str+='F' ...
#coding=utf-8 class InventoryItem(object): def __init__(self, title, description, price, store_id): self.title = title self.description = description self.price = price self.store_id = store_id def __str__(self): return self.title def __eq__(self, other): i...
#!/usr/bin/env python ''' Solution file for PA03 Maze. Uses longest distance algorithm. ''' import rospy from geometry_msgs.msg import Twist from sensor_msgs.msg import LaserScan # constants SAFE_DISTANCE = 0.3 # meters MAX_RANGE = 10 # meters INDEX_THRESHOLD = 10 # degrees MOVE = True # bool # get scan values of 180...
def minDeletionSize(A): """ :type A: List[str] :rtype: int Input: ["cba","daf","ghi"] Output: 1 Explanation: After choosing D = {1}, each column ["c","d","g"] and ["a","f","i"] are in non-decreasing sorted order. If we chose D = {}, then a column ["b","a","h"] would not be in non-decrea...
#!/usr/bin/env python class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root: root.right, root.left = self.invert...
#!/usr/bin/env python def Unique_Email_Add(email_list): unique_email = set() for str in email_list: host, _, domain = str.partition('@') if '+' in host: host = host[:host.index('+')] unique_email.add(host.replace(".","") + '@' + domain) return (unique_email) if __name__...
#!/usr/bin/env python import random import time def bubble_sort(listarry): for i in range(len(listarry)): for j in range(i, len(listarry)): if listarry[i] > listarry[j]: listarry[i], listarry[j] = listarry[j], listarry[i] return listarry def select_sort(listarry): for i...
import sqlite3 connection = sqlite3.connect('banter.db') cursor = connection.cursor() #sql = """CREATE TABLE Userdetails (id INTEGER PRIMARY KEY AUTOINCREMENT,fname TEXT,lname TEXT,uname TEXT UNIQUE,passwd TEXT )""" #sql = "INSERT INTO Userdetails (fname,lname,uname,passwd ) VALUES ('vijesh', 'v','vijay','catfoss')"...
import numpy as np import matplotlib.pyplot as plt def read_report_data(csv): train = [] validation = [] with open(csv, 'r') as f: next(f) # skip csv header title(step,loss,acc) last = -1 for line in f: step, loss, acc = line.rstrip('\n').split(',') step = int(step) loss = float(loss) acc = floa...
import function x=input("enter the numer") y=input("enter the numer") a=function.add(int(x),int(y)) print(a)
from . import Arm from . import Optimizer class Instruction: CNTR = 0 def __init__(self, optimizer: Optimizer, arm: Arm, x1: int, y1: int, x2: int, y2: int): self.O = optimizer self.No = Instruction.CNTR self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 ...
toni = 100 rani = 87 jaka = 90 diah = 69 print("nilai toni = "+str(toni)+ " dan nilai rani = " +str(rani)+ \ " dan nilai jaka = " +str(jaka)+ " dan nilai diah = "+str(diah)) print("nilai toni = {} dan nilai rani = {} dan nilai jaka = {} dan nilai diah = {}" \ .format(toni, rani, jaka, diah)) print...
#!/usr/bin/env python3 # simulates an enigma machine with 1 rotor and 1 plug in a plugboard # known: if x = 'axe' and k = (3, 'a', 'f') then ans = 'UOX'. rotor = [6, 14, 7, 8, 12, 17, 9, 13, 20, 23, 16, 21, 25, 15, 24, 18, 0, 19, 5, 4, 22, 2, 10, 1, 11, 3] def main(): # parameters: s = "axed" key = [3, 'a...
# Define our variables Wage = float(input("What is your Hourly Wage?")) Hours = int(input("Regularly, how many Hours do you receive in a week?")) Overtime = float(input("Do you have any Overtime Hours?")) Pay = float(Wage * Hours) Overpay = float(Overtime * (Wage * 1.5)) Total = (round(Overpay + Pay, 2)) # Hav...
#名字管理器 #打印功能 print("="*50) print('Name System') print('1: add new name') print('2: delet name') print('3: revise name') print('4: search name') print('5: quite') print("="*50) name = [] #獲取用戶的選擇 #根據選擇,執行相印功能 while True: num = int(input("please enter the option: ")) if num == 1: new_name = input("enter the name: ") ...
# not allowed to import any libraries so can't use time # can't even import regex, god damn # helper fucntion to split out time and duration into hours and minutes def stringloop(string): # split out time into 3 vars. can't use regex so looping through chars loopstage = "hour" hour = "" minute = "" ...
mystring="hello" #string myfloat=10 #floating point myint=20 #integer print #Printing on Screen print mystring print myfloat print myint print print mystring, "I am,", myfloat," I will be", myint, "in ten years." print #Mathematical operations print (4+8)*19/6 print 65*9/3 print 89*1999/9 print 500/8*2 print 88817...
import unittest # function to return the factorial of a number # Add comments def factorial(num): ans = 1 if num < 0: return None elif num < 2: return ans else: for i in range(1, num + 1): ans = ans * i return ans # function to check if the input year is a l...
""" CSC464 Assignment 1 Producer Consumer Classical Problem in Python Thor Reite V00809409 10/11/2018 """ import threading pc_cond = threading.Condition() item_buffer = 0; ##tracks items in buffer def main(): producer().start() consumer().start() producer().join() consumer().join() exit(1) class...
max_palindrome = 0 for i in range(100, 999): for j in range(i, 999): mult = i * j mult_str = str(mult) if mult_str == mult_str[::-1] and int(mult) > max_palindrome: max_palindrome = mult print (max_palindrome) print(max([i * j for i in range(100, 999) for j in range(i, 999) if ...
import unittest from pairing import Pairing from result import Result #It's an open question whether we want a separate TestCase class for each Guidewords class we are testing. Result and pairing can be tested in the same test case, since Result inherits from pairing and doesn't override anything. But should tournamen...
a=int(input("enter number :")) b=int(input("enter number :")) c=(input("enter name :")) d=[a,b,c] print(d) for h in d: print("the values are :",h)
class cal4: def setdata(self,num): self.num = radius def display(self): return num**2 num = int(input("enter the number : ")) obj.cal4() obj.setdata(num) square = obj.display() print(f'square of {num} is {square}.')
import sqlite3 import pprint import sys from knn_utils import * def manhattan_distance(x1,x2): ''' Returns a tuple of the Manhattan distance between a pair of attribute vectors and a tuple of the three attributes on which the two vectors are the most similar. ''' relevant_attributes = [...
#!/usr/bin/env python """From flight data, gather info about distance between airports and check for consistency. Then write to distance.csv""" from sets import Set import numpy as np import pandas as pd pd.options.mode.chained_assignment = None #Suppress overwrite error. def get_distancefreq(): #Empty datafram...
first_number = 0 second_number = 1 for i in range(10): third_number = first_number + second_number first_number = second_number second_number = third_number print(first_number)
class Menu(): """ Simple representation of a menu: one state of the state machine created by Candela. Consists of a series of Commands One Shell instance may have one or more menus. """ def __init__(self, name): self.name = name self.title = '' self.commands = [] ...
import math def root(n, base=9): return n % base or n and base def root_with_factor(n, base=9): base_factor = math.floor((n/base)) root = n % base or n and base if get_factor: return root, base_factor return root
"""Method 1 a=input() b=len(a) count=0 for i in a: if(i=="i" or i=="I"): count+=1 print("number of i is",count) print("length of input is",b) """ #Method 2 a=input() count=0 b=0 for i in a: count+=1 if(i=="i" or i=="I"): b+=1 print("number of i is",b) print("length of input...
# -*- coding: utf-8 -*- """ Created on Wed Jul 11 00:23:53 2018 @author: atulr """ import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model import pandas as pd df= pd.read_csv('./Stockdata/ethi.csv') X=df["Open"] Y=df["Close"] dim= df.shape[0] print(dim) per=( .7 *dim...
class member: #type should have 3 options #generic, important, personal #generic means simple automated message #important means complex automated message #personal means should be sent a personal message #consturctor def __init__(self, name, age = 0, birthdate = " ", phone = " ", ptype = "g...
import matplotlib.pyplot as plt import numpy as np class lr(): """ Linear regression using least squares method """ def fit(self, x, y): """ Fit model Parameters ---------- X : array_like, shape (n_samples, n_features) Training data y : array_like, shape (n_samples, ) T...
''' Rounding to get plot instead of interpolating. Future work will use interpolation instead of rounding. Creates a plot of the change in a desired weather variable vs. distance as altitude and location above the Continental US changes. ''' import pickle import copy import csv import matplotlib.pyplot as plt fro...
# guessing game secret_word = "lion" guess = "" attempts = 0 attempt_limit = 2 out_of_guesses = False while guess != secret_word and not(out_of_guesses): if attempts < attempt_limit: attempts += 1 guess = input("Enter guess: ") if attempts < attempt_limit: print("You have one g...