text stringlengths 37 1.41M |
|---|
#Peter Tran
#1104985
#lab1-problem4
amt = float(input("Enter projected amount of total sales: $"));
print("Expected annual profit is ${:,.2f}".format(.24*amt));
##Enter projected amount of total sales: $10000
##Expected annual profit is $2,400.00
|
"""This problem was asked by Google.
A unival tree (which stands for "universal value") is a tree where all nodes
under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
0
/ \
1 0
... |
"""This problem was asked by Google.
The edit distance between two strings refers to the minimum
number of character insertions, deletions, and substitutions
required to change one string to the other. For example,
the edit distance between “kitten” and “sitting” is three:
substitute the “k” for “s”, substitute the... |
"""This problem was asked by Google.
Implement locking in a binary tree. A binary tree node can be locked or unlocked only if all of its descendants or ancestors are not locked.
Design a binary tree node class with the following methods:
• is_locked, which returns whether the node is locked
• lock, which attempts to lo... |
print("1" ,"2" , sep="--")
print("1","2", end="|")
print("Model S" , "Model 3" , end="|")
print("100" , "200" , end="|")
print("USA" , "France")
# данный код
print("Добро пожаловать!")
# требуемый вывод:
# Добро пожаловать!
# данный код
my_text="print()"
print(my_text)
# требуемый вывод:
# Функция print()
# данный к... |
"""
Course: CS101
File: <name of your file>
Project: <project number>
Author: <Your name>
Description:
<What does your project/program do?>
"""
"""
Instructions:
1) Create a function to display the welcome message at the start
of the program.
2) You need to create a function that prompts the user for the curren... |
"""
Course: CS101
File: team.py
Author: Brother Comeau
Description:
This is the code for the weekly team activity.
Please work together in groups of 2 to 3.
You will not be sumbitting your code for this activity.
You are free to continue working on this activity after class if you need more time.
Sample ... |
"""
Course: CS101
File: team02.py
Author: Brother Comeau
Description:
This is the code for the weekly team activity.
Please work together in groups of 2 to 3.
You will not be sumbitting your code for this activity.
You are free to continue working on this activity after class if you need more time.
Sampl... |
#!/usr/bin/python
import math
""" The file contains help methods to logic functions.
These are object independent; they only need the data given as parameters
to return a result.
"""
point_proximity_radius = 5
def direction_to_point(current, target):
a = math.radians(current.latitude)
b = math.radia... |
import sys
import tkinter as View
from tkinter import messagebox as MessageBox
from tkinter import font
# Tkinter クラスのインスタンス化
MainWindow = View.Tk()
# ウィンドウのタイトル
MainWindow.title("ほげほげ")
# ウィンドウサイズの指定
MainWindow.geometry("700x400")
# ウィンドウの最小サイズの指定
MainWindow.minsize(100,100)
# ウィンドウの最大サイズの指定
MainWindow.maxsize(1000... |
#Quiz: List Indexing
#Use list indexing to determine how many days are in a particular month based on the integer variable month, and store that value in the integer variable num_days. For example, if month is 8, num_days should be set to 31, since the eighth month, August, has 31 days.
#Remember to account for zero-b... |
#Nearest Square
#Write a while loop that finds the largest square number less than an integerlimit and stores it in a variable nearest_square. A square number is the product of an integer multiplied by itself, for example 36 is a square number because it equals 6*6.
#For example, if limit is 40, your code should set t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# author: wq
# description: ""
class Solution:
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = len(nums)
if l <= 1:
return 0
start = 0
reach = 0
step = 0
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。
# 返回这三个数的和。
# 假定每组输入只存在恰好一个解。
# 示例 1:
# 输入:nums = [-1,2,1,-4], target = 1
# 输出:2
# 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
# 示例 2:
# 输入:nums = [0,0,0], target = 1
# 输出:0
# 提示:
# 3 <= nums.len... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# author: wq
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
... |
# Daniel Rono.
# Astrophysics II.
# CNO Coding.
import math
print ("Welcome to the CNO cycle!")
c = 3*(10**8) # the speed of light in vacuo, in metres per second.
L_sol = 3.839*10**26 # solar luminosity in Watts
M_sol = 1.9891*10**30 # solar mass in kg
He4 = 4.00260325413 # mass of Helium-4 in AMU
H = 1.00782503... |
# -*- coding: utf-8 -*-
def fizzbuzz(x):
if x % 15 == 0:
return 'fizzbuzz'
if x % 3 == 0:
return 'fizz'
if x % 5 == 0:
return 'buzz'
return x |
import pygame, math
Black = (0,0,0)
White = (255,255,255)
Blue = (0,0,255)
clock = pygame.time.Clock()
size = (900,600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Double Pendulum")
origin = [int(size[0]/2),100]
r1 = 100
r2 = 100
m1 = 10
m2 = 10
g = 1
a1 = math.pi/2
a2 = math.pi/8
a1_v = 0
a... |
def grader(name, score) :
if score < 60 :
grade = 'F'
elif score >= 60 and score <= 64 :
grade = 'D'
elif score >= 65 and score <= 69 :
grade = 'D+'
elif score >= 70 and score <= 74 :
grade = 'C'
elif score >= 75 and score <= 79 :
grade = 'C+'
e... |
###
#Jhamni Young-Shinnick
#10.25.17
#RisingSun.py
#Interactive Animation w/rising Sun
###
import time
import Tkinter as tk #names TKinter to be used as tk
from Tkinter import *
root = tk.Tk() #Creates root window
canvas = tk.Canvas(root, width=1000, height=1000, borderwidth=0, highlightthickness=0, bg="whi... |
import os
import random
import sys
class Piece:
def __init__(self, x, y, c):
self.x, self.y, self.color = x, y, c
def flip(self):
if self.color == 'b':
self.color = 'w'
else:
self.color = 'b'
class Board:
def __init__(self):
self.pie... |
from PIL import Image
import glob
import os
def rotate(image_path, degrees_to_rotate, saved_location):
"""
Rotate the given photo the amount of given degrees, show it and save it
@param image_path: The path to the image to edit
@param degrees_to_rotate: The number of degrees to rotate the image
@p... |
# 思考 : 計算每個人的時候 都要重新輸入 身高體重
# 應該以物件(人)為單位
# 好好記得每個人自己的身高體重
def bmi(h, w):
return w / (h / 100) ** 2
print(bmi(175,75))
# Step1 設計圖 __init__ 使用
# 1.1 屬性 1.2 專屬功能
class Person():
# 有了 init 不必再宣告成員變數
# init 初始化的建構
def __init__(self, n, h, w):
self.name = n
self.height =... |
# Import necessary packages and libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# Load the passenger data
passengers = pd.r... |
'''http://rosalind.info/problems/lexv/
In this practice I also tried some implementation of class methods
'''
from itertools import permutations
class lexv():
"""Somehow like building a comination with replacement.
alphabet - a list of element with ordering
n - an int of the maximum outp... |
# -*- coding: utf-8 -*-
"""nlp100 in python3"""
__author__ = "Yu Sawai (tuxedocat@github.com)"
__copyright__ = "Copyright 2015, tuxedocat"
__credits__ = ["Naoaki Okazaki", "Inui-Okazaki Lab. at Tohoku University"]
__license__ = "MIT"
import random
def typoglycemia(s):
"""
create typoglycemia for given seque... |
import string
num2alpha = dict(zip(range(1, 27), string.ascii_lowercase))
name =[]
s=""
while True:
alph=int(input("enter number: "))
if (alph <=26 and alph >=1):
name.append(num2alpha[alph])
print (name)
else:
print ("Name is %s" %(s.join(name)))
break
|
#!/usr/bin/env python3
def is_leap_year(year):
if year % 4 != 0:
# If not divisible by 4, not a leap year:
return False
elif year % 100 != 0:
# If divisible by 4 but not 100, a leap year
return True
elif year % 400 != 0:
# If divisible by 100 but not 400, not a l... |
# https://leetcode.com/explore/featured/card/september-leetcoding-challenge/554/week-1-september-1st-september-7th/3445/
from itertools import permutations
class Solution:
def isValid(self, candi):
hh, mm = candi[:2], candi[3:]
return 0 <= int(hh) <= 23 and 0 <= int(mm) <= 59
def largestT... |
from gates import NOR, NAND, NOT, AND, XOR, OR
# function to take input
def take_input():
return input('Enter two decimal numbers: (Enter with empty string to exit) :').split()
# validate if there are 2 and only 2 elements entered
def validate_count(nums):
if len(nums) == 2:
return ... |
#! /usr/bin/env python3
import argparse
import math
from collections import defaultdict
class Day6:
""" Day 6: Universal Orbit Map """
def __init__(self, input_file):
self.process(input_file)
def process(self, input_file):
orbits = defaultdict(list)
# Read data input.
with... |
#! /usr/bin/env python3
import argparse
import math
class Day10:
""" Day 10: Monitoring Station """
def __init__(self, input_file):
self.x_max = 0
self.y_max = 0
self.grid = []
self.asteroids = set()
self.process(input_file)
def process(self, input_file):
#... |
#! /usr/bin/env python3
import argparse
class Day22:
""" Day 22: Slam Shuffle """
def __init__(self, input_file, deck_size):
self.deck = Deck(deck_size)
self.process(input_file)
def process(self, input_file):
with open(input_file, "r") as input:
for line in input:
... |
#! /usr/bin/env python3
import argparse
import math
class Day3:
""" Day 3: Crossed Wires """
def __init__(self, input_file):
self.grid_len = 40000
self.grid = [[0] * self.grid_len for i in range(self.grid_len)]
self.process(input_file)
def process(self, input_file):
list ... |
# -*- coding: utf-8 -*-
""" Contain everything if you want to play with the data
- create color vector for signal and background
- plot one feature VS another feature
- split the data set in one set with only signal and one with only background
- PLot some histograms --> REMOVE OK?????????
"""
import n... |
class Relationship(object):
""" defines how two people are related """
def __init__(self, this, that, distance):
super(Relationship, self).__init__()
self.this = this
self.that = that
self.distance = distance
def couple(self):
""" the two considered """
... |
string = 'My name is Niteesh Panchal'
alphabets_frequency = dict()
string1 = list(string.upper().replace(" ",""))
string2 = list()
for i in string1:
alphabets_frequency[i] = string1.count(i)
if i not in string2:
string2.append(i)
else:
continue
minimum = sorted(alphabets_frequency.values())
minimum_values = [0... |
inf = float('inf')
start = 'A'
stop = 'D'
graph = {}
graph['A'] = {}
graph['A']['B'] = 2
graph['A']['F'] = 3
graph['B'] = {}
graph['B']['C'] = 7
graph['C'] = {}
graph['C']['D'] = 1
graph['F'] = {}
graph['F']['E'] = 3
graph['E'] = {}
graph['E']['D'] = 5
graph['D'] = {}
costs = {}
parents = {}
for node in graph:
c... |
"""
The goal is to classify 2 sets of data according to the distribution
of X1 and X2 in the 2D space, e.g. data points on the left part
of the y-axis will be classified as class 1, and on the right part
as class 2. The points are normally distributed according to the distance h
to the origin.
"""
import numpy a... |
import random
number = random.randint(1, 10)
tries = 1
username = input("Hi there! would you like to share your username ?")
print("Hello ", username + ".")
question = input("would you like to play a guessing game with me ? [y/n]")
if question == "n":
print("Never mind we will play it another time.. ")
if ques... |
import heapq
import inspect
import sys
"""
Data structures useful for implementing Best-First Search
"""
class FrontierPriorityQueueWithFunction(object):
'''
FrontierPriorityQueueWithFunction class implement a search frontier using a
PriorityQueue for ordering the nodes and a set for
constant-time c... |
from state import State
class ProgressionPlanning(object):
'''
ProgressionPlanning class implements all necessary components
for implicitly generating the state space in a forward way (i.e., by progression).self
'''
def __init__(self, domain, problem):
self._problem = problem
self._a... |
#!/usr/bin/python
class tree():
def __init__(self, size, trunk, branch):
self.size = size
self.trunk = trunk
self.branch = branch
def drawtree(self):
for i in range(int(self.size/2) + 1):
print(' ' + (int(self.size/2) - i)*' ' + str((2*i + 1)*self.branch))
print(' ' + (int(self.size/2) - 1)*' ' +... |
import re
"""stop_words are words are the most common words of a language and are often removed to improve statistics. """
stop_words = {w.strip() for w in open('data/stops.txt', 'r').readlines()}
# Sentiment analysis data from <https://github.com/jeffreybreen/twitter-sentiment-analysis-tutorial-201107>
"""pos_words ... |
import json
import argparse
from utils import ACCESS_FILE
def get_access_list():
with open(ACCESS_FILE, 'r') as file:
data = json.load(file)
return data
def save_access_list(data):
with open(ACCESS_FILE, 'w') as file:
json.dump(data, file)
print("Access list saved with success")
def ... |
# Function: Date String Formatter
def date_str_formatter(input_date_str, current_format, target_format):
"""
Input:
input_date_str: Input Date in string format e.g "01-Jan-2000"
current_format: Corresponding date format i.e "%d-%b-%Y"
target_format: Target date format e.g: "%d-%m-%Y"
... |
def key_of_max_value(dt=dict()):
values = list(dt.values()) #[]
print(values)
if not values:
return 'Не передано значень'
M_value = max(values)#5
for k, v in dt.items():
if v == M_value:
return k,v
def myfunc(a=0,b=0):
return a if a>=b else b |
def main():
num = int(input())
for i in range(1, 10):
print(num, "*", i, "=", num * i)
if __name__ == '__main__':
main()
|
"""
封装get、post方法,判断接口是否能请求
"""
import requests
from Pubilc.DoExcel import ReadExcel
from Config import globalconfig
import os
import json
# from Pubilc.DoExcel import WriteExcel
class DoRequest():
def __init__(self, excel_name, sheet_name):
self.excel_name=excel_name
self.sheet_name=sheet_name
... |
import unittest
from src.quicksort import quicksort
class TestQuicksort(unittest.TestCase):
def test_quicksort_with_ints(self):
self.assertEqual(quicksort([3, 1, 4, 2, -1]), [-1, 1, 2, 3, 4])
def test_quicksort_with_strs(self):
self.assertEqual(quicksort(["a", "j", "e", "z"]), ["a", "e", "j"... |
import random
class Egg:
def __init__(self, critical_floor):
self.critical_floor = critical_floor
def drop(self, floor):
if (floor >= self.critical_floor):
return True
else:
return False
class FloorAlgorithm:
def __init__(self, floors, ... |
"""
LeetCode
#1.TwoSum
Description:Given an array(List) and a target,return indices of two numbers that add up to a specific target
Solution:
Method:
add 160524
"""
"""
"""
class Solution:
def __init__(self):
self.resLessThanHalf=[]
self.resMoreThanHalf=[]
self.finalRes=[]
def twoSum(se... |
#Given a number n, provide the fibonnaci sereis value upto n
#use cache(dictionary) to strore the memoization values
#when the value for a particular n is in cache, return cache[n]
#if n is not in cache, carry return the recursive method
class fibonnaci:
def fib(self,n):
cache={}
if n in cache:
return ... |
from collections import defaultdict
class MyList(list):
def __len__(self):
# Each time this method is called with a non-existing key, the
# key-value pair is generated with a default value of 0
d = defaultdict(int)
# This value comes from calling "int" without arguments. (Try
... |
# multiple_inheritance.py
class Researcher:
def __init__(self, field):
self.field = field
def __str__(self):
return "Research field: " + self.field + "\n"
class Teacher:
def __init__(self, courses_list):
self.courses_list = courses_list
def __str__(self):
out = "C... |
class Deck:
def __init__(self):
self.cards = []
for p in ['Spades', 'Diamonds', 'Hearts', 'Clubs']:
for n in range(1, 14):
self.cartas.append(Card(n, p))
def __iter__(self):
return iter(self.cards)
for c in Deck():
print(c)
|
# code13.py
import collections
import threading
class MyDeque(collections.deque):
# We inherit from a normal collections module Deque and
# we add the locking mechanisms to ensure thread
# synchronization
def __init__(self):
super().__init__()
# A lock is created for this queue
... |
def dec_count(n):
print("Counting down from {}".format(n))
while n > 0:
yield n
n -= 1 |
# We create the list with seven numbers
numbers = [6, 7, 2, 4, 10, 20, 25]
print(numbers)
# Ascendence. Note that variable a do not receive
# any value from assignation.
a = numbers.sort()
print(numbers, a)
# Descendent
numbers.sort(reverse=True)
print(numbers)
|
# 8.py
# KeyError exception: incorrect use of key in dictionaries.
# In this example the program ask for an item associated with a key that
# doesn't appears in the dictionary
book = {'author': 'Bob Doe', 'pages': 'a lot'}
print(book['editorial'])
|
import time
import hashlib
import pickle
cache = {}
def is_obsolete(entry, duration):
return time.time() - entry['time'] > duration
def compute_key(function, args, kw):
key = pickle.dumps((function.__name__, args, kw))
# returns the pickle representation of an object as a byte object
# instead of ... |
# 17.py
class Operations:
@staticmethod
def divide(num, den):
if not (isinstance(num, int) and isinstance(den, int)):
raise TypeError('Invalid input type')
if num < 0 or den < 0:
raise Exception('Negative input values')
return float(num) / float(den)
# Open... |
# 9.py
class Operations:
@staticmethod
def divide(num, den):
if den == 0:
# Here we generate the exception and we include
# information about its meaning.
raise ZeroDivisionError('Denominator is 0')
return float(num) / float(den)
print(Operations().divide... |
import numpy as np
def maximum(values):
temp_max = -np.infty
for v in values:
if v > temp_max:
temp_max = v
yield temp_max
elements = [10, 14, 7, 9, 12, 19, 33]
res = maximum(elements)
print(next(res))
print(next(res))
print(next(res))
print(next(res))
print(next(res))
print(next(r... |
# operator_overriding_3.py
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other_point):
self_mag = (self.x ** 2) + (self.y ** 2)
other_point_mag = (other_point.x ** 2) + (other_point.y ** 2)
return self_mag < other_point_mag
if __name__ ... |
from matplotlib import pyplot as plt
import numpy as np
pow2 = lambda x: x ** 2
# Creates a 100 element numpy array, ranging evenly from -1 to 1
t = np.linspace(-1., 1., 100)
plt.plot(t, list(map(pow2, t)), 'xb')
plt.show()
|
class MyMetaClass(type):
def __init__(cls, name, bases, dic):
print("__init__ of {}".format(str(cls)))
super().__init__(name, bases, dic)
class MyClass(metaclass=MyMetaClass):
def __init__(self, a, b):
print("MyClass object with a=%s, b=%s" % (a, b))
print('creating a new object...... |
"""
Tests for the 'abstract_iterator'.
"""
import abstract_iterator as it
import unittest
class TheTests(unittest.TestCase):
def test_1(self):
first = [1,2,3,4]
second = [5,6,7]
third = [8,9,10,11,12]
ideal = [1,2,3,4,5,6,7,8,9,10,11,12]
result_1 = list(it.... |
"""
Given a word, we find its stems, template, and template's flections.
This is an intermediate modeule, it is not used anywhere later.
Some ideas from here are used in the "creating_databases" module.
"""
import mwclient as mw
site = mw.Site('ru.wiktionary.org')
def template(word):
"""
Returns... |
"""Create a weak reference with a list.
"""
import weakref
class MyList(list):
"""My list is just inherits from `list`.
Need this because built-in list does not work with weak refs.
"""
pass
def test():
"""Simple test.
"""
my_list = MyList([1, 2, 3])
print('List:', my_list)
pri... |
class AppleBasket:
def __init__(self, color: str, amount: int):
self.color_apple = color
self.quantity_apple = amount
def increase(self):
self.quantity_apple += 1
def __str__(self):
return f"A basket of {self.quantity_apple} {self.color_apple} apples."
def main():
exam... |
"""
Universidad de El Salvador
Authors:
- Avelar Melgar, José Pablo – AM16015
- Campos Martínez, Abraham Isaac – CM17045
- Lizama Escobar, Oscar Omar – LE17004
- Paredes Pastrán, Carlos Enrique – PP17012
- Quinteros Lemus, Diego Enrique – QL17001
Activity: Applica... |
#creat multiplication table using forloop
number=int(input('ENTER THE VALUE OF TABLE:'))
for count in range(1,11):
result=number*count
print(number ,"*",count,"=",result)
#thanks akhlakansari94@gmail.com |
from utils import today
def myprogram():
name = input("¿cómo te llamas? ")
hoy = today()
print("Hola ", name, ", hoy es ", hoy)
#myprogram() |
from collections import deque
class State:
def __init__(self, symbol=None):
self.children = dict()
self.root = False
if symbol is None:
symbol = "ROOT"
self.root = True
self.symbol = symbol
self.output = list()
self.fail = None
self.... |
class sorting:
array = []
def __init__(self, array):
self.array = array
def sort(self, algorithm="bubble"):
array = []
if(algorithm == "bubble"):
array = self.bubble_sort()
elif(algorithm == "insertion"):
array = self.insertion_sort()
elif(algorithm == "selection"):
array = self.selection_sort... |
# My solution
def same_frequency(num1,num2):
num1_list = list(str(num1)[0:])
num2_list = list(str(num2)[0:])
if len(num1_list) != len(num2_list):
return False
dict1 = {}
dict2 = {}
for (i,num) in enumerate(num1_list):
if num in dict1:
dict1[num] += 1
else:
... |
import re
def parse_date(text):
pattern = re.compile(r'(?P<d>[0-3][0-9])[,/.](?P<m>[0-1][0-9])[,/.](?P<y>\d{4})')
match = pattern.fullmatch(text)
if match:
return {'d': match.group('d'), 'm': match.group('m'), 'y': match.group('y')}
return None
print(parse_date('01/22/1999'))
print(parse_date(... |
# Author: Ravi Teja Gannavarapu
#
# Difficulty: Easy
#
# https://leetcode.com/problems/distance-between-bus-stops/submissions/
# https://leetcode.com/contest/weekly-contest-153/problems/distance-between-bus-stops/
class Solution:
def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) ... |
# Author: Ravi Teja Gannavarapu
#
# Difficulty: Easy
#
# https://leetcode.com/problems/number-of-1-bits/
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
cnt = 0
while n:
if (n & 1):
cnt += 1
... |
a=10
b=100
for n in range(a,b+1):
sum=o
temp=n
while(temp>0):
digit=temp%10
sum=digit**3
if(num==sum):
print(num)
|
a=int(input("enter the number"))
b=int(input("enter the number"))
c=int(input("enter the number"))
if(a>b):
print("a is big")
elif(c<b):
print("b is big")
else:
print("c is big")
|
import datetime
numbers = [1,2,3,4,5,6,7,8,9,10]
print(numbers)
print()
reverse=numbers.sort(reverse=True)
print()
print(reverse)
print(numbers[0:8])
print(len(numbers))
even=list(range(0, 10, 2))
odd=list(range(1, 10, 2))
print(even)
print(odd)
# for i in numbers:
# print("This is Number -> " , i) |
import numpy as np
def zeros_matrix(rows, cols):
m = []
while len(m) < rows:
m.append([])
while len(m[-1]) < cols:
m[-1].append(0.0)
return m
def copy_matrix(m):
rows = len(m)
cols = len(m[0])
mc = zeros_matrix(rows, cols)
for i in range(rows):
for j i... |
# Karatsuba String Multiplication
# Wanted to implement this algorithm but with strings instead
import unittest
from random import randint
def add(s1, s2):
return str(int(s1) + int(s2))
def sub(s1, s2):
return str(int(s1) - int(s2))
def karatsuba(s1, s2):
if int(s1) < 10 or int(s2) < 10:
return str(int(s1) * i... |
"""How to make cash with Python, fast!
The binned Poisson likelihood in astronomy is sometimes called the Cash fit
statistic, because it was described in detail in a paper by Cash 1979
(http://adsabs.harvard.edu/abs/1979ApJ...228..939C).
For observed counts ``n`` and expected counts ``mu`` it is given by:
C = 2 ... |
import sys
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self._maxSum = -sys.maxsize
def maxPathSum(self, root):
"""
:type root: TreeN... |
def findAnagram(A, B):
L = len(B)
if L == 0: return None
mapB = {}
for i in range(L):
b = B[i]
if b not in mapB: mapB[b] = i
anaMap = []
for i in range(L):
a = A[i]
anaMap.append(mapB[a])
return anaMap
|
class Solution:
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
ROW = len(board) - 1 if board != None else -1
COL = len(board[0]) - 1 if ROW >= 0 else -1
if ROW < 0 or COL < 0: re... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
self._quickSortList(head, None)
return head
def _quickSo... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
self._walkBST(root, 0)
return root
def _walkBST(self, root, sumOfGreaters):
if not r... |
def formatLicenseKey(key, K):
str = ""
for i in range(len(key)):
c = key[i]
if c != "-": str += c
k = K
newKey = ""
l = len(str) - 1
str = str.upper()
while l >= 0:
if k == 0:
newKey = "-" + newKey
k = K
newKey = str[l] + newKey
l -= 1
k -= 1
if newKey[0] == "... |
# 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 largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if ... |
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0: return '0'
ans = ''
isMinus = False
if num < 0:
num *= -1
isMinus = True
while num > 0:
ans = str(num % 7... |
# coding: utf-8
# In[45]:
'''
Since the data have been audited, cleaned and transfered into table and database, the following questions such as :
Number of nodes
Number of unique users
Number of ways
Most contributing users
Number of users who contributed only once
Top 10 amenities in New Delhi
Can be answer... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import csv
input = sys.argv[1]
#csv input
with open("problem.csv", "rb") as f:
fcsv = csv.reader(f, delimiter="\t")
flist = [i for i in fcsv]
class Pilot():
def __init__(self, list):
self.nome = list[1].split("-")
... |
# https://www.hackerrank.com/challenges/merge-the-tools/problem
def merge_the_tools(string, k):
for i in range(0,len(string),k):
s=string[i]
for j in range(i+1,i+k):
if string[j] not in s:
s+=string[j]
print(s) |
class my_class():
def abc(self):
a = str(12345)
print "value of a" ,a
def xyz(self,arg1,arg2):
sum = arg1 + arg2
print "value of sum %s" %(sum)
class child_my_class(my_class):
def abc(self):
my_class.abc(self)
print "pratik"
#Notic... |
class pizza():
pratik = 1
def __init__(self):
print "hello"
def get_size1(self):
return "123"
class dabali(pizza):
def get_size(self,pratik):
self.pratik = pizza.pratik
print self.pratik
return 123
z = dabali()
z.get_size(5) |
import time
class Man_United:
def Result(Score,MANU,OTHER_TEAM):
Score.MANU=MANU
Score.OTHER_TEAM=OTHER_TEAM
if (MANU > OTHER_TEAM):
print("MANCHASTER UNITED")
elif(MANU < OTHER_TEAM):
print("OTHER TEAM")
else:
print("MATCH DRAW")... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.