text
stringlengths
37
1.41M
# User Input val = int(input('Enter any Number: ')) add = 0 # For Loop & Logic for num in range(1, val + 1): num = (num ** 2) add += num print (add)
""" Write a function that takes a string as input argument and returns a dictionary of vowel counts i.e. the keys of this dictionary should be individual vowels and the values should be the total count of those vowels. You should ignore white spaces and they should not be counted as a character. Also note that a smal...
#!/usr/bin/env python # coding: utf-8 # ## q-1-2 # # A bank is implementing a system to identify potential customers who have higher probablity of availing loans to increase its profit. Implement Naive Bayes classifier on this dataset to help bank achieve its goal. Report your observations and accuracy of the model. ...
class Node: '''class representing individual node within a singly linked list''' def __init__(self, data=None): self.data = data self.next = None # Pointer ---> class SinglyLinkedList: '''class containing functionality for generating/modifying a singly linked list''' def __init__(self)...
# BOX 1 def func(s,q): for i in range(q//3): print("|",end=" ") for j in range(q//3): print(s,end=" | ") s+=1 print() # BOX 2 def func1(s,q): for i in range(3): print("|",end=" ") for j in range(3): print(chr(s),end=" | ") ...
STARTING_FREQUENCY = 0 def one(data): result = sum([int(x) for x in data]) print(result) return result def two(data): frequencies = [int(x) for x in data] values = set([STARTING_FREQUENCY]) actual_frequency = STARTING_FREQUENCY i = 0 while True: actual_frequency += frequencies[...
#задача 1 my_list = [False, bool, None, "asdfasdf", True, 5, 5.5] def my_type(list): for list in range(len(my_list)): print(type(my_list[list])) return my_type(my_list) #задача 2 count = int(input("введи кол-во элм. списка: ")) my_list = [] i = 0 n= 0 while i < count: my_list.appe...
""" 回文判断函数练习 1. 函数重载(支持不同类型传参) 2. 字符串双指针/数字整除 """ def is_palind(obj): # 处理字符串判断 if isinstance(obj, str): return _check_str(obj) if isinstance(obj, int): return _check_int(obj) # 字符串回文检查 def _check_str(obj): # 双指针 obj_len = len(obj) mid = obj_len // 2 end = mid # 奇数跟st...
# python 中的set 集合类型也是无序,唯一的类型 # python里的set自带子交并补集等方法 from functools import reduce # 求并集 def union(*args): set_arr = set() for item in args: set_arr = set_arr.union(item) return [item for item in set_arr] # 求交集 def intersection(*args): inter_sets = reduce(_inter_one, args) return [item ...
""" 找出所有的水仙花数 水仙花数也被称为超完全数字不变数、自恋数、自幂数、阿姆斯特朗数,它是一个3位数, 该数字每个位上数字的立方之和正好等于它本身,例如:$1^3 + 5^3+ 3^3=153$。 练习点: 整除/取余,反转 """ def floor(): # 三位数 rst = [] for num in range(100, 1000): # 求个十百位 low = num % 10 # // 可以做整除运算, 替代math.floor mid = num // 10 % 10 high = num // 100 ...
""" 线程与锁 js是单线程语言,所以没有提供thread这种机制 ps: nodeJS 12.x 以上已经有了woker_thread 模块 """ from threading import Thread, Lock from time import sleep # 无线程锁测试 class Account(object): def __init__(self): self._money = 0 # 加钱方法 def add_money(self, count): # 这个写法其实也有点问题,如果在pending之前访问并存储这个变量,就会有问题 ...
# 循环链表 from data_structures.linklist import LinkList # 循环链表实现 class LoopLinkList(LinkList): def __init__(self): super().__init__() # 构建循环链表 # 链表指针 self.cur_node = self.head self.head.next = self.head # 修改to_arr方法 def to_arr(self): cur_node = self.head ...
# -*- coding: utf-8 -*- def print_lugares(lugares, tab=""): linha_0 = tab + " Lugar:" linha_1 = tab + " Marcação:" for id_lugar in lugares: linha_0 += " {0: <5} ".format(id_lugar) linha_1 += " {0: <5} ".format(str(lugares[id_lugar].marcas)) print(linha_0) print(linha_1) ...
name_school= input("Enter school name: ") name = input("Enter your name: ") name_project = input('Enter your name project: ') madlib = f"I want to study in the university called {name_school}. My name is {name}. This is my first project in Python which name is {name_project} " print(madlib)
""" 使用二分法、牛顿法、割线法、修正牛顿法和拟牛顿法求解非线性方程(组) @author:Swiftie233 @Date:2020/10/20 @Harbin Institute of Technology """ from math import sin, exp import sympy as sp import numpy as np import copy as cp def diff(f, x): return f.diff(x) def bisection_method(): def f1(x): return sin(x)-0.5*x**2 ...
# -*- coding: utf-8 -*- """ Created on Tue Jan 16 15:54:14 2018 @author: Chandrasen.Wadikar """ print("Hello World") 2**2 ein=9 print (ein) type(ein) i_int=10; print(i_int) i_float=10.9 print(i_float) type(i_float) s="897132897183712" type(s) print(int(float(s))) type(s) c="534.98...
import random import math MIN = 0 MAX = 100 n = random.randint(MIN, MAX) closest_power_of_two = int(math.pow(2, math.ceil(math.log(n, 2)))) if n!=0 else int(math.pow(2, 0)) integers = list() print(f"n is {n}, the closest power of 2 (upper bound) is {closest_power_of_two}") for i in range(closest_power_of_two): in...
def convert_into_currency(num): if num < 0: raise ValueError('Некорректный формат!') dec = num % 1 number = int((num - dec)) dec = int(dec * 100) print(f'{number} руб. {dec} коп.') convert_into_currency(12.5)
#####using print function name='Mitchell Johnson' phone='98606060660' yr=1999 index=99.12345 print(name) print(name,phone,yr) print(type(name)) '''now using format''' print('My name is:'+name) print('My name is:',name) print('My name is: '+name+" "+phone+" -- "+str(yr)) # for printing several strigs use'+' ##m...
############################### ###Dictionary Examples####### ############################### d= {'dog':'chases a cat', 'cat':'chases a rat', 'rat':'rats runaway'} word=input("Enter a word:") print("The defination is:",d[word]) d2=d.copy() print(d2) #################################################333 let...
from socket import * # Get input from user sender = '<'+raw_input('What email address is SENDING this message? ')+'>\r\n' recipient = '<'+raw_input('What email address is RECEIVING this message? ')+'>\r\n' subject = raw_input('Subject: ')+'\r\n' msg = '\r\n'+raw_input('Please enter your message: ') endmsg = '\r\n...
from random import shuffle from enum import Enum class Suit(Enum): hearts = 1 diamonds = 2 spades = 3 clubs = 4 class Card: def __init__(self, suit, value) self.suit = suit self.value = value def __str__(self): text = "" # Value try: text...
from tkinter import * import random # Dictionaries and vars outcomes = { "rock": {"rock": 1, "paper": 0, "scissors": 2}, "paper": {"rock": 2, "paper": 1, "scissors": 0}, "scissors": {"rock": 0, "paper": 2, "scissors": 1} } comp_score = 0 player_score = 0 # Functions def converted_outcome(number): i...
import heapq_max import re def user_welcome(): print('Welcome to Pied Piper -- A one stop place for you to keep track of all available opportunities!') print('\nAre you a job seeker or a job poster?\nEnter 1 for job seeker \nEnter 2 for job poster\nEnter 3 to close a job position\nEnter 4 to quit') ...
def flipbits(byte): """ this is just for practice doing bit shifting in python pass in a byte and flip all of the bits in it """ bytecopy = 0 for i in range(8): if (byte >> i) & 1 == 1: bytecopy += 1 bytecopy = bytecopy << 1 return bytecopy print(flipbits(2)) p...
# -*- coding: utf-8 -*- import json alphabet_f = open("alphabet.json", "r") alphabet = json.load(alphabet_f) alphabet_f.close() def main(first=True): if first: print "--------------------------------------" print "Zamiennik polskich liter na rosyjskie" print "------------------------------...
class Solution: def isPalindrome(self, x: int) -> bool: a = list(str(x)) b = a[::-1] return a==b # 巨大的坑就是python只能识别True和False是bool变量,如果if a==b: return true就会把true当作变量而报错
import random def caesar(plaintext,shift): alphabet=["a","b","c","d","e","f","g","h","i","j","k","l", "m","n","o","p","q","r","s","t","u","v","w","x","y","z"] #Create our substitution dictionary dic={} for i in range(0,len(alphabet)): dic[alphabet[i]]=alphabet[(i+shift)%len(alphabet)]...
from tkinter import * def select(): print ("You have selected " + variable.get()) #master.quit() def logIn(): print("This section is to transport user to sign in section") def addUser(): print("This section is to add a User") master = Tk() variable = StringVar(master) variable.set("(select person)...
import pandas as pd import matplotlib.pyplot as plt import numpy as np def readInCSV(title): df = pd.read_csv(title) return convertToDateTime(df) def convertToDateTime(df): rows = df.shape[0] # The number of rows in the dataframe for i in range(0,rows): # Change all dates to pandas date time...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name o...
import numpy as np import math import time from plotting import plot_lines, plot_points, plot_vectors def is_inside(point, polygon): """ Check is given 2d point inside given polygon or not :param point: 2d point for check :param polygon: list of lines of polygons :return: boolean value: 1 if point...
#!/usr/bin/env python # coding: utf-8 # In[3]: #!/usr/bin/env python # coding: utf-8 # In[10]: # Shambhavi Awasthi # Data Structures and Algorithms Nanodegree # Project 2 - Problems vs Algorithms # Problem 6: Max and Min in a Unsorted Array def get_min_max(ints): """ Return a tuple(min, max) out of list ...
import csv import os #Set path for file csvpath =os.path.join("Resources","election_data.csv") #csvpath =os.path.join("..","Resources","election_data.csv") #open file with open(csvpath,newline='') as election: reader=csv.reader(election) next(election) names=[item[2] for item in reader] candidate_li...
""" Tic tac toe game copyright @Avisek Shaw """ import time import random def row_check(chart,l): r = chart[0] c = chart[1] m = l[r][c] count = 0 for k in range(3): if(m==l[r][k]): count = count + 1 if(count==3): return True else: return False def c...
class Animal: sound = "" feed = 0 def __init__(self, age_in_months, breed, required_food_in_kgs): self._age_in_months = age_in_months self._breed = breed self._required_food_in_kgs = required_food_in_kgs self._reserved_food_in_kgs = 0 if self._age_in_months !...
''' Maximum_subarray_problem Summary: Given an array, it will computer the value of the largest subarray, it doesn't keep track of the indices though ''' def max_sub(Array): #set default values of accumulators to first element max_ending_here = max_so_far = Array[0] #iterate through array for...
#CK import pygame pygame.init() # | Paddle() # |------------------------------------------------- # | Class for a paddle, which handles the paddle's # | location, movement and drawing of paddle # |------------------------------------ class Paddle(pygame.sprite.Sprite): def __init__(self, xPos, yPos, windowHeight,...
# РЕАЛИЗАЦИЯ ВЫВОДА ПОСЛЕДНИХ 10 ЦИФР ОТ ФАКТОРИАЛА ВВЕДЕННОГО ЧИСЛА def factorial_last_ten_digits(n): try: n = int(n) except ValueError: raise ValueError if n == 0: print(1) return elif n < 0: print("Value should be greater than zero.") return res = ...
class Solution: def fizzBuzz(self, n: int) -> List[str]: list = [] for i in range(n): s = str(i+1) if (i+1) % 3 == 0 : s = "Fizz" if (i+1) % 5 == 0 : s = "Buzz" if (i+1) % 15 == 0 : s = "FizzBuzz" ...
import random # 3 组数据,每个数不超过 10 位 n = 3 hi = 10 ** 10 print(n) for _ in range(n): a = random.randrange(0, hi) # randrange 不包含 hi b = random.randrange(0, hi) print(a, b)
def collect_list(n): inp_list = [] for i in range(0, n): inp_list += [int(input())] return inp_list if __name__ == '__main__': list_size = int(input()) in_list = collect_list(list_size) list_sum = sum(in_list[:]) print(list_sum)
import math truck_width = float(input()) truck_depth = float(input()) truck_height = float(input()) number_of_barrels = int(input()) truck_volume = truck_width * truck_depth * truck_height for i in range(number_of_barrels): barrel_radius = float(input()) barrel_height = float(input()) barrel_volume = mat...
if __name__ == '__main__': arr = list(map(int, input().split())) sorted_arr = arr[:1] for i in range(1, len(arr)): for j in range(0, len(sorted_arr)): inserted = False if arr[i] < sorted_arr[j]: sorted_arr = sorted_arr[:j] + [arr[i]] + sorted_arr[j:] ...
if __name__ == '__main__': input_string = input().split() rotated_string = [] rotated_string += input_string[-1:] for i in range(0, len(input_string) - 1): rotated_string += input_string[i:i+1] print(' '.join(rotated_string))
def swap(_list: list, index1: int, index2: int): if 0 > index1 or index1 > (len(_list) - 1) or 0 > index2 or index2 > (len(_list) - 1): return _list.__str__() else: _list[index1], _list[index2] = _list[index2], _list[index1] return _list.__str__() def enumerate_list(_list: list): r...
def reverse_insert_sort(arr): for i in range(1, len(arr)): for j in range(0, i): if arr[i] > arr[j]: temp = arr[i:i + 1] + arr[j:i] arr[j:i + 1] = temp return arr if __name__ == '__main__': unsorted_arr = list(map(int, input().split())) n = int(input...
from find_contact import * from edit_contact import * if __name__ == '__main__': INPUT_PROMPT = """"Please enter your choise: 1.Find contact by name 2.Find contact by town 3.Find contact by phone number 4.Print all contacts 5.Add new contact 6.Delete contact 7.Edit contact\n""" _inp...
input_list = [int(num) for num in input().split()] def multiply(data_list, params): if params[0] == 'list': data_list = data_list * int(params[1]) return data_list else: m = int(params[0]) n = int(params[1]) data_list = [el * n if el == m else el for el in data_list] ...
class BankAccount: def __init__(self, name, bank, balance): self.name = name self.bank = bank self.balance = balance accounts = [] _input = input() while not _input == 'end': _input = list(_input.split(' | ')) bank = _input[0] name = _input[1] balance = float(_input[2]) ...
import os import sys import time options = [1, 2] def select_op(op): if op in options: return True return False def print_menu(): print " __________________________________" print " | >> Multiply matrixes program << |" print " |__________________________________|" def csv_to_matrix(f_name): opened = Fa...
from typing import List from mortgage.mortgage import Mortgage def compute_mortgage(periods: List[int], interest_rates: List[float], mortgage_amount: int, mortgage_duration: int = 360, name: str = 'Mortgage') -> Mortgage: """ ...
# coding:utf-8 class Solution: def isPalindrome(self, x: int) -> bool: if x < 0 or (x > 0 and x % 10 == 0): return False y = 0 if x < 10: return True while x > 0: t = x % 10 x = x // 10 y = 10 * y + t print(x, ...
# coding: utf-8 class Solution: def reverse(self, x: int) -> int: flag = False if x < 0: flag = True x = -x y = 0 while x > 0: n = x % 10 x = x//10 y = y*10+n pass if flag: y = -y if ...
import numpy as np __all__ = [ 'nrmse', 'nmse', 'rmse', 'mse' ] def nrmse( input, target, discard=0, var=-1 ): """ NRMSE calculation. Calculates the normalized root mean square error (NRMSE) of the input signal compared to the target signal. Parameters: ----------- ...
# reduceReuseRecyle - Holden Higgens & Joyce Wu # Softdev2 pd 7 # k18 -- Reductio ad Absurdum # 2018-04-30 from functools import reduce def open_f(): #opens file and creates list of words in text f = open("pope.txt", "r") file = f.read() return file.split() #test ary sample = ['hi', 'hello', 'hola', ...
import socket #This allows us to create socckets and various network protcol data communications import os #This lets us initiate functions on the operating system kernel import sys #This lets us initiate import random #This will allow us to randmize our port that is being assigned to the server THIS SI GOOD FOR TES...
import math r = float(input()) area = r * r * math.pi cir = 2 * r * math.pi print('%f %f'%(area,cir))
# Hi Lo Guessing game print("Choose a number between 1 and 100") print("After each guess, enter:") print("0 - if I got it right") print("-1 - if I guessed too high") print("1 - if I guessed too low") def take_guess(high, low, guesses): guess = (high + low) / 2 keep_asking = 1 while keep_asking == 1: print ("My gue...
p1=int(raw_input()) if(p1>=2): if(p1%2==0): print("enen") elif(p1%2!=0): print("odd") else: print("not valid")
# Read data # data_file = open('day1/input.txt') # data_in = data_file.readlines() # frequency = 0 # # Sum frequency # for i in data_in: # frequency += int(i) # print('Result: %d' % frequency) # Single line solution - Sum all frequencies print('Result: %d' % sum(map(int, open('day1/input.txt').readlines())))
#1번 문제의 이차원 점을 상속 받고 3차원 의 두점을 입력 받아서 합을 출력 x1 = int(input()) y1= int(input()) z1 = int(input()) x2= int(input()) y2= int(input()) z2= int(input()) class plus: def __init__(self, x,y): self.x = x self.y = y def __add__(self, other): self.x =self.x + other.x self.y = se...
# 1부터 입력한 수까지의 짝수의 합 x = int(input()) sum = 0 for i in range(0, x+1,2): sum += i print(sum)
""" Contains a neural network based on the Neural Networks and Deep Learning online course on Coursera """ # Package imports import numpy as np import copy import matplotlib.pyplot as plt def sigmoid(x): """ Compute the sigmoid of x Arguments: x -- A scalar or numpy array of any size. Return: ...
# вывсети значения которые есть в обоих списках def same_elements(list_1, list_2): new_list = [] for i in list_1: for j in list_2: if i == j: new_list.append(i) break return new_list if __name__ == "__main__": list_1 = [1, 3, 5, 8, "g...
# converting our csv file to a sqlite file import sqlite3 import csv conn = sqlite3.connect('fires.sqlite') cur = conn.cursor() cur.execute('DROP TABLE IF EXISTS fires') cur.execute(''' CREATE TABLE "fires"( "id" SERIAL PRIMARY KEY, "fire_year" INT, "report_date" DATE, "county" VARCHAR, "latitude" DEC, "lon...
def solution(array, commands): answer = [] for command in commands: sort = array[command[0]-1:command[1]] for i in range(len(sort)): for j in range(i, len(sort)): if sort[i] > sort[j]: sort[i], sort[j] = sort[j], sort[i] answer.append(sort[...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from linearRegression.linearRegression import LinearRegression from metrics import * np.random.seed(42) N = 30 P = 5 X = pd.DataFrame(np.random.randn(N, P)) y = pd.Series(np.random.randn(N)) print("===============================================...
#!/usr/bin/env python3 def main(): c = input() if c == 'z' * 20 or c == 'a': print('NO') else: if len(c) == 1: print(chr(ord(c[0])-1)+'a') elif sorted(c) != sorted(c, reverse=True): if list(c) == sorted(c): print(''.join(sorted(c, reverse=Tru...
#!/usr/bin/env python3 import math # n進数の各位の和 def base_10_n(x, n): if x == 0: return 0 # logで桁数出してはいけない、浮動小数点の誤差があるから死ぬ a = int(math.log(x, n)) ans = 0 for i in range(a, -1, -1): ans += x // n**i x %= n**i ans += x return ans def s(n, r): if n == 0: re...
#!/usr/bin/env python3 from collections import deque, Counter from heapq import heappop, heappush from bisect import bisect_right def main(): A, B, C = map(int, input().split()) if A < C < B or B < C < A: print('Yes') else: print('No') if __name__ == "__main__": main()
#!/usr/bin/env python3 def main(): S = input() ans = 0 for l in S.split('+'): if len(l) == 1 and l != '0': ans += 1 elif '0' not in l: ans += 1 print(ans) if __name__ == "__main__": main()
#!/usr/bin/env python3 def main(): N = int(input()) if int(str(N)[-1]) in [2,4,5,7,9]: print('hon') elif int(str(N)[-1]) in [0,1,6,8]: print('pon') else: print('bon') if __name__ == "__main__": main()
class Employee: def __init__(self, first, last, pay): # instance variables self.first = first self.last = last self.pay = pay @property # we can call this method as an attribute def email(self): return '{}.{}@company.com'.format(self.first, se...
from turtle import Turtle STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)] MOVE_DISTANCE = 20 UP = 90 DOWN = 270 LEFT = 180 RIGHT = 0 class Snake: def __init__(self): self.bodies = [] self.create_snake() self.head = self.bodies[0] def create_snake(self): for starting_point ...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import division import numpy as np """ Computes a given quantile of the data considering that each sample has a weight. x is a N float array weights is a N float array, it expects sum w_i = 1 quantile is a float in [0.0, 1.0] """ def wei...
# Import the module that stores string data import string # Collect and print out all ascii letters - lowercase and uppercase # Collect and print out all of the numeric digits ###################### # Import the module that can generate random numbers # Collect and print out a random integer between 1 and 10 # Ra...
############### # APPEND MODE # ############### # The "a" mode stands for append and allows the application to add new text onto the end of an existing file notesFile = open("Notes.txt", "a") # The .write() method in conjunction with the append mode will write to the end of a file notesFile.write("\nThis is a complet...
name=input("Enter your name: " ) bname= "B" + name[1:] print(bname) print("Oh is it so")
import os import csv #define variables total_months = 0 total_revenue = 0 revenue_average = 0 revenue_change = 0 month_change = [] month_count = [] month =[] # Path to collect data from the Resources folder budget_path = os.path.join('Resource', 'budget_data.csv') # Read in the CSV file with open(budget_path, 'r') as ...
import calendar import time t1 = time.time() # Create a plain text calendar c = calendar.TextCalendar(calendar.MONDAY) str = c.formatyear(1900, w=2, l=1, c=6, m=3) #print(str) count = 0 for year in range(1901,2001): for month in range(1,13): res = calendar.monthrange(year, month) if res...
import time t1 = time.time() def is_prime(n): if n == 1: return False if n%2 == 0: return False for i in range(3,int(n**0.5)+1,2): if n%i == 0: return False return True def sieve(n): prime = [True]*n prime[0] = False prime[1] = False prime[2] = True...
import time start = time.time() def fact(n): if n == 0: return 1 f = 1 for i in range(2,n+1): f *= i return f count = 0 for n in range(23,101): for r in range(1,n): val = fact(n)/(fact(r)*fact(n-r)) if val > 1000000: count += 1 pri...
import time def right_triangle(b, c): d1 = b[0]**2 + b[1]**2 d2 = c[0]**2 + c[1]**2 d3 = (b[0] - c[0])**2 + (b[1] - c[1])**2 if (d1 + d2 == d3) or (d1 + d3 == d2) or (d2 + d3) == d1: return True else: False def generate_points(x_limit, y_limit): point_pairs = [] for i in range(x_limit + 1): ...
# -*- coding: utf-8 -*- """ Created on Sun Feb 17 16:34:26 2019 @author: Krozz """ #First Method ''' def divn(x,n): for i in range(1,n+1): if x%i != 0: return False return True res = 0 n = 20 temp = n while temp>res: temp += n if divn(temp,n): res = temp print(res) ...
# Integers # a = 34 # b = 23 # c = 31 #print (a + b + c) #print ("Output Vars") #print ("Output Vars") #print ("La suma de") #print ("La suma de") #print(type(a)) # Float #a = 20.90 #b = 23.12 #c = 22.43 #print(a + b + c) #print(type(a)) # Boolean #d = true #e = false # String #s = "Este es un String de comillas d...
#Neural network for feedforward propagation import numpy as np import Config #Neural net weights from Config num_w0 = Config.num_w0 num_w1 = Config.num_w1 num_w2 = Config.num_w2 num_w3 = Config.num_w3 #Shapes of neural net matrices W1_shape = (num_w1, num_w0) W2_shape = (num_w2, num_w1) W3_shape = (num_w3, num_w2) #...
from random import randint play = ["Rock", "Paper", "Scissors"] computer = play[randint(0, 2)] print('Computer: {}'.format(computer)) player = input("Rock, Paper, Scissors? ") print('Player: {}'.format(player)) if player == computer: print("Tie!") elif player == "Rock": if computer == "Scissors": pr...
# Input Image, Convert to Grayscale, Write to current folder # Show Image using Matplotlib and OpenCV import cv2 # Import OpenCV import matplotlib.pyplot as plt # Import pyplot from Matplotlib import numpy as np ...
from datetime import datetime, timedelta h, m = map(int, input().split(' ')) dt = datetime(2017,3,7,hour=h, minute=m) td = dt - timedelta(minutes=45) print (td.hour, td.minute)
import math testcases = int(input()) for t in range(testcases): candidates = int(input()) cdV = [] for c in range(candidates): cdV.append(int(input())) maxCV = max(cdV) minCV = min(cdV) midV = sum(cdV)/2 if not(maxCV == minCV) and maxCV > midV: print("majority winner " +...
def get_permutations(sequence): ''' Enumerate all permutations of a given string sequence (string): an arbitrary string to permute. Returns: a list of all permutations of sequence ''' if len(sequence) <= 1: return [sequence] else: permutations = [] first_char = seque...
# Manage dependencies import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # For web scraping from urllib.request import urlopen from bs4 import BeautifulSoup import lxml # Get html # url = "http://www.hubertiming.com/results/2017GPTR10K" url = 'https://en.wikipedia.org/wiki/Li...
from copy import deepcopy from src.CourseMaterials.Week3.Oef1.place import Place class Board: starting_board = [[Place(x, y) for x in range(3)] for y in range(3)] def __init__(self, inner_board=starting_board, value="", children=[], parent_board=deepcopy(starting_board)): self.inner_board = deepcopy(i...
import random board_width = 10 board_height = 10 # board = [['.'] * board_width] * board_height # Dit gaat niet omdat er dan een referenties tussen de arrays liggen # als je element 0 in array 0 aanpast zal element 0 overal aangepast worden better_board = [['.' for x in range(board_width)] for y in range(board_height)...
# encoding: utf-8 """ @ author: wangmingrui @ time: 2021/3/10 14:09 @ desc: Box类拥有add()与remove()方法, 并提供了对execute()方法的访问。 这样我们就可以执行添加或者删除条目的动作。 对execute()方法的访问是通过RLock()来管理 """ import threading import time class Box(object): # 设置可重入锁,他可以在一个线程中多次被获取,但是获取后必须被释放 lock = threading.RLock() def __in...
print("__________________________________________________________________") print("| PERSON \U0001F464 | RATING \u2764 | FRIENDS \U0001F465| POSTS \U0001F6A9| COMMENTS \U0001F4AC|") class User: def __init__(self, nickname, rating, friends, posts, comments): self.nickname = nickname self....
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: # https://leetcode.com/discuss/66147/recursive-preorder-python-and-c-o-n # rcs # iter, next # 200ms def serialize(se...
class Solution(object): def fractionToDecimal(self, numerator, denominator): """ :type numerator: int :type denominator: int :rtype: str """ # s = str(1.0 * numerator / denominator) # res = [s.split('.')[0]] # Wrong answer caused by Scientific Notation...
class Solution: # @param num, a list of integers # @return an integer def majorityElement(self, num): # Majority Vote vote = 1 candidate = num[0] for i in num[1:]: if vote == 0: candidate, vote = i, 1 elif i == candidate: vo...