text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
keys_1=[]
keys_2=[]
keys_3=[]
def checkAvail(se,pat):
patr=r''+pat
mf=re.search(patr,se)
'''if mf:
print "found"
else:
print "not found"'''
return mf
def rescoreSent(sen,keys):
scr=0;
for tri in keys['tri']:
... |
"""Test the convert functions to ensure that they work correctly."""
from pytest import approx
from converter import convert
from converter import units
def test_convert_celsius_to_fahrenheit():
"""Check to ensure that Celsius to Fahrenheit conversion works."""
temperature = 0
converted_temperature = co... |
class Gun:
def __init__(self,model):
self.model = model
self.bullet_count = 0
def add_bullet(self,count):
self.bullet_count+=count
def shoot(self):
if self.bullet_count<=0:
print('没有子弹了。。。')
return
self.bullet_count-=1
print("%s 发射子弹%d.... |
class BinaryHeap:
def __init__(self):
self.heap = [[-1, -1]]
def insert(self, e, p):
self.heap.append([e, p])
self._up_heap(len(self.heap) - 1)
def find_min(self):
return self.heap[1]
def del_min(self):
var = self.heap[1]
if len(self.heap) > 2:
... |
# TASK 8
# (HL) Define data structures to represent J1 programs, with pretty printers.
# e::= v|(e e...)|(if e e e)
# v::= number|boolean|prim
# prim ::= + | * | / | - | <= | < | = | > | >=
prim_list = ['+', '*', '/', '-', '<=', '<', '=', '>', '>=']
class E_v:
def __init__(self, n):
if str(n).i... |
# TASK 4
# Implement a big-step interpreter for J0.
# Connect to your test suite.
class Num:
def __init__(self, n):
self.n = n
def interp(self):
return self.n
def __str__(self):
return str(self.interp())
class Add:
def __init__(self, l, r):
self.l =... |
# (HL) Write a dozen test J5 programs that use the standard library.
prim_list = ['+', '*', '/', '-', '<=', '<', '=', '>', '>=', 'pair', 'fst', 'snd', 'inl', 'inr']
class x:
def __init__(self, x):
self.x = x
def __str__(self):
return str(self.x)
class V:
def __init__(self, v... |
# TASK 2
# Write a pretty-printer for J0 programs.
class Add:
def __init__(self, l, r):
self.l = l
self.r = r
def __str__(self):
return '(' + '+ ' + str(self.l) + ' ' + str(self.r) + ')'
class Num:
def __init__(self, n):
self.n = n
def __str__(self):
... |
"""day26_contiguous_array.py
Created by Aaron at 26-May-20"""
from typing import List
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
mx=0
count=0
dict={0: -1}
for x,val in enumerate(nums):
count-=1 if val==0 else -1
if count in dict:
... |
## 1. 集合的特性
## 1.1 set是无序的,没有下表索引,不支持列表的所有方法
type({1,2,3,4,5,6}) ## class 'set'
## 1.2 集合是不重复的
{1,1,2,2,3,3} ## {1,2,3}
## 2. 集合的方法
1 in {1,2,3} ## true
1 not in {1,2,3} ## false
## 集合的差集
{1,2,3,4,5,6} - {3,4} ## {1,2,5,6}
## 集合的交集
{1,2,3,4,5,6} & {3,4} ## {3,4}
## 集合的合集
{1,2,3,4,5,6} | {3,4,7} ## {1,2... |
# -*- coding: UTF-8 -*-
# randrange() 方法返回指定递增基数集合中的一个随机数,基数默认值为1
import random
# random.randrange ([start,] stop [,step])
# start -- 指定范围内的开始值,包含在范围内。
# stop -- 指定范围内的结束值,不包含在范围内。
# step -- 指定递增基数
print "randrange(100, 1000, 2): ", random.randrange(100, 1000, 2)
print "randrange(0, 1000, 3): ", random.randrange(0, 1... |
class Todo():
def __init__(self):
self.tasks = []
def add(self, task):
if task in self.tasks: # check if task was added
return "task already exists" # if added, return error
else:
self.tasks.append(task) # otherwise add task to list
def remove(self, task):... |
'''
The Antique Comedians of Malidinesia prefer comedies to tragedies.
Unfortunately, most of the ancient plays are tragedies. Therefore the
dramatic advisor of ACM has decided to transfigure some tragedies into
comedies. Obviously, this work is very hard because the basic sense of
the play mus... |
import numpy as np
from DecisionTree import ClassificationTree, RegressionTree
from abc import ABCMeta
from scipy.stats import mode
"""
References
----------
.. [1] Murphy, K. P. (2012). Machine learning: A probabilistic perspective.
Cambridge, MA: MIT Press.
.. [2] The Elements of Statistical Learning: Dat... |
"""
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the
array which gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a <= b <= c)
The solution set must not contain duplicate triplets.
For exa... |
# Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, current_room, items=[]):
self.name = name
self.current_room = current_room
self.items = items
def __str__(self):
if len(self.items) == 0:
retu... |
# Implement a class to hold room information. This should have name and
# description attributes.
class Room:
def __init__(self, **kwargs):
self.name = kwargs["name"]
self.description = kwargs["description"]
self.items = kwargs["items"]
# Declare all the rooms
all_rooms = {
'outside':... |
import periodictable as pt
absolute_difference_function = lambda list_value : abs(list_value - given_value)
# Because .isnumeric() returns false for floats, we create this new
# function that will allow us to check for floats
def is_number(string):
try:
float(string)
return True
except... |
# link - http://www.geeksforgeeks.org/greedy-algorithms-set-5-prims-minimum-spanning-tree-mst-2/
# April 18, 2017
class Prims:
def __init__(self):
self.__V = 5
def __get_min(self, dist, visited):
minimum = float("inf")
for i in range(0,self.__V):
if visited[i] is False a... |
# Felipe Martins Gomes
# Comp 20
# Exercício 7.26.13
# Programa compilado com PyCharm 2018.1.2
import turtle
import turtle
def fazer_janela (cor, titulo):
janela = turtle.Screen()
janela.bgcolor(cor)
janela.title(titulo)
return janela
def fazer_turtle (cor, tamanho):
tartaruga = turtle.Turtle()... |
# Felipe Martins Gomes
# Comp 20
# Exercício 15.12.3
# Programa compilado com PyCharm 2018.1.2
class Point:
""" Point class represents and manipulates x,y coords. """
def __init__(self, x=0, y=0):
""" Create a new point at the origin """
self.x = x
self.y = y
def slope_from_origi... |
from classes.Ability import Ability
from classes.Enemy import Enemy
class Chicken(Enemy):
# https://www.youtube.com/watch?v=miomuSGoPzI
name = "Chicken"
strength = 5
defense = 0.1
max_mana = 10
max_health = 50
def __init__(self, action_log):
super(Chicken, self).__ini... |
class ActionLog:
def __init__(self):
self.action_list = []
def write_action_log_to_file(self):
# with statement opens text file, writes action_list in file then closes file.
with open("log.txt",'w') as log:
log.writelines(self.action_list)
# Appends action_list... |
#!/usr/bin/python
from exercise_1 import fnv
class Dictionary:
def __init__(self, initial_capacity):
self.capacity = initial_capacity
self.hash_table = [[] for _ in range(initial_capacity)] # generate a list of empty lists with the give capacity
def insert(self, string):
position = s... |
#!/usr/bin/python
class MyComplex:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self): # can be used by invoking "print(...)" on a MyComplex instance
if (self.y >= 0):
sign = "+"
else:
sign = ""
return str(self.x) + "*i" + sign + str(self.y)
def AddSub(self, complexNumber):
add ... |
# list test
classmates = ['Micheal', 'Bob', 'Tracy']
classmates.append('Adam')
classmates.insert(1, 'Jack')
tmp = classmates.pop(1)
print("classmates:", classmates, '\nlen=%d' % len(classmates))
print(tmp)
# tuple test
classtuple = ('Micheal', 'Bob', 'Tracy')
tuple1 = (1, ['Micheal', 'Bob', 'Tracy'])
print(clas... |
#!/usr/bin/env python
from platform import python_version
print('This is Python version',python_version(),'\n')
mainString = "Python is the best language for String manipulation!"
print(mainString,'\n')
print(mainString[::-1],'\n')
print(mainString[::-2],'\n')
print(mainString.swapcase(),'\n')
print("The sentenc... |
import sys
lst = sys.argv[1:]
str1 = " ".join(lst)
summ = eval(str1.replace(" ","+"))
print("The sum of ",str1," is ",summ) |
#!usr/bin/env python
abbr = input('What is the three letter abbreviation of this course? ')
answer_status = 'wrong'
if abbr == 'ECL': answer_status = 'correct'
if answer_status == 'correct':
print('Your answer is correct')
else:
print('Your answer is wrong')
|
from string import ascii_lowercase
from typing import List, Tuple, Dict
class Stack:
def __init__(self, values=None):
self._values = values or []
def push(self, x):
self._values.append(x)
def pop(self):
return self._values.pop()
def copy(self):
return type(self)(self... |
# list_avg.py
# Average user-submitted numbers
# Jeff Smith
import math
# Create empty list
nums = []
# Ask user for numbers to evaluate
# Ensure all text is converted to lowercase
ele = input('Enter a number or type done: ').lower()
if ele == 'done':
# If user types 'done', exit
print('Ok. Perhaps another t... |
# lotto.py
# Pick 6-style lottery simulator
# Jeff Smith
'''
Steps
/Loop 100,000 times, for each loop:
/Generate a list of 6 random numbers representing the ticket
/Subtract 2 from the balance (for price of ticket)
/Find how many numbers match
/Add winnings from matches to balance
/After loop, ... |
# is => es
# is not => no es
frutas = ['carambola','guayaba','higo','melocoton']
fruta = 'carambola'
print(id(fruta))
print(id(frutas))
#el 'is' e 'is not' se usa mas que todo pra validar si las variables a comparar estan apuntando a la misma direccion de memoria o no
#las variables que son colecciones de datos como l... |
import os
import pathlib as Path
from collections import defaultdict
import csv
# os.walk() returns the generator which is of type path, directory, filename
#to check for the unique files in a csv
# from more_itertools import unique_everseen
# with open('1.csv','r') as f, open('2.csv','w') as out_file:
# out_file... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 23:29:36 2020
@author: Saurabh Kumbhar
"""
import turtle
def drawHangman(chance,exitStatus):
if(chance == 7):
#Step 1
turtle.circle(50)
if(chance == 6):
#Step 2
turtle.right(90)
turtle.fo... |
#OpenCV Resize image using cv2.resize()
#Resizing an image means changing the dimensions of it, be it width alone, height alone or both. Also, the aspect ratio of the original image could be preserved in the resized image. To resize an image, OpenCV provides cv2.resize() function.
#In this tutorial, we shall the sy... |
import cv2
import numpy as np
img =cv2.imread('lena.jpg')
height ,width =img.shape[:2]
rotation_matrix = cv2.getRotationMatrix2D((width/2,height/2),70,.5)
#getRotationMatrix2D is a function and rotate the img and (width,height ,angle,scaling factor)
#Means scaling factor will increase then img information destroy and ... |
def emptyMatrix(n):
result = []
for i in range(n):
result.append([])
for j in range(n):
result[i].append(0)
return result
def mul(X, Y):
result = emptyMatrix(len(X))
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
... |
import winsound, time, os, platform
def sound():
for i in range(2): # Number of repeats
for j in range(9): # Number of beeps
winsound.MessageBeep(-1) # Sound played
time.sleep(2) # How long between beeps
def alarm(n):
print()
print("Wait time:", n, "seco... |
#student1, fireman, and doctor are all parts of the human class.
class Human:
def __init__(self,Name, Gender, Age):
self.gender = Gender
self.age = Age
self.name = Name
def run(self):
print('{name} is running.'.format(name=self.name))
class Student1(Human):
def study(self)... |
'''
Created on Aug 21, 2017
@author: anhvu
'''
n = int(input());
edgeLen = 2;
for i in range(n):
edgeLen += edgeLen - 1;
print(pow(edgeLen, 2)); |
'''
Created on Jul 20, 2017
@author: anhvu
'''
from math import sqrt
triple = [int(i) for i in input().split(" ")];
n = triple[0];
w = triple[1];
h = triple[2];
diagonal = sqrt(w * w + h * h);
for j in range(n):
l = int(input());
# print(j, ":", n, ":", l);
if (l <= diagonal):
print("DA");
else:... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 13
@author: 陈佳榕
某个数字建筑领域公司的笔试题目
要求实现顺时针打印矩阵
比如对于矩阵
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
打印出1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
"""
def clockwisePrint(matrix):
"""
:param matrix:list[list],二维矩阵
:rtype :list,顺时针打印出来的矩阵元素
"""
left = top = 0... |
def compare(a,b,c):
if (a > b > c):
return a
elif (a > c > b):
return a
elif (b > a > c):
return b
elif (b > c > a):
return b
elif (c > a > b):
return c
else:
return c
a = int(input())
b = int(input())
c = int(input())
print(compare(a, b, c))
|
list = []
length = int(input())
list = input().split()
place = 1
x = 0
lowest = int(0)
while x < len(list):
if int(list[x]) <= int(lowest):
lowest = list[x]
place = x
x += 1
else:
x+=1
if len(list) > length:
print('Sua lista é maior que o esperado, mas:')
print('Menor ... |
def fatorial(n):
if n < 2:
return 1
if n % 2 == 1:
return n * fatorial(n-1)
else:
return fatorial(n-1)
n = int(input("Digite o valor que deseja saber o fatorial: "))
print(fatorial(n)) |
import queue #inbuilt stacks and queue
q = queue.Queue(maxsize = 10) #inbuilt queue
q.put(1)
q.put(2)
q.put(3)
q.put(4)
print(q.qsize())
while not q.empty():
print(q.get())
q = queue.LifoQueue() #inbuilt stack
q.put(1)
q.put(2)
q.put(3)
while not q.empty():
print(q.get())
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
def midpoint_linkedlist(head):
slow = head
fast = head
while fast.next and fast.next.next is not None:
slow = slow.next
fast = fast.next.next
return slow
def merge(head1,head2):
final_head = N... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
def midpoint_linkedlist(head):
slow = head
fast = head
while fast.next and fast.next.next is not None:
slow = slow.next
fast = fast.next.next
return slow
def ll(arr):
if len(arr)==0:
r... |
import queue
class Graph:
def __init__(self, nVertices):
self.nVertices = nVertices
self.adjMatrix = [[0 for i in range(nVertices)] for j in range(nVertices)]
def addEdge(self, v1, v2):
self.adjMatrix[v1][v2] = 1
self.adjMatrix[v2][v1] = 1
def __dfsHelper(self, sv, visited):
... |
import queue
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def printAtK(root,k,lst):
t=k
if root is None:
return
if k==0 or t==0:
print(root.data)
return 0
else:
printAtK(root.left,k-1,lst)
... |
'''
输入一个整数和进制,转换成十进制输出
输入格式:
在一行输入整数和进制
输出格式:
在一行十进制输出结果
'''
source=input().split(",")
out=int(source[0],int(source[1]))
print(out) |
'''
缩写词是由一个短语中每个单词的第一个字母组成,均为大写。例如,CPU是短语“central processing unit”的缩写。
函数接口定义:
acronym(phrase);
phrase是短语参数,返回短语的缩写词
裁判测试程序样例:
/* 请在这里填写答案 */
phrase=input()
print(acronym(phrase))
输入样例:
central processing unit
输出样例:
CPU
'''
def acronym(phrase):
output=''
for i in phrase.split():
first_str=i[0... |
'''
本题要求将输入的任意3个整数从小到大输出。
输入格式:
输入在一行中给出3个整数,其间以空格分隔。
输出格式:
在一行中将3个整数从小到大输出,其间以“->”相连。
'''
list1=input().split(" ")
list3=[]
for i in list1:
list3.append(int(i))
list1=list3
list2=[]
while list1:
MIN=list1[0]
for i in list1:
if i < MIN:
MIN=i
list2.append(str(MIN))
list1.remove... |
# self hace referencia al propio objeto, y sirve para diferneciar entre el ambito de clase
#y el ambito del método
class Galleta:
chocolate=False
def __init__(self):
print('Acabas de crear una galleta')
def untar_chocolate(self):
# chocolate=True #esto hace referencia a una variable de l... |
#designed and coded by Jacqueline St Pierre
class NPC:
def __init__(self, mobType, level=1, attack=1, defense=1, startX=0, startY=0):
if(level<1 or attack<0 or defense<0):
print("Invalid Input")
self.valid = False
else:
self.valid = True
self.level = level
self.mobType = mobType
self.attack = att... |
#https://pythonworld.ru/osnovy/tasks.html №5
def bank(deposit, years):
i = 0
while i < years:
deposit = deposit * 0.01 + deposit
i += 1
return round(deposit, 2)
if __name__ == "__main__":
deposit = int(input('Введите сумму депозита: '))
years = int(input('Введите количество лет... |
# Planner
# COMPLETED
# 1.0) Create chess board array, subclasses for colour and piece type, place in starting
# 1.1) Possible moves - Each piece is unique
# 2.0) Implement UI using pygame (drawing board, drawing pieces, alternating square colours)
# 1.2) Check mechanism - Valid moves (all of the other player's next... |
#!/usr/bin/env python
# -*-coding:utf-8-*-
def func(a,b,c=0,*args,**kw):
print 'a:',a
print 'b:',b
print 'c:',c
print 'args=',args
print 'kw=',kw
print '------这是一条开心的分割线--------'
func(1,2)
func(1,2,c=3)
func(1,2,3,'a','b','c')
func(1,2,3,'a','b',x=99)
args=(1,2,3,4)
kw={'x':99}
func(*args,... |
import math
import numpy
if __name__=='__main__':
arr = list(map(float, input("Enter the numbers\n").split(",")))
n = len(arr)
squareplus = 0.00
mean =0.00
rms = 0.00
for i in range(0,n):
squareplus = squareplus + (arr[i]**2)
mean = (squarepl... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv("Salary_Data.csv")
print(dataset)
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:,-1].values
print("<<<<<<<xxxxxxxxxxxxxxxx")
print(X)
print("<<<<<<<yyyyyyyyyyyyyyyy")
print(Y)
from sklearn.model_selection import train_tes... |
if __name__ == "__main__":
vowels = ('a', 'e', 'i', 'o', 'u')
# i = 0
# while i < len(vowels):
# print(vowels[i])
# i += 1
# for letter in vowels:
# print(letter)
# for i in range(10, 21, 2):
# print(i)
for i in range(5):
print('pre nested loop')
... |
import random
# roll = random.randint(1, 6)
# while True:
# print(roll)
# if roll == 4 or roll == 5:
# break
# roll = random.randint(1, 6)
# for i in range(1, 7):
# if i == 4 or i == 5:
# continue
# print(i)
# fruits = 'apples cherries blueberries blackberries'.split()
# for fr... |
"""
Tests for the Stack class.
"""
import unittest
from stack.stack import Stack, NumberOutOfRangeError
class StackTestCase(unittest.TestCase):
"""
This Case of tests checks the functionality of the implementation of Stack
"""
def test_new_stack_is_empty(self):
"""
Create an empty ... |
num = int(input("What's the number to check? "))
check = int(input("What's the number to divide by? "))
if num % 4 == 0:
print("It's a multiple of 4! :)")
elif num % check == 0:
print(str(num) + " is divisible by " + str(check))
else:
print(str(num) + " ain't divisible by " + str(check)) |
import Image
import argparse
def calc_pi(filename):
try:
img = Image.open(filename)
except:
print "Couldn't open image."
area = 0
rgb_img = img.convert('RGB')
rgb_values = rgb_img.load()
(width, height) = rgb_img.size
is_black = lambda (r,g,b): r==0 and g==0 and b==0
... |
import numpy as np
def compute_distances(features_instances, features_query):
"""
Compute euclidean distance.
computes the distances from a query house to all training houses.
The function takes two parameters:
(i) the matrix of training features and
(ii) the single feature ve... |
# Inheritance helps with reusing instance variables and instance methods
class Parent():
def __init__(self, last_name,eye_color):
print("Parent Constructor Called")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print("Last Name: "+self.last_name)
print("Eye Color: ... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
np.random.seed(0)
x = np.random.rand(100,1)
x_train = np.c_[np.ones((x.shape[0], 1)), x]
y = 2 + 3 * x + np.random.rand(100,1)
model = LinearRegression()
model.... |
l=int(input())
l1=[1,2,3,4,5,6,7,8,9,10]
if l in l1:
print("yes")
else:
print("no")
|
num = raw_input("if hillary clinton and donald trump go on a cruise togethor and the ship sinks who survives")
if num.lower()== "america":
print("You're correct")
else:
print("You're incorrect the correct answer was america") |
#Implementing the linked list class
class Node:
def __init__(self, x): # x is the value of the node
self.value = x
self.next = None
def append(self, next_node): # next_node is a Node
if self.next == None:
self.next = Node(next_node) # next_node is a number
else... |
box_w = int(raw_input('How wide is the box (an integer)? '))
box_h = int(raw_input('How high is the box (an integer)? '))
for i in range(0, box_h):
row = ''
for j in range(0, box_w):
if i != 0 and i != (box_h - 1):
if j == 0 or j == (box_w - 1):
row = row + '*'
el... |
class Contact():
def __init__(self, first, last, phone):
self.first = first
self.last = last
self.phone = phone
kyle = Contact('Kyle', 'Booth', '212-442-1373')
print kyle.phone
print kyle.first |
def sum(numbers):
total = 0
for number in numbers:
total += number
return total
print
print sum([10,3,34])
print |
string = raw_input('A string for me to Leet, please: ')
string_length = len(string)
string_leet = ''
leet = []
leet_chars = [A,E,G,I,O,S,T]
leet_nums = [4,3,6,1,0,5,7]
for i in range(0, string_length-1):
for j in range(0, len(leet_chars)):
if string[i] == leet_char[j]:
string[i] = leet_num[j]
s... |
def positives(numbers):
positive_nums = []
for number in numbers:
if number > 0:
positive_nums.append(number)
return positive_nums
print
print positives([10,-3,-34,2,57])
print |
#Tam Hoang
# July 13 2018
#Having a secure password is a very important practice,when much of our information is stored online.
#Write a program that validates a new password, following these rules:
#• The password must be at least 8 characters long.
#• The password must have at least one upper case and one lowercase l... |
# -*- coding: utf-8 -*-
# Written by Sam Lööf <saml@kth.se>
from math import sqrt
# Returnerar medelvärdet för lista
def mean(lista):
return float(sum(lista)) / len(lista)
# Returnerar standardavvikelsen för lista
def standardDeviation(lista):
summa = 0.0
medel = mean(lista)
for i in l... |
stevilka1 = int(input("Vnesi prvo številko: "))
operation = input("Izberi računsko operacijo, ki je lahko +, -, * ali /: ")
stevilka2 = int(input("Vnesi drugo številko: "))
if operation == "+":
print(stevilka1 + stevilka2)
elif operation == "-":
print(stevilka1 - stevilka2)
elif operation =="... |
x,y,z=map(int,input().split())
if x>z and x>y:
print("x is greater")
elif y>z:
print("y is greater")
else:
print("z is greater")
|
a=int(input())
b=a**0.5
if(b%2==0):
print("yes")
elif(a==2):
print("yes")
elif(a==1):
print("yes")
else:
print("no")
|
'''
Read and filter CSV file using standard library
'''
#%%
# standard library
import csv
from pprint import pprint as pp
fn = 'data/CLEAN1A.csv'
#%% quick-and-dirty
data = list(csv.reader(open(fn, encoding="utf-8-sig")))
pp(data[:5])
#%% better
with open(fn, encoding="utf-8-sig") as csvfile:
data = list(csv.r... |
CACHE = {}
#return True after setting the data
def set(key, value):
CACHE[key] = value
return True
#return the value for key
def get(key):
return CACHE.get(key)
#delete key from the cache
def delete(key):
if key in CACHE:
del CACHE[key]
#clear the entire cache
def flush(... |
def printStar(num):
for i in range(1, num + 1, 1):
print(" " * (num - i), end = "")
print("*" * i)
n = int(input(""))
printStar(n)
|
def mean(numbers):
return float(sum(numbers))/len(numbers)
print('введите числа:')
nums=map(int, input().split())
l=list(nums)
print(l, type(l))
print("среднее =" +str(mean(l)))
l = [1, 2, 3]
for e in l:
print(e)
m = np.random.randint(1, 20, (10, 10))
def minor(m, i, j):
return [row[:j] + row[j + 1... |
#!usr/bin/env python
#-*-coding:utf-8 -*-
#导入SQLITE3模块
import sqlite3
#SQLite数据库名
DB_SQLITE_NAME="test.db"
def sqliteHandler():
#连接数据库
try:
sqlite_conn=sqlite3.connect(DB_SQLITE_NAME)
except sqlite3.Error,e:
print "连接sqlite3数据库失败", "\n", e.args[0]
return
#获取游标
sqlite_cu... |
print "Welcome to the English to Pig Latin translator!"
original = raw_input("What word would you like to be translated?")
if len(original) > 0 and original.isalpha():
print original
else:
print "empty"
|
from tkinter import *
class Aplicacion:
def __init__(self):
self.win = Tk()
self.win.title("Mi primer App")
self.etq1 = Label(self.win,text="Nombre: ")
self.etq1.grid(column=0,row=0)
self.dato1 = StringVar()
self.nombre = Entry(self.win, textvariable=self.dato1)
... |
# FizzBuzz Game #
# The Following code will run the FizzBuzz Game
# However, unlike the original I have included Bang when the number 4 appears
for i in range(1, 101):
output = ""
if i % 3 == 0:
output += 'Fizz'
if i % 5 == 0:
output += 'Buzz'
if i % 4 == 0:
... |
import math
p=int(input(""))
b=int(input(""))
d=int(round((math.atan(p/b))*180/(math.pi)))
deg=str(d)+"°"
print(deg) |
def print_rangoli(n):
string="abcdefghijklmnopqrstuvwxyz"
Lest=list(string)
k=n
c=2
L=[]
for i in range(k-1,-1,-1):
star=(2*n)-c
List=[]
if i==(k-1):
List.append(Lest[k-1])
for j in range (n-1,i,-1):
List.append(Lest[j])
List.append("-")
f="-"*star
if i!=k-1:
l=f+"".join(List)+string[i]+""... |
class Node:
def __init__(self,data):
self.data = data
self.next = None
def Insert_Node(root, data):
if(root == None):
root = Node(data)
return root
root.next = Insert_Node(root.next,data)
return root
def Remove_Node(root):
if(root.next == None)
head = None
head = In... |
def subsets(nums: List[int]) -> List[List[int]]:
def explore(chosen, remaining, res):
if not remaining:
res.append(chosen[:])
return
d = remaining.pop(0)
#choose
chosen.append(d)
#explore
explore(chosen, rem... |
#29211757 Kevin Yin and 72238150 Jenny Kim, Project 2
#This module contains the interface for a local Connect 4 game played on the console.
from connectfour import *
from collections import namedtuple
ConnectFour_Turn= namedtuple('ConnectFour_Turn', 'gamestate turntype column')
def playgame():
game_stat... |
'''
Question Description :-
Consecutive Characters
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.
Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of ... |
'''
Question Description :-
Convert Binary Number in a Linked List to Integer
Given head which is a reference node to a singly-linked list.
The value of each node in the linked list is either 0 or 1.
The linked list holds the binary representation of a number.
Return the decimal value of the number in the lin... |
#!/usr/bin/env python
import sys
def select_list_by_value(select_list, value):
select_list.select_by_visible_text(value)
def select_list_by_index(select_list, index):
try:
select_list.select_by_visible_text(select_list.options[index].text)
except IndexError:
print("ERROR: Option #: {} d... |
import argparse
import sys
class SubArgumentParser:
"""
Example usage:
parser = SubArgumentParser()
parser.add_subcommand('fetch', help='git fetch',
callable=git_func)
# parser.fetch is an argparse.ArgumentParser for everything after subcommand.
parser.fetch.add_argu... |
# futval-periods.py
# by Joshua Pedro. November 20th, 2018
# A program to compute the value of an investment
# carried 10 years into the future
def main():
print("This program calculates the future value")
print("of a x-year investment.")
principal = int(input("Enter the principal balance: "))
periods... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.