text stringlengths 37 1.41M |
|---|
class Planet:
def __init__(self,name,size,color):
self.name = name
self.size = size # big middle small
self.color = color
self.humanity = True
self.oxygen = True
self.water = False
self.population = True
self.temp = 0
def set_humanity(self):
... |
class Cat:
def __init__(self,size,weight):
self.size = size
self.weight = weight
self.position = 0
self.power = 0
self.damage = 0
self.exp = 0
print('кот успешно создан')
def description(self):
print(f"размер:{self.size},вес:{self.weight},позиц... |
"""
This is an abstract class that can be used as the basis for the
creation of new views. The only two views of the program -
ViewBraille and ViewCLI - are both inheritors of this class.
"""
import abc
class ViewType(metaclass=abc.ABCMeta):
@abc.abstractmethod
def option_select(self):
"""Given a l... |
def largest_factor(n):
"""Return the largest factor of n that is smaller than n.
>>> largest_factor(15) # factors are 1, 3, 5
5
>>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40
40
>>> largest_factor(13) # factor is 1 since 13 is prime
1
"""
"*** YOUR CODE HERE ***"... |
class Student:
def __init__(self,name,lastname,department,year_of_entrance):
self.name = name
self.lastname = lastname
self.department = department
self.year_of_entrance = year_of_entrance
get_student_info = Student('Mary','Black',
'software engineering','2019')
print(get_student_in... |
#here is a little snippet showing the basics of variable usage
#declare a variable and initialize it
f=0
print (f)
#redeclaring a variable also works
f="abc"
g="defg"
print (f)
#you can't directly concatenate variables of different types, for instance here "this is a string" and "123" by using print("this... |
#!/bin/python3
'''
Problem Approach :-
Fibonacci sequence F(n) = F(n-1) + F(n-2)
The target is to filter out all the non-even numbers in the sequence and then find the sum of all remaining even numbers.
1. Observe the sequence; and find a pattern
We see that every third number is an even number
2. Now, figure out... |
https://stepik.org/lesson/58180/step/4?thread=solutions&unit=35865
Task:
Количество столбцов
Прочитайте изображение из файла img.png и выведите количество столбцов этого изображения на стандартный вывод.
В примере входа указана ссылка на файл. Это сделано для вашего удобства. Вы можете скачать этот файл, сохранить ... |
Напишите программу, на вход которой подаётся список чисел одной строкой.
Программа должна для каждого элемента этого списка вывести сумму двух его
соседей. Для элементов списка, являющихся крайними, одним из соседей
считается элемент, находящий на противоположном конце этого списка.
Например, если на вход подаётся ... |
from tkinter import *
from tkinter.messagebox import *
import math as m
#some usefull variabble
font = ('Verdana',20,'bold')
# working functions
def clear():
ex=textfield.get()
ex = ex[0:len(ex)-1]
textfield.delete(0,END)
textfield.insert(0,ex)
def all_clear():
textfield.delete(0,E... |
"""
This module illustrates how to retrieve the k-nearest neighbors of an item. The
same can be done for users with minor changes. There's a lot of boilerplate
because of the id conversions, but it all boils down to the use of
algo.get_neighbors().
"""
# needed because of weird encoding of u.item file
import io # noq... |
""" Algorithm predicting a random rating.
"""
import numpy as np
from .algo_base import AlgoBase
class NormalPredictor(AlgoBase):
"""Algorithm predicting a random rating based on the distribution of the
training set, which is assumed to be normal.
The prediction :math:`\\hat{r}_{ui}` is generated from... |
from helper import *
def main_options():
while True:
print "Please select one of the following:"
print "'l': Get all departments: score and classifier by Most Positive to Most Negative"
print "'d': Department Specific: get all children score and classifer by Most Positive to Most Negative"
... |
from os import system
import random
# Global Variables
null = 0
compWins = 0
playerWins = 0
# Display Function
def choise():
print('Choose One :\n\n\t1) Rock\n\t2) Paper\n\t3) Scissors\n')
# Random Conputer Choise Function
def conputerChoise():
return random.randint(1, 3)
# Verification Pl... |
def largest_num(arr):
finalarr = []
index = 0
for subarr in arr:
#print(subarr)
for i in subarr:
if i > index:
index = i
finalarr.append(index)
print(finalarr)
largest_num([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 85... |
def repeat_a_string(str, num):
final = []
i = 0
while i < num:
final.append(str)
rpt = "".join(final)
i = i + 1
print(rpt)
repeat_a_string("abc", 3)
def repeatString(str, num):
final = ""
i = 0
while i < num:
final = final + str
i = i+1
print(fin... |
# navigable string objects
from bs4 import BeautifulSoup as bs
soup = bs("<h2 id='message'>Hello, Tanish op!</h2>","html.parser")
content = soup.string
print(content)
print(type(content)) # <class 'bs4.element.NavigableString'>
# important points ---- The navigable string object is used to represent the contents ... |
# .descendants is used to iterate over all of the children and indirect children
from bs4 import BeautifulSoup as bs
html_doc = """
<html><head><title>Tutorials Point</title></head>
<body>
<p class="title"><b>The Biggest Online Tutorials Library, It's all Free</b></p>
<p class="prog">Top 5 most used Programming Langua... |
def ALIGNW_ODD(size):
return 3 if (size) < 3 else (size) + (((size) % 2) ^ 0x01)
def align_size(size):
WSIZE = 4
return (ALIGNW_ODD(((size) + WSIZE - 1)/WSIZE)) * WSIZE
def calc_min_bits(size):
bits = 0;
while (size >> bits) > 0:
bits += 1
return bits
def alignment_test(bits):
for i in range(1, 32):
pri... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","root","","db_demo" )
def test_create_table():
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 如果数据表已经存在使用 execute() 方法删除表。
cursor.execute("DROP TABLE IF EXISTS employee")
# 创建数据表SQL语句
sql = ... |
from .constants import RED, GREY, SQUARE_SIZE, CROWN
import pygame
class Piece:
PADDING = 20
OUTLINE = 5
def __init__(self, row, col, color):
self.row = row
self.col = col
self.color = color
self.king = False
self.x = 0
self.y = 0
self.calc_pos()
... |
# CLASSES & OBJECTS
"""
Double underscore means private property in Python Classes
which cannot be accessed from outside property
"""
'''Below is the Person Class with Getters and Setters'''
class Person:
__name = ''
__email = ''
def __init__(self, name, email):
self.__name= name
self.__e... |
#!/usr/local/bin/python
num1 = 20
num2 =23
sum_two_numbers = num1+num2
print("Sum of Two Numbers is: {0}".format(sum_two_numbers))
def sum_two_numbers(num1,num2):
return num1+num2
print("Sum of Two Numbers Using Function is is: {0}".format(sum_two_numbers(2,5))) |
#==========================
# Dictionaries in Python
#=========================
"""
A dictionary is a type of collection in which we store unordered,changeable and index value.
Dictionaries have multiple values written with curly braces in which each item has keys and values.
"""
## A Simple dictionaries of Person ... |
#Complete the function to return the tens digit and the ones digit of any interger.
def two_digits(a):
quotient = a // 10
remainder = a % 10
return quotient, remainder
#Invoke the function with any interger as its argument.
print(two_digits(79))
|
'''
Ship.py
implements the Ship class, which defines the player controllable ship
Lukas Peraza, 2015 for 15-112 Pygame Lecture
'''
import pygame
import math
from GameObject import GameObject
class Ship(GameObject):
# we only need to load the image once, not for every ship we make!
# granted, there's probab... |
# genetic_alg.py
# authors: Megan Olsen, based on C code by Jessa Laspesa and Ned Taylor
# purpose: all functions necessary for running the genetic algorithm.
import individual
import random
import sys
# purpose: mutate genes in each individual based on mutation rate, uniformally at random
# parameters: the populati... |
from guizero import App, Text, PushButton, TextBox
app = App(title="Hello world")
welcome_message = Text(app, text="Smart Butler", size=20, color="green")
my_name= TextBox(app)
def forward():
welcome_message.value = my_name.value
PushButton(app,command=forward, text ="Butler FORWARD")
app.display()
|
player_details=[]
def create_player(id,name,matches_played,runs_scored,playing_zone):
player_d={}
zone=["north","south","east","west"]
if(len(id)==6 and id[:3] == "ICC" and id[3:].isnumeric()):
if playing_zone.lower() in zone:
player_d['Id']=id
player_d['Name']=name
... |
from tkinter import *
def click():
for i in range(len(labels)):
labels[i].config(text=str(i)+" Replaced", fg="yellow", bg="green")
def close_window():
window.destroy()
exit()
window = Tk()
window.title("Label Change Test")
window.configure(background="black")
labels = []
Label(window, text="Basi... |
import matplotlib.pyplot as plt
import seaborn as sb
from pandas.plotting import scatter_matrix
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
# Draw 2D scatter
def scatter_2d(data_frame, col_x, col_y):
"""
:param d... |
# Every piece has a type, value, and belongs to a player
class Piece():
def __init__(self, player, type, value):
self.player = player
self.type = type
self.value = value
# String representation of each piece
def __str__(self):
return f"{self.type} ({self.player[0]})"
class... |
import pandas as pd
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is',
'portal', 'for', 'Geeks']
# Calling DataFrame constructor on list
df = pd.DataFrame(lst)
print(df)
csvdata=pd.read_csv("file.csv",index-col="name")
#single row loc
#df.loc
first=csvdata.loc["vedavyas"]
#==== iloc - retrive ... |
# print("Hell o")
# x1=(lambda x,y,z: (x+y)*z)(1,2,7)
# print(x1)
# y1=(lambda x,y,z: (x+y) if (z==0) else (x*y))(1,2,0)
# print(y1)
# print(type(y1))
# nums=[99,22,33,141,112,134,189,312,54,89]
# def Key(x):
# return x%2
# print(nums)
# print(sorted(nums ,key=Key))
# x1=(lambda x: "one" if x==1 else ("Two" ... |
'''Welcome to python 101'''
##a,e
a=2
b="vedavyas"
c=3.1423456789
d=True
print(a)
print(type(a))
print(type(b))
print(type(c))
print(type(d))
##b
p=q=r=s=t=45
print(p)
print(q)
print(r)
print(s)
print(t)
##c
'''import keyword
print(keyword.kwlist)
True False break class continue def elif finally for while
and return''... |
from ..utils.vector import Vector, Vector2
from .constants import G
from simulator.graphics import Screen
def gravitational_force(pos1, mass1, pos2, mass2):
""" Return the force applied to a body in pos1 with mass1
by a body in pos2 with mass2
"""
F=-(G*mass2/(Vector.norm(pos1-pos2)**3))*(p... |
# The following file is meant to show how to work with various math functions in Python, as well as properly including numerical results in a string
print("5 + 3 = " + str(5+3))
print("4 * 2 = "+ str(4*2))
print("16 / 2 = "+str(16/2))
print("2^3 = "+ str(2**3))
favorite_number = 33
message= "My favorite number is: "+ ... |
#Make a list of the multiples of 3 from 3 to 30. Use a for loop to print the numbers in your list.
numbers = [value *3 for value in range (3,31)]
for number in numbers:
print(number)
|
#Simple hello message
message = "Oh Hello there! "
print (message)
message2 = "This is concatenation"
print(message + message2) |
# 2_3 Practice Personal Message
message_name = "matthew compton"
message = "Hello " + message_name.title() + ". How are you doing today?\nWould you like to learn some Python?"
print(message)
second_name = "Jeremy Simpson"
# 2_4 Practice Famous Quote
print(second_name.upper())
print(second_name.lower())
print(second... |
my_pizzas = ['pepperoni','cheese','sausage']
friend_pizzas = ['pepperoni','cheese','sausage']
my_pizzas.append('hawaiian')
friend_pizzas.append('bacon')
print('My favorite pizzas are: ')
for pizza in my_pizzas:
print(pizza.title())
print("My friend's favorite pizzas are: ")
for pizza in friend_pizzas:
print(... |
ordinal_numbers = [1,2,3,4,5,6,7,8,9]
for place in ordinal_numbers:
if place == 1:
print(str(place) +'st')
elif place == 2:
print(str(place)+'nd')
elif place == 3:
print(str(place)+'rd')
else:
print(str(place)+'th')
print() |
languages = ['english','german','french','spanish'] #Creates original list of languages
languages.append('russian') #appends or adds to end of list
print(languages)
languages.insert(2,'swahili') #inserting at place 2 in list swahili
print(languages)
languages.remove('english') #removes data = english
print(language... |
friends = ['cody','josh','chase','preston']
print("Why hello there " + friends[0].title() + " how are you doing?")
print("Why hello there " + friends[1].title() + " how are you doing?")
print("Why hello there " + friends[2].title() + " how are you doing?")
print("Why hello there " + friends[3].title() + " how are ... |
#Make a list of the first 10 cubes and use a for loop to print out the value of each cube
numbers = []
for number in range(1,11):
numbers.append(number **3)
print(number**3)
print(numbers) |
###################################
# Build 2 stacks, 1 to keep track of the max value and 1 to keep track of actual values. Print from max value from max_stack.
N = int(input())
stack = []
max_stack = [0]
for _ in range(N):
item = [int(x) for x in input().split()]
if item[0] == 1:
stack.append(item[1... |
import numpy as np
import math
#Process the input and output
def main():
sys.stdin = open('data/input.txt', 'r')
N = int(input())
for _ in range(N):
input()
ratings = [float(i) for i in input().strip().split()]
corrs = [pearsonCorr(ratings, [float(i) for i in input().strip().split()... |
#!/bin/python3
import os
from collections import defaultdict
# Complete the bfs function below.
def generate_graph(edges):
graph = defaultdict(list)
for node1, node2 in edges:
# Bidirectional BFS (unidirectional fails)
graph[node1].append(node2)
graph[node2].append(node1)
return gr... |
'''s = "identifier"
for i in s:
if i.islower():
print(i,end="")
else:
print("",i,end="")'''
s = 'camelCaseProgram'
print(''.join(c if c.islower() else ' ' + c for c in s)) |
import random
def yes_no(question):
valid = False
while not valid:
response = input(question).lower()
if response == "yes" or response == "y":
response = "yes"
return response
elif response == "no" or response == "n":
response = "no"
... |
#!/usr/bin/python3
animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')
def how_many(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
... |
#!/usr/bin/env python3
import string
def sum_digits(s):
""" assumes s a string
Returns an int that is the sum of all of the digits in s.
If there are no digits in s it raises a ValueError exception.
"""
sum = 0
err = True
for char in s:
if char.isdigit():
sum += ... |
#!/usr/bin/env python
"""
There are code for the problems listed as tasks for week 1
"""
"""
s = 'azcbobobegghakl'
counter = 0
for c in s:
if c == 'a' or c =='e' or c == 'i' or c == 'o' or c == 'u':
counter += 1
print(counter)
"""
"""
PROBLEM 2
Assume s is a string of lower case characters.
Write a pro... |
import re #Library for using regular expressions.
file_name = "Book.txt"
text = open(file_name, "r") #Read text directly from file.
every_row = [] #Array with type list to store words per each row in text.
words = {} #Array with type dictionary to store unique wor... |
import os #Library for getting information about OS.
from stat import * #Library for getting statistical information about OS.
import time #Library to convert time.
other_dir = True #Variable to make program work repetible.
def FileSystemCreation() : #Functi... |
"""
This problem was asked by Facebook.
Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock once. You must buy before you can sell it.
For example, given [9, 11, 8, 5, 7, ... |
"""
This question was asked by Apple.
Given a binary tree, find a minimum path sum from root to a leaf.
For example, the minimum path in this tree is [10, 5, 1, -1], which has sum 15.
10
/ \
5 5
\ \
2 1
/
-1
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, ... |
print('Tim can bac hai cua a mod n')
print('(Tim cac x de x^2 = a mod n)')
while True:
a = int(input('Nhap a: '))
if a == 0:
break
n = int(input('Nhap n: '))
print(f'Cac can bac hai cua {a} mod {n} la: ')
for i in range(1,n):
if i**2 % n == a:
print('%8s'% i,end='')
... |
str1 = input().split("+")
str2 = ""
str1.sort()
for str in str1:
str2+=(str+"+")
print(str2[:-1]) |
str1 = input()
list1 = list()
for str in str1 :
if str not in list1:
list1.append(str)
# print(len(list1))
if len(list1)%2==0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
|
#!/usr/bin/python
import sys
# Use Euclid's algorithm to find the GCF
# Find the difference between two numbers
# Replace the larger number with the difference
# Repeat until both parameters are equal
def gcf(a, b):
if a == b:
return a
elif a > b:
return gcf(a-b, b)
else:
return gcf(b-a, a)
def lcm(a, b)... |
numbers=list(range(2,21))
primes=[2,3,5,7,11,13,17,19]
count=[0]*len(primes)
for i in primes:
for j in numbers:
a=0
while j%i==0:
j /= i
a+=1
if a > count[primes.index(i)]:
count[primes.index(i)]=a
product=1
for i in range(len(primes)):
product *= prim... |
from random import randint
class Openness:
# contruct a random player with specified number of player
def __init__(self, player):
self.player = player
#random player always returns a random number between 0 and 1
def play(self):
if self.player == 1:
return randint(1, 2)
else:
return randint(3,4)
|
# Leetcode 1162. Find Peak Element
# Time Complexity : O(log n) where n is the size of the array
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach: Condition: If both the neighbours are lesser than the current then its the min.
# ... |
# coding=utf-8
from __future__ import unicode_literals, absolute_import
class Dictionary(object):
"""
A glorified set
"""
def __init__(self):
self.words = set()
def load(self, filename):
"""
Opens filename and loads each word from the file into the dictionary
:para... |
# The pre-order traversal of a Binary Tree is a traversal technique that starts
# at the tree's root node and visits nodes in the following order:
# Current node
# Left subtree
# Right subtree
#
# Given a non-empty array of integers representing the pre-order traversal of a
# Binary Search Tree (BST), writ... |
# Write a function that takes in an n x m two-dimensional array (that can be
# square-shaped when n == m) and returns a one-dimensional array of all the
# array's elements in spiral order.
# Spiral order starts at the top left corner of the two-dimensional array, goes
# to the right, and proceeds in a spiral p... |
# Write a function that takes in an array of integers and returns the length of
# the longest peak in the array.
# A peak is defined as adjacent integers in the array that are strictly
# increasing until they reach a tip (the highest value in the peak), at which
# point they become strictly decreasing. At ... |
# Write a function that takes in a Binary Search Tree (BST) and a positive
# integer k and returns the kth largest integer contained in the
# BST.
#
# You can assume that there will only be integer values in the BST and that
# k is less than or equal to the number of nodes in the tree.
#
# Also, for the pur... |
# There's an algorithms tournament taking place in which teams of programmers
# compete against each other to solve algorithmic problems as fast as possible.
# Teams compete in a round robin, where each team faces off against all other
# teams. Only two teams compete against each other at a time, and for each
# ... |
# You're given three nodes that are contained in the same Binary Search Tree:
# nodeOne, nodeTwo, and nodeThree. Write
# a function that returns a boolean representing whether one of
# nodeOne or nodeThree is an ancestor of
# nodeTwo and the other node is a descendant of
# nodeTwo. For example, if your functi... |
# coding=utf-8
# 通过Python编程完成一个银行ATM机模拟系统,具备如下功能:
# (1)登陆验证:用户输入用户名密码登陆,检测用户名是否存在以及用户名密码是否匹配;用户名密码各有三次输入机会,超过三次系统退出。
# (2)菜单界面:登陆成功后显示功能操作界面,输入序号选择对应功能。
# (3)用户注册:用户可以输入用户名和密码创建自己的账号,并输入电话号码等信息,如果用户名存在则让用户重新输入用户名。注册后免费赠送5000元余额。
# (4)账户管理:用户可以随时查看自己的账户余额。用户可以输入其他账户用户名,实现转账功能;用户名必须存在。用户也可以模拟实现存取款功能。
# (5)用户名和密码以及账户信息等必须... |
total = float(input(" What is your bill total? ").strip('$'))
# the above total variable is an input string into a float with a $ being taken away
fifteen = int(total) * 0.15
eightteen = int(total) * 0.18
twenty = int(total) * 0.20
# the above lines turn the total variable into an integer times the tip percentage
pri... |
#dictionaries and lists can be inside of each other
animal_sounds = {
"cat": ['meow', 'pur'],
"dog": ['bark', 'woof'],
"fox": []
}
# above is a dictionary of lists
ant = {'name': 'Ant', 'height': 70, 'shoes': 12, 'hair': 'brown', 'eyes': 'brown'}
oscar = {'name': 'Oscar', 'height': 68, 'shoes': 11, 'hair... |
# from https://www.reddit.com/r/dailyprogrammer/comments/3s4nyq/20151109_challenge_240_easy_typoglycemia/
from random import shuffle
import itertools
import re
text = """According to a research team at Cambridge University, it doesn't matter in what order the letters in a word are,
the only important thing is that t... |
# shuffle a list in Python without using random.shuffle()
from random import shuffle
from random import randrange
values = list(range(0,10000))
def cheating_shuffle_it(values):
shuffle(values)
def shuffle_it_one(values):
# This version takes the last value from the list and
# inserts it back in to a ra... |
class Event:
def __init__(self, start, end):
"""
initializes event node with start and end time stored as Data
"""
self.data = {
'start': start,
'end': end,
}
self.next = None
return
def output(self):
"""
format... |
import argparse
import random
import string
def get_random_ascii_string(size=20):
return "".join(random.choices(string.ascii_lowercase, k=size))
def main():
parser = argparse.ArgumentParser(description="""Generates 2 files.\n
Format of each line of the first... |
from prettytable import PrettyTable
from file_reader import read_file
import unittest
import os
from collections import defaultdict
class Student:
"A class that stores all the information about students."
pt_hdr = ['CWID', 'Name', 'Completed Courses']
def __init__(self, cwid, name, major):
... |
from typing import Any, Dict, Optional
from .utils import random_string
class Publication(object):
"""Publication is a class where the attributes of each
of its objects are passed to the constructor."""
def __init__(self, attrs: Dict[str, Any]) -> None:
"""Constructs a new Publication.
... |
"""Utilities module.
Contains useful functions that don't belong to any class in particular.
"""
import random
import string
def random_string(length: int, character_set: str = string.ascii_lowercase) -> str:
"""Returns a random string of length 'length'
consisting of characters from 'character_set'."""
... |
#based on :https://github.com/llSourcell/Lets_Build_a_Compiler_LIVE/blob/main/compiler.py
#regular expression library (search pattern)
import re
#Tokenizer function receives starting input
# i.e (add 2 (subtract 4 2))
def tokenizer(input_expression):
#counter variable for iterating through input array
curren... |
def solve(a, b):
sol=[0,0,0]
for i in range(3):
a[i]=int(a[i])
b[i]=int(b[i])
#a[2]=(0-a[2])
#b[2]=(0-b[2])
#print(a,b)
sol[0]=(a[1]*b[2])-(a[2]*b[1])
sol[1]=(a[2]*b[0])-(b[2]*a[0])
sol[2]=(b[1]*a[0])-(a[1]*b[0])
#print(sol)
final=[0,0]
final[0]=int((sol[0]/so... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 18 21:07:18 2017
@author: louiemceliberti
"""
def numbers(*args):
sum = 0
for x in args:
sum += x
print(sum)
numbers(39)
numbers(5,9238,85)
numbers(4207,45486689)
numbers(2,683,461) |
import time
def merge(left, right):
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[... |
import sqlite3
dbase = sqlite3.connect('test_01.db')
dbase.execute(""" CREATE TABLE IF NOT EXISTS employees_records(
Id INT PRIMARY KEY NOT NULL,
Name TEXT NOT NULL,
Division TEXT NOT NULL,
Stars INT NOT NULL)
""")
def insert_record(Id,Name,Division,Stars ):
dbase.execu... |
num = 3.75
num2 = 3.70
# print(type(num))
#print(round(num, 1))
#print(num == num2)
num3 = '100'
num4 = 200
#print(num3 + num4)
#-_-_-_Casting-_-_-
num5 = int(num3)
#print(num5 + num4)
# print(type(num5))
num6 = str(num4)
# print(type(num6))
#print(help(int))
|
"""
Option validation with exception handling.
"""
class Validator:
"""
When a given validation function returns True, given exception is raised.
"""
def __init__(self, validation_function, exception):
self.validation_function = validation_function
self.exception = exception
def ... |
# 007 Reverse Integer
class Solution(object):
max_int = 2**31
min_int = -2**31-1
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
# special case: last digit is 0
# special case: reversed int overflow
if str(x)[0] != "-":
return self.r... |
# 223 Rectangle Area
class Solution(object):
def computeArea(self, A, B, C, D, E, F, G, H):
"""
:type A: int
:type B: int
:type C: int
:type D: int
:type E: int
:type F: int
:type G: int
:type H: int
:rtype: int
"""
# co... |
# 028 Implement strStr()
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
k = len(needle)
if k == 0:
return 0
for i in xrange(len(haystack)-k+1):
for kk in xra... |
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
rev = 0
# neg number is NOT palindrome...
if x < 0:
return False
temp = x
while (temp != 0):
rev = rev * 10 + temp%10
temp ... |
# 202 Happy Number
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 0:
return False
n = n if n > 0 else -n
numbers = set() # a set
while 1:
if n in numbers:
return False
... |
# 171 Excel Sheet Column Number
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
base = 26
letters = {"A":1,"B":2,"C":3,"D":4,"E":5,"F":6,"G":7,"H":8,"I":9,"J":10,"K":11,"L":12,"M":13,"N":14,"O":15,"P":16,"Q":17,"R":18,"S":19,"T":20... |
# 022 Longest Increasing Subsequence
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n == 0:
return []
def helper(totalL, totalR, n):
res = []
if totalL == n and totalR == n:
... |
# 357 Count Numbers with Unique Digits
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
count = [1,10]
if n <= 1:
return count[n]
if n > 10:
n = 10
currCount = 9
for i i... |
from datetime import datetime
from dateutil.relativedelta import relativedelta
SATURDAY = 5
SUNDAY = 6
def getDays(dayOfMonth, holidays):
today = datetime.today()
monthsLeftInYear = 12 - (today.month - 1)
for i in range(monthsLeftInYear):
day = datetime(today.year, today.month, dayOfMonth) + rela... |
# You are given an integer array nums. You are initially positioned at the array's first index,
# and each element in the array represents your maximum jump length at that position.
# Return true if you can reach the last index, or false otherwise.
# Input: nums = [2,3,1,1,4]
# Output: true
#Explanation: Jump 1 ste... |
#Enter the string,and it wll be changed by autocorrect if required
from textblob import TextBlob
text = raw_input("Enter the string:")
print "After AutoCorrect:",TextBlob(text).correct()
|
"""
Code for representing each block
"""
class Block:
color = ""
size = "small"
xloc = 0
yloc = 0
def getColor(self):
return self.color
def getSize(self):
return self.size
def getLocation(self):
return self.xloc, self.yloc
def setColor(self, newColor):
self.color = newColor
def setSize(self, newS... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.