text stringlengths 37 1.41M |
|---|
def lcm(text1, text2):
"""
Given two strings text1 and text2, return the length of their longest common subsequence.
A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "... |
def binary_search(arr, low, high, target):
if low == high:
return arr[low] == target
while low < high:
midpoint_index = low + ((high - low) // 2)
midpoint = arr[midpoint_index]
if midpoint == target:
return True
if midpoint < target:
low = midpo... |
# nums is always sorted
def get_index_equals_value(nums):
return binary_search_solution_recursive(nums, 0, len(nums) - 1, -1)
# return binary_search_iterative(nums)
# better solution because it's simple, fewer lines of code, and not recursive
def binary_search_iterative(arr):
left = 0
right = len(arr)... |
"""
Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).
Example 1:
Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:
Input: 000000... |
"""
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth =... |
"""
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
"""Commentary
The naive solution is the check... |
def find_grants_cap(grants_array, new_budget):
return solution_v1(grants_array, new_budget)
def solution_v1(grants_array, new_budget):
if sum(grants_array) <= new_budget:
return max(grants_array)
grants_array = sorted(grants_array)
grants_remaining = len(grants_array)
current_cap = new_bu... |
def quicksort(arr, low, high):
# sort only if there is more than one element in the array
if low < high:
# partition/sort the current array based on some partition
partition_index = partition(arr, low, high)
# sort the left side of the partition
quicksort(arr, low, partition_inde... |
def find_min(nums):
"""
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
"""
# handles case of a sorted array t... |
def is_fifo(takeout, dine_in, served):
"""
My cake shop is so popular, I'm adding some tables and hiring wait staff so folks can have a cute sit-down cake-eating experience.
I have two registers: one for take-out orders, and the other for the other folks eating inside the cafe. All the customer orders get ... |
def valid_parenthesis(string):
stack = []
closing = {")": "(", "]": "["}
opening = set(["(", "["])
for char in string:
if char in opening:
stack.append(char)
elif char in closing:
if stack:
peek = stack[-1]
if peek == closing.get(c... |
"""
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve i... |
"""Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
"""
""" Commentary
This problem tests your ability to traverse a binary tree, specifically inorder, postorder, preorder tra... |
#!/usr/bin/env python
class Node(object):
def __init__(self,name):
# A list of (label,node) pairs
self.successors = set()
self.name = name
class Graph(object):
def __init__(self):
self.nodes = set()
def tarjan(self):
components = []
stack = []
indi... |
import string
import sys
import json
class JSON(object):
def __init__(self, data):
self.__dict__ = json.loads(data)
def lines(fp):
print(str(len(fp.readlines())))
def calculator(text, dict):
result = 0;
non_senti_words = []
list_of_words = text.split(' ')
for word in list_of_words:... |
# "Magic 8 Ball with a List" game
from random import shuffle # this part we will learn letter
messages = ['It is certain', 'It is decidedly so', 'Yes definitely',
'Reply hazy try again', 'Ask again later', 'Concentrate and ask again',
'My reply is no', 'Outlook not so good', 'Very doubtfu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
num = 0
numsum = 0
while num < 100:
num += 1
numsum += num
print (numsum) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
age = int(input('you age'))
if age >= 999:
print('age', age)
print('you can see av')
elif age >= 99:
print('age', age)
print('old')
else:
print('age', age)
print('fk you cant see av') |
#A function can have multiple return statements. When any of them is executed, the function terminates.
#Bubble sort works by comparing number at index 0 to index 1. If number at index 0 is larger, then the larger number
#is swapped to index 1. And the smaller number is swapped to index 0.
#Next, the numbers at index 1... |
import pygame # import the pygame module
import time # import the time module
import random # import the random module
pygame.init() # initialize pygame: returns a tuple or success or fail
# Setting up the RGB Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Displa... |
from collections import deque, OrderedDict
class Node(object):
def __init__(self, name, data):
self.name = name
self.data = data
self.inputs = {}
self.outputs = {}
def connect_to(self, node):
if not node in self.outputs:
self.outputs[node] = True
... |
class Node:
def __init__(self, data = None, next = None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def InsertInBegining(self, data):
node = Node(data, self.head)
self.head = node
def InsertAtTheEnd(self, data)... |
number_of_shares = int(input("Enter number of shares:"))
purchase_price = float(input("Enter purchase price:"))
sale_price = float(input("Enter sale price:"))
buy = float(number_of_shares * purchase_price)
first_commission = float(buy * .11)
sale = float(number_of_shares * sale_price)
second_commission = float(sale *... |
import math
X = int(input())
Y = input()
N = int(input())
count = 0
i = 0
def isHappy(i):
s = 0
while(i > 0):
s = s + (i % 10) * (i % 10)
i = i // 10
if (s == 1):
return True
elif (s == 4):
return False
return isHappy(s)
def isPrime(i):
if (i ==... |
from numpy import array, amax, delete, insert
class Tetris:
def __init__(self, width, height, dict_fields):
self.width, self.height, self.dict_fields, self.piece = width, height, dict_fields, None
self.empty_field = array([["-"]*self.width]*self.height)
self.field = self.copy_field(self.em... |
print "Welcome to Pypet!"
print
cat = {
'name': 'Weiwei',
'age': 22,
'weight': 11.6,
'hungry': True,
'photo': '(=^o.o^=)__',
'happiness': 0,
}
mouse = {
'name': 'Kaikai',
'age': 26,
'weight': 20.5,
'hungry': False,
'photo': '<:3 )~~~~',
'happiness': 0,
}
pets = [cat, m... |
#CTI 110
#M5HW2_SoftwareSales
#Michael Peters
#20 November 2017
# this program will account for a bulk discount on products sold
#product is $99
#4 discounts
# 10% - 10-19 items sold
# 20% - 20-49 items sold
# 30% - 50-99 items sold
# 40% - 100+ items sold
def main():
... |
#CTI 110
#M5HW1_AgeClassifier
#Michael Peters
#20 November 2017
# this program will ask for a persons age and then classify them in an age group.
def main():
# 4 catagories of age;
# 0-1 infant
# 2-12 child
# 13-19 teenager
# 20 and older an adult
age = float(input('How ol... |
class Arbol:
def __init__(self,valor):
self.valor = valor
self.izquierda = None
self.derecha = None
#Metodo para agregar nodos a la izquierda del arbol, no importando que nodo
#del arbol queremos como padre de este
def AgregaIzquierda(self,padre,dato):
if self.valor != padre:
if self.izquierda != None:
... |
# further research:
# - proof of RSA's correctness (Wikipedia)
# - coprime check
# - modular multiplicative inverse
# - primality testing
import math
from Crypto.PublicKey import RSA
from util import modexp, gen_prime
def multiplicative_inverse(a, m):
# totally naive
for i in range(m):
if a * i % m ... |
from programs.vowels import vowels
def test_hello():
assert vowels("hello")==2
def test_mixed_case():
assert vowels("AAAaaaBBBbbb")==6
def test_empty_string():
assert vowels("")==0 |
width=800
height=600
left_score = 0
right_score = 0
left_y = 40
right_y = 260
ball_x = 390
ball_y = 290
ball_dy = -3
ball_dx = -3
left_key = ""
right_key = ""
mode = "instruction-screen"
def reset_game():
global left_score, right_score, left_y, right_y, ball_x, ball_y, ball_dy, ball_dx
left_score = 0
right_... |
# Fibonacci functions
from decorator import memoized
from math import sqrt
def trivialFib(n):
'''Trivial fibonacci implementation, complexity O(2^n).
Starts getting slow with n>30
'''
if n <= 1:
return n
else:
return trivialFib(n-1) + trivialFib(n-2)
@memoized
def memoizedTri... |
import webbrowser
class Movie():
""" This class will hold movie information.
Attributes:
movie_title: Title of the movie.
movie_storyline: Storyline of the movie.
poster_image: Poster image of the movie.
trailer_youtbe: Youtube link to the trailer of the movie.
"""
de... |
class Person():
def __init__(self):
self.money = 100
def getMoney(self):
return self.__money
def setMoney(self,money):
if money <= 0:
print("传入金额有误")
else:
self.__money = money
xiaoming = Person()
xiaoming.__money = -100
xiaoming.setMoney(20)
print(xiaoming.getMoney())
xiaoming.__money
|
c = 'yangzhenya'
h = '123456'
account=(input("请输入账户"))
pwd =(input("请输入密码"))
if account == c and pwd == h:
print('登录成功')
else:
print('密码或者用户名错误')
|
list = [11,22,33,44,55,44,33]
l1 = []
for i in list:
if i not in l1:
l1.append(i)
print(l1)
|
list = []
name_list=[]
count = 0
while True:
if count == 3:
break
#输入
dict = {}
#for i in list:
# name_list.append(i.get("name"))
name = input("请输入你的名字")
age = int(input("请输入你的年龄"))
sex = input("请输入你的性别")
qq = int(input("请输入你的QQ"))
weight = float(input("请输入你的体重"))
#字典赋值
if name not in n... |
class Person():
def __init__ (self,money):
self._money = money
def getmoney(self):
return self._money
def setmoney(self,money):
self._money = money
if money <= 0:
print("输入有误")
else:
print("输入正确")
xiaoming = Person()
xiaoming.setmoney(20)
|
class Person():
def sleep(self):
print("睡觉")
def eat(self):
print("吃饭")
def study(self):
print("学习")
def introduce(self):
print("我的名字叫%s体重%d身高%d"%(self.name,self.weight,self.height))
yangzhenya = Person()
yangzhenya.sleep()
yangzhenya.eat()
yangzhenya.study()
yangzhenya.name = "杨振亚"
yangzhenya.weight... |
count = 0
mysum = 0
while count < 100:
print("当前数字:%d"%count)
count+=1
mysum = count + mysum
print("求和是%d"%mysum)
|
import sqlite3
#Conectar a la base de datos
conexion = sqlite3.connect("Database/Personas.sqlite3")
#Seleccionar el cursor para realizar la consulta
consulta = conexion.cursor()
#Codigo sql para insertar datos a la tabla personas
sql = """
insert into personas
values (1,'Carlos Slim', 80, 1.73, 'Masculino', 'Acuar... |
from random import randrange as rnd, choice
from random import randint
import pygame
from pygame.draw import *
import math
pygame.init()
screen_size_x = 1000
screen_size_y = 600
screen_size = (screen_size_x, screen_size_y)
FPS = 50
# Colors
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
... |
from collections import defaultdict
import os
import json
class Graph:
def __init__(self):
self.graph = make_graph_from_json('romania.json')
# # function to add an edge to graph
# def addEdge(self, u, v):
# self.graph[u].append(v)
# Function to print a BFS of graph
def BFS(self, ... |
class Sort:
def __init__(self, nums):
self.nums = nums
def BubbleSort(self):
n = len(self.nums)
for i in range(n - 1):
for j in range(n-i-1):
if self.nums[j] > self.nums[j+1]:
tmp = self.nums[j]
self.nums[j] = self.nums... |
class Solution:
def simplifyPath(self, path: str) -> str:
data = path.split('/')
stack = []
for d in data:
if d == '' or d == '.':
pass
elif d == '..':
stack.pop() if stack else '#'
else:
stack.append(d)
... |
def solution(s):
answer = True
p = 0 # p의 개수
y = 0 # y의 개수
for a in s:
if a == "p" or a == "P":
p += 1
if a == "y" or a == "Y":
y += 1
if p != y:
answer = False
return answer |
our_list = [1,2,1]
if len(our_list) > 2 and our_list[0] == our_list[-1]:
print(True)
|
#!/usr/bin/python
#
# ANN - Artificial Neural Network
# $Id: ann.py 2 2005-05-05 03:48:18Z $
import math, random
class Neuron:
def __init__(self, inputCount):
# Init Obj Attrs
self.inputs = inputCount
self.weights = []
self.threshold = random.random()
self.e... |
"""
This is a sample program to show how to draw using the Python programming
language and the Arcade library.
Multi-line comments are surrounded by three double-quote marks.
Single-line comments start with a hash/pound sign. #
"""
# This is a single-line comment.
# Import the "arcade" library
import arcade
# Open u... |
#!/usr/bin/python3
import sys
import demo.demo2
import demo.demo3
# 输出语句
print("hello world!")
print(sys.version)
demo2 = demo.demo2
demo2.func1()
demo.demo3.demo3().say()
demo.demo3.demo4().say()
demo.demo3.demo4().say1()
# 元数据类型 相当于不可该的list
tup1 = ('g', 'g')
print(tup1[1:])
# fuck 代码块和块之间要间隔两... |
"""
Script file: parse.py
Created on: September 8, 2020
Last modified on: September 8, 2020
Comments:
Main script to analyze the input JSON file and generate two files.
- watchers.json
- managers.json
Each should contain a dictionary with the manager/watcher in the key, and a list of projects in the va... |
import sqlite3
searchInput = input("What would you like to search? \n")
connection = sqlite3.connect("sms.db")
cursor = connection.cursor()
cursor.execute("select message.text, handle.id "
"from message, handle "
"where message.text like '%" + searchInput + "%' and handle.ROWID = message... |
def bisection(f,a,b,tol):
if f(a)*f(b)>0:
print("Bisection method fails!")
return None
i = 0
while True:
c=(a+b)/2
i+=1
if f(a)*f(c)>0:
a=c
elif f(a)*f(c)<0:
b=c
elif f(c)==0:
return c
else:
print("Bisection method fails!")
return None
if... |
import operator
# Define dictionary with operators
ops = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv
}
class PrefixOperation:
def __init__(self, expression):
self.expression = str(expression)
self.rev_elems = None
self.parse_expressio... |
import re
mobile=input("enter the mobile no:")
x='^91[0-9]{10}'
matcher=re.fullmatch(x,mobile)
if(matcher!=None):
print("valid")
else:
print("invalid") |
# 1 Find the probabilities of the following rocks rounded to the nearest hundredth:
rocks = {
"sedimentary": 58,
"metamorphic": 213,
"igneous" : 522,
}
# Expected ouput:
# There is 0.07 probability of the sedimentary rock
# There is 0.27 probability of the metamorphic rock
# There is 0.66 probability of... |
MIN_LENGTH = 100
APPROPRIATE_SYMBOLS = ('0', '1')
all_filtered_text = ''
triads = {}
capital = 1000
def filter_text(text):
filtered_text = [character for character in text if character in APPROPRIATE_SYMBOLS]
return ''.join(filtered_text)
def prediction(random_text):
predicted_string = random_text[:3]
... |
# Karatsuba algorithm used to multiply two integers
# together that are of equal and even length
# Implemented in Python by: Henry Dunham
import split_int_in_half as half_int
import recursive_product
import int_length
def karatsuba(int1, int2):
# Confirm length of two integers is the same
if len(str(int1)) ... |
import turtle
turtle.shape('turtle')
def prm (n, l):
turtle.forward(l)
turtle.left(180-180//n)
return
n = 11
l = 100
turtle.left(180)
for x in range(n):
prm(n, l)
|
import turtle
turtle.shape('turtle')
def okr(l1:int, l2:int):
for _ in range(180):
turtle.forward(l1)
turtle.right(1)
for _ in range(180):
turtle.forward(l2)
turtle.right(1)
return
l1 = 0.5
l2 = 0.2
turtle.left(90)
for x in r... |
# other-recommendations.py
# Avoid trailing whitespace anywhere because it's usually invisible, it can be
# confusing
# Always surround these binary operators with a single space on either side:
# assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=,
# <>, <=, >=, in, not in, is, is not), Boo... |
class Vertex(object):
def __init__(self, vertex_id):
"""
Initialize a vertex and its neighbors dictionary.
"""
self.id = vertex_id
self.neighbors_dict = {} # id -> (obj, weight)
def add_neighbor(self, vertex_obj, weight):
"""
Add a neighbor by storing it ... |
'''
Chef and Icecream
Problem Code: CHFICRM
'''
from sys import stdin
input = stdin.readline
def process(data):
ice_cream = 5
chef_balance = {5:0,10:0,15:0}
change = 0
if data[0] != ice_cream:
return 'NO'
for i in data:
# print()
# print()
if i == 5:
... |
def half_diamond(size, row):
temp = size
# hello this is a comment
while temp > 1:
if temp > row:
print(' ', end = ' ')
temp -= 1
else:
print(temp, end = ' ')
temp -= 1
while temp <= size:
if temp > row:
print(' ', end =... |
# -*- coding: utf-8 -*-
"""
@Time : 2020/10/21 20:21
@Auth : Mr. William 1052949192
@Company :特斯汀学院 @testingedu.com.cn
@Function :简单算法
"""
"""
算法1:把字符串'a,b,c,d,e,f,g,h,i,j,k,l',变成一个字符列表,不需要逗号
算法分析:通过遍历,我们取出每一个字符,然后不要逗号,存放到列表
"""
s = 'a,b,c,d,e,f,g,h,i,j,k,l'
# 通过遍历,取出每一个字符
slist = []
for ss in s:
# 如果是逗号就不要它
if... |
# -*- coding: utf-8 -*-
"""
@Time : 2020/10/23 21:49
@Auth : Mr. William 1052949192
@Company :特斯汀学院 @testingedu.com.cn
@Function :递归快排
"""
import time
def quick_sort(height, left, right):
"""
我们每一轮,选取最后一个元素为基准,把元素分成左右两部分,左边都比
基准小,右边都比基准大。进行如下操作:从左往右找比基准大的,交换到
h位置, h往左移动一位;再从h位置从右往左找比基准小的,交换到之前l
的位... |
# -*- coding: utf-8 -*-
"""
@Time : 2020/10/16 20:17
@Auth : Mr. William 1052949192
@Company :特斯汀学院 @testingedu.com.cn
@Function :算术运算
"""
################ 算术运算 ##################
# # 四舍五入/取整
# """
# 精度:计算机在算术运算的时候,小数是不能全部保存的,它只会保存双精度的位数
# 买一个水果:2元3个,假设买100W个
# """
# # 先算1个多少钱
# price = int((2/3) * 100) / 100
# print(p... |
# -*- coding: utf-8 -*-
"""
@Time : 2020/10/16 20:17
@Auth : Mr. William 1052949192
@Company :特斯汀学院 @testingedu.com.cn
@Function :比较运算
"""
################ 数值的比较运算 ##################
# ==,!=,>,<,>=,<=
# 和java的区别:Python里面可以连写
# x = 1
# y = 2
# z = 2
# print(x < y < z)
################ 字符串的比较运算 #################
# ascii... |
# -*- coding: utf-8 -*-
"""
@Time : 2020/10/14 21:17
@Auth : Mr. William 1052949192
@Company :特斯汀学院 @testingedu.com.cn
@Function :数据类型的要点
"""
# 转义:\ (把有特殊含义的符号转成普通符号,使它失去特殊含义)
# 你要在字符串里面出现单引号和双引号怎么办?
s = "'''''''''''''"
print(s)
s = "\""
print(s)
# 转义字符:(把无特殊含义的符号转成有特殊含义的符号,使它具备符合规则的特殊含义)
print("a\ta\na")
# 类型的互斥:数字和... |
x = 5
y = "7"
# Write a print statement that combines x + y into the integer value 12
print(x + y)
#int("7") + 5 # integer 12
# Write a print statement that combines x + y into the string value 57
print(printx + y)
#"2" + str(4) # string 24
#str(5) + "7" # string 57
|
class Add:
@staticmethod
def __call__(x, y):
return x.data+y.data
@staticmethod
def vjp(dz, x, y):
x.set_grad(dz)
y.set_grad(dz)
def __str__(self):
return "Add"
class Subtract:
@staticmethod
def __call__(x, y):
return x.data-y.data
@staticmethod
... |
# Author Loisa Kitakaya
# This is a program that will translate text from one language to another.
# The program is written in python3.
# It will use the following modules/libraries: IBM Watson™ Language Translator | Tkinter
# The program will work mainly with english to french and vice versa.
import os
import json
i... |
FruitList = ['Apple', 'Orange','Pear','Grape','Kiwi'] #List of fruits
PriceList = [1.30,1.00,0.80,2.20,1.70] #Price list; index matches FruitList
def swap_func(a,b): #returns new a and b
a = int(a) + int(b)
b = a-int(b)
a=a-b
return str(a),str(b)
def lookup_func(fruit,qty): #returns tota... |
import random
from brain_games.engine import run_game
def play():
RULE = "What number is missing in the progression?"
run_game(RULE, generate_data)
def generate_data():
a1 = random.randrange(20)
# a1 is the first number of arithmetic progression
d = random.randint(2, 9)
# d is the differance... |
'''
Constructs magic square. Property of magic square is that the sums of all rows and columns are equal.
'''
#!/usr/bin/env python
size = 0
while(size%2==0):
size = int(raw_input("Enter ODD number: "))
Matrix = []
for i in xrange(size):
row = []
for j in xrange(size):
row.append(0)
Matrix.append(row)
curPos ... |
""" Human resources (HR) module
Data table structure:
- id (string)
- name (string)
- birth date (string): in ISO 8601 format (like 1989-03-21)
- department (string)
- clearance level (int): from 0 (lowest) to 7 (highest)
"""
from model import data_manager, util
DATAFILE = "model/hr/hr.csv"
HEADE... |
# -*- coding: utf-8 -*-
from தமிழ் import எழுத்து
from தமிழ்.சொல் import *
def பிரம்மி(வாக்கியம்):
pass
def பண்டைய_எழுத்து(வாக்கியம் , வருடம் ):
pass
def பண்டைய_சொல் (வாக்கியம், வருடம் ):
pass
def பண்டைய_வாக்கியம்_ஆக்கு(வாக்கியம், வருடம் ):
pass
def தனிமொழி_ஆக்கு(வாக்கியம் ):
pass
def தொடர... |
#Sin & Cos
# I am using Python 3
from math import sin, cos, pi
x = pi/4
val = (sin(x))**2 + (cos(x))**2
print (val)
#Compute S in meters
v0 = 3 #m/s
t = 1 #s
a = 2 #m/s**2
s = v0 * t + 0.5*(a*t)**2
print (s)
#Verifying Equations
a = 3.3
b = 5.3
a2 = a**2
b2 = b**2
eq1_sum = a2 + 2*(a*b) + b2
eq2_sum = a2 - 2*(a*b) ... |
"""
Loading output of sql querries to CSV
"""
import os
import pandas as pd
from connectivator import gsheets
def add_slash(dir_name):
"""
Adds a slash at the end of a string if not present
"""
if not dir_name.endswith('/'):
dir_name += '/'
return dir_name
def make_dir(filepath):
"... |
# 415. Add Strings
# Given two non-negative integers num1 and num2 represented as a string,
# return the sum of num1 and num2.
# The length of both num1 and num2 is < 5100.
# Both num1 and num2 contains only digits 0-9.
# Both num1 and num2 does not contain any leading zero.
# You must not use any built-in BigInt... |
# Consider the word "abode". We can see that the letter a is in position 1 and b
# is in position 2. In the alphabet, a and b are also in positions 1 and 2.
# Notice also that d and e in abode occupy the positions they would occupy in
# the alphabet, which are positions 4 and 5.
# Given an array of words, return ... |
# Modify the kebabize function so that it converts a camel
# case string into a kebab case.
# kebabize('camelsHaveThreeHumps') // camels-have-three-humps
# kebabize('camelsHave3Humps') // camels-have-h
def kebabize(string):
"""Given a string in camel case convert it to kebab case."""
result = ""
fo... |
import os
import math
# Intro \o/
print("Advent of Code 2019")
print("Solution for Day 1 by Th3Shadowbroker (github.th3shadowbroker.org)")
# Required variables
masses_source = "masses.txt"
masses = []
fuel_amounts = []
fuel_total = 0
fuel_additional = 0
# Read masses from masses_source
def readMasses():
masses_f... |
from sympy import factorint
#Critère de divisibilité dans une base optimale d'un premier p
def p_bestbase(p):
"""Renvoie la période minimale du critère de divisibilité par le
premier p, étudie pour cela l'entier m tel que p=2*m+1"""
m = (p-1)//2
Lf = factorint(m) #produit un dictionnaire où chaque clé... |
Decorator: is used to add additional functionalities
to the function without editing function
# ================================================================================
# Wrap function by function (closure)
def trace(func):
def wrapper():
print(func.__name__, '함수 시작')
func()
print(func.__name__... |
# .-"-.
# /|6 6|\
# {/(_0_)\}
# _/ ^ \_
# (/ /^\ \)-'
# ""' '"" 하늘
# written by
# @author Wolverine 왕경민
# File Name : Halloween Sale.py
# Date Created : 13/12/2019
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the howManyGames function below.
def ... |
import random
secret_number = random.randint(1,101)
tries = 0
while tries < 10:
tries += 1
guess = int(input(' enter a number: '))
if guess < secret_number:
print(str(10 - tries) + ' Attempts left : Your guess is lower.. Try Again')
elif guess > secret_number:
print(str(10 - tries) + ' Attempts le... |
# Module that contains functions that can be used across all files
# df represents pandas DataFrame
import pandas as pd
import numpy as np
def sklearn_data_to_df(data):
'''
translate sklearn df to a pandas dataframe
dependencies: numpy, pandas
target attribute will be named "target"
'''... |
# Problem 1
#
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
#
# Author: Jose Manuel Martinez Salas
entry = 1000
print(sum([num for num in range(0,entry) if (num % 3 == 0) o... |
A_List = CircularDoublyLinkedList()
while True:
print('1.Add Node')
print('2.Delete Node')
print('3.Display ')
print('4.Display Sorting')
print('5.Capacity ')
print('6.List_capacity')
print('7.Quit')
do = int(input('What would you like to do'))
if do == 1:
A_List.insert()
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 8 10:49:31 2021
@author: Elijah
"""
#Boolean Keywords
print(type(True))
print(type(False))
print(type("True"))
David = 4.0
Elijah = 3.5
Cesar = 3.5
Gabin = 1.5
print("Who is better? Is David better than Elijah? ")
print(David > Elijah)
print("Are El... |
# cerate a method that takes one argument as a string (that string is your name)
# and if the name == "dunni" returns true, else false
def checkname(name):
return name == "dunni" |
arr1=[1,2,3,4,5,6]
arr2=[2,3,4,6,8]
arr3=[]
def fn(arr1,arr2):
if arr1[0] <= arr2[0]:
arr3.append(arr1[0])
arr1.pop(0)
if len(arr1) >0:
fn(arr1, arr2)
else:
arr3.extend(arr2)
else:
arr3.append(arr2[0])
arr2.pop(0)
if len(arr2) >0:
... |
#!/usr/bin/env python3
from functools import lru_cache
from utils import coded_colors
from utils import serial_ends_with_odd
def cut(desc):
print(f'Cut the {desc} wire.')
# @lru_cache(len(coded_colors))
# def color_of(name):
# return input(f'Color of {name}: ').lower()
# @lru_cache(len(coded_colors))
# def num(... |
"""
Binary Search Tree:
For each node, left is less than the node's value and right is greater than the node's value
When searching through the tree, by comparing the node's value to the search value, we know
which direction down the tree to go
"""
class Node(object):
def __init__(self, value):
self.value = valu... |
"""
Write a function that spiral prints a matrix (a list of lists)
Given a list of lists ...
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
the function prints ...
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
"""
def spiralPrint(matrix):
output = []
# initialize index trackers to help reduce the matrix
col_start... |
import argparse
import os
"""
This script normalizes a given substitution matrix.
To normalize the matrix the diagonal values are substituted by the mean value of the diagonal values.
"""
"""
Calculate the mean value of the diagonal entries.
@:param matrix given matrix
@:param isInt boolean value indicating if matri... |
"""
Created by Sai Ram (31009751) for Assignment 1 of FIT9136
Start Date: 04/04/2020
End Date: 28/04/2020
Last edit: 01/05/2020
Description: Inventory system of cantilever umbrellas for a company to record the available stock and revenue for a
given year.
"""
# Input to the program
def read_data():
... |
def modular(a,b,modulo):
if b == 0:
return 1
else:
result = modular(a,b//2,modulo)
if b&1 == 0:
return (result*result)%modulo
else:
return (result*a*result)%modulo
a = int(input())
b = int(input())
modulo = int(input())
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.