text
stringlengths
5
121k
def sum(arr, total = 0): if (len(arr) == 0): return total else: num = arr.pop() total += num return sum(arr, total) print(sum([1, 2, 3, 4, 5, 5, 1])) def sum_answer(list): if list == []: return 0 return list[0] + sum_answer(list[1:]) print(sum_answer([1, 2,...
''' unit test: 1 4 4 1 2 2 3 3 4 2 4 1 ''' class Graph(object): def __init__(self, n): self.num_nodes = n self.path_list = [[] for _ in range(n)] def connect(self, start_node, end_node): self.path_list[start_node].append(end_node) self.path_list[end_node].append(start_...
import panda as ps data = { 'person1': ["Tim", "Marck", "Feranses"], 'ages': [13, 10, 8] } x = pd.DataFrame(data) print(x)
a = input("Enter your name: ") b = input("Enter your password: ") c = input("Enter your age(in letters): ") data = { "username": a, "password": b, "age": c } class fail: def __init__(self, exception, prevent): self.exception = exception self.prevent = prevent def printError(self): ...
class Person: def __init__(self, name, age): self.name = name self.age = age def __del__(self): print("Nesne silindi") class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector(self.x + other.x, self.y + o...
'''ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits. If the function is passed a valid PIN string, return true, else return false.''' import re def validate_pin(pin=str): listas = [] for i in str(pin): listas.append(i) ...
num1=int(input("Enter first number: ")) num2=int(input("Enter second number: ")) ch=input(" Enter for opration symbol addition (+),substraction (-),substraction (*),substraction (/), % (get remainder) and for exit enter '$' ") if ch=='+': print("Sum is : ",num1+num2) if ch== "-": ...
(""" 1) Write a function that performs the sum of every element in the given number unless it comes to be a single digit. Example 12345 = 6 """) def Calsum(num): c=0;sum=0 while num>0: lastdigit=num%10 sum+=lastdigit num=num//10 k=sum ...
'''4) Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: a. 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... b. By considering the terms in the Fibonacci sequence whose values do not exceed four hundred, find the sum of the even-valued t...
import constants def main(): guess = int(input("Guess the number between 1 & 9 (integer): ")) print("") if guess == constants.CORRECT_NUMBER: print("You guessed the number!") if __name__ == "__main__": main()
class Queue: def __init__(self): self.array = [] def isEmpty(self): return len(self.array) == 0 def peek(self): if len(self.array) > 0: return self.array[0] return None def pop(self): if len(self.array) > 0: ...
import requests import nba_py from nba_py import player import json class GameData: games = [] def __init__(self): james = player.PlayerGameLogs('2544', '00', '2017-18', "Regular Season") resp = james.json['resultSets'] for x in resp: s...
from array import * a=array('i',[]) n=int(input("enter array size: ")) for i in range (n): a.append(int(input())) for i in range(n): for j in range(n): if(a[j]==i+1): a.remove(a[i]) a[j]=a[i-1] n=n-1 print(a)
x=int(input("enter the radius")) a=(3.14*(x**2)) c=(2*3.14*x) print("area:",a) print("circumference:",c)
def is_in_range(_var, start, end): if (_var < start or _var > end): return (0) else: return (1) def is_in_list(_var, _list): for elem in _list: if (elem == _var): return (1) return (0)
lst = [5, 4, 1, 5, 1, 2, 7, 5, 3, 4, 5, 6] def backtrack(lst, aux_list, pos, i): if (pos < len(lst)): if (len(aux_list) == 0): aux_list.append(lst[pos]) print(aux_list) else: if (i < len(lst) and lst[i] > aux_list[len(aux_list) - 1]): aux_list.append(lst[i]) print(aux_list) else: aux_list ...
unsorted_list = [5, 6, 7, 2, 3, 4, 1, 0, 23, 41, 21, 6, 5, 4, 2, 3, 3, 4, 1] def quicksort(lst, lo, hi): if (lo < hi): p = partition(lst, lo, hi) quicksort(lst, lo, p - 1) quicksort(lst, p + 1, hi) def partition(lst, lo, hi): pivot = lst[hi] i = lo for j in range(lo, hi): if (lst[j] <= pivot): aux ...
''' An iterator ''' class Iterator: def __init__(self, start, end, step=1): self.index = start self.start = start self.end = end self.step = step def __iter__(self): print(self) return self def __next__(self): if not (self.index + self.s...
bd = { "Sara": "12345", "Maria": "54321", "Alexandra": "23415", "Teodora": "34125" } name = input("Please enter a name: ") while name != "stop": try: print (bd[name]) name = input("Please enter a name: ") except KeyError: print ("Je ne connais pas cette personne") ...
def prn_board(tb): for x in range(3): print("{}|{}|{}".format(tb[x][0], tb[x][1], tb[x][2])) print("-"*5) turn = 'X' board = [[' ', ' ',' '], [' ', ' ',' '], [' ', ' ',' ']] prn_board(board) for x in range(9): while True: y,x = map(int,input("좌표(y,x): ").split...
class Solution: def numWaterBottles(self,numBottles,numExchange): sumb = numBottles empty = numBottles while empty // numExchange: bottle = empty // numExchange empty = bottle + empty % numExchange sumb += bo...
class Solution: def groupAnagrams(self,strs): dict={} for s in strs: key = tuple(sorted(s)) dict[key] = dict.get(key,[]) + [s] return list(dict.values()) if __name__ == "__main__": so ...
num = list(input().split()) if sorted(num) == num: print('ascending') elif sorted(num,reverse=True) == num: print('descending') else: print('mixed')
N = int(input()) num = N for i in range(2,N+1): while not num%i: print(i) num = int(num/i) '''처음 풀이 - 시간이 너무 오래 걸림 nums = [False,False] + [True] * (N-1) for i in range(2, int(N**0.5)+1): if nums[i]: #True nums[i*2::i] = [False] * ((N-i)//i) prime = [idx for idx,val in enumerate(nums) ...
import sys input = sys.stdin.readline def isRight(a,b,c): if a == b+c or b == a+c or c == a+b: return 'right' return 'wrong' while True: a,b,c = map(int,input().split()) if a==0 and b==0 and c==0: break a,b,c = a**2,b**2,c**2 print(isRight(a,b,c))
import sys def palindrome(num): l = len(num) for i in range(0,l//2): if num[i] != num[l-i-1]: return 'no' return 'yes' for line in sys.stdin: if line.rstrip() == '0': break print(palindrome(line.rstrip()))
''' Created on Oct 16, 2015 @author: Iaroslav ''' import numpy as np class RNN: training = False; def __init__(self, xsz, ysz, neurons_per_block): self.W = np.random.randn(neurons_per_block+xsz+ysz+1, neurons_per_block)*0.001 self.xsz = xsz self.ysz = ysz def forward(self,x)...
my_family = [] my_family.append(input("What`s your name: ").title()) select = input("Have you got family? (Y/N)").upper() if select == "Y": my_family.append(input("OK. What is the first member`s name of your family: ").title()) select = input("Have you got any other member? (Y/N)").upper() if select == "...
""" 912. Sort an Array Given an array of integers nums, sort the array in ascending order. Example 1: Input: nums = [5,2,3,1] Output: [1,2,3,5] Example 2: Input: nums = [5,1,1,2,0,0] Output: [0,0,1,1,2,5] """ class Solution: def sortArray(self, nums: List[int]) -> List[int]: return self.quicksort(nums...
""" Printing using %s vs printing using .format """ def display_safe(employee): """ Display details of the employee instance """ print("Employee: {name}, Age: {age}, profession: {job}".format(**employee)) def display_unsafe(employee): """ Display details of employee instance """ print("Employee:...
""" Module test_datetimehelper - Unit test module for testing datetimehelper module """ import unittest import datetime import datetimehelper from unittest.mock import patch class DateTimeHelperTestCase(unittest.TestCase): """ Unit-test testcase class for DateTimeHelper class """ def setUp(self): ...
""" Implementation of the Factory/Factory Method Design Pattern """ from abc import ABCMeta, abstractmethod class Employee(metaclass=ABCMeta): """ An Employee class """ def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender @abstractmethod...
""" StreamHasher - Class providing hashing of data from an input stream using pluggable algorithms """ class StreamHasher(object): """ Stream hasher class with configurable algorithm """ def __init__(self, algorithm, chunk_size=4096): self.chunk_size = chunk_size self.hash = algorith...
""" Proxy design pattern - An example of an instance counting proxy """ from abc import ABCMeta, abstractmethod class Employee(metaclass=ABCMeta): """ An Employee class """ def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender @abstractme...
""" Example with collections.deque for rotating sequences """ from collections import deque def rotate_seq1(seq1, n): """ Rotate a sequence left by n """ k = len(seq1) - n return seq1[k:] + seq1[:k] def rotate_seq2(seq1, n): """ Rotate a sequence left by n using deque """ d = deque...
""" Using generators, print details of the most recently modified file, matching a pattern. """ import glob import os from time import sleep def watch(pattern): """ Watch a folder for modified files matching a pattern """ while True: files = glob.glob(pattern) files = sorte...
""" Examples of using defaultdict """ from collections import defaultdict counts = {} text="""Python is an interpreted language. Python is an object-oriented language. Python is easy to learn. Python is an open source language. """ word="Python" for word in text.split(): word = word.lower().strip() try...
def fetch_url(url, ntries=3, timeout=30): """ Fetch a given url and return its contents. @params url - The URL to be fetched. ntries - The maximum number of retries. timeout - Timout per call in seconds. @returns On success - Conte...
class Node: def __init__(self,data,next): self.data = data self.next = next class LinkedList: def __init__(self,head = None): self.head = head def input(self,data): node = Node(data,self.head) self.head = node def PrintAll(self): currentNode = self.head...
class Node: def __init__(self,data,string,next): self.data = data self.string = string self.next = next def str(self): return self.data,self.string class LinkedList: def __init__(self,head = None): self.head = head def insert(self,data,string): node ...
st = 'Print only the words that start with s in this sentence' for word in st.split(): if word[0] == 's': print(word) li = list(range(1,15,2)) print(li) div3 = [x for x in range(1,50) if x%3 == 0 ] print(div3) firstLetter = [word[0] for word in st.split()] print(firstLetter)
class Author: def __init__(self,book): self.books = book def info(self): print("Writer name :" ,self.name.title()) print("Published Year :" ,self.publishedTime.title()) def show(self): ...
import cv2 as cv img = cv.imread('Photos/cat.jpg') cv.imshow('cat',img ) gray = cv.cvtColor(img,cv.COLOR_BGR2HSV_FULL) cv.imshow('gray',gray) blur = cv.GaussianBlur(img, (7,7), cv.BORDER_DEFAULT) cv.imshow('blur',blur) canny = cv.Canny(img, 150, 175) cv.imshow ('Canny Edge',canny) dilate = cv.dilate(c...
import sys sys.path.append('../doubly_linked_list') from doubly_linked_list import DoublyLinkedList, ListNode class Queue: def __init__(self): self.size = 0 self.storage = DoublyLinkedList() def __str__(self): cur_node = self.storage.head output = '' output += str(cur...
'muli thread' import threading __author__ = 'fucai' lock = threading.Lock() thread_local = threading.local def loop(): lock.acquire() try: print('thread %s is running...' % threading.current_thread().name) n = 0 while n < 5: n = n+1 print('thread %s ...
class User: def __init__(self, name, email_address): self.name = name self.email = email_address self.account = BankAccount(int_rate = 1.02, balance = 500) def make_deposit(self, amount): self.account.deposit += amount return self def make_withdrawl(self, amo...
import turtle as t t.shape('turtle') for i in range(100): t.forward(i * 10) t.left(90)
from ast import Expr, Assign def transform(ast_list): """ Transforms an AST list into a single expression :param ast_list: List of AST :return: List of AST """ res_exprs = [] for ast in ast_list: res_exprs.append(transform_expr(ast)) return res_exprs def transform_expr(ast): ...
'''create 3 functions (with the same name as those attributes), which should return the corresponding value for the attribute. extra: create a function that returns a boolean''' year_recorded = 2003 artist = 'Snow Patrol' def show_favorite_band(artist): return artist def return_recording_year(year = 1900): ...
'''Create a function that allows you to add things to a list. Anything that's passed to this function should get added to myUniqueList, unless its value already exists in myUniqueList. (If the value doesn't exist already, it should be added and the function should return True. If the value does exist, it should not...
def func1(): print("Hello") def func2(): print("Goodbye") def func3(): print("Default") def inline_try(x): try: return int(x) except ValueError: return x switch = { 1 : func1, 2 : func2, } if __name__ == "__main__": import time start = time.time() for i in ...
def decrypt(encrypted_text, n): if encrypted_text == None or encrypted_text == '' or n <= 0: return encrypted_text str_len:int = len(encrypted_text) half_str_len = str_len // 2 result: str = ''.ljust(str_len) for j in range(n): res_list = list(result) for i in range(half_str_...
def convertFracts(lst): if lst == None or lst ==[] or lst == [[]]: return [] if len(lst) == 1: return lst[0] def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) def lcm(a, b): return a // gcd(a, b) * b lcm_res = lcm(lst[0...
import unittest from common import common def common(lists): ''' Input: lists | Array of arrays of positive integers Output: num_common | number of numbers common to all arrays ''' num_common = 0 if len(lists) == 0: return 0 common_set = {x for x in lists[0]} ...
def f(n): if n<=1: return n else: return(f(n-1)+f(n-2)) n = int(input("enter number")) for i in range(n): print(f(i),end=" ")
l=list(range(1,101)) odd=list() sum = 0 for n in l: if n%2 !=0 : odd.append(n) sum += n print(sum,"is the sum of odd number between 1 to 100")
class Game: def __init__(self): print('Welcome to our Games') print('choose a game : ') print('press [1] to play the Even-odd game') print('Press [2] to play the Average game') print('Press [3] to play the Multiplication') self.choose() de...
class Solution: def fib(self, N: int) -> int: if N == 1: return 1 if N == 0: return 0 first = 0 second = 1 for _ in range(2, N+1): total = first + second first = second second = total return second
''' Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 2: Input: [1,2,3,4] Output: 24 ''' ''' First solution: O(nlogn) runtime/ O(logn) space caus of sortings Sort the array, Find the product of the last 3 numbers Find the...
''' Optimal solution: Use a dict (hashmap), go through each element in list1, save the elements in the hashmap Go through list2, check if there is an element that match an element in the hashmap If there is, then return that element, Else keep going through, If could not find any then return null Runtime: O(n) Space:...
n=int(input()) if(n==1 or n==2 or n==3 or n==4 or n==5 or n==6 or n==7 or n==8 or n==9 or n==10): print("yes") else: print("no")
import sqlite3 from models import Employee conn = sqlite3.connect('employee.db') conn.row_factory = sqlite3.Row cursor = conn.cursor() ''' id = row[0] first = row[1] last = row[2] print(str(id) + " " + first + " " + last) e = Employee(first, last) print(e) '''
class Calculadora(): ''' Atributos ''' marca = None color = None tipo_de_calculadora = None tamano = None tipo_de_corriente = None fabricacion = None modelo = None material = None lenjuage = None def __init__(self): print("clase calculadora") ...
import os import time import datetime def check_ping(): hostname = "google.com" response = os.system("ping -n 1 " + hostname) if response == 0: response = "Network Active" else: response = "Network Error" return response while True: ...
row1 = ["X", "X", "X"] row2 = ["X", "X", "X"] row3 = ["X", "X", "X"] row4 = ["X", "X", "X"] map = [row1, row2, row3, row4] print(f"{row1}\n{row2}\n{row3}") x = int(input("Type the row number(x) : ")) y = int(input("Type the coloumn number(y) : ")) map[x-1][y-1] = "O" print(f"{row1}\n{row2}\n{row3}\n{row4}")
import random test_seed = int(input('Input a seed number : ')) random.seed(test_seed) side = random.randint(0,1) if side ==1 : print('Heads') else : print('Tails')
''' Created on 2017年12月11日 @author: user ''' """ """ class Student(object): ''' this is a Student class ''' count = 0 books = [] def __init__(self, name, age): self.name = name self.age = age pass
import json data = {} data['people'] = [] data['people'].append({ 'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska' }) data['people'].append({ 'name': 'Larry', 'website': 'google.com', 'from': 'Michigan' }) data['people'].append({ 'name': 'Tim', 'website': 'a...
class Employee: num_of_emps = 0 raise_amount = 1.04 def __init__(self,first,last, pay): self.first = first self.last = last self.pay = pay self.email = first + "." + last + '@company.com' Employee.num_of_emps += 1 def fullname(self): return '{} {}' .format(self.first, self.last) def apply_raise(...
while True: while True: try: t = int(input('Input minutes: ')) break except(ValueError, TypeError): print('Incorrect input!') if 1 <= (t % 6) <= 3: print('Green') elif (t % 6) == 4: print('Yellow') else: print('Red') print(f...
def reverseWordsInString(string): reversedWords = [] for word in string[::-1].split(' '): reversedWords.append(word[::-1]) return " ".join(reversedWords) def reverseWordsInString2(string): def reverseList(l): start, end = 0, len(l) - 1 while start < end: ...
"""Given an integer NN, write a Python function that returns all of the prime numbers up to NN. """ def prime_numbers(N): primes = [] for num in range(2, N): if all(num % i != 0 for i in range(2, num)): primes.append(num) return prim...
""" Let’s say we have a group of N friends represented by a list of dictionaries where each value is a friend name and their location on a three dimensional scale of (x, y, z). The friends want to host a party but want the friend with the optimal location (least distance to travel as a group) to host it. Write a funct...
"""Given a string, write a function recurring_char to find its first recurring character. Return None if there is no recurring character. Treat upper and lower case letters as distinct characters. You may assume the input string includes no spaces.""" def recurring_char(input): seen = set() for char in input:...
from sortedcontainers import SortedList, SortedDict class Solution(object): """ Count number of integers that is smaller than current number in array from left to right. """ def countSmaller(self, nums): """ :type nums: List[int] :rtype: List[int] """ output = ...
"""Given a percentile_threshold, sample size N, and mean and standard deviation m and sd of the normal distribution, write a function truncated_dist to simulate a normal distribution truncated at percentile_threshold. """ import numpy as np import scipy.stats as st def truncated_dist(m, sd, n, percentile_threshold):...
""" Write a class for Min Max Stack. Pushing and Popping value from the stack; Peeking value at top of the stack; Getting both minimum and maximum value in the stack at any time. """ from collections import deque class MinMaxStack: def __init__(self): self.minMaxStack = deque() def pee...
""" You are given the layout of a rectangular building with rooms forming a grid. Each room has four doors to the room to the north, east, south, and west where exactly one door is unlocked and the other three doors are locked. In each time step, you can move to an adjacent room via an unlocked door. Your task is to d...
class Solution(object): """ Rearrange an array to even and odd """ def even_odd (self, A): next_even, next_odd = 0, len(A) - 1 while next_even < next_odd: if A[next_even] % 2 == 0: next_even += 1 else: A[n...
""" Given an array of arrays where each subarray hold two integer values represent an item. The first value is item's value, the second value is item's weight. You are also given maximum capacity. Your goal is find maximum combined value of items without exceed capacity. """ def knapsackProblem(items, capacity): ...
import math def calculate_rmse(y_pred, y_true): sum = 0 n = len(y_pred) for i in range(n): sum += (y_true[i] - y_pred[i])**2 return math.sqrt(sum/n) y_pred = [3,4,5] y_true = [3,4,5] print(calculate_rmse(y_pred, y_true))
class BST: def __init__(self, value): self.value = value self.left = None self.right = None def findClosestValueInBst(tree, target): currentNode = tree closest = currentNode.value while currentNode is not None: if abs(target - currentNode.value) < abs(target ...
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 1, 10) y = 1 + x + x * np.random.random(len(x)) A = np.vstack([x, np.ones(len(x))]).T y = y[:, np.newaxis] AT = np.transpose(np.array(A)) print("A_T = ", AT) coefficients = np.dot(np.linalg.inv(np.dot(A.T, A)), A.T) print(coefficients) pr...
""" Count the minimum number of bills to get to an amount. If cannot find a combination then return -1. """ def minNumberOfCoinsForChange(amount, bills): if amount <= 0: return 0 minNumOfBills = [float('inf') for _ in range(amount + 1)] minNumOfBills[0] = 0 for bill in bills: ...
import calendar month,day,year=map(int,input().split()) print((calendar.day_name[calendar.weekday(year, month, day)]).upper())
"""Given an array and a target integer, write a function sum_pair_indices that returns the indices of two integers in the array that add up to the target integer if not found such just return empty list. Note: even though there could be many solutions, only one needs to be returned.""" def sum_pair_indices(array, targ...
import random class Solution(object): def uniform_random(self, lower_bound, upper_bound): random_number = upper_bound - lower_bound + 1 while True: result, i = 0, 0 while (1 << i) < random_number: zero_one_random = random.randint(0, 1) ...
"""Given two strings, write a function to return True if the strings are anagrams of each other and False if they are not. A word is not an anagram of itself. """ def is_anagram(string1, string2): if string1 == string2 or len(string1) != len(string2): return False string1_list = sorted(string1) str...
""" Write a function that takes in two strings and returns the minimum number of edit operations (insert, delete, substitute) a char to obtain the second string. """ def levenshteinDistance(str1, str2): edits = [[x for x in range(len(str1) + 1)] for y in range(len(str2) + 1)] for i ...
from collections import deque myStack = deque() myStack.append('a') myStack.append('b') myStack.append('c') deque(['a', 'b', 'c']) print(myStack.pop()) print(myStack.pop()) print(myStack.pop())
def binary_search_iterative(array, target): if not array: return -1 left = 0 right = len(array)-1 while left <= right: mid = (left + right) // 2 if array[mid] == target: return mid elif target < array[mid]: right = mid - 1 ...
def add(x,y): total = float(a)+float(b); return total print("Enter two number:") a = input() b= input() print(add(a,b));
from abc import ABCMeta, abstractmethod class Gun(metaclass=ABCMeta): @abstractmethod def toString(self): pass class UFOGun(Gun): def toString(self): return "1000 damage" class RocketGun(Gun): def toString(self): return "10 damage"
import tweepy import pandas as pd import numpy as np from IPython.display import display import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import seaborn as sns from credentials import * def twitter_setup(): """ Utility function to setup the Twitter's API ...
def zamenjaj(s, i, j): s[i], s[j] = s[j], s[i] def zamenjan(s, i, j): t = s[:] zamenjaj(t, i, j) return t def uredi(s): t = s[:] menjave = [] oznaka = len(s) - 1 menjano = True while menjano: menjano = False for i in range(0, oznaka): if t[i] > t[i + ...
username = str(input("Enter your username, username should be alice or bob: ")) ''' Convert the username to lowercase letters and compare if the what the user entered correlates with accepted string ''' if username.lower() == "alice" or username.lower() == "bob": print("Welcome to programming with...
from Search import BinarySearch from Search import LinearSearch list=[10,20,30,40,50,60] print(" Binary Seach Return Value : ",BinarySearch.binary_search(list,-1)) print(" Linear Seach Return Value : ",LinearSearch.linear_search(list,60))
name="Harry" for character in name: print(character) for i in [0,1,2,3,4,5]: print(i) for j in range(6): print(j) names=["Harry", "Ron", "Hermione"] for name in names: print(name)
import pandas as pd from sklearn.cluster import KMeans import matplotlib.pyplot as plt from sklearn import metrics cc_dataset = pd.read_csv('CC.csv') nullvalues = cc_dataset.isnull().sum() print(nullvalues) cc_dataset.fillna(cc_dataset.mean(), inplace=True) print('checking null values after removing :',cc_datase...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.metrics import classification_report, accuracy_score glass_data = pd.read_csv('glass.csv') x_train = glass_data.drop("Type", axis=1) y_train = glass_data['Type'] x_train, x_test, y_train, y_test = train...