text stringlengths 5 121k |
|---|
class Contact:
all_contacts = []
def __init__(self, name, email):
self.name = name
self.email = email
Contact.all_contacts.append(self)
class Supplier(Contact):
def order(self, order):
return(
"If this were a real system we would send"
... |
Fibonacci = [1,1,2]
sum = 0
n=2
while Fibonacci[n] <= 4000000:
Fibonacci.append(Fibonacci[n] + Fibonacci[n-1])
n+=1
for item in Fibonacci:
if item <= 4000000 and item%2 == 0:
sum+=item
print(Fibonacci)
print(sum) |
class Value:
def getAddNum(self):
global val_in_mem
a = input("Enter the first number that you want to add: \n")
if a == 'mrc':
a = float(val_in_mem)
else:
a = float(a)
b = input("Enter the second number that you want to add: \n")
if b == 'mrc... |
def number_guessing():
import random
play_again = True
while play_again == True:
while(True):
guess = input('Guess a number between 1 to 100: ')
ran = random.randint(1,101)
if(guess==ran):
print("You guessed the exact number\n")
else:
... |
n0 = input("enter a number ")
n1 = input("enter another number")
div = int(n0) / int(n1)
remainder = int(n0) % int(n1)
print("the answer is {0} remainder {1}".format(div, remainder)) |
def forExamples():
print('Example 1')
for counter in range (1,10):
print(counter)
print()
print('Example 2')
for counter in range (2,11,2):
print(counter)
print()
print('Example 3')
for counter in range(1,22):
print(counter,end='')
forExamples()
|
print("Adding until rogue value")
print()
print("This program adds up values until a rogue values is entered ")
print()
print("it then displays the sum of the values entered ")
print()
Value = None
Total = 0
while Value != 0:
print("The total is: {0}.".format(Total))
print()
Value = int(input("Please ent... |
def is_prime(integer):
i = integer - 1
while i > 1:
if integer % i != 0:
i -= 1
continue
return False
return True
item1 = 1
item2 = 1
print(item1)
print(item2)
while True:
nextItem = item1 + item2
if nextItem > 1000:
break
... |
def cal(a, b, operator):
return a + b if operator == '+' else a - b if operator == '-' else a * b if operator == '*' else a / b if operator == '/' else 'error'
print(cal(1, 5, '/')) |
import sys
def get_max_and_min(a, b, c):
if a < b:
min, max = a, b
else:
min, max = b, a
if c < min:
min = c
if c > max:
max = c
return (min, max)
print(get_max_and_min(3,8,2))
|
"""
Mixing both types of class instances
"""
class mloader:
value = 0
def sync(self, new_value):
"""
This will only sync the current instance.
If you use that one time the sync all won't work
"""
self.value = new_value
@staticmethod
def sync_all(n... |
def word_count(s):
dic = {}
words_raw = s.split()
words = []
for x in words_raw:
new = x.lower().strip('":;,.-+=/\\|[]{}()*^&')
words.append(new)
u_words = set(words)
for i in u_words:
count = 0
if i != "":
for j in words:... |
import typing
import heapq
import math
def dijkstra(adjacency_list: typing.Dict[int, typing.Dict], source_vertex: int) -> typing.Tuple[typing.Dict[int, float], typing.Dict[int,int]]:
n: int = len(adjacency_list)
min_distance: typing.List[typing.Tuple] = [(0,source_vertex)]
distances: typi... |
def is_abcderian(word):
word_len = len(word)
result = True
for iterator in range(len(word) - 1):
if word[iterator] <= word[iterator+1]:
iterator += 1
continue
else:
result = False
break
return result
words_abcderian = 0
words_file_path = "../resources/words.txt"
fin = open(words_file_path)
for ... |
words_file_path = "../resources/words.txt"
fin = open(words_file_path)
words_exceeding_twenty_characters = 0
character_threshold = 20
for line in fin:
word = line.strip()
if len(word) > character_threshold:
words_exceeding_twenty_characters = words_exceeding_twenty_characters + 1
print(word)
print(words_exceedi... |
board = [" " for i in range(1,10)]
def printboard():
row1="|{}|{}|{}|".format(board[0],board[1],board[2])
row2="|{}|{}|{}|".format(board[3],board[4],board[5])
row3="|{}|{}|{}|".format(board[6],board[7],board[8])
print()
print(row1)
print(row2)
p... |
for a in range(1,11):
print("Hi")
print(a)
even_numbers = [x for x in range(1,100) if x%2 == 0]
print(even_numbers)
odd_numbers = [x for x in range(1,100) if x%2 != 0]
print(odd_numbers)
words = ["ram","krishna","sai"]
answer = [[w.upper(),w.lower(),len(w)] for w in words]
print(answer)
word ... |
class Menu:
def __init__(self):
self.menus = [
'Add Student',
'Store Grade on Existing Student' ,
'View Grade of Students for each Assesment',
'View Students with below Average Grade for each Assesment',
'View Report of Students Total Grade for the Semester',
'View Report of Students with below ... |
import random
from screen_box import ScreenBox
from turtle import Turtle
FILL_COLORS = ["cornflower blue", "lime green", "orchid", "bisque3", "DarkOliveGreen4", "turquoise3", "purple3"]
CAR_COLOR = "white"
CAR_SHAPE_NAME = "car"
CAR_SHAPE = ((3, -10), (3, -6), (10, -5), (10, 4), (3, 6), (3, 8), (1, 10),
... |
cod1, n1, valor1 = input().split(" ")
cod1 = int(cod1)
n1 = int(n1)
valor1 = float(valor1)
cod2, n2, valor2 = input().split(" ")
cod2 = int(cod2)
n2 = int(n2)
valor2 = float(valor2)
total = (n1 * valor1) + (n2 * valor2)
print(f'VALOR A PAGAR: R$ {total:.2f}') |
import sqlite3
con = sqlite3.connect('TEST.db')
cursor = con.cursor()
records = [
(123456, 'John', 25, 'M', 50000.00),
(234651, 'Juli', 35, 'F', 75000.00),
(345121, 'Fred', 48, 'M', 125000.00),
(562412, 'Rosy', 28, 'F', 52000.00)
]
sql = '''
INSERT INTO EMPLOYEE VALUES ( ?, ?, ?, ?, ?)
... |
import turtle
def paddle(x,y):
paddle = turtle.Turtle()
paddle.speed(0)
paddle.shape("square")
paddle.color("white")
paddle.shapesize(stretch_wid=5,stretch_len=1)
paddle.penup()
paddle.goto(x,y)
return paddle
def ball(x,y):
circle = turtle.Turtle()
circle.shape("circle")
ci... |
number = int (input('Podaj liczbe\n'))
p_n=True
if number%2==0:
print('parzysta')
else:
print('niepRZYSTA')
|
def is_it_quibc(number_1):
return(round(pow(number,1.0/3.0),8) % 1 == 0)
try:
number = int(input('Podaj liczbę: '))
print('Jest sześcianem ?:', is_it_quibc(number))
except:
print('Incorrect value!') |
import turtle
def create_window():
window = turtle.Screen()
window.title('Pong Akademia Kodu')
window.bgcolor('black')
window.setup(width=800,height=600)
window.tracer(0)
return window
def create_paddle(x,y):
paddle = turtle.Turtle()
paddle.speed(0)
paddle.shape("square")
paddle.... |
def number_of_divisors(n):
counter = 0
for i in range(1,n+1):
if n%i == 0:
counter+=1
return counter
print(number_of_divisors(9240))
|
import pandas as pd
df = pd.read_csv('2019.csv')
print(df.head())
print(df.columns)
max_index = 0
min_index = 0
for index in df.index:
print(index)
if(df['Score'][index] > df['Score'][max_index]):
max_index = index
if(df['Score'][index] < df['Score'][min_index]):
min_index = index
print(df... |
import math
import itertools
def f(x,k):
return pow(-1,k-1)*pow(x,k)
e=0.001
a=-0.9
b=1
k=0
i=0
print('X ','f(x)','f(x)набл','eps ','iteration')
for x in itertools.count(start=a,step=0.2):
if x>b:
print('break')
break
tmp=f(x,k)
result=tmp
if 1+x == 0:
... |
'''
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without
any elements with the same value next to each other and preserving the original order of elements.
'''
def unique_in_order(iterable):
list = []
for i in iterable:
if len(list) < 1 or not i... |
def NQueen(n):
"""
args: n
return res(list)
"""
if n <= 0:
return []
if n == 1:
return ["Q"]
Q = ["."*n for i in range(n)]
for row in range(n):
for col in range(n):
return back_track(n, row, col,Q)
def back_track(n, i, j,Q):
Q[... |
'''
@Author: lifeiteng@live.com
@Github: https://github.com/feitenglee/target_offer
@Date: 2019-08-31 17:05:53
@LastEditTime: 2019-09-01 16:50:24
@Description:
@State: PYTHON35 PASS
'''
import sys
class TreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = ... |
'''
@Author: lifeiteng@live.com
@Github: https://github.com/feitenglee/target_offer
@Date: 2019-09-05 20:56:57
@LastEditTime: 2019-09-06 09:32:44
@Description: 二叉树的深度, 判断是否是平衡二叉树
题目1:二叉树深度
思路1:深度是max(左子树,右子树)+1,递归解决
题目2:是否是平衡二叉树
思路:不太理解
@State: PYTHON35 PASS
'''
import sys
class TreeNode:
def __init__(self, data=... |
'''
@Author: lifeiteng@live.com
@Github: https://github.com/feitenglee/target_offer
@Date: 2019-09-05 20:41:15
@LastEditTime: 2019-09-05 20:54:16
@Description: 二叉树的中序遍历,是二叉树的升序
@State: PYTHON35 PASS
'''
import sys
class TreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
... |
import random
b = 3
while True:
a = (random.randint (0,1))
print (a,'=')
x = int (input ('=')) ... |
import time
x = 0
while x < 20:
print('x ni qiymati = ', x)
x = x + 1
time.sleep(2)
|
import math
def introduction_message():
print("This program computers the roots")
print("of a second order equation:")
print()
print(" ax^2+bx+c=0 ")
print()
def input_and_solve():
a = eval(input ("please enter a: "))
b = eval(input ("please enter b: "))
c = eval(input ("please e... |
def welcome_message(name):
return "Welcome to this Python script, {}!".format(name)
def enjoy_yourself(name):
return "Long time you wanted to learn python, congratulations {}".format(name)
print(welcome_message("Udacity Student"))
print(enjoy_yourself('eduardo')) |
"""
Created on Wed Oct 31 11:36:32 2018
@author: awanis.azizan
"""
deposit = input("How much would you like to deposit?")
freeToaster
if float(deposit) > 100:
freeToaster = True
else :
print("Enjoy your free mug!")
if freeToaster:
print("You get a free toaster!")
print("Have a nice day!") |
"""
Created on Wed Oct 31 10:41:07 2018
@author: awanis.azizan
"""
import datetime
nextBirthday = datetime.datetime.strptime('11/26/2018',"%m/%d/%Y").date()
currentDate = datetime.date.today()
print(nextBirthday - currentDate) |
"""
Created on Wed Oct 31 11:20:04 2018
@author: awanis.azizan
"""
answer = input("Would you like express shipping?").lower()
if answer == "yes" :
print("That would add $10 to the fees")
print("Thank you!")
else :
print("Thank you for your purchase!") |
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_fwf('baseline.txt', delimiter=" ", names = ['Class', "Count"])
df
df = df.dropna()
df
df = df.copy()
df['Values'] = range(-5,6)
df
df['Count'].sum()
df['Score'] = df['Count']*df['Values']
df['Normalized Count']=df['Count']/df['Count'].sum()... |
a = int(input(""))
b = int(input(""))
c = int(input(""))
resultado = (a + b + c)/3
print(resultado)
|
def is_isogram(string):
check=True
string=string.lower()
for i in string:
if i!=" " and i!="-" and string.count(i)>1:
check=False
break
return check
|
"""Create a Python3_Homework03 project and assign it to your Python3_Homework working set. In the
Python3_Homework03/src folder, create a file named decoder.py, which contains an iterator named alphabator.
When passed a list, simply return objects as-is unless they are integers between 1 and 26, in which case it
sho... |
"""Here are your instructions:
Create a Python3_Homework04 project and assign it to your Python3_Homework working set. In the Python3_Homework04/src
folder, create a program named find_regex.py that takes the following text and finds the start and end positions of the
phrase, "Regular Expressions".
Text to use in ... |
def isStackFull():
global SIZE, stack, top
if top >= SIZE -1 :
return True
else:
return False
def isStackEmpty():
global SIZE, stack, top
if top <= -1 :
return True
else:
return False
def pop() :
global SIZE, stack, top
if (isStackEmpty()) :
pri... |
def name():
a = 6
return a * 6
print(name())
def name():
a = 6
print(a * 6)
name()
x = lambda a: a * 6
print(x(6))
def multiply():
a = 6
b = 5
return a * b
print(multiply())
def multiply():
a = 6
b = 5
print(a * b)
multiply()
multiply = lambda a... |
"""
Problem ID: IPRB
http://rosalind.info/problems/iprb/
Mendel's First Law
------------------
Given: Three positive integers k, m, and n, representing a population
containing k+m+n organisms: k individuals are homozygous dominant for
a factor, m are heterozygous, and n are homozygous recessive.
Return: The probabi... |
ani=(input())
cute=0
for i in range(0,len(ani)):
suro=(ani[:i]+ani[i+1:])
if(int(suro) % 8==0):
cute=1
break
if(cute==1):
print("yes")
else:
print("no")
|
fruits = ["christian", "joseph", "tyler", "kiwi", "azra"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist) |
"""N-Dimensional Norm
Defines the norm of 2 points in N dimensional space with different norms.
"""
import numpy as np
def norm(a, pow=2):
""" Lp Norm
Arguments:
a (numpy.ndarray): A numpy array of shape (2,). Defines a point in 2-D space.
pow (float): The norm used for distance (Default: 2... |
def zfib(n):
if n <= 1:
return n
return zfib(n-1)+zfib(n-2)
if __name__ == "__main__":
inp = int(input("N: "))
for i in range(inp):
print(zfib(i)) |
import multiprocessing
def print_records(records):
for record in records:
print("Name: {0}\nScore: {1}\n".format(record[0], record[1]))
def insert_record(record, records):
records.append(record)
print("New Record Added!\n")
if __name__ == "__main__":
with multiprocessing.Manager() as manager:... |
import heapq
class Solution(object):
def kClosest(self, points, k):
"""
:type points: List[List[int]]
:type k: int
:rtype: List[List[int]]
"""
def calcu(x,y):
return x ** 2 + y ** 2
heap = []
ans = []
for point in ... |
from linked_list import Node
def reverse(head):
'''
>>> head = Node(1)
>>> reverse(head)
1
>>> head = Node(1, Node(2, Node(3)))
>>> reverse(head)
3 -> 2 -> 1
>>> reverse(reverse(head))
1 -> 2 -> 3
'''
new_head = None
curr = head
while curr:
new_head = Node(c... |
def main():
for n in range(10):
for m in range(10):
print('{:>4}'.format((n+1)*(m+1)),end="")
print("")
if __name__ == "__main__":
main()
|
import math
def main():
while True:
shape=input("Choose a shape (triangle, rectangle, circle):")
shape=str(shape)
if shape=="":
break
elif shape=='triangle':
base=float(input('Give base of the triangle:'))
height=float(input('Give height of the... |
import numpy as np
import matplotlib.pyplot as plt
def to_grayscale(image):
"""avg=np.array([0.2126,0.7152,0.0722 ]).reshape(1,3)
new=image*avg
new=new.sum(axis=2)"""
avg=[0.2126,0.7152,0.0722]
new=np.sum(image*avg, axis=2)
return new
def to_red(image):
m=[1,0,0]
new=image*m
retu... |
import re
def integers_in_brackets(s):
result=re.findall(r'\[\s*([+-]?\d*)\s*\]', s)
return list(map(int,result))
def main():
s1="afd [128+] [47 ] [a34] [ +-43 ]tt [+12]xxx"
print(integers_in_brackets(s1))
if __name__ == "__main__":
main()
|
def extract_numbers(s):
word = s.split()
List=[]
for l in word:
try:
List.append(int(l))
except ValueError:
try:
List.append(float(l))
except ValueError:
continue
return List
def main():
print(extract_num... |
def fib(n):
if n == 1:
return 0
if n == 2:
return 1
if n == 3:
return 1
else:
w = fib(n - 1) + fib(n - 2)
return w
print(fib(8))
|
'''
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
'''
class Solution(object):
def letterCombinations(self, dig... |
from tkinter import *
root = Tk()
root.title('Zaagcalculator')
def show():
myLabel=Label(root, text=clicked.get()).pack()
options = [
"Multiplex",
"MDF",
"Spaanplaat",
"Plexiglas"
]
clicked = StringVar()
clicked.set(options[0])
drop = OptionMenu(root, clicked, *options)
dr... |
def is_palindrome(string):
rev_string=string[::-1]
if string==rev_string:
return True
else:
return False
if __name__=="__main__":
str="radarrr"
if is_palindrome(str):
print("Is palindrome")
else:
print("Not palindrome")
|
from threading import Thread, Lock
lock1 = Lock()
lock2 = Lock()
l = []
def value1():
for i in range(65, 91):
lock1.acquire()
print(chr(i))
lock2.release()
def value2():
for i in range(1, 53, 2):
lock2.acquire()
print(i)
print(i+1)
lock1.release()
t... |
class Node:
def __init__(self, element):
self.link = None
self.data = element
class LinkedStack:
def __init__(self):
self.top = None
def isEmpty(self):
return self.top == None
def push(self, e):
newNode = Node(e)
newNode.link = self.top
self.top = ... |
def maxSubArray(nums):
if nums == None or len(nums)==0:
return 0
maxSum = nums[0]
curSum = maxSum
for i in nums[1:]:
if curSum<0:
curSum = i
else:
curSum = curSum+i
maxSum = max(maxSum, curSum)
return maxSum
def maxSubArray2(nums):
if nu... |
user_info = {}
user_first_name = input('What is your first name?: ')
user_info['first_name'] = user_first_name
user_last_name = input('What is your last name?: ')
user_info['last_name'] = user_last_name
print(user_info) |
def lowerCamelCase(name):
return name[0].lower() + name[1:]
def isPointer(name):
if name.strip()[-1:] == "*":
return True
else:
return False
def split(name):
return name.split("_")
def camelCase(splitted):
newSplitted = []
for splittedWord in splitted:
splittedWord = s... |
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
print(raise_to_power(2, 3))
|
from Graphics.Graphics import *
class Board:
__x_pixels = -1
__y_pixels = -1
__vertical_boxes = -1
__horizontal_boxes = -1
__matrix__ = None
__win__ = None
def __construct_board(self):
self.__win__ = GraphWin('board', self.__x_pixels, self.__y_pixels)
self.__win__.setCo... |
import numpy as np
from itertools import izip
def random_q():
"""
uniform random rotation in angle axis formulation
input: 3 uniformly distributed random numbers
uses the algorithm given in
K. Shoemake, Uniform random rotations, Graphics Gems III, pages 124-132. Academic, New York, 1992.
This ... |
class Dog():
print('哈哈哈哈')
count = 10
def __init__(self,name):
self.name = name
self.__age = 10
def getAge(self):
return self.__age
tom = Dog('Tom')
print(tom.name)
print(tom.getAge())
print(Dog.count)
|
import random
class Guess:
def guess(self):
a = random.randint(0,101)
while True:
u = int(input('请输入数字'))
if u > a:
print('猜大了')
elif u < a:
print('猜小了')
else:
print('猜对了')
... |
list = [1,2,3,4,5,4,4]
list1 = []
for i in list:
if i not in list1:
list1.append(i)
print(list1)
|
def hi (name):
if name == 'zoro':
print('hello my dear')
elif name == 'zola':
print('hello zola roronoa !! ')
else:
print('hi miss! ')
hi ("zola") |
class Solution(object):
def zigzagLevelOrder(self, root):
if not root:
return []
ans, level = [], [root]
curDepth = 1
while level:
if curDepth % 2 == 0:
ans.append([node.val for node in level[::-1]])
else:
ans... |
class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
ret, level = [], [root]
while level:
maxNum = level[0].val
for node in level:
... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
... |
class Node(object):
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 0
class AVLTree(object):
def __init__(self):
self.root = None
def height(self, node):
if node is None:
return -1
return node... |
def check_valid_parenthesis(exp):
s_cnt = m_cnt = l_cnt = 0
for each_brac in exp:
if s_cnt < 0 or m_cnt < 0 or l_cnt < 0:
return False
if each_brac == '(':
s_cnt += 1
elif each_brac == ")":
s_cnt -= 1
elif each_brac == "{":
m_cnt +... |
def RPN_evaluate(expression):
delimt = ","
operators = {'+': lambda x, y: x + y,
'-': lambda x, y: y - x,
'*': lambda x, y: x * y,
'/': lambda x, y: int(x / y)}
current_stack = []
cnt = 0
operator = ""
for token in expression.split(delimt):
... |
''' WAP which takee input two strings s and t of bits encoding binary numbers Bs and Bt, respectively
and returns a new string of bits represeting the number Bs + Bt '''
import time
def cache_table(a, b, c):
if a == '0' and b == '0' and c == '0':
return '0', '0'
elif a == '0' and b == '0' and c == '1'... |
'''
WAP that takes two arrays_1D representing integers, and returns an integer representing their product
Example <1,2> and <2> returns <2,4>
'''
import time
def multiply_two_list(A, B):
sign = -1 if A[0] < 0 or B[0] < 0 else 1
A[0], B[0] = abs(A[0]), abs(B[0])
num1 = 0
prod = 1
for i in reversed... |
class MaxArea:
def max_area(self, height):
"""
:type height: List[int]
:rtype: int
"""
max_area = 0
length = len(height)
for i in range(length):
for j in range(length):
if i != j:
area = MaxArea.find_area(i, j, h... |
def solution(phone_book):
answer = True
phone_book.sort()
for num in range(len(phone_book)):
phone_num = phone_book[num]
for nextNum in range(num+1, len(phone_book)):
if phone_num == phone_book[nextNum][:len(phone_num)]:
return False
... |
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr[0])
print(arr[4])
arr = np.array([[6, 3], [0, 2]])
print(repr(arr[0]))
arr = np.array([1, 2, 3, 4, 5])
print(repr(arr[:]))
print(repr(arr[1:]))
print(repr(arr[2:4]))
print(repr(arr[:-1]))
print(repr(arr[-2:]))
arr = np.array([[1, 2, 3],
... |
import numpy as np
arr = np.array([[0, 2, 3],
[1, 3, -6],
[-3, -2, 1]])
print(repr(arr == 3))
print(repr(arr > 0))
print(repr(arr != 1))
print(repr(~(arr != 1)))
arr = np.array([[0, 2, np.nan],
[1, np.nan, -6],
[np.nan, -2, 1]])
print(repr(np.isnan(ar... |
import string
import csv
import os
from os import listdir
import json
def countWordsUnstructured(filename):
wordCounts = {}
datafile = open(filename).read()
data = datafile.split()
for word in dat... |
def reverseInParentheses(inputString):
if "(" not in inputString:
return inputString
else:
last_opening_index = 0
corresponding_closing_index = 0
startIndex = None
results = []
reversedString = ""
... |
def solution(deposit, rate, threshold):
def calculate_yearly_increase(amount):
return amount * ((rate/100) + 1)
amount = deposit
years = 0
while True:
amount = calculate_yearly_increase(amount)
years += 1
print(amount)
if amount >= threshold:
... |
def checkPalindrome(inputString):
middleIndex = int(len(inputString)/2)
if len(inputString) % 2:
return inputString[middleIndex+1:] == inputString[:middleIndex][::-1]
else:
return inputString[middleIndex:] == inputString[:middleIndex][::-1]
print(checkPalindrome("aabaa"))
print(... |
def solution(n):
if n < 10:
return 0
count = 0
def recursively_solve(number, count=count):
count += 1
string_representation = str(number)
sum_digits = sum([int(digit) for digit in string_representation])
if sum_digits > 9:
return recursively... |
import sys
def prime_point_calc(numerator, denominator):
prime = True
while denominator < numerator:
if (numerator % denominator) == 0:
prime = False
break
else:
denominator += 1
if prime:
return numerator
def prime_list_calc(numerator_limi... |
def quit():
quit = ""
no_answer = True
while no_answer:
answer = input("Would you like to quit? (y/n) ")
try:
quit = answer[0].lower()
no_answer = False
except:
print ("Invalid entry please enter 'y' for yes and 'n' for no.")
continue... |
import numpy as npy
import matplotlib.pyplot as plt
import csv
class LinearRegression(object):
def __init__(self):
self.w = 0
self.b = 0
self.rho = 0
def fit(self, X, y):
mean_x = X.mean()
mean_y = y.mean()
errors_x = X - mean_x
errors_y = y - mean_y
errors_product_xy = npy.sum(npy.multip... |
class Mindmap:
def __init__(self):
self.l=[]
self.x=0
def insert(self):
for i in range(self.x):
m=[]
for j in range(self.x):
sm=[]
name=input("Enter name")
reveal=opencl=notim=0
... |
"""
This module contains test cases for City
"""
import unittest
from models.base_model import BaseModel
from models.city import City
import pep8
from datetime import datetime
class TestCity(unittest.TestCase):
"""" Test cases class of City """
def test_pep8_city(self):
"""pep8 test.
Mak... |
from math import sin,cos,tan,log
print("""
Operations available
[1]-sin
[2]-cos
[3]-tan
[4]-ln
""")
epsilon=0.01
def apply_funtion(f,n):
function={
1:sin,
2:cos,
3:tan,
4:log
}
result = {}
for i in range(1, n+1):
result[i]=function[f](i)
return result
de... |
"""Find optimal threshold"""
import numpy as np
def find_best_threshold(arr0, arr1):
"""Find the best threshold seprating arr0 from arr1.
We maximize the number of elements from arr0 that are less than or equal to
the threshold plus the number of elements from arr1 that are greater than
the threshol... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.