text stringlengths 37 1.41M |
|---|
import numpy as np
def to_pixel_no(coordinate):
row = coordinate[1]
column = coordinate[0]
if row % 2 == 0:
return 20 * row + column
else:
return 20 * row + 19 - column
def pixel_to_matrix_cord(pixel_no):
row = int(pixel_no / 20)
column = pixel_no % 20
... |
from random import random
from random import choice
from collections import deque
from sys import argv
import re
# Global Vars
row = 0
col = 0
num_blocking_squares = 0
word_dictionary = ""
# Unless otherwise noted, board is a string for inputs
# Generates empty crossword board (string with boundaries rep... |
class Guess:
def __init__(self, word):
self.secretWord = word
self.numTries = 0
self.guessedChars = []
self.currentStatus = '_'*len(self.secretWord)
self.currentword = '_'*len(self.secretWord)
self.indexnumL =[]
def display(self):
return 'Current: '+ se... |
#fname=input("Enater file name ")
handle=open("mbox-short.txt")
lst=list()
count=0
for line in handle:
line=line.rstrip()
if not line.startswith("From "):continue
print(line)
lst=line.split()
#print(lst[1])
count+=1
print("There were", count, "lines in the file with From as the first word")
|
import pandas as pd
import matplotlib.pyplot as plt
# 使用matplotlip呈现店铺总数排名前十的国家
file_path = "./starbucks_store_worldwide.csv"
df = pd.read_csv(file_path)
print(df.info())
country_data = df.groupby(by="Country")
print(country_data)
country_brand_count = country_data["Store Number"].count().sort_values(ascending=False)... |
import pandas as pd
df = pd.read_csv("./dogNames2.csv")
# print(df.head())
# print(df.info())
# dataframe中排序的fangfa,默认升序,可以用ascending来使其逆序
# 按照某一列进行排序
# df = df.sort_values(by="Count_AnimalName")
df = df.sort_values(by="Count_AnimalName", ascending=False)
# print(df)
# pandas取行或者列的注意事项
# - 方括号中写数组,表示取行,对行进行操作
# - 方... |
import math
def optional_params(x, y=0):
return x + y
def optional_params_pitfalls(x, y=[]):
y.append(x)
return y
def optional_params_pitfalls_alternate(x, y=None):
if y is None: y = []
y.append(x)
return y
def using_args(*numbers_to_sum):
return sum(numbers_to_sum)
def using_kwargs(**... |
import numpy as np
def addition_feature_combiner(fv_word1, fv_word2):
"""
Returns the element-wise addition of the feature vectors for each word.
:param fv_word1: the feature vector for the first word of the co-occurrence pair
:param fv_word2: the feature vector for the second word of the co-occurrenc... |
import pandas as pd
import numpy as np
import multiprocessing
__all__ = ['parallel_groupby']
def parallel_groupby(gb, func, ncpus=4, concat=True):
"""Performs a Pandas groupby operation in parallel.
Results is equivalent to the following:
res = []
for (name, group) in gb:
res.append(func(... |
def main():
text = input("Text: ")
letter = count_letter(text)
words = count_words(text)
sentence = count_sentence(text)
# Coleman-Liau指数
L = int(letter) * 100 / int(words)
S = int(sentence) * 100 / int(words)
index = float(0.0588 * L - 0.296 * S - 15.8)
# 四捨五入
if index % 1 <... |
ticket = 37750;
def ticket_cal(adults,children):
cost = ticket*adults+(ticket/3)*children
with_tax_cost = cost + (cost*0.07)
final_cost = with_tax_cost - (with_tax_cost*0.1)
return final_cost
a = int(input("Enter the number of Adults "))
c = int(input("Enter the number of childrens"))
... |
from matplotlib import pyplot as plt
#%matplotlib inline
#plotting to our canvas
x = [5,8,10]
y = [12,16,6]
x2 = [6,9,11]
y2= [6,15,7]
#plt.plot(x, y)
plt.plot(x,y,'g',label="girls",linewidth = 3)
plt.plot(x2,y2,'r',label="boys",linewidth = 3)
#plt.plot([1,2,9],[1,9,6],[1,9,6])
#showing waht we plotted
plt.tit... |
#!/usr/bin/env python3
import sys
from multiprocessing import Process,Queue
queue = Queue(maxsize=5)
def f1():
queue.put('hello shiyanlou')
def f2():
#if queue.empty() is not True:
data = queue.get()
print(data)
#else:
# print('Queue is empty!')
def main():
Process(target=f1).start()
... |
def factorial(n):
return 1 if(n==0 or n==1) else n*factorial(n-1)
num =5
print("factorial of ",num,"is",factorial(num))
|
def printaph(list1):
z = len(list1)
maxx = 0
#ls = []
for i in range(len(list1)):
if(maxx<len(list1[i])):
maxx = len(list1[i])
#print(maxx)
for i in range(maxx):
for j in range(len(list1)):
if(len(list1[j])<maxx):
if(len(list1[j])+i>=maxx):... |
def result(char):
mean = int(len(char)/2)
print(char[0:mean:2])
cases = int(input())
for i in range(0,cases):
n=input()
result(n)
|
from tkinter import Tk
from tkinter import Label
import time
import sys
root = Tk()
root.title = ("Digital Clock")
def get_time():
timeVar = time.strftime ('%H:%M:%S %p')
clock.config(text=timeVar)
clock.after(200, get_time)
clock = Label(root, font = ("Calibri",90), background = "black", foreground = "w... |
"""
Es la estructura más simple que proporciona Pandas,
y se asemeja a una columna en una hoja de cálculo de Excel.
Un objeto Series tiene dos componentes principales:
un índice y un vector de datos.
Ambos componentes son listas con la misma longitud.
"""
import pandas as pd
import numpy as np
indice = range(5... |
#
def person(name,*data):
print(name)
print(data)
person('Pranik',21,'Amravati',7058187989)
#Code2
def person1(name,**data):
print(name)
for i,j in data.items():
print(i,j)
person1('Pranik',21,'Amravati',7058187989) |
class Board:
# INIT
def __init__(self, screen = None, hint = True):
self.__board = self.__clean_board() # Initializing an empty board
self.__player = 0 # Initializing the first player (white)
self.__valid_moves = self.__get_valid_moves() # Have to know
self.__screen = screen # C... |
import turtle
def draw_squares(some_turtle):
for i in range(1,5):
some_turtle.circle(100)
some_turtle.right(40)
def draw_circles(some_turtle):
for i in range(1,5):
some_turtle.circle(100)
some_turtle.right(40)
def draw_shapes():
#BG COLOR
window = ... |
from random import choice
#from random method import choice
#choice will randomize word from list below
def open_and_read_file(file_path):
"""Takes file path as string; returns text as string.
Takes a string that is a file path, opens the file, and turns
the file's contents as one string of text.
""... |
def create_num(all_num):
print("------1-----")
a,b = 0,1
current_num = 0
while current_num < all_num:
print("------2-----")
# print(a)
yield a #如果函数当中有yield语句,那么这个就不再是函数,而是一个生成器的模板
a,b = b, a+b
current_num+=1
print("------3-----")
#如果在调用函数的时候,发现函数中与yield,那么此时不再是调用函数,而是创建一生成器
obj = crea... |
# Shi-Tomasi Algorithm to find specified amount of corners
# R = min(λ1, λ2)
import cv2 as cv
import numpy as np
if __name__ == "__main__":
img = cv.imread('../../assets/test10.jpg')
img = cv.resize(img, None, fx=.5, fy=.5)
cv.imshow("Original Image", img)
gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRA... |
# captcha simulation / bot recognizing simulation
# asking user to select the quarter with no face in
# a tiny project with use of mouse handling in opencv
import cv2 as cv
import numpy as np
GREEN = (0, 153, 0)
RED = (0, 0, 255)
TARGET = None # number of the quarter with no face
DETECTED = -1 # -1: not ... |
# -*- coding: utf-8 -*-
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
... |
# List teman rio sebanyak 10
chingu = ['Sonny', 'Bagus', 'Attar', 'Alvin', 'Ano', 'Ryan', 'Raka', 'Nanda', 'Wahyu', 'Tito']
# menampilakan list indeks nomor 1,3,5
print(chingu[1], chingu[3], chingu[5])
# Mengganti list 2,5,9
chingu[2] = 'Ahmed'
chingu[4] = 'Rahmat'
chingu[9] = 'Rizal'
print(chingu)
# Menambah 2 tem... |
al = input("Sayı Giriniz: ")
bul = len(str(al))
say = 0
for i in range(bul):
say = say + int(al[i]) ** int(bul)
if say == al:
print("{} armstrong sayısıdır".format(al))
else:
print("{} armstrong sayısı değildir.".format(al))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 删除字符串中不需要的字符
s = ' hello world \n'
print(s.rstrip() + '|')
print(s.lstrip())
t = '-----hello====='
print(t.lstrip('-'))
print(t.lstrip('-h'))
print(t.strip('-='))
# with open('README.md') as f:
# lines = (line.strip() for line in f)
# for line in lines: # 这样会报错 Val... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 过滤序列元素
from itertools import compress
mylist = [1, 4, -5, 10, -7, 2, 3, -1]
print [i for i in mylist if i > 2]
print (i for i in mylist if i > 2)
print [i if i > 0 else 0 for i in mylist]
print (i if i > 0 else 0 for i in mylist)
values = ['1', '2', '-3', '-', '4', '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 删除序列相同元素并保持顺序
# hashable
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
def dedupe2(items, key=None):
seen = set()
for item in items:
val = key(item) if key els... |
def max2(x,y):
if x > y : print(x)
else : print(y)
def min2(x,y):
if x< y : print(x)
else : print(y)
def my_max(x):
print(max(x))
def my_min(x):
print(min(x))
max2(4,8)
min2(4,8)
max2('a','b')
max2([1,5],[2,4])
my_max([1,2,3])
my_min('addfasfd1')
|
#Tugas no 1 prongkom minggu 3
#list 10 konco dulur
konco = ['ilham','fairuz','fasya','tasya','yayuk',
'kinor','azzam','dio','maul','maman']
#menampilkan isi list temen no 4,6,7
print(konco[4])
print(konco[6])
print(konco[7])
#Ganti nama konco list 3 5 9
konco[3] = 'nadhira'
konco[5] = 'noor'
k... |
values = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
numbers = ['MCMXC', 'MMVIII', 'MDCLXVI']
def solution(roman):
decimal = 0
for i in range(len(roman)-1):
if (value := values[roman[i]]) >= values[roman[i+1]]:
decimal += value
e... |
import pandas as pd
df = pd.read_csv('GPAdata.csv')
suma = 0
sumb = 0
sumc = 0
sumf = 0
for index,item in df.iterrows():
if item['評価'] == 'A':
suma += item['単位数']
elif item['評価'] == 'B':
sumb += item['単位数']
elif item['評価'] == 'C':
sumc += item['単位数']
elif item['評価'] == 'D':
... |
from tkinter import *
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
engine=pyttsx3.init('sapi5')
voices=engine.getProperty('voices')
engine.setProperty('voice',voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def w... |
#!/usr/bin/env python3
from local_align import local_align, all_alignment
class recordAligner:
#These default delimiters render as ^^, ^_, and the space character in tools such as less
#They are the delimiters for:
#30/^^: classificationRecordSet
#31/^_: classificationRecord
#32/ : classificatio... |
vowels = ["A", "E", "I", "O", "U"]
string = "facetiously"
vowel_count = 0
for char in string.upper():
if char in vowels:
vowel_count += 1
print("The number of vowels is: " + str(vowel_count))
|
import matplotlib.pyplot as plt
x=[1,2,3,10,8,9,5]
y=[1,2,3,4,5,6,7]
plt.scatter(x,y , label = 'scatter' , color='g' ,s=25, marker='x')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('Scatter plot')
plt.legend()
plt.show()
|
## python 2.7 by Jeremy Benisek
# How do you feel?
# Start with 0 and False
ageinted = 0
ageintstatus = False
# Input your name
name = raw_input("Enter your name please: ")
# Print a Welcome message with inputed name
print "Hello and Welcome",name
# While True, if false re-enter age with a number
while True:
age =... |
Score = raw_input("Enter Grade Score: ")
try:
ScoreFloated = float(Score)
if ScoreFloated >= 0.9:
print "A"
elif ScoreFloated >= 0.8:
print "B"
elif ScoreFloated >= 0.7:
print "C"
elif ScoreFloated >= 0.6:
print "D"
elif ScoreFloated < 0.6:
print "F"
excep... |
'''
Kullanıcının girdiği iki sayının ortalamasın alan program
1 Başla
2 Sayı Al "Birinci Sayıyı Girin:", sayi1
3 Sayı Al "İkinci Sayıyı Girin:", sayi2
4 ort = (sayi1+sayi2)/2
5 Yaz ort
6 Bitir
'''
'''
15. Satır: input() fonksiyonu ile kullanıcıdan veri alınıyor.
bu veri int() fonksiyonu ile tamsayıya dönüştürülüyor ve... |
import math # matematik fonksiyonlarını ugulamada kullanabilmek için math kütüphanesini ekliyoruz
'''
Öğenci vize notunu girdikten sonra dersi geçmek(50) için alması gereken notu yazan program
'''
vize = 100
while vize >= 0 and vize <= 100:
vize = int(input("Vize Notunuz:"))
final = 0
final = math.ceil((40... |
"""
Test script using pytest for validator_if
Author: Varisht Ghedia
"""
from validator import validate_if
def test_size_one():
"""
Test that password is of size 1.
"""
assert validate_if("a") == True
def test_size_twentyone():
"""
Test that password cannot be of size more than 20
"""
... |
import random
ai = random.randint(1,4)
print("gissa på ett av valen från menyn")
meny = 0
while meny != 5:
print("tryck på 1 för att gissa på hjärter ♥")
print("tryck på 2 för att gissa på spader ♠ ")
print("tryck på 3 för att gissa på klöver ♣ ")
print("tryck på 4 för att gissa på ruter ♦ ")
pri... |
from sqlite3.dbapi2 import Cursor
import mysql.connector as mysql
import csv
connection = mysql.connect(
host='localhost',
user='root',
password='',
database='sales'
)
cursor = connection.cursor()
create_query = '''
CREATE TABLE salesperson(
id INT(255) NOT NULL AUTO_INCREMENT,
firstname VAR... |
#Panda Data Frames
import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101) #Defining a seed for the random func
df = pd.DataFrame(randn(5,4),index="A B C D E".split(),columns ="W X Y Z".split()) #the randn would create a 5x4 Matrix with random values and index just like in Series but... |
"""
Умова: Нехай число N - кількість хвилин, відрахованих після півночі. Скільки
годин і хвилин буде показувати цифровий годинник, якщо за відлік взяти 00:00?
Програма повинна виводити два числа: кількість годин (від 0 до 23) і кількість
хвилин (від 0 до 59). Візьміть до уваги, що починаючи з півночі може пройт... |
number1 = int(input("Enter the first number:"))
number2 = int(input("Enter the second number"))
number3 = int(input("Enter the third number"))
if (number1 < number2) and (number2 < number3):
print(number1)
elif (number1 < number3) and (number3 < number2):
print(number1)
elif (number2 < number1) and (numb... |
# Modified starter code from Laura
# %%
# Step 1: Import modules used in this script
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn.linear_model import LinearRegression
import datetime
import json
import urllib.request as req
import urllib
import ... |
# %%
import os
import numpy as np
import pandas as pd
import matplotlib as plt
# we can name our rows and columns an refer to them by name
# we don't have to have just 1 datatype
# Three things - Series, DataFrames, Indices
# loc is using row names, iloc is using row numbers
# %% 9/29 in class exercise
data = np.one... |
def add_fns(f_and_df, g_and_dg):
"""Return the sum of two polynomials."""
def add(n, derived):
return f_and_df(n, derived) + g_and_dg(n, derived)
return add
def mul_fns(f_and_df, g_and_dg):
"""Return the product of two polynomials."""
def mul(n, derived):
f, df = lambda x: f_and_df(... |
def g(n):
"""Return the value of G(n), computed recursively.
>>> g(1)
1
>>> g(2)
2
>>> g(3)
3
>>> g(4)
10
>>> g(5)
22
"""
if n <= 3 :
return n
else :
return g(n-1) + 2* g(n-2) + 3 * g(n-3)
def g_iter(n):
"""Return the value of G(n), c... |
## Trees, Dictionaries ##
#########
# Trees #
#########
import inspect
# Tree definition - same Data Abstraction but different implementation from lecture
def tree(root, branches=[]):
#for branch in branches:
# assert is_tree(branch)
return lambda dispatch: root if dispatch == 'root' else list(branches)
... |
while True:
# main program
while True:
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print('Invalid input.')
if answer == 'y':
continue
else:
print('Goodbye')
break |
# 기존 계획(Naver Shopping API 활용) 폐지, webbrowser 모듈 활용, url open에 집중
# User가 후기를 본 후 제품명을 입력하면, 해당 제품의 Naver Shopping 사이트로 연결
import io
import os
import sys
import webbrowser as wb
class Shopping:
def goToShopSite(self):
url = 'https://search.shopping.naver.com/search/all?query=' + self.finalProduct
... |
num = int(input("Input the number for calculating the factorial:").strip())
fact = 1
i=1
print(type(num))
while i <=num:
fact = fact*i
i = i + 1
print (fact)
|
# -*- coding: utf-8 -*-
"""
Created on Sat May 2 01:07:45 2020
@author: Moon
"""
import csv
# read data
with open('C:/Users/ED/Desktop/covid/COVID-19/Date/list_state.csv', newline='') as csvfile:
rows = csv.reader(csvfile)
for list_state in rows:
print(list_state)
with open('C:/Users/ED/Desktop/c... |
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#loading the dataset
dataset=pd.read_csv('Social_Network_Ads.csv')
x=dataset.iloc[:,[2,3]].values
y=dataset.iloc[:,4].values
#Visualizing the dataset
dataset.iloc[:,[2,3]].count().plot(kind='bar')
#Describ... |
# Write your function, here.
def char_count(target, string):
res = 0
i = 0
while i < len(string):
char = string[i]
if char == target:
res += 1
i += 1
return res
print(char_count("a", "App Academy")) # > 1
print(char_count("c", "Chamber of Secrets")) # > 1
print(ch... |
# Write your function, here.
def is_empty(dictionary):
return len(list(dictionary)) == 0
# Solution 2
def is_empty(d):
return not d
print(is_empty({})) # > True
print(is_empty({"a": 1})) # > False
|
# Write your function, here.
def is_valid_hex_code(code):
if code[0] != "#" or len(code) != 7:
return False
i = 1
while i < len(code):
c = code[i].lower()
if not c.isdigit():
if c != "a" and c != "b" and c != "c" and c != "d" and c != "e" and c != "f":
re... |
# It's time to put your knowledge of lists, tuples and dictionaries together. In this exercise, you will complete the basic statistics calculations for
# Minimum
# Maximum
# Mean
# Median
# Mode
# Follow the instructions in the code comments. Be sure to test your work by running your code!
# You will likely need to lo... |
def cap_space(string):
res = ""
i = 0
while i < len(string):
char = string[i]
if char.isupper():
res += " "
res += char
i += 1
return res.lower()
print(cap_space("helloWorld")) #> "hello world"
print(cap_space("iLoveMyTeapot")) #> "i love my teapot"
print(cap_space("stayIndoors")) ... |
# Create your function, here.
def increment(num):
return num + 1
print(increment(0)) # > 1
print(increment(9)) # > 10
print(increment(-3)) # > -2
|
# dictionary tut
dict = {"key" : "val", "jey2":"val"}
dict["key"] # prints out "val" associated with key
#dictionaries are non sequential so printing a dict would give different results every time it is done
#dictionary problem
ques = "Enter Customer ? "
ques2 = "Customer Name: "
dict_list = []
while (True):
ans... |
import socket
from typing import Any
def port_validation(value: Any, check_open: bool = False) -> bool:
#check if the port is correct
try:
# converting to int number
value = int(value)
if 1 <= value <= 65535:
# if Port Busy
if check_open:
... |
def convert_to_minutes(num_hours):
"""(int) -> int
Return the number of minutes there are in num_hours hours.
>>> convert_to_minutes(2)
120
"""
result = num_hours * 60
return result
def convert_to_seconds(num_hours):
"""(int) -> int
Return the number of seconds there are in num_hours hours.
>>> convert_to_mi... |
x=3
if(x%2!=0)
print("x is odd")
else:
print("x is invalid")
|
#https://www.interviewbit.com/problems/combinations/
def combinations(A,B):
final_arr = []
combinationsUtil(A,B,1,0,[],final_arr)
return final_arr
def combinationsUtil(A,B,num,level,cur_list,final_arr):
if level==B:
final_arr.append(cur_list)
return
for i in xrange(num,A+1):
... |
def squareRoot(A):
if A <= 1:
return A
start = 0
end = A
while start <= end:
mid = (start+end)/2
res = A/mid
if res == mid:
return mid
if res < mid:
end = mid-1
if res > mid:
start = mid+1
return mid if mid*mid... |
#https://www.interviewbit.com/problems/combination-sum-ii/
"""
def combSumII(A,B):
A.sort()
print A
final_result = []
combSumIIUtil(A,0,B,[],final_result)
#combSumIIUtil(A,B,[],final_result)
return final_result
def combSumIIUtil(A,cur_sum,target,stri,final_result):
#print "A:",A,"cur_sum:",... |
#https://www.interviewbit.com/problems/counting-triangles/
#Find all possible triangle
def greatersum(A):
n = len(A)
if n < 3:
return 0
A.sort()
#Below approach is based on the fact that for A<=B<=C, to be a valid triangle
#Following condition must be true, A+B > C
count = 0
low = ... |
#https://www.interviewbit.com/problems/nearest-smaller-element/
INF = 10**10
def nearestSmallerElem(A):
stack = []
top = -1
G = []
for val in A:
while top >= 0 and stack[top] >= val:
stack.pop()
top -= 1
if top == -1:
G.append(-1)
else:
... |
#https://www.interviewbit.com/problems/sorted-permutation-rank/
def sortedPermRank(A):
strLookup = sorted(list(A))
n = len(A)
print strLookup,n
rank = i = 0
lookup = []
while i < n:
x = strLookup.index(A[i])
minus = 0
print "lookup:",lookup,
for j in lookup:
... |
def primeSum02(A):
if A%2!=0:
return
i = 2
while i <= A/2:
if prime02(i) and prime02(A-i):
return i,A-i
i += 1
return
def prime02(x):
if x<2:
return False
if x==2:
return True
if x%2==0:
return False
p = 3
while p*p <= x:
... |
def mergeIntervals(A,B):
n = len(A)
temp = [[A[i],B[i]] for i in range(n)]
temp = sorted(temp,key=lambda item:item[0],reverse=True)
print temp
stack = []
while len(temp)>1:
top1 = temp.pop()
top2 = temp.pop()
if top2[0] < top1[1]:
top1[1] = max(top1[1],top2[1])
temp.append(top1)
else:
stack.a... |
#[?] 1부터 1,000까지의 정수 중 13의 배수의 갯수(건수, 횟수)
# 갯수 알고리즘(Count Algorithm) : 주어진 범위에 주어진 조건에 해당하는 자료들의 갯수
#[1] Input
count = 0 # 갯수를 저장할 변수를 0으로 초기화
#[2] Process : 갯수 알고리즘의 영역 -> 주어진 범위에 주어진 조건(필터링)
for i in range(1,1000): #주어진 범위
if i % 13 == 0: #주어진 조건: 13의 배수면 갯수를 증가
# count = count + 1
count += 1 #... |
""" A convenience log function, behaves similar to print() """
from logging import getLogger
def log(*args, level="info", name=None):
# TODO basic logger formatting
logger = getLogger(name=name)
message = " ".join([str(a) for a in args])
level = level.lower()
if level == "exception" or level == ... |
import sqlite3
#import os
from sqlite3 import Error
'''the function below called create_connection() returns a Connection object
which represents an SQLite3 database specified by the database file parameter db_file.'''
def create_connection(db_file):
""" create a database connection to the SQLite database
... |
from pyspark import SparkContext
from numpy import array
from pyspark.mllib.clustering import KMeans, KMeansModel
############################################
#### PLEASE USE THE GIVEN PARAMETERS ###
#### FOR TRAINING YOUR KMEANS CLUSTERING ###
#### MODEL ###
#########################... |
#!/usr/bin/python3
user_input = float(input("Enter Number: "))
if user_input > 100:
print("Greater")
elif user_input == 100:
print("Is the same")
else:
print("Smaller") |
# DEFINIZIONE DELLA FUNZIONE CHE CONTROLLA CHE I DUE NUMERI
# SIANO COMPRESI FRA DUE ESTREMI DATI
# estremo1 => estremo inferiore
# estremo2 => estremo superiore
def verifica(estremo1,estremo2):
numero = int(input("Inserire un numero da " + str(estremo1) + " a " + str(estremo2) + ": "))
while(... |
# Esercizio_1
somma_pari = 0
somma_dispari = 0
numero = 0
risposta = str(input("Vuoi inserire un numero? "))
while(risposta == "si"):
numero = int(input("Inserisci un numero intero: "))
if numero % 2 == 0:
somma_pari = somma_pari + numero
else:
somma_dispari = somma_di... |
from queue import Queue
from threading import Thread
def loop(fn, input, output) -> None:
while True:
work = input.get()
if work:
output.put(fn(work))
input.task_done()
if not work:
break
class ThreadPool(object):
def __init__(self, target, num_threads... |
def encrypt_messege(messege, x):
e_messege = ""
if type(x) != int:
raise ValueError()
for l in messege:
e_messege += chr(ord(l)+x)#(Char value of l) + x
return e_messege
#print encrypt_messege("Meeting at 5PM tomorrow.", 6)
def left_aligned_triangle():
hight = int(raw_input("Enter ... |
#!/usr/bin/env python3
def parse(line):
# 1-3 b: cdefg
parts = line.split()
# 000 11 22222
p_count = tuple(map(int, parts[0].split("-")))
p_char = parts[1][0] # drop colon
password = parts[2]
# (1,3), 'b', 'cdefg'
return p_count, p_char, password
def checkpass(p_count, p_char, passw... |
# Do not change these lines
friend1 = "Mary"
friend2 = "Mohammad"
friend3 = "Mike"
friends = []
# Add your code below...
# 1) Use the appropriate List method to add the
# three friends names to the 'friends' List
friends.append(friend1)
friends.append(friend2)
friends.append(friend3)
# print( friends )
# 2) Use th... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
for i in range(n):
for j in range(i+1, n):
if nu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# just quick sort
nums.sort()
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
re... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
dups = []
n = len(nums)
for val in nums:
nums[(val - 1) % n] += n
for (idx, val) in enu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
s_map = {}
t_map = {}
for c in s:
cnt = s_map.get(c, 0)
s_map[c] = cnt+1
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def rotate(self, matrix):
if not matrix:
return None
n = len(matrix)
ans = [[0] * n for _ in range(n)]
for i in range(n-1, -1, -1):
row = matrix[i]
for j in range(n):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
class Solution(object):
def bulbSwitch_tle(self, n):
tot = 0
for x in range(1, n+1):
cnt = 0
i = 1
while i*i <= x:
if x % i == 0:
cnt += 2 if x/i != i else 1
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def maxArea(self, height):
n = len(height)
if n <= 1:
return 0
i, j = 0, n-1
maxW = 0
while i < j:
h = min(height[i], height[j])
maxW = max(maxW, (j-i)*h)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
... |
#!/usr/bin/env python
# -*- coding : utf-8 -*-
class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
n = len(triangle)
if n == 0:
return 0
if n == 1:
return triangle[0][0]
... |
import torch
import torchvision
from torchvision.datasets import MNIST
# Download training dataset
dataset = MNIST(root='data/', download=True)
len(dataset)
#The dataset has 60,000 images which can be used to train the model.
#There is also an additonal test set of 10,000 images which can be created by pass... |
def calculObj(data, function1, function2) :
"""
Calcul des fonctions objectifs pour chaque observation
data -> vecteurs d'entrée
function1, function2 -> fonctions objectifs à minimiser
return : même dataframe avec valeurs des fonctions objectifs pour chaque observation
"""
x1 = ... |
import argparse
import sys
import time
class LetterNode():
__slots__ = ('children', 'val', 'isEndValue')
def __init__(self, val, isEndValue, children):
"""Creates a new LetterNode
val -- The letter in this node
isEndValue -- Bool determining if a word ends at this node
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.