text stringlengths 37 1.41M |
|---|
# A dictionary that contains the subjects with their individual marks.
marks = {'Maths': 90, 'English': 78, 'Swahili': 67, 'Science': 54, 'Social Studies': 20}
"""
Loop through the Dictionary & print the grades of each subject:
80-100 = A
70-80 = B
60-70 = C
40-60 = D
Below 40 = FAIL
"""
for k, v in marks.items():
i... |
import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)
def sql_table(conn):
cursorObj = conn.cursor()
# Create the table
cursorObj.execute("CREATE TABLE salesman(salesman_id n(5), name char(... |
import sqlite3
# connect to the database.
conn = sqlite3 . connect ( 'mydatabase.db' )
# defining a cursor
cursor = conn . cursor ()
# creating the table (schema) agent_master
cursor . execute ( """
CREATE TABLE agent_master(agent_code char(6),
agent_name char(40),working_area char(35),
commission decimal(10,2),... |
import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.array = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.... |
'''
we do (sum(nums) - sum(1 to n)) to find out the duplicate number if it the duplicate only
appear twice, but it may cause overflow. and it doen't work if the duplicate appears more
than twice
Do the 'loop in a linked list' trick with two pointers. If there's only one number that' s
duplicate, then the duplicate wil... |
"""this version use O(n) memory and does not consider corner cases
def product_of_other_numbers(nums):
product_before = [1] * len(nums)
product_after = [1] * len(nums)
for i in range(1, len(nums)):
product_before[i] = product_before[i-1] * nums[i-1]
j = len(nums) - 1 - i
product_after[j] = product_after[j+1] ... |
class No:
def __init__(self,chave=None,valor=None,lef=None,rig=None,mid=None):
self.chave=chave
self.valor=valor
self.lef = lef
self.rig = rig
self.mid = mid
class Trie:
def __init__ (self):
self.raiz = No()
self.valores = list()
def vaz... |
import pandas as pd
import numpy as np
import statsmodels.api as sm
from sklearn.datasets import load_boston
import matplotlib.pyplot as plt
boston_data = load_boston() # Host load_boston
df = pd.DataFrame() # Create an empty dataframe df
df["MedianHomePrice"] = boston_data.target
df2 = pd.DataFrame(boston_data.d... |
import argparse
# A Red-Black Tree that only supports insertions
# as that's all we need to demonstrate ACsploit
class RedBlackNode:
BLACK = 'black'
RED = 'red'
rotations = 0
@staticmethod
def make_tree():
root = RedBlackNode()
return root
@classmethod
def get_rotations(... |
from acsploit.options import Options
options = Options()
options.add_option('order', 2, 'Order n of linear program (aka number of equations)')
options.add_option('mu', 3.0, 'Determines `shape` of constraint region (Must be >= 3.0; Epsilon = 1/mu)')
options.add_option('pivot_type', 'largest_coefficient', 'Choice of piv... |
import random
import string
from acsploit.options import Options
class CharGenerator:
"""Character generator"""
INPUT_NAME = "char"
def __init__(self):
"""Initialize the Chracter generator."""
self.options = Options()
self.options.add_option('min_value', 'a', 'Minimum ASCII chara... |
a=int(input("Enter the first number"))
b=int(input("Enbter the last number"))
for i in range(a,b+1):
if i>1:
for j in range(2,i//2+2):
if i%j==0:
break
else:
if j==i//2+1:
print(i,end=" ")
|
import create_database_student_info
from create_database_student_info import *
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
# def show_data():
# cursor = connection.execute(" SELECT * FROM " + TABLE_NAME + ";")
#
#
#
# for row in cursor:
# ... |
# 스택 기본 클래스
# class Stack:
# def __init__(self):
# self.arr = []
#
# def push(self, item):
# self.arr.append(item)
#
# def pop(self):
# return self.arr.pop(-1)
#
# def isEmpty(self):
# return len(self.arr) == 0
#
# S = Stack()
#
# for i in range(5):
# S.push((i, i))
... |
import sys
sys.stdin = open('B2635.txt')
N = int(input())
def check(num1, num2):
global max_num, result
temp = []
cnt = 0
while num1 >= 0:
cnt += 1
temp.append(num1)
num1, num2 = num2, num1 - num2
if max_num < cnt:
max_num = cnt
result = temp
max_num = 0... |
import sys
sys.stdin = open('sample_input3.txt', 'r')
T = int(input())
def bise(low, high, key, cnt=0):
cnt += 1
if low > high:
return 0
else:
mid = (low+high)//2
if key == mid:
return cnt
elif key < mid:
return bise(low, mid, key, cnt)
el... |
# gets set of number as a string
# prints the occurence of numbers from 0 to 9 in the string
number = input()
count = 0
for i in range(0,10):
for num in number:
if i == int(num):
count += 1
print(i,count)
count = 0 |
try:
a = int(input("Numerador: "))
b = int(input("Denominador: "))
r = a/b
except ZeroDivisionError:
print("Não dá pra dividir por zero!")
except Exception as erro:
print(f"O erro foi: {erro.__class__}")
else:
print(f"O resultado é {r:.1f}")
finally:
print("Volte sempre") |
tupla = (
int(input("Digite um numero:")),
int(input("Digite um numero:")),
int(input("Digite um numero: ")),
int(input("Digite um numero: ")),
int(input("Digite um numero: "))
)
print(tupla)
print(f"O valor 9 apareceu {tupla.count(9)} vezes")
if 3 in tupla:
print(f"O valor 3 apareceu na posiçã... |
def aumentar(preco, taxa, formatar = False):
"""
-> Aumenta o valor de um float com base em uma taxa em Porcentagem
:param preco: (Obrigatorio) Preco sobre o qual sera calculado o aumento
:param taxa: (Obrigatorio) Taxa em Porcentagem sobre o qual o preço vai aumentar
:param formatar: Incluir format... |
salario = int(input("Salario: "))
if(salario <= 1250):
salarioAjustado = salario + salario * 0.15
elif(salario > 1250):
salarioAjustado = salario + salario * 0.1
print("Seu salario ajustado será: R${:.2f}".format(salarioAjustado)) |
total = 0
soma = 0
for i in range(1, 500):
if(i % 3 == 0 and i % 2 != 0):
total += 1
soma += i
print("Soma dos {} numeros impares multiplos de 3 é {}".format(total, soma)) |
jogador = dict()
partidas = list()
jogador['nome'] = input("Nome: ")
n = int(input(f"Quantas partidas {jogador['nome']} jogou? "))
for i in range(0, n):
partidas.append(int(input(f' Quantos gols na partida {i + 1}? ')))
jogador['gols'] = partidas[:]
jogador['total'] = sum(partidas)
print("-="*30)
print(jog... |
cont = 0
num = int(input("Digite um Número: "))
for c in range(1, num + 1):
if(num % c == 0):
print('\033[33m', end='')
cont += 1
else:
print('\033[31m', end='')
print(c, end=' ')
print('\n\033[34mO número {} foi dividido {} vezes\033[m'.format(num, cont))
if cont == 2:
prin... |
nome = str(input('Qual seu nome? ')).strip()
nomes = nome.split()
print("Seu primeiro nome e {}".format(nomes[0]))
print('Seu ultimo nome e {}'.format(nomes[len(nomes) - 1]))
|
numero = int(input("TABUADA: Insira um numero:"))
n = 1
while(n <= 10):
print("{} x {} = {}".format(numero, n, numero * n))
n += 1 |
idade = int(input("Qual sua idade? "))
if(idade >= 18):
print("Você é maior de idade")
else:
print("Você é menor de idade") |
from time import sleep
for n in range(10, 0, -1):
print("{}!!".format(n))
sleep(1)
print("Feliz Ano Novo!!") |
__author__ = "Thomas van Haastrecht"
__credits__ = ["Thomas van Haastrecht"]
import numpy as np
from itertools import combinations_with_replacement
from display import display_grid
def solve(rows, columns):
r = len(rows)
c = len(columns)
grid = np.zeros((r, c))
probability_grid = np.add(n... |
# a1.py
# Beverly Balasu bb532
# 2/28/17
# Skeleton by Walker M. White (wmw2), Lillian Lee (LJL2), Feb 2017
"""Module for currency exchange
This module provides several string parsing functions to implement a simple
currency exchange routine using an online currency service. The primary
function in this module is exc... |
from multiprocessing import Pool
from math import *
def frange(x, y, jump):
while x < y:
yield x
x += jump
def eval_fun(function, val):
xs = [x.strip().replace('^', '**') for x in function.split('+')]
return sum([eval(n.replace('x', str(val))) for n in xs])
def Integrate... |
#created by Matthew Walsh
#created for ICS3U
#created on oct 2017
#converts celcius to fehrenheit
def convert_to_fahrenheit(user_input):
fahrenheit = (1.8 * user_input) + 32
print("The temperature is " + str(fahrenheit) + " degrees fahrenheit")
user_input = input('Enter tempurature in degree celcius: ')
... |
from greeting import speaky ,record_audio
import webbrowser
import speech_recognition as sr
from urllib import request
import json
import pyttsx3
import wikipedia
#-----------------------------------------------------jokes----------------------------------------------------
url = 'http://official-jo... |
def find_all(array, n):
findings = []
for i in range(0, len(array)):
if array[i] == n:
findings.append(i)
return findings
print(find_all([6, 9, 3, 4, 3, 82, 11], 3))
|
def count_vowels(s = ''):
return sum(x in 'aeiouAEIOU' for x in s) if type(s) == str else None
|
class Direction:
def __init__(self, x, y):
self.x = 0
self.y = 0
return
class Position:
def __init__(self, x, y):
self.x = 0
self.y = 0
return
def move(self, direction:Direction):
self.x += direction.x
self.y += direction.y
return
class Size:
def __init__(self, width, height):
self.width = 0... |
import random
import time
from hangman import Hangman
def wordPicker():
wordset=["cat","rat","bat",
"father","mother","sister","brother"]
idx=random.randrange(0,len(wordset))
return wordset[idx]
def printBreak():
print("\n"+ "-"*10 + "#"*20 + "-"*10 + "\n")
def playGame():
# picki... |
# 1. Input: What is the input parameter?
# 2. Output: What is the datatype of your answer that your function has to return?
# 3. What data structures and methods associated with it will be used
# 4. Where are you going to store temp data ( if needed )
# 5. Describe the model of your algorithm before implementing soluti... |
# 1. Input: What is the input parameter?
# 2. Output: What is the datatype of your answer that your function has to return?
# 3. What data structures and methods associated with it will be used
# 4. Where are you going to store temp data ( if needed )
# 5. Describe the model of your algorithm before implementing soluti... |
# 1. Input: What is the input parameter?
# 2. Output: What is the datatype of your answer that your function has to return?
# 3. What data structures and methods associated with it will be used
# 4. Where are you going to store temp data ( if needed )
# 5. Describe the model of your algorithm before implementing soluti... |
# 1. Input: What is the input parameter?
# 2. Output: What is the datatype of your answer that your function has to return?
# 3. What data structures and methods associated with it will be used
# 4. Where are you going to store temp data ( if needed )
# 5. Describe the model of your algorithm before implementing soluti... |
print("Merhaba Ben Bejo ")
#input Dışarıdan veri girişi yapmak istediğimiz zaman kullanılır
### Dokunma
print("")
### Dokunma
print("merhaba")
ad= input("Lütfen İsminizi Giriniz: ")
soyad= input ("Lütfen Soyadınızı Giriniz: ")
print("Merhaba" , ad, soyad)
|
###########################################################################
#
#
#Tumple düzenli ve değitrilemez koleksıyondur.
#Pythonda tumple yuvarlak parentezle yazılır
#
#
###########################################################################
print("")
print("")
print("Bejo Kod Yazıyor.")
print("")
print("")
... |
"""
4. Пользователь вводит две буквы. Определить, на каких местах
алфавита они стоят, и сколько между ними находится букв.
"""
b1 = ord(input('Введите первую букву: '))
b2 = ord(input('Введите вторую букву: '))
print(f'Номер первой буквы = {int(b1)-97+1}' ) # строчные английские буквы находятся в ASCII в диап... |
import json
class Menu:
menu = 'Welcome\nLogin: '
invalid_login = 'Invalid login'
def login(self):
file_angajati = open("lista_angajati.json", "r")
angajati = json.load(file_angajati)
file_angajati.close()
tmp_list = []
try:
id = int(input(f'{self.men... |
import math
angulo = float (input("Digite o ângulo: "))
seno = math.sin(math.radians(angulo))
print ("O ângulo de {}, tem o seno {:.2f}".format(angulo, seno)) |
numero = int (input("Digite um número: "))
if (numero % 2 == 0):
print ("O número {} é par ".format(numero))
else:
print ("O número {} é ímpar ".format(numero)) |
num = list (range(10))
for n in range (0,10):
num [n] = int (input("Digite um valor "))
for i in range (0,10):
for j in range (0,1):
if (num[i] < num [j]):
aux = num [i]
num [i] = num [j]
num [j] = aux
for n in range (0,10):
print (num)
|
# #code..
# a=1
# b=2
# c=3
# s=a+b+c
# r=s/3
# print(r)
#code..
# def average(a,b,c):
#
# s=a+b+c
# r=s/3
# print(r)
#
# average(10,20,30)
def average(a,b,c):
s=a+b+c
r=s/3
return r
print(average(10,20,30))
def a():
return 'haha'
print(a()) |
'''
Chess board with random number of marbles on it, no more than one in each square.
One square is "selected", i.e. it is shown to a person, who can then
a) add 1 marble to any empty square
b) remove a marble from any square
c) do nothing
After that, another person with no prev. knowledge of a board
should tell... |
# converts binary (represented by an input string) to a decimal
bin_str = str (input ('string representation of binary: '))
l = len (bin_str)
sum = 0
err=False
for i in range(0, l):
ch = bin_str[i]
if (ch == '1'): sum += 2**(l-i-1)
else:
if (ch != '0'):
err = True
break
if (err):
print('inva... |
import collections
import sys
class SnakeGame:
def __init__(self, width, height, food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the firs... |
"This a a neural network implementation based on the discussion nielsen Michael book"
import numpy as np
class Neural_Network:
"Generate initial weights and biases"
def generate_initial_weights(self,neurons_per_layer):
weights=[]
biases=[]
for j,k in zip(neurons_per_layer[1:],neurons_per... |
import numpy
def get_seasonal_forcing(
period: float, shift: float, prop_amplitude: float, average_value: float
):
"""
Factory function to get a trigonometric/sinusoidal function (using cosine) to represent seasonal forcing of
transmission in a model.
Note that the time unit is not specified (... |
import sys
def main():
csv_file = sys.argv[1] # reads the input file
output_csv = "output_mcmc.csv"
output_writer = open(output_csv,"w") # open output file for writing
lines = [line.strip() for line in open(csv_file,"r").readlines()] # parsing lines to remove the extra brake line character
line... |
"""
String manipulation functions
"""
from functools import lru_cache
def create_stratum_name(stratification_name, stratum_name, joining_string="X"):
"""
generate a name string to represent a particular stratum within a requested stratification
:param stratification_name: str
the "stratification"... |
import pygame
from .constants import RED, WHITE, SQUARE_SIZE, PADDING, BORDER, GRAY, CROWN
class Piece():
"""This class will hold all the infomation about a certain piece
"""
def __init__(self, row, col, color):
self.row = row
self.col = col
self.color = color
self.king... |
a = 10
b = 65
if a + b == 9:
print("Vse pravilno")
elif a + b <= 5:
print("Nado reshit pravilno")
else:
print("Ne verno")
|
#!/usr/bin/python
import math
def recipe_batches(recipe, ingredients):
'''
make list of times
loop over recipe
loop over ingredients
find number of times ingredient[i] can be subtracted by recipe[i]
return lowest number in list
'''
times = []
for key, value in recipe.items():
for ke... |
from math import sin, cos
from random import uniform
from numpy.linalg import solve
import matplotlib.pyplot as plt
def function_1(x):
return x ** 2 - 12 * x + 30
def function_2(x):
return sin(x) - cos(x)
def function_3(x):
return 2 * (x ** 3) - 3 * x + 15
def read_x0_xn():
try:
x0 = flo... |
from sigmoid import sigmoid
import numpy as np
def predict(Theta1, Theta2, X):
"""
PREDICT Predict the label of an input given a trained neural network
p = PREDICT(Theta1, Theta2, X) outputs the predicted label of X given the
trained weights of a neural network (Theta1, Theta2)
Args
Theta1:... |
from sigmoid import sigmoid
def sigmoidGradient(z):
"""
SIGMOIDGRADIENT returns the gradient of the sigmoid function
evaluated at z
g = SIGMOIDGRADIENT(z) computes the gradient of the sigmoid function
evaluated at z. This should work regardless if z is a matrix or a
vector. In particular, if z i... |
from sigmoid import sigmoid
import numpy as np
def costFunction(theta, X, y):
"""Compute cost and gradient for logistic regression
J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the
parameter for logistic regression and the gradient of the cost
w.r.t. to the parameters.
Args
... |
import sys
import urllib.request
import csv
import pandas as pd
import numpy
import urllib.request
import random as rand
import matplotlib.pyplot as plt
#Function takes in three parameters, a training data set file name, a testing data set file name, and the name of
#the target classLabel that we are predicting
def tr... |
# Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
class Solution(object):
def maximalSquare(self, matrix):
if len(matrix) == 0:
return
area = 0
sol = [[0 for i in range(len(matrix[0]))]for j in range(len(matrix)... |
import collections
# Given a non-empty array of integers, every element appears twice except for one. Find that single one.
class Solution(object):
def countElements(self, arr):
count=0
for num in arr:
if arr.__contains__(num+1):
count += 1
return count
if _... |
class Solution(object):
def minStartValue(self, nums):
minValue = 1
i=0
numsSum = minValue
while i<len(nums):
if numsSum+nums[i]<=0:
minValue += 1
numsSum = minValue
i=0
else:
numsSum += nums[i]... |
import collections
# Given a non-empty array of integers, every element appears twice except for one. Find that single one.
class Solution(object):
def singleNumber(self, nums):
freq = collections.Counter(nums)
for key in freq:
if freq[key] == 1:
print(key)
if __n... |
"""
https://leetcode.com/explore/challenge/card/september-leetcoding-challenge/556/week-3-september-15th-september-21st/3465/
An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
Return a sorted list of all the integers in the range [low, high] inclusive that ha... |
def is_full():
for i in range(1,10):
if onboard[i] =='':
return False
return True
def Judge(onboard,player):
return((onboard[7]==player1 and onboard[8]==player and onboard[9]==player) or
(onboard[4]==player1 and onboard[5]==player and onboard[6]==player) or
(onboard[... |
class Bateria():
def __init__(self, mah, tempoDeCarregamento):
self.mah = mah
self.tempoDeCarregamento = tempoDeCarregamento
self.carga = 0
self.uso
self.carregavel
def carregar(self, tempo):
if self.carregavel == True:
if self.carga == self.mah:
... |
# import funcoes
class dados:
def __init__(self, numero_celular, nome, sobrenome):
self.numero_celular = numero_celular
self.nome = nome
self.sobrenome = sobrenome
# Alterando o número do celular.
def redefinir_numero_celular(self, numero_celular):
self.numero_celular = num... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 6 03:24:02 2019
@author: RDxR10
"""
def is_number(s):
try:
float(s)
return True
except (ValueError,TypeError):
return False
s = input("Enter the string to be checked: ")
print(is_number(s))
|
# Importing libraries
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor
# K Nearest Neighbors Regression
class K_Nearest_Neighbors_Regressor():
def __init__(self, K):
self.K = K
# Function to store trai... |
from tkinter import *
from functools import partial
global ROWS
global COLUMNS
global canvas
global mainWindow
global currentCol
global haveNew
SQUARE_SIZE = 60
COIN_RADIUS = 0.8 * SQUARE_SIZE / 2
BOARD_PADDING = 10
BUTTON_MARGING = 10
LARGE_FONT = ("Verdana", 12)
NORM_FONT = ("Helvetica", 10)
S... |
class User:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def make_withdrawal(self, amount):
self.balance -= amount
return self
def make_deposit(self, amount):
self.balance += amount
return self
def display_user_bala... |
# --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file is stored in the variable path
#Code starts here
# Data Loading
data = pd.read_csv(path)
data.rename(columns={'Total':'Total_Medals'}, inplace=True)
# Summer or Winter
data['Better_Even... |
## The idea is to implement merge sort.
## However, to pass the Coursera homework we need to count how many times we spot an inversion
## during the merge process. An inversion is simply the situation where the right hand value is larger
## than the left when merging 2 arrays.
## Merge 2 arrays and count inversions... |
class Board:
"""
Defines the game board and all pertinent aspects of the game
Board positions are 1 - 9, ignoring index 0 in lists
"""
# sets of winning moves
win_sets = [{1, 2, 3}, {4, 5, 6}, {7, 8, 9},
{1, 4, 7}, {2, 5, 8}, {3, 6, 9},
{1, 5, 9}, {3, 5, 7}]
... |
"""
The script demonstrates a simple example of using ART with Keras. The example train a small model on the MNIST dataset
and creates adversarial examples using the Fast Gradient Sign Method. Here we use the ART classifier to train the model,
it would also be possible to provide a pretrained model to the ART classi... |
import string
text = 'Did you see a purple cow?'
text = text.lower()
# 去掉标点
# text = ''.join(c for c in text if c not in string.punctuation)
_ = lambda c : c if c not in string.punctuation else ' '
text = list(map(_, text))
text = ''.join(text)
# 去掉重复空格
text = text.split()
text = ' '.join(text)
print(text)
'''
p... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Created by Kelly Hwong on 2018年09月18日16:16:19
# Part A: House Hunting
import math
'''
annual_salary = int(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = int(input("Enter the co... |
'''
Given a string in the form 'AAAABBBBCCCCCDDEEEE' compress it to
become 'A4B4C5D2E4'. For this problem, you can falsely "compress"
strings of single or double letters. For instance, it is okay
for 'AAB' to return 'A2B1' even though this technically takes more
space.
The function should also be case sensitive, so tha... |
#
#Check if the string has all unique characters
#option 1
def UniqueCh(s):
#set command omits duplicates
print(set(s),"vs", list(s))
if len(list(set(s)))== len(s):
return True
else:
return False
#option 2
#def UniqueCh(s):
# s=s.replace(" ","")
# #print(s)
# ChUnique=[None]*26... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#Disclaimer- onlly for learning purpose
#print("Whats up python!")
# importing calendar module
import calendar
# Program make a simple calculator
# This function adds two numbers
def add(x, y):
return x + y
# This function... |
import pandas as pd
df = pd.read_csv('data/enrolment_1.csv')
# 코드를 작성하세요.
df["status"] = "allowed"
# "information technology” 과목은 심화과목이라 1학년은 수강할 수 없습니다.
condition = (df["course name"] == 'information technology') & (df["year"]==1)
df.loc[condition, "status"] = "not allowed"
#“commerce” 과목은 기초과목이고 많은 학생들이 듣는 수업이라 4학년... |
# Ransom note algorithm using hashmap
from collections import defaultdict
class Solution():
def canSpell(self, magazine, note):
letters = defaultdict(int)
# letters = {i : 0 for i in magazine} # <-- cannot handle letters not in magazine
for c in magazine:
letters[c] += 1
... |
import util
import copy
class GameState():
"""
This class contains information of the state of a Gomoku game.
Normally it is 5 in a row. We extend the game to N in a row.
Parameter:
N: N in a row
boardSize: The board will be boardSize x boardSize
numPlayers: How many ... |
"""Class of list's items"""
class Item():
"""Class of list's items"""
next_item = None
prev_item = None
elem = None
def __init__(self, next_item, prev_item, elem):
self.next_item = next_item
self.prev_item = prev_item
self.elem = elem
def get_next_item(self):
... |
import sqlite3
conn = sqlite3.connect("users.db")
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS users (uname text, pword text)")
conn.commit()
conn.close()
def addUser():
conn = sqlite3.connect("users.db")
c = conn.cursor()
c.execute("INSERT INTO users VALUES ('bob', 'bob');")
c.execute("INS... |
# https://leetcode.com/problems/kth-largest-element-in-a-stream/
from typing import List
import heapq
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.nums = []
for num in nums:
if len(self.nums) < self.k:
heapq.heappush(self.nums, ... |
from tkinter import *
print("hello1")
#import click_pictures
print("hello2")
root = Tk()
root.title("Attendance Manager")
print("hello3")
def button_click():
myLabel = Label(root, text="Hello ")
myLabel.pack()
print("hello4")
button_1 = Button(root, text="Scan", padx=40, pady=20, command=lambda:exe... |
import sqlite3
#from Utils import *
db = '__HOME__/project.db'
GAME_ID_TO_NAME = {0: "Poker", 1: "Blackjack", 2: "PushUps"}
def request_handler(request):
if request['method'] == "POST":
args = request['form']
username = str(args['username'])
conn = sqlite3.connect(db) # connect to that... |
"""Renders the poker game for clients to process.
This module provides a way for clients to access the game
state from the Poker API. Serves as a conversion from
the data in the SQL database to a JSON output.
"""
import json
import sys
import datetime
sys.path.append('__HOME__/team079/poker-game')
from settings impor... |
#!/usr/bin/env python3
"""
A palindromic number reads the same both ways. The largest palindrome made from
the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
import time
start = time.time()
def isPalindrome(num):
numStr = str(num)
... |
#!/usr/bin/env python3
"""
2520 is the smallest number that can be divided by each of the numbers from 1
to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the
numbers from 1 to 20?
"""
import time
start = time.time()
primes = [2,3,5,7,11,13,17,19]
startNum = 1
fo... |
#!/usr/bin/env python
import time
start = time.time()
""" Find all prime factors, then return the greatest factor"""
primeLookup = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]
def isPrime(num):
if num in primeLookup:
return True
else:
stopNumber = int(num**0.5)
... |
'''
Darin Brown and Skyler Penna
CS415 Project 2
Dr. Gurman Gill, Sonoma State Univrsity
This program represents very long (up to 1000 digits) integers as
lists and multiplies and exponentiates them
'''
def convertIntToList(integer):
intList = [int(i) for i in str(integer)]
return list
def multiplyDigit(int1... |
# Other's solution
# Backtracking
# 逻辑: 1)基本情况: 字符长度等于两倍n就完成了字符串; 2)左括号数量等于n,右括号数量应该永远小于等于当前左括号; 3)在每一个分节点,需要解决的都是同一个问题:是不是可以加左括号和右括号
'''
(
(( ()
((( (() ()(
((())) (()( (()) ()() ()((
(()() (())( (... |
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 and not l2:
return None
head = fast = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
fast.next= l1
l1 = l1.next
e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.