text stringlengths 37 1.41M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 5 08:02:45 2018
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44
As 1 = 14 is not a sum it is not included.
The sum of these ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 2 15:23:57 2018
The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1);
so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its alphabetical
pos... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 26 20:46:03 2018
@author: daniel
Given an array of integers, find the first missing positive integer in linear
time and constant space. In other words, find the lowest positive integer that
does not exist in the array. The array can contain duplica... |
class Solution(object):
def removeSubfolders(self, folders):
"""
:type folders: List[str]
:rtype: List[str]
"""
folders = sorted(folders)
print folders
unique_folders = []
if len(folders) > 0:
unique_folders.append(folders[0])
for current_folder in folders:
for folder ... |
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
sorted_nums = sorted(nums)
i = 0
j = len(nums) - 1
found = False
while i < j:
sum = sorted_nums[i] + sorted_nums[j]
if sum == target:
fo... |
class Solution(object):
def is_palindrome(self, part_str):
if part_str == part_str[::-1]:
return True
return False
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
for idx in len(s)
s = Solution()
print s.partition('aab')
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return head
... |
class Solution(object):
def __init__(self):
self.known_solutions = {}
def get_key(self, m, n):
return '{},{}'.format(m, n)
def lookup_solution(self, m, n):
return self.known_solutions.get(self.get_key(m, n))
def store_solution(self, m, n, value):
self.known_solutions[self.get_key(m, n)] = val... |
# WIP
class NumFreq(object):
def __init__(self, val, count):
self.val = val
self.count = count
class Solution(object):
def insert_into_heap(self, current_heap, num):
cur_index = len(current_heap) - 1
if current_heap[cur_index].count > num.count:
return
current_heap[cur_index] = num
n... |
import inspect
import collections
def get_arg_count(func):
args, *rest = inspect.getfullargspec(func)
return len(args)
def convert_args_to_kwargs(func, args):
args_names, *rest = inspect.getfullargspec(func)
return dict(zip(args_names, args))
def get_default_args(func):
"""
returns a dicti... |
'''
Liani Lye, HW 02
SoftDes Fall '14
Due 09.16.14
'''
n = raw_input("enter grid dimension: ");
n = int(n);
horiz = "+ - - - - ";
vert = "| ";
fullHoriz = horiz*n + "+";
fullVert = ((vert*n + "|") + "\n")*3 + (vert*n + "|");
# forget about ending the rows / column for now
def createGrid():
for i in range(0... |
class Cell:
def __init__(self, quantity):
if type(quantity) is not int:
raise ValueError
if quantity <= 0:
raise ValueError("Ячеек в клетке должно бытыть больше 0.")
self.quantity_count = quantity
def __add__(self, other):
if type(other) is not Cell:
... |
def sum():
sum_res = 0
end = False
while end == False:
number = input("Введи числа или введи $ для выхода: ").split()
res = 0
for i in range(len(number)):
if number[i] == "$":
end = True
break
else:
res = res + i... |
time = input("Введи кол-во секунд ")
time = int(time)
hour = time // 3600
min = (time - hour * 3600) // 60
sec = time - (hour * 3600 + min * 60)
print("Секунд: {} \nМинут: {} \nЧасов: {} ".format (sec, min, hour))
|
a = input("Введи результат первого дня: ")
b = input("Введи общий результат: ")
a = int(a)
b = int(b)
days = 1
while a < b:
a += a * 0.1
days += 1
days = str(days)
print("Номер дня: " + days) |
import threading
import time
def f(i):
for p in range(3):
time.sleep(i+1.5)
print(threading.current_thread().getName())
return
# start threads by passing function to Thread constructor
for i in range(3):
t = threading.Thread(target=f, args=(i,))
t.setName( 'Thread#'+str(i) )
t.star... |
print(' ooooooooooooo oo oo ')
print(' oo oo oo oo ')
print(' oo oo oo oo ')
print(' oo oo oo oo ... |
from tkinter import *
root = Tk()
def myClick():
myLabel = Label(root, text="Look, I clicked the button")
myLabel.grid(row=0,column=0)
enabledButton = Button(root,
text='Click me!',
padx=50,
pady=50,
command=myClick,
... |
class node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
def PreOrderTraversal(root):
if(root):
print(root.data, end=" ")
PreOrderTraversal(root.left)
PreOrderTraversal(root.right)
def InsertNode(root, data):
new_node ... |
class node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = node()
def InsertAtEnd(self, data):
new_node = node(data)
if(self.head.data is None):
self.head = new_node
new_nod... |
import sys
import pandas
DTYPES = {
"float64" : "double",
"int64" : "int64",
"datetime" : "timestamp",
"str" : "string",
"bool" : "bool",
}
def convert(input_file, output_file, options={}):
"""Convert a CSV data table to a GLM library object list
This converts a CSV data file to a GLM lib... |
import unittest
from classroom import Classroom
classroom_016 = Classroom('016', 80, ['PC', 'projector', 'mic'])
classroom_007 = Classroom('007', 12, ['TV'])
class ClassroomTest(unittest.TestCase):
def test_is_larger(self):
self.assertEqual(Classroom.is_larger(classroom_016, classroom_007), True)
d... |
print("ax^2+bx+c=0")
a = int(input("a"))
b = int(input("b"))
c = int(input("c"))
d = b ** 2 - 4 * a * c
e = -b / 2 * a
f = (- b + d ** 0.5 ) / (2 * a)
g = (- b - d ** 0.5 ) / (2 * a)
if d < 0:
print("pt vo nghiem")
if d == 0:
print("pt co nghiem kep")
print("x1=x2=", e)
if d > 0:
print("pt co 2 nghiem ... |
from turtle import *
shape("turtle")
color("green")
speed(0)
for i in range(300):
for a in range(4):
forward(100)
left(90)
left(7)
mainloop() |
print('1,')
print("a,")
for i in range(20):
print("*",end=" ")
print()
print("b,")
stars = int(input("Enter a number: "))
for i in range(stars):
print("*",end=" ")
print()
print("c,")
for i in range(9):
if i % 2 == 0:
print("x",end=" ")
else:
print("*",end=" ")
print()
print("d,")
b = in... |
while True:
quiz = input("""How many legs does a spider have?
a = None
b = 4 legs
c = 8 legs
d = 12 legs""")
print(quiz)
if quiz == "a":
print("correct")
break
else:
print("Not correct")
|
while True:
a = {
"dog" : 'chó',
"cat" : 'mèo',
"duck" : "vịt"
}
b = input("what word do u want to translate: ")
c = b.lower()
print(a[c])
|
items = ['com', 'pho', 'bun', 'chao']
# 1.Index-based
i = 1
items.pop(i)
print(items)
#2. value-based
item_to_delete = 'chao'
items.remove(item_to_delete)
print(items) |
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 1:
return True
if n % 2:
return False
left = 0
right = len(str(n)) / 3 * 10 + 10 #Narrow the range of n can save many time
... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""
A test for class AnonymousSurvey.
"""
def setUp(self):
"""
Creat a object of surey and a group of answers,
for test methods use.
... |
import sys
print('Practica 2')
## Define las variables independientes
a= 1.03
b=503
c= 2** 2
d= a*b+c
## Imprime los valores de las variables
print("a= "+str(a)+" b= "+str(b)+" c= "+str(c)+" d= "+str(d))
|
def swap_ab(a, b):
a, b = b, a
print(f'a={a}, b ={b}')
a = int(input('Input value a :'))
b = int(input('Input value b:'))
print(f'a={a}, b ={b}')
swap_ab(a, b) |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
#连接mysql数据库,删除数据库中的数据
#打开数据库链接
username ="root"
password ="070809"
databaseName="testdb"
db = MySQLdb.connect("localhost",username,password,databaseName)
# 使用cursor()方法获取操作游标
cursor = db.cursor()
#更新语句
#sql ="DELETE FROM EMPLOYEE2 WHERE AGE >'%d'"%(20)
sql ="... |
#!/usr/bin/python
# Deep Learning Homewor3
# Question 5b
# Alex Pine (akp258)
import numpy as np
# args are two 2d numpy arrays. kernel must be smaller than input.
def convolution(input, kernel):
result = np.zeros((np.shape(input)[0] - np.shape(kernel)[0] + 1,
np.shape(input)[1] - np.shape... |
# MICHAEL TYRONE GARCIA
# CS 153 THV (SUSAN PANCHO-FESTIN): PROJECT - GALOIS FIELD CALCULATOR [GF(2^m)]
# May 25, 2017
# Generally assume correct input.
import os
import time
import sys
import numpy as np
from numpy.polynomial import polynomial as P
# numberCheck is a function that validates if an input ... |
def Zad3():
ms1 = list()
n = int(input("Введите число элементов массива№1: "))
for i in range(n):
a = int(input("Введите элемент: "))
ms1.append(a)
ms2 = list()
n = int(input("Введите число элементов массива№2: "))
for i in range(n):
a = int(input("Введите элемен... |
#!/usr/bin/env python
# coding:utf-8
# get reverse complementary sequences
#
import sys
import argparse
parser = argparse.ArgumentParser(
description="""
Get reverse complementary fasta sequences""",
epilog="""
With no FILE, or when FILE is -, read standard input.
Examples:
fa-rec f reverse complement f file
... |
# Faça um programa que leia um número de 0 a 9999 e mostre na tela:
# qual é o número da unidade, dezena, centena e milhar
num = int(input("Entre com um número de 0 a 9999: "))
if num < 0 or num > 9999:
print("Fora da faixa!")
elif num >= 1000:
t = int(num / 1000)
h = int((num - (t * 1000)) / 100)
d =... |
class Client:
def __init__(self, name, age):
self.__nomeCliente = name
self.__idadeCliente = age
self.__enderecos = []
def insereEndereco(self, street, city, state, cep):
address = Address(street, city, state, cep)
self.__enderecos.append(address)
def listaEndereco(se... |
# Elabore um programa que, ao inserir o valor de um produto e sua condição de pagamento,
# ele informe o seguinte: Se for pagamento à vista, mostre o preço do produto com 10% de desconto;
# Se for cartão à vista, mostre o preço com 5% de desconto; Se for cartão mas parcelado,
# mostre o preço do produto 15% mais caro
... |
# Desenvolva um programa que leia seis números inteiros e mostre a soma
# total apenas daqueles que forem ímpares
s = 0
nums = []
for i in range(6):
nums.append(int(input("Entre com o " + str(i + 1) + "º número: ")))
for i in nums:
if i % 2 != 0:
s += i
if s == 0:
print("Não há números ímpares!"... |
# Crie um programa capaz de ler vários números e colocá-los em uma lista. Depois disso, mostre:
# a. Quantos números foram digitados;
# b. A lista de valores ordenada de forma decrescente;
# c. Se o valor 5 está ou não dentro da lista.
from random import randint
qtt = randint(1, 10) #Gera um número aletatório entre... |
"""Assignment 2 - Blocky
=== CSC148 Fall 2017 ===
Diane Horton and David Liu
Department of Computer Science,
University of Toronto
=== Module Description ===
This file contains the player class hierarchy.
"""
import random
from typing import Optional, Tuple
import pygame
from renderer import Renderer, BOARD_WIDTH
... |
print("python")
n = 73
if (n % 5 == 0):
n = n + (5 - n % 5)
print(n)
else:
print("not multiple")
n = n + (5 - n % 5)
print(n)
|
##
## Intro to Git, Python, and Programming Basics (bypassing XML)
##
# going over some git basics
# git --version
# git help
# Pull down a repo from somewhere
# git clone <url>
# git branches; discussed to some degree; means of doing changes off to side without affecting core code
# then we can merge this stuff i... |
def calculator(dias,hora,minutos,segundos):
global resultado
hora += dias * 24
minutos += hora * 60
segundos += minutos * 60
resultado = segundos
return resultado
resultado = 0
a = int(input("Introduzca un nº de días "))
b = int(input("Introduzca un nº de horas "))
c = int(input("Intro... |
a = int(input("Inputkan nilai a: "))
b = int(input("Inputkan nilai b: "))
#Contoh statement pertambahan antara 2 number di Python
# Operator Penjumlahan
c = a + b
print ("Hasil %i + %i = %i" % (a,b,c))
#Contoh statement perkurangan antara 2 number di Python
# Operator Pengurangan
c = a - b
print (f'Hasil {a} - {b} = ... |
class Account:
def __init__(self, balance):
""" Konstruktor w klasie Account - tworzenie nowego konta """
self._balance = balance
def pay(self, amount):
""" Wpłata na konto """
self._balance += amount
def take(self, amount):
""" Wypłata z konta """
if self.... |
#Menu
def menu():
print("\nMenu:\n"
"1. Binarios.\n"
"2: Octales.\n"
"3. Salir.\n")
opcion = int(input('Ingrese la opcion deseada...\n'))
if opcion == 1:
binarios()
if opcion == 2:
octal()
if opcion == 3:
print('\nHasta pronto.')
... |
#!/bin/python
import sys
def gcd(x,y): return y and gcd(y, x % y) or x
def lcm(x,y): return x * y / gcd(x,y)
n = 1
for i in range(1, 31):
n = lcm(n, i)
print(n)
|
# Polynomial Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values # Independent Variables
y = dataset.iloc[:, 2].values # Dependent Variable
# Fitting Linear R... |
from functools import reduce
def call(Input):
String = Input
Sum = int(str(reduce(lambda x,y: x+y, map(int, [e[::-1] for e in String.split()])))[::-1])
return Sum
def Check(Input):
number = Input
if isinstance(number, int) == True:
if number <= 10000 and number > 0:
re... |
'''************************************************************
Name : RSA Calculations Demonstration
Description: A graphical programme that demonstrates the
working of the RSA cryptosystem in crude way
Author : Aadi B.
Date : 25 Dec 2018
Files : rsa.py => Contains all mathematics ... |
import torch
def hello():
"""
This is a sample function that we will try to import and run to ensure that
our environment is correctly set up on Google Colab.
"""
print('Hello from knn.py!')
def compute_distances_two_loops(x_train, x_test):
"""
Computes the squared Euclidean distance bet... |
# List, tuple, dictionary and set
# list [] 是一种保存有序项集合的数据结构。 项目列表应该使用方括号扩起来.
# start from 0
# tuple ()元组用于将多个对象组合在一起。可以将它们近似看作列表,但是没有列表类提供的许多功能。
# 元组的一个重要特征是,它们和字符串一样是 **不可变的 **,即你不能修改元组。
# dictionary {} 字典就像是一个地址簿,只要知道一个人的名字,你就可以找到他 / 她的地址或联系方式,
# 即,我们将键 (名字)与 值 (详细信息)相关联。
# 注意,
# 1. key is unquie
# 2. key must... |
class Solution:
# @param A : integer
# @return an integer
def sqrt(self, A):
if (A<0 or A==0):
return 0
if (A==1):
return 1
start = 1
end = A
mid = 0
while(start<=end):
mid = (start+end)/2
if ((mid*mid =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""List files in directory.
Experiment comparing os.walk with os.scandir
@author Miguel Maltez Jose
@date 20210314
"""
import os
import argparse
from dataclasses import dataclass
from abc import abstractmethod
from pprint import pprint
@dataclass
class FileInfo:
"""File... |
import random
from Assignment1 import card
from Assignment1 import player
class Deck:
def __init__(self):
# Construct Deck
self._deck = {}
self._random_state = list(range(0, 52))
for value in range(0, 52):
if value < 13:
suit = 'Hearts'
s... |
import collections
class Solution:
"""
@param: numCourses: a total of n courses
@param: prerequisites: a list of prerequisite pairs
@return: the course order
"""
def findOrder(self, numCourses, prerequisites):
# write your code here
if numCourses == 0:
retur... |
#Zelarous & Group
#SERVER
import socket
import os
argumants = {}
#This function checks to make
def check_login(username, password):
"""Reads from a specified text file with username and password information. It then checks to make sure that the
user's input is valid. If the username and password are correc... |
def mul(lst):
mul=1
for i in lst:
mul=mul*i
print(mul)
lst=[]
n=int(input("no of elements:"))
for i in range(0,n):
ele=int(input("values:"))
lst.append(ele)
mul(lst)
|
import wikipedia
def wiki_search():
page_or_phrase = input('Type page name or phrase here:')
while page_or_phrase != '':
page_or_phrase = input('Type page name or phrase here:')
search_page = wikipedia.search(page_or_phrase)
print(wikipedia.summary(search_page))
wiki_search()
|
def main():
import random
print(random.randint(5, 20)) # line 1
print(random.randrange(3, 10, 2)) # line 2
print(random.uniform(2.5, 5.5)) # line 3
#What did you see on line 1?
#What was the smallest number you could have seen, what was the largest?
#5 and 20
#What did you see on line 2?
#What wa... |
#!/usr/bin/env python3
"""
@author: M. Garbellini
@email: matteo.garbellini@studenti.unimi.it
Albert-Ludwigs-Universität Freiburg
Computational Physics: Material Science
Exercise Sheet 01 - Planetary Evolution
The following is the code for plotting the computational results.
List of plots:
(1) Planets position... |
import pandas as pd
import numpy as np
import datetime
'''
Author: Nora Barry
This module contains methods used to load and clean the Weather dataset.
'''
def read_csv(file_name):
df = pd.read_csv(file_name)
print df.shape
return df
def drop_nas(df):
'''Missing values are recorded as -9999. Use thi... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
class Timer(threading.Thread):
"""
a timer that execute an action at the end of the timer run.
"""
def __init__(self, seconds, action=None, args=None, once=False):
self.counter = 0
self.runTime = seconds
self.args ... |
"""
Assignment1: Code Part 3
by Adelbert Choi
This script aims to generate simple descriptive summaries of the data
"""
import tweetProcessor as tp
import matplotlib.pyplot as plt
def main():
"""
This script mainly utilised tweetProcessor to obtained a pre-processed data frame of the tweets
Also, descr... |
#!/usr/bin/python
import re
pattern = re.compile(r'hello')
print('Pattern is: ' + str(pattern))
m = ''
while(m != 'exit'):
m = str(input('Input match string (type exit to quit): '))
if pattern.match(m):
print(pattern.match(m).group())
print(pattern.match(m).groups())
else:
print... |
# -*- coding: utf-8 -*-
"""
Plot example
Use some modules and those functions to make beutiful plot for own purpose
You can read the full code by typing command line "plot_test??" on the ipython
console or ctrl+left_click on the spyder text editor after importing this code.
If you want to plot a graph on new window ... |
a= float(input("Dati a="))
b= float(input("Dati b="))
c= float(input("Dati c="))
if ((a>0) and (b>0) and (c>0)):
if ((a+b>c) and (a+c>b) and (b+c>a)):
if ((a==b) and (a==c) and (b==c)):
print ("triunghi -Echilateral")
elif ((a==b) or (a==c) or (b==c)):
print("triunghi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/11/11 9:00 下午
# @Author : whp
# @File : 152.乘积最大子数组.py
from typing import List
class Solution:
def maxProduct(self, nums: List[int]) -> int:
res = float("-inf")
imax, imin = 1, 1
for i in range(len(nums)):
if... |
# -*- coding: utf-8 -*-
"""
74.搜索二维矩阵
从右上角开始
"""
from typing import List
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
# 从右上角开始
h = len(matrix)
if h == 0:
return False
w = len(matrix[0])
if w == 0:
return Fal... |
def Fib(n):
if n <= 0:
print("Run Again")
elif n == 1:
return 1
elif n == 2:
return 1
else:
return Fib(n-1)+Fib(n-2)
n = int(input('Please Enter n: '))
print(Fib(n))
|
import itertools as it
import numpy as np
'''
Tools for computing the viable set (in state-action space) and viability kernel (in state space) of a dynamical system. Note, all methods appended with `_2D` are specific to 2D systems and deprecated. They are left here since they are a lot easier to read, in case you're i... |
##########################################################
# CS217: telephoneNumber
# Assignment: Lab5
# Author: James Burch
# Date: 11/29/2016
# Filename: telephoneNumber.py
# Purpose:
#
##########################################################
# python model of a basic telephone... |
def mergeSort(list) :
if len(list) > 1:
mid = len(list) // 2
left = list[:mid]
right = list[mid:]
print("left : ", left)
mergeSort(left)
print("right : ", right)
mergeSort(right)
i = 0
j = 0
k = 0
while i < len(left) and j ... |
# -*- coding: utf-8 -*-
def merge_and_count_split_inv(B, C):
"""
>>> merge_and_count_split_inv([1, 3, 5], [2, 4, 6])
([1, 2, 3, 4, 5, 6], 3)
>>> merge_and_count_split_inv([1, 3, 5], [2, 4, 6, 7])
([1, 2, 3, 4, 5, 6, 7], 3)
>>> merge_and_count_split_inv([1, 3, 5, 6], [2, 4, 7])
([1, 2, 3,... |
# -*- coding: utf-8 -*-
class BinarySearchTreeNode:
def __init__(self, key=None, parent=None, left=None, right=None):
self.key = key
self.parent = parent
self.left = left
self.right = right
def __repr__(self):
return "%s" % (self.key)
def __bool__(self):
r... |
# Lista 5
# Questao A
x = 2
y = 5
if y > 8:
y = y * 2
else:
x = x * 2
print (x + y)
|
# Questao 4
# 4. Faça um Programa que leia três números e mostre o maior deles.
n1 = float(input('Digite o valor 1: '))
n2 = float(input('Digite o valor 2: '))
n3 = float(input('Digite o valor 3: '))
if n1>n2 and n1>n3:
maior = n1
elif n2>n1 and n2>n3:
maior = n2
else:
maior = n3
print('O maior nume... |
# Questao 2
# 2. Sorteie 20 inteiros entre 1 e 100 numa lista.
# Armazene os números pares na lista PAR e os números ímpares na lista IMPAR. Imprima as três listas.
import random
listaInteira = []
listaPar = []
listaImpar = []
for i in range(20):
n = random.randint(1,100)
listaInteira.append(n)
if n... |
"""
ftp 客户端
c/s模式 发送请求 获取结果
"""
from socket import *
import time
import sys
ADDR = ('127.0.0.1',8888)
# 具体请求方法实现在类中
class FTPClient:
def __init__(self,sockfd):
self.sockfd = sockfd
def do_list(self):
self.sockfd.send(b'L') # 发送请求
# 等待回复 YES NO
data = self.sockfd.recv(128).d... |
import collections
from random import randint
# # # Задание для 1 таблицы
# # def get_size(international_size, target):
# # dictionary = {
# # 'S': {
# # 'Russia': 40,
# # 'Germany': 34,
# # 'USA': 6,
# # 'France': 36,
# # 'UK': 8
# # },
#... |
import os
import csv
import sys
election_data_csv = os.path.join("Resources","election_data.csv")
with open(election_data_csv, newline="") as csvfile:
csvReader = csv.reader(csvfile, delimiter=",")
next(csvReader)
breakLine = "-------------------------"
totalVotes = 0
candidates = []
KhanVot... |
from Subject import Subject
class form():
def __init__(self, Recess_period,period_num:list,subjects={},max_sub_pd=2,assembly=[0,0]):
self.Recess_period=Recess_period
self.assembly=assembly
self.period_num=period_num
self.max_sub_pd=max_sub_pd
if subjects=={}:
se... |
dividend = 1
divisor = 1
count = 0
sign = 0
if dividend < 0 or divisor < 0:
sign = -1
else:
sign = 1
newdivident = abs(dividend)
newdivisor = abs(divisor)
while newdivident >= newdivisor:
newdivident = newdivident - newdivisor
count +=1
print(count * sign) |
from unittest import TestCase
from L8.board.tic_tac_toe_board import TicTacToeBoard
class TestTicTacToeBoard(TestCase):
def setUp(self):
self.under_test = TicTacToeBoard()
def test_init_board(self):
self.assertIsNotNone(self.under_test)
self.assertIsNotNone(self.under_test.current_s... |
def determineEthnicity(dataframe):
'''This method defines the ethnicity of the borrower (see Avery et al 2007)
The hierachy is as follows (if either app or co-app has declared):
Black, Hispanic, American Indian, Hawaiian/Pacific
Islander, Asian, white Non-Hispanic'''
imp... |
# sWAP cASE : Swap case in python
# From hackerrank.com
#
# Problem Statement:
# You are given a string and your task is to swap cases. In other words, convert
# all lower case letters and vice versa.
#
# Example:
# Input:
# HackerRank.com presents "Pythonist 2".
# Output:
# hACKERrANK.COM PRESENTS "pYTHONIST 2".
# S... |
import socket
import threading # manages differect threads (Threads means instances we use this lib for our msg handling stuff)
import sys
HEADER = 64
FORMAT = "utf - 8"
PORT = 5050 #defing a port for the server to bind to
DISCONNECT_MSG = "!DISCONNECT"
#defining the server ip address
##SERVER = "192.168.... |
#!/usr/bin/env python3
import os
import sys
count_GCgc = 0
if len(sys.argv) <2:
print('Usage: {} FILE'.format(os.path.basename(sys.argv[0])))
exit(1)
if not os.path.isfile(sys.argv[1]):
print('"{}" is not a file'.format(sys.argv[1]))
sys.exit(1)
for line in open(sys.argv[1]):
count_GC... |
from sys import argv
script, filename = argv
print(f"Wymażemy {filename}.")
print("Jeśli tego nie chcesz, wciśnij CTRL + C (^C).")
# print("Jeśli chcesz, wciśnij RETURN.")
# input("?")
print("Otwieranie pliku...")
target = open(filename, 'w')
print("Wykasowanie pliku. Do widzenia!")
target.truncate()
print("Tera... |
#####################################################################
#
#David Wang
#CAS CS320, Lapets
#Fall 2015
#Assignment 3, interpret.py
exec(open('parse.py').read())
Node = dict
Leaf = str
#tokens to look for: "Plus", "Variable", "Number"
#the sole purpose of evalTerm is to return a Number-dict object
def eval... |
###############################################################################
# If we list all the natural numbers from 1 to 10 that are multiples of 3 or 5,
# we would return 3, 5, 6 and 9.
# The sum of these multiples is 23.
#
# Print out...
# - All the multiples of 3 or 5 from 1-500.
# - The total number of multip... |
# ex7RandomNumGenerator
##############################################################################
#
# Create a program that allows input to guess a random number between 1 and 10
# (including 10). It will count your guesses (and print them) and will print a
# statement based on how many guesses it took to g... |
# Depending on your ability with Python: You can either create a baseball game
# based on one at bat where...
# pitches are thrown and they are either strikes or balls. 3 strikes and your
# out or 4 balls is a walk - whichever comes first that's it.
# It should start with an input 'p' to pitch - which initiates the ran... |
# Convert school to a list of 4 words, then use a for loop to print the words
# on 4 consecutive lines.
school = "Warren County Community College"
# Your code below:
school_list = school.split()
for i in range(len(school_list)):
print(school_list[i])
|
print("This is cool")
print("Water Bottle")
y = []
for x in range(5):
y.append("humor")
print(y) |
""" hash
"""
import connected_list as L
class ChainedHash:
""" Chained Hash using connected-list
hash functions
- int(k * m) if 0 <= k <= 1
- k % m
- int(m * ((k * A) % 1)) for 0 < A < 1
"""
def __init__(self, h, size=10):
self.T = []
for i in range(size):
self.T.append(L.List())
self.... |
""" Union-Find data-structure for disjoint-set
"""
class UF:
def __init__(self, size):
self.V = [i for i in range(size+1)] # list for all elements
self.size = size
for i in range(1, self.size+1):
self.V[i] = i
def __str__(self):
return str(self.V)
def union(self, u, v):
s1 = self.V[u]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.