text
stringlengths
5
121k
from typing import List from blessed import Terminal import math def print_xy(term: Terminal, x: int, y: int, value: str, flush=True, max_width: int = None, center=False, trim=False): """trim and center both require max_width to be given""" if max_width is not None: empty_len = max(max_wi...
from datetime import datetime import csv movieItems = [] def csv_dict_reader(file_obj): """ Read a CSV file using csv.DictReader The line is basically a dictionary object. """ reader = csv.DictReader(file_obj, delimiter=',') for line in reader: if line["id"] != '': ...
class Obstacle(object): def __init__(self): self.area = -1 self.x = -1 self.y = -1 self.angle = -100 self.width = -1 self.height = -1 self.position = 'None' def update(self, x, y, width, height, area, angle, pos): self.area = area ...
import random rand = random.randint(1, 200) tentiva = 10 print(" Bem vindo ao jogo da advinhacao!") print(" Tente advinhar o numero sorteado, e ele deve ser menor que 200!") while True: numero1 = int(input("digite o numero: ")) if numero1 == rand: print(" parabens voce acertou! ") break ...
from MathOperations import MathOperation """ Python file for implementing the solution of the project """ class Solution: """ This class is responsible for the calculation of the value of alpha and the length between the two coasters of same radius """ alpha_value = float(10) @staticmethod ...
class Solution: def tribonacci(self, n: int) -> int: if(n==0): return 0 if(n==1): return 1 if(n==2): return 1 n1 = 0 n2 = 1 n3 = 1 for i in range(3,n+1): n4 = n1+n2+n3 n1 = n2 n2 = n3 ...
def solution(phone_book): answer = True phone_book.sort() for i in range(1,len(phone_book)): if(phone_book[i-1] == phone_book[i][:len(phone_book[i-1])]): answer = False return answer
def printOneCount(arr): myDict = dict() for i in arr: myDict[i] = myDict.get(i,0) + 1 arrMax = min(myDict, key=myDict.get) lengthOne = list() for key, value in myDict.items(): if (value == 1): lengthOne.insert(len(lengthOne),key) if (len(lengthOne) == 1): print(arrMax) else: print(...
def binarySearchRot(arr, value, startRealIndex): end = ((startRealIndex - 1) + len(arr)) % len(arr) start = startRealIndex startPassedEnd = False while (startPassedEnd != True): mp = ((( ((start - startRealIndex) % len(arr)) + ( (end - startRealIndex + len(arr)) % len(arr))) // 2) + startRealIndex) % ...
def quick_sort(arr): if len(arr) < 2: return arr else: pivot = arr[0] less = [num for num in arr[1:] if num <= pivot] greater = [num for num in arr[1:] if num > pivot] return quick_sort(less) + [pivot] + quick_sort(greater) q = quick_sort([7, -9, 12, 8, 89]) print(q) ...
def finder_bitwise(l1, l2): result = 0 for num in l1 + l2: result ^= num return result out = finder_bitwise([5, 5, 7, 7], [5, 7, 7]) print(out)
def calc_fib(frm,till): arr_nums = [0,1] if (till <= 1): return till for i in range(2,till+1): arr_nums.append((arr_nums[-1]+arr_nums[-2])%10) a = sum(arr_nums[frm:till+1]) %10 return a if __name__ == '__main__': frm, till = map(int, input().split()) print(calc_fib(frm, till))
import json import re import mmh3 ''' GOAL: Get all links to other wikipedia pages from the json file of a single page. ''' WIKILINK_REGEX = r'\[\[([\| \w+]*)\]\]' rgx = re.compile(WIKILINK_REGEX) def getPageIndex(pageName): ''' Creates an Index from page name, thanks to a hash function We need to ha...
import random from typing import Text class Board: def __init__(self, length): """The class constructor Args: self (Display): an instance of Display """ self._items = {} self._solutionLength = length def to_string(self): """Converts the board data to its string repr...
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False z = x rev = 0 prev = rev while ( z != 0 ): current = z % 10 rev = rev * 10 + current ...
""" Otto All moves python test OttDIY Python Project, 2020 | sfranzyshen """ import otto9, time Otto = otto9.Otto9() Otto.init(5, 12, 13, 14, True, 0, 1, 2, 3) Otto.home() Otto.walk(2, 1000, 1) Otto.walk(2, 1000, -1) Otto.turn(2, 1000, 1) Otto.home() time.sleep_ms(100) Otto.turn(2, 1000, -1)...
import matplotlib.pyplot as plt import numpy as np from numpy.random import rand beta = 1.0 def initialise(n): state = np.random.randint(2,size=(n,n)) return 2*state -1 def metropolis(state,beta,n): a = np.random.randint(0,n) b = np.random.randint(0,n) spin_ij = state[a,b] spin_neighbou...
my_name = 'Valkyrie' my_age = 23 my_height = 130 my_weight = 66 my_eyes = 'Brown' my_teeth = 'White' my_hair = 'Black' print(f"Let's talk about {my_name}.") print(f"She's {my_height} centimeters tall.") print(f"She's {my_weight} kilograms heavy.") print(f"Actually that's not too heavy.") print(f"She's got {my_eyes}...
print("From The Top!!!") print('You\'d need to know \'bout escapes with \\ that do:') print("\n newlines and \t tabs.") poem = """ \tMove him into the sun— Gently its touch awoke him once, At home, whispering of fields half-sown.\nAlways it woke him, even in France, Until this morning and this snow. If anything might ...
import numpy as np samples = ('The cat sat on the mat.', 'The dog ate my homework.') token_index = {} for sample in samples: for word in sample.split(): if word not in token_index: token_index[word] = len(token_index) + 1 max_length = 10 results ...
def check_win(d): """Input is a dictionary with keys 1-9 according to a numerical keypad: 789 456 123 function checks win condition for tic tac toe and returns the dicts value""" w = ( (7, 8, 9), (4, 5, 6), (1, 2, 3,), (1, 4, 7), (2, 5, 8), (3, 6, 7), ...
from pybraincompare.compare.network import connectogram from pybraincompare.template.visual import view import pandas connectivity_matrix = "data/parcel_matrix.tsv" parcel_info = pandas.read_csv("data/parcels.csv") networks = list(parcel_info["Community"]) groups = ["%s-%s" %(parcel_info["Hem"][x],parcel_info["ID...
NUMBERS = ["a ","two ","three ","four ", "five ", "six ","seven ","eight ","nine ","ten ","eleven ","twelve ", "thirteen ", "fourteen ", "fifteen ","sixteen ","seventeen ", "eighteen ","nineteen "] NUMERALS = ["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth"] O...
def fibonacci(n, multiplier=1): """ Generate Fibonacci Sequence fib(n) = fib(n-1) + fib(n-2)*multiplier NB Uses recursion rather than Dynamic programming """ if n <= 2: return 1 return fibonacci(n-1, multiplier) + fibonacci(n-2, multiplier) * multiplier def fibonacciDynamic(n,...
import json class DictWrapper: def __init__(self, data): self.data = data class DataBaseWrapper: def __init__(self): try: db = open('db.json', 'r') dict_db = json.load(db) db.close() except: db = open('db.json', 'w') ...
albums = [("Welcome to my Nightmare", "Alive Cooper", 1975), ("Bad Company", "Bad Company", 1974), ("Nightflight", "Budgie", 1981), ("More Mayhem", "Emilda May", 2011), ("Ride the Lightning", "Metallica", 1984), ] print(len(albums)) for album in albums: name, art...
import math import string import sys occurences = {} for line in sys.stdin: str = line.splitlines()[0] denominator = 1 for char in string.ascii_letters: occurences[char] = 0 for char in str: occurences[char] += 1 for item in occurences: if occurences[item] != 0: ...
def outer(num): print('outing') test_num = 10 def inner(num_inner): nonlocal test_num print(test_num) test_num += 1 if type(num_inner) is int: print('是整数') else: print('不是整数') inner(num) outer('1')
class Gun: def __init__(self, model): self.model = model self.bullet_num = 0 def add_bullet(self, count): self.bullet_num += count def shoot(self): if self.bullet_num <= 0: print(f'{self.model}没有子弹了') return self.bullet_num -= 1 print...
def longestPalindrome(text): '''Prints the longest Palendrome substring from text''' palstring = set() longest = 0 for i in range(len(text)-1): for j in range(i+2,len(text)+1): pattern = text[i:j] if pattern == pattern[::-1]: palstring.add(pattern) ...
from ex12.game import Game from ex12.ai import AI from ex12.gui import GUI from ex12.starting_menu import Menu P_V_P = 1 AI_V_P = 2 P_V_AI = 3 AI_V_AI = 4 DRAW = -2 def player_decider(main_menu): """ This will call game_loop with the proper player configurations""" game_type = main_menu.get_pla...
def jogar(): import random print("###############################") print("Bem vindo ao jogo de Adivinhacao") print("###############################") numero_secreto = int(round(random.randrange(1 , 101))) total_de_tentativas = 0 pontos = 1000 print("Escolha o nivel de dificuldade") print("(1)-Facil (2)-Me...
''' Walrus operator is := official name : PEP 572 Assignment Expressions. Problem being solved: A regular "=" assignments is a statement and statements cant be used inside statement Rules: 1) The assignment expression must be in paranthesis 2) The return value is wjatever was assigning. ...
a_list = [0, 1, [2, 3], 4, 5, [6, 7]] def flatten(nestedList): result = [] if not nestedList: return result stack = [list(nestedList)] while stack: current = stack.pop() next = current.pop() if current: stack.append(current) if isinstance(next, list): if nex...
'''a class to mange aliens''' import pygame from pygame.sprite import Sprite class Alien(Sprite): """docstring for Alien""" def __init__(self, ai_settings,screen): super(Alien, self).__init__() self.screen = screen self.ai_settings = ai_settings self.image = pygame.image.load('images/alien.bmp') self.r...
"""Calculate tree heights using Python and writes to csv. Accepts Two optional arguments: file name, and output directory path.""" __author__ = 'Luke Swaby (lds20@ic.ac.uk), ' \ 'Jinkai Sun (jingkai.sun20@imperial.ac.uk), ' \ 'Acacia Tang (t.tang20@imperial.ac.uk), ' \ 'Dengk...
"""Groupwork: to do vectorize1 using Python""" __author__ = 'Luke Swaby (lds20@ic.ac.uk), ' \ 'Jinkai Sun (jingkai.sun20@imperial.ac.uk), ' \ 'Acacia Tang (t.tang20@imperial.ac.uk), ' \ 'Dengku Tang (dengkui.tang20@imperial.ac.uk)' __version__ = '0.0.1' import sys import t...
''' This module defines an abstract class 'Population' for particle filter search. ''' import numpy as np class Population(object): ''' An abstract container class for a collection of individuals to be used in a 'particle filter' type of search. At each generation, the probability that t...
class Solution: def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ """ 思路: 约束①:空链表 约束②:链表长度不是 K 的整数倍时,余下的部分不进行逆转 DO: 创建新的逆转后的链表 newList 在每个 长度为(k-1)的 for 循环中 ...
from datetime import date class Person: def __init__(self, name, surname, birthdate, email, address, mob, tel): self.name = name self.surname = surname self.birthdate = birthdate self.email = email self.address = address self.mob = mob self.tel = tel ...
import unittest def SetLiteral(formula, lit): new = formula[:] for i in formula: nuevo_i = list(i) for j in nuevo_i: if j == lit: new.remove(i) elif j == -1 * lit: i.remove(j) return new def IsSatisfiable(formula): if...
'''from nltk.book import *''' import nltk import math import numpy def main(): print("hi") ''' Open a text file, tokenize and return an nltk.Text object ''' def open_textfile(fname): f = open(fname, 'r') raw_text = f.read() tokens = nltk.word_tokenize(raw_text) text = nltk.Text(tokens) re...
def fizz_buzz(numbers): ''' Given a list of integers: 1. Replace all integers that are evenly divisible by 3 with "fizz" 2. Replace all integers divisble by 5 with "buzz" 3. Replace all integers divisible by both 3 and 5 with "fizzbuzz" >>> numbers = [45, 22,14,65, 97, 72] >>> fizz_buzz(numbers) ...
""" 程式設計練習題 2.2-2.10 2.21 財務金融應用程式:複利值. 利息公式: 100 * (1 + 0.00417) = 100.417 (100 + 100.417) * (1 + 0.00417) = 201.252 (100 + 201.252) * (1 + 0.00417) = 302.507 以下是輸出樣本: ``` Enter the monthly saving amount:100 After the sixth month, the account value is 608.81 ``` """ import ast amount = ast.literal_eval(input("Ent...
from Set import Set set = Set() set.add(45) set.add(13) set.add(43) set.add(43) set.add(1) set.add(2) print("Elements in set: " + str(set)) print("Number of elements in set: " + str(set.getSize())) print("Is 1 in set? " + str(set.contains(1))) print("Is 11 in set? " + str(set.contains(11))) set.remove(2) print...
def factorial(n): return factorialHelper(n, 1) def factorialHelper(n, result): if n == 0: return result else: return factorialHelper(n - 1, n * result)
number = eval(input("Enter an integer: ")) if number % 5 == 0 : print("HiFive"); if number % 2 == 0 : print("HiEven");
annualInterestRate = eval(input( "Enter annual interest rate, e.g., 8.25: ")) monthlyInterestRate = annualInterestRate / 1200 numberOfYears = eval(input( "Enter number of years as an integer, e.g., 5: ")) loanAmount = eval(input("Enter loan amount, e.g., 120000.95: ")) monthlyPayment = loanAmount * m...
import turtle from UsefulTurtleFunctions import * drawLine(-50, -50, 50, 50) writeText("Testing useful Turtle functions", -50, -60) drawPoint(0, 0) drawCircle(0, 0, 80) drawRectangle(0, 0, 60, 40) turtle.hideturtle() turtle.done()
import re regex = "\d{3}-\d{2}-\d{4}" ssn = input("Enter SSN: ") match1 = re.match(regex, ssn) if match1 != None: print(ssn, " is a valid SSN") print("start position of the matched text is " + str(match1.start())) print("start and end position of the matched text is " + str(match1.span())...
import random import time correctCount = 0 count = 0 NUMBER_OF_QUESTIONS = 5 startTime = time.time() while count < NUMBER_OF_QUESTIONS: number1 = random.randint(0, 9) number2 = random.randint(0, 9) if number1 < number2: number1, number2 = number2, number1 answer = eval(in...
def quickSort(list): quickSortHelper(list, 0, len(list) - 1) def quickSortHelper(list, first, last): if last > first: pivotIndex = partition(list, first, last) quickSortHelper(list, first, pivotIndex - 1) quickSortHelper(list, pivotIndex + 1, last) def partition(list, first, last): ...
def decimalToHex(decimalValue): hex = "" while decimalValue != 0: hexValue = decimalValue % 16 hex = toHexChar(hexValue) + hex decimalValue = decimalValue // 16 return hex def toHexChar(hexValue): if 0 <= hexValue <= 9: return chr(hexValue + ord('0')) els...
from tkinter import * class SierpinskiTriangle: def __init__(self): window = Tk() window.title("Sierpinski Triangle") self.width = 200 self.height = 200 self.canvas = Canvas(window, width = self.width, height = self.height) self.canvas.pa...
def add(x, lst = []): if x not in lst: lst.append(x) return lst def main(): list1 = add(1) print(list1) list2 = add(2) print(list2) list3 = add(3, [11, 12, 13, 14]) print(list3) list4 = add(4) print(list4) main()
import math class Circle: def __init__(self, radius = 1): self.__radius = radius def getRadius(self): return self.__radius def getPerimeter(self): return 2 * self.__radius * math.pi def getArea(self): return self.__radius * self.__radius * math.pi
def mergeSort(list): if len(list) > 1: firstHalf = list[ : len(list) // 2] mergeSort(firstHalf) secondHalf = list[len(list) // 2 : ] mergeSort(secondHalf) merge(firstHalf, secondHalf, list) def merge(list1, list2, temp): current1 = 0 c...
from tkinter import * class ControlAnimation: def __init__(self): window = Tk() window.title("Control Animation Demo") self.width = 250 self.canvas = Canvas(window, bg = "white", width = self.width, height = 50) self.canvas.pack() f...
def main(): n = eval(input("Find all prime numbers <= n, enter n: ")) list = [] NUMBER_PER_LINE = 10 count = 0 number = 2 squareRoot = 1 print("The prime numbers are \n") while number <= n: isPrime = True if squareRoot * squareRoot < num...
""" 程式設計練習題 2.2-2.10 3.8 財務應用:貨幣單位. 請解決範例程式3.4 ComputeChange.py的float轉成int導致的精確度遺失,以輸入「分」(cents)方式 解決。 """ from ast import literal_eval amount = literal_eval(input("Enter an amount in cents, e.g., 1156: ")) remainingAmount = int(amount) numberOfOneDollars = int(remainingAmount / 100) remainingAmount = int(remai...
from Circle import Circle def main(): myCircle = Circle() n = 5 printAreas(myCircle, n) print("\nRadius is", myCircle.radius) print("n is", n) def printAreas(c, times): print("Radius \t\tArea") while times >= 1: print(c.radius, "\t\t", c.getArea()) c.ra...
NUMBER_OF_ELEMENTS = 5 numbers = [] sum = 0 for i in range(NUMBER_OF_ELEMENTS): value = eval(input("Enter a new number: ")) numbers.append(value) sum += value average = sum / NUMBER_OF_ELEMENTS count = 0 for i in range(NUMBER_OF_ELEMENTS): if numbers[i] > average: count += 1 print("...
def main(): filename = input("Enter a filename: ").strip() infile = open(filename, "r") counts = 26 * [0] for line in infile: countLetters(line.lower(), counts) for i in range(len(counts)): if counts[i] != 0: print(chr(ord('a') + i) + " appears " + s...
import turtle def main(): drawChessboard(-260, -20, -120, 120) drawChessboard(20, 260, -120, 120) turtle.hideturtle() turtle.done() def drawChessboard(startx, endx, starty, endy): turtle.pensize(3) turtle.penup() turtle.goto(startx, starty) turtle.pendown() turtle.colo...
from random import randint def getRandomCharacter(ch1, ch2): """Generate a random character between ch1 and ch2.""" return chr(randint(ord(ch1), ord(ch2))) def getRandomLowerCaseLetter(): """Generate a random lowercase letter.""" return getRandomCharacter('a', 'z') def getRandomUpperCaseLetter()...
""" 程式設計練習題 2.2-2.10 3.2 幾何:大圓距離. 撰寫一程式提示使用者輸入球面上兩點,並計算出這兩點間在圓表面的最短距離。 地球半徑平均6371.01km。 d = RADIUS * acos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2)) 以下是程式的執行結果: ``` Enter point 1 (latitude and longitude) in degrees: 39.55, -116.25 Enter point 2 (latitude and longitude) in degrees: 41.5, 87.37 The distance...
""" 程式設計練習題 1-6 1-20 Turtle:畫一矩形體. 撰寫一程式,顯示矩形體。 """ import time from turtle import Turtle TURTLE = Turtle() TURTLE.showturtle() TURTLE.goto(50, 0) TURTLE.goto(50, -40) TURTLE.goto(0, -40) TURTLE.goto(0, 0) TURTLE.penup() TURTLE.goto(10, 20) TURTLE.pendown() TURTLE.goto(50 + 10, 0 + 20) TURTLE.goto(50 + 10, -40 + ...
name_list = [] def addlist(name): for i in range(50): name_list.append(name) return print(name_list) print(addlist(input('ditt namn: ')))
from constants import * from math import sin, cos, pi class Segment: """ Defines a segment with a length of 1 according to its starting point and its direction """ def __init__(self, x, y, dct): assert dct <= 3 and dct >= 0 self.x = x self.y = y self.dct = dct def mov...
class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = Node() def insert(self, word: str) -> None: """ Inserts a word into the trie. """ node = self.root for c in word: node = node.a...
class Solution: def middleNode(self, head: ListNode) -> ListNode: fp = head sp = head while fp and fp.next: sp = sp.next fp = fp.next.next return sp
def intToRoman2(num): thousand = num // 1000 hundred = (num // 100) % 10 ten = (num // 10) % 10 one = num % 10 dic = {1: {0: "I", 1: "X", 2: "C", 3: "M"}, 5: {0: "V", 1: "L", 2: "D"}, 4: { 0: "IX", 1: "XL", 2: "CD"}, 9: {0: "IX", 1: "XC", 2: "CM"}} l = [thousand, hundred, ...
''' G(i) = i ^ (i/2); 如 n = 3: G(0) = 000, G(1) = 1 ^ 0 = 001 ^ 000 = 001 G(2) = 2 ^ 1 = 010 ^ 001 = 011 G(3) = 3 ^ 1 = 011 ^ 001 = 010 G(4) = 4 ^ 2 = 100 ^ 010 = 110 G(5) = 5 ^ 2 = 101 ^ 010 = 111 G(6) = 6 ^ 3 = 110 ^ 011 = 101 G...
''' On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. Example 1: Input:...
print("enter list elements: ") sample = list(map(int, input().split())) sumi = 0 sum_left=[] for val in sample: sumi += val sum_left.append(sumi) sum_right=[] for val in sample: sum_right.append(sumi) sumi -= val k=len(sum_left) for i in range(k): if sum_left[i] == sum_right[i]: ...
num1=float(input('Write the first number:')) num2=float(input('Write the second number:')) print(num1+num2)
""" Opening is just another name of erosion followed by dilation. It is useful in removing noise, as we explained above. Here we use the function, cv2.morphologyEx() Closing is reverse of Opening, Dilation followed by Erosion. It is useful in closing small holes inside the foreground objects, or small black ...
import cv2 import numpy as np img = cv2.imread('messi5.jpg',0) rows,cols = img.shape M = cv2.getRotationMatrix2D((cols/2,rows/2),27,1) dst = cv2.warpAffine(img,M,(cols,rows)) cv2.imshow('Rotated Image',dst)
import os os.system("clear") def methodception(another): return another() def add_two_numbers(): return 35 + 77 my_list = [13, 56, 77, 484] print(list(filter(lambda x: x!=13, my_list))) def not_thirtheen(x): return x!=13 print(list(filter(not_thirtheen, my_list))) print([x for x in my_list i...
class Student(object): """docstring for Student.""" def __init__(self, name, school): super(Student, self).__init__() self.name = name self.school = school self.marks = [] def average(self): return sum(self.marks) / len(self.marks) @classmethod def go_t...
import pygame class Projectile(pygame.sprite.Sprite): def __init__(self, x, y, taille, direction, image): self.x = x self.y = y self.taille = taille self.direction = direction self.image = image self.rect = pygame.Rect(self.x, self.y, self.taille[0], self.taille[1]) def afficher(self, surface): py...
from sklearn.neural_network import MLPClassifier import matplotlib.pyplot as plt from sklearn import datasets from sklearn import svm digits = datasets.load_digits() clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5,2), random_state = 4) X,y = digits.data[:-10], digits.target[:-10] cl...
def main(): m_m = 50 l_l = 0 h_h = 100 i_i = 'l' g_g = 0 while (i_i != 'c'): print(m_m) i_i = input("enter h to guess the number is too high,'l' if number is low 'c' indicate number is correct") if(i_i=='h'): h_h=m_m m_m=(h_h+l_l)//2 elif(i_i=='l'): l_l=m_m m_m=(h_h + l_l)//2 print('gue...
'''# Write a python program to find the square root of the given number # using approximation method # testcase 1 # input: 25 # output: 4.999999999999998 # testcase 2 # input: 49 # output: 6.999999999999991''' def main(): ''' bisection ''' s_s = int(input()) epsilon = 0.01 ...
a=10 print("hello!") while a>0: print(a) a=a-2
import d6 import d20 import sys while True: try: type = input("Please enter the type of die you want to roll\n(d6 or d20): ") num = int(input("Enter the number of die you want to roll: ")) myResult = [] if type == "d6": pri...
def sum_of_multiples(limit, multiples): sum = 0 lowest_multiply = sorted(multiples)[0] if len(multiples) != 0 else 0 for i in range(lowest_multiply, limit): for j in multiples: if j != 0 and i % j == 0: sum += i break return sum
class ExceptionHandlingClass: """All input queries to the user are handled via this class. First, inputs are checked for ValueErrors, and the user is queried for valid entries until there is not ValueError. Second, inputs are checked for all exceptions, just in case there are any that aren't ...
list1=[12,-7,5,64,-14] for num in list1: if num>=0: print(num,end=",") list2=[12,14,-95,3] for num2 in list2: if num2>=0: print(num2,end=",")
import sys def optimal_sequence(n): sequence = [] while n >= 1: sequence.append(n) if n % 3 == 0: n = n // 3 elif n % 2 == 0: n = n // 2 else: n = n - 1 return reversed(sequence) def dynamic_sequence(n): sequence=[] a=[0]*(n+1) ...
import sys def gcd_naive(a, b): while b!=0: a=a%b if a==0: break b=b%a current_gcd =a if a!=0 else b return current_gcd def lcm_naive(a, b): gcd=(gcd_naive(a,b)) lcm=gcd*(a//gcd)*(b//gcd) return lcm if __name__ == '__main__': input = sys.stdin.read() ...
import sys def acyclic(adj): visited=[] path=[] for u in range(len(adj)): if u not in visited and explore(u,adj,path,visited): return 1 return 0 def explore(u,adj,path,visited): if u in path: return True visited.append(u) path.append(u) for v in...
numbers = [1,2,3,4,5,20] nombre = "Arthur Wells" for elemento in nombre: print(elemento)
import random chars = 'etaoinsmpru' word_list=[] number=[3,4,5,6,7] for num in number: for i in range(50): str = [] for k in range(1, num+1): str.append(random.choice(chars)) str = "".join(str) word_list.append(str) print(word_list)
import numpy as np import kmeans import common import naive_em import em X = np.loadtxt("toy_data.txt") X_netflix_incomplete = np.loadtxt("netflix_incomplete.txt") X_netflix_complete = np.loadtxt("netflix_complete.txt") K = 1 seed = 1 min_cost = np.ones(4)*np.inf min_cost_seed = np.zeros(4) for K in range(1,5)...
nowDay = 4 nowMonth = 10 nowYear = 2019 day = int(input('Enter day>')) month = int(input('Enter month>')) year = int(input('Enter year>')) if (month > nowMonth) or (month == nowMonth and day > nowDay): print (nowYear - year - 1) else: print(nowYear - year)
""" Hackerrank - Day Of Programmer. 1. Calculate day of the year in Russia. 2. Years -> 1700 - 2700 3. From 1700 to 1917 : Julian calender. 4. From 1919 : Gregorian calender. 5. 1918 of 31st jan : Julian calender. ***After 31st jan 14th feb came in 1918*** 6. 1918 of 14th feb : Gregorian calender. * In both calend...
x = 0 f = "Fizz" b = "Buzz" q = "Fizz Buzz" def unless(): o = 1 o = o + 1 y = 15 y = y + 15 if o % 3 == 0: print(end='\r', flush=True) if o % 5 == 0: print(end='\r', flush=True) if o == y: print(end='\r', flush=True) else: '\n' whi...
""" This class uses static methods to operate with the other helper classes to get a corpus or parse / crawl a directory or file. The filename(s) is sent to the processor class which takes care of parsing the files. Lastly the similarity class is called, that vectorizes the text and calculates the similarity using nump...
import plotly.figure_factory as ff import plotly.graph_objects as go import statistics import random import pandas as pd import csv df = pd.read_csv("medium_data.csv") data = df['reading_time'].tolist() def random_set_of_mean(counter): data_set = [] for i in range(0,counter): random_index = random...