text stringlengths 37 1.41M |
|---|
# Open a frame
###################################################
# Open frame
# Student should add code where relevant to the following.
import simplegui
message = "My second frame!"
# Handler for mouse click
def click():
print message
frame = simplegui.create_frame("My secode frame", 100, 200)
# Assign ca... |
import cards_tools
while True:
cards_tools.cards_menu()
action = input("请选择希望执行的操作:")
print("您选择的操作是【%s】" % action)
# 1,2,3 针对名片的操作
if action in ["1", "2", "3"]:
# 根据用户输入决定后续的操作
if action == "1":
cards_tools.add_card()
elif action == "2":
cards_tools.... |
# Bubble sort is the basic sorting algorithm to sort array elements. It compares the pair of adjacent elements from an array. If the order is wrong, it just swaps the element.
# If there are n-elements in the array, it iterates loop n times. In each iteration, one element is placed in the order at the end of the arr... |
import csv
def transform_user_details(csv_file_name):
new_user_data = []
with open("user_details.csv", newline='') as csvfile:
user_details = csv.reader(csvfile, delimiter=",")
for user in user_details:
new_user_data.append(user)
return new_user_data
def create_ne... |
'''
1. 质数是只能被1和它本身整出的数,编程找出100以内全部的质数。
2. 斐波那契数列是两个1构成,从第三项开始,每一项是由前面两项的和构成,如下:1,1,2,3,5...
请通过编程得到数列的前100项,并输出99项与100项的比值。
'''
def zs(fw):
fw += 1
for i in range(2,fw):
#对于从2到fw之间的数,每个数都拿来除以从2到它自身一半(i/2)的所有数,看是否能被整除;
for k in range(2,int(fw/2)):
if i%k == 0:break
#如果2-1... |
from api.engine import Tokenizer, Languages
"""
The language detector should identify the language of the text for all the supported languages.
For other languages it should return the label OTHER
"""
def test_english_language_detector():
text = 'This language is english.'
ld = Tokenizer(Languages.ENGLISH)
... |
def is_Chinese(uchar):
"""
check whether the unicode is a Chinese character
"""
if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
return True
else:
return False
def contain_Chinese(word):
"""
check whether the word contains Chinese character
"""
for uchar in word:
... |
from collections import Counter
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
char_counter = Counter(chars)
res = 0
for w in words:
word_counter = Counter(w)
ok = True
for c, v in word_counter.items():
if ... |
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board:
return
m, n = len(board), len(board[0])
def bfs(x, y):
nonlocal board
visit ... |
# Default shell for a Python 3.x program
# Copy this and rename it to write your own code
#
__author__ = 'Ethan Richards'
# CIS 125
# Fahrenheit-to-Celcius
# Converts a number from Fahrenheit to Celcius.
def main():
F = eval(input("Input a temperature in Fahrenheit:"))
C = (F-32) * (5/9)
print("{} in Fahre... |
def encrypt_caesar(plaintext: str) -> str:
"""
>>> encrypt_caesar("PYTHON")
'SBWKRQ'
>>> encrypt_caesar("python")
'sbwkrq'
>>> encrypt_caesar("Python3.6")
'Sbwkrq3.6'
>>> encrypt_caesar("")
''
"""
i = 0
ciphertext = ""
while i < len(plaintext):
if 'a' <= plain... |
#Import pandas, numpy, matplotlib, and seaborn.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
#Read in the Ecommerce Customers csv file as a... |
# MIT-6.00.1
counter = 0;
for i in s:
if i in 'aeiuo':
counter += 1
print ('Number of vowels: '+str(counter))
|
#!/usr/bin/env python
from copy import deepcopy
CONFIG = "settings.json"
BLOCK = -5
EMPTY = -1
HEIGHT = 8
WIDTH = 6
REDS = [(2,1), (4,2), (3,3), (5,4), (2,5), (5,5), (4,6)]
START = (3,0)
END = (HEIGHT * WIDTH) - len(REDS)
def create_board(height, width, block_list):
""" Given a height, width, and list of tuple p... |
import queue
import collections
Tuple=("Red","Green","Blue")
Dictionary = {"Name": "Ansh", "Age": 16, "Class": "XI"}
Stacks=[1,2,3,4,5,6,7,8]
Queues=queue.Queue(3)
Deques=collections.deque("ABCDEF", 10)
Tuple=Tuple.__add__(("Black",))
print(Tuple)
print(Tuple.__contains__("Black"))
print(len(Tuple))
print(Dictionary.... |
String1 = "Hello World"
String2 = "Python is Fun!"
print(String1[0])
print(String1[0:5])
print(String1[:5])
print(String1[6:])
String3 = String1[:6] + String2[:6]
print(String3)
print(String2[:7]*5)
print()
MyString = " Hello World "
print(MyString.upper())
print(MyString.strip())
print(MyString.center(21, "*"))
print... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
fname="Ripa"
lname='Shah'
# In[2]:
print(fname + " "+ lname)
# In[3]:
print(lname + "123")
# In[4]:
print(lname+ str(123))
# In[5]:
s1="This is a long string"
print(len(s1))
# In[6]:
s2= " Lots of spaces in here "
print(s2)
# In[7]:
print("... |
import random # import is how you tell python that you want to use a library in a script
# 'if' and 'True' are python KEYWORDs, and should NEVER EVER be used as a variable
if True:
print('Obviously...')
# False is a python KEYWORD, and should NEVER EVER be used as a variable
if False:
print('This will never... |
import os
import re
import random
# handling punctuation requires Regular Expressions, this one says
# to match on any group of what's in the square brackets. in this case,
# it's a mess of punctuation characters.
PUNCTUATION_AND_SPACES_REGEX = r'[,\.\-\;\:\"\(\)\' ]+'
def print_each_line_and_word(file_path)... |
# this is a little silly, but will reinforce everything
# required to start using internet-based APIs
# create a dictionary that will represent our checked bag
checked_bag = {
'sets of clothes': 5,
'passport': 1,
'toiletries bag': {
'toothbrush': 1,
'toothpaste': 1,
'condi... |
import socket
import pickle
import argparse
from PIL import Image
text = 'This is a client for receiving images'
parser = argparse.ArgumentParser(description=text)
parser.add_argument("-s", '--server', help='write the server and port number seperated by : to use')
parser.add_argument("-q", '--path', help='type the pat... |
list_one = [2, 3, 4]
list_two = [2*i for i in list_one if i > 2]
print(list_two)
|
def avg(a, b, c):
sum = 0
for n in [a, b, c]:
sum += n
return sum / 3
print(avg(1, 3, 5))
print(avg(2, 3, 4))
print(avg(1, 6, 9))
|
for n in range(1, 11):
if n % 3 == 0:
continue
print(n, sep='\n')
|
name = input('What is your name? ')
favorite_color = input('What is you favorite color?')
print(name + ' likes ' + favorite_color) |
def pal_perm(str1):
# palindrome must have 2 of each char plus potentially 1 of another
charmap = {}
fstr = str1.upper().replace(' ','')
for char in fstr:
val = charmap.get(char, 0)
if val == 0:
charmap.update({char: 1})
elif val == 2:
return False
... |
import copy
import heapq
from util import *
from node import Node
class priority_queue():
def __init__(self, query_vec, farthest=False):
self.heap = []
self.set = set()
self.query_vec = query_vec
self.farthest = farthest
def __repr__(self):
return str(self.set)
def ... |
print("How old are you?"),
age=input("Your age?")
print("How tall are you?"),
height=input("Your height?")
print("How much do you weight?"),
weight=input("Your weight?")
print("So, you're %r old, %r tall and %r heavy." % (age,height,weight))
|
"""Helper functions to make vector manipulations easier."""
import math
def add_vec(pos, vec, dt):
"""add a vector to a position"""
px, py, pz = pos
dx, dy, dz = vec
px += dx * dt
py += dy * dt
pz += dz * dt
p = (px, py, pz)
return p
def sub_vec(v1, v2, dt=1):
x1, y1, z1 = v1
... |
def flatten(mylist):
newlist = [y for x in mylist for y in x]
return newlist
mylist = [[1,3,4],[1,34,67],[32,1],[34,56,4]]
print(mylist)
print(flatten(mylist))
|
def sortsecond(l):
return l[1]
def sortfirst(l):
return l[0]
student = []
n = int(input("Enter No of student: "))
for i in range(n):
name = input("Enter name of Student{}: ".format(i))
per = float(input("Enter Per of student{}: ".format(i)))
student.append([name,per])
student = sorted(student,key = sortse... |
str = input("Enter AlphaNumeric String: ")
list = []
for x in str:
if x in "1234567890":
list.append(int(x))
print(sorted(list)) |
from random import randint
num = randint(1,100)
while True:
guess = int(input("Guess the number(from1 to 100):"))
if num == guess:
print("Congratulation! you guess it right")
break
if guess>num:
print("Number is too large! Try again")
elif guess<num and guess>0:
print("Number is too small! try again")
else... |
def remove_mark(s):
return ''.join([t for t in s if t.isalpha()])
def begin_duplicate(tokens):
for f in range(1, len(tokens)):
if tokens[:f] == tokens[f:2*f]: return f
return None
def distinct(tokens):
if not tokens: return ''
duplicate = begin_duplicate(tokens)
if duplicate:... |
# lesson 1, what is regression?
# supervised learning, take examples of inputs and outputs,
# then take another input, and predict the output
# discrete outputs, continuous outputs,<- we are looking at continuous outputs
#
# We expect Charles' children to be between Charles' height and average height.
# lesson... |
class GradeProc:
def __init__(self):
self.data =[]
def inputData(self):
while True:
name = input('이름:')
kor = int( input('국어:') )
eng = int( input('영어:') )
math = int( input('수학:') )
self.data.append( (name, kor, eng,math) )
... |
#!/usr/bin/env python3
import math
from sys import argv
HEIGHT = 450
WIDTH = 450
def ssv(iterable):
return " ".join(str(i) for i in iterable)
if __name__ == "__main__":
if len(argv) != 2:
print("usage: {} ANGLE".format(argv[0]))
exit(1)
angle = float(argv[1])
sign = math.copysign(1, ... |
#!/usr/local/bin/python
import sys
wort = input ("Bitte das Wort eingeben, das geprueft werden soll, ob es ein Palindrom ist: ")
# anna = palindrom
# hans != palindrom
# lagerregal = palindrom
i = 0
wortlaenge = len(wort)
while i < wortlaenge:
if
wort
i+=1
else:
print ("Das Wort \""+wort+"\" ist kein Palin... |
import random
class Lottery:
def __init__(self):
self.my_num = set() # Entered numbers
self.winning_num = set() # Winner's numbers.
self.bonus = set()
# Reset numbers.
def init(self):
self.winning_num.clear()
self.bonus.clear()
while len(... |
NO_POSSIBLE_PLAY = "none"
STAIRS = "stairs"
FULL = "full"
POKER = "poker"
JATZEE = "jatzee"
plays = [NO_POSSIBLE_PLAY, STAIRS, FULL, POKER, JATZEE]
possible_numbers = [1, 2, 3, 4, 5, 6]
jatzee_hand_length = 5
def consequent_check(sorted_hand, last, x):
return x == last or x + 1 == sorted_hand[sorted_hand.index(... |
def isPrime(n):
for d in range(2, n):
if n % d == 0:
return False
return True
for prime in range(3, 18):
if isPrime(prime):
print(" \item (Modulo %d)" % prime)
print(" ", end = " ")
for i in range(2, prime):
result = (i * i) % prime
p... |
from itertools import permutations
import unittest
class Permutation:
def __init__(self, ls):
self.ls = ls
self.n = len(ls)
def sends(self, i):
return self.ls[i]
def __eq__(self, other):
for i in range(self.n):
if self.sends(i) != other.sends(i):
... |
r = float(input('Write the radius of a circle'))
p = 3.14159
d = 2 * r
c = 2 * p * r
s = p * r ** 2
print('The diameter is', d)
print('The circumference is', c)
print('The area is', s)
|
from lib import is_prime
def repeating_digits(val):
if len(set(str(val))) == len(str(val)):
return []
result = []
for d in set(str(val)):
if str(val).count(d) > 1:
result.append(int(d))
return result
i = 1
done = False
while True:
if done:
break
i += 1
... |
import numpy as np
import scipy.io as scipy_io
import pdb
from collections import *
import matplotlib.pyplot as plt
import sys
class Graph:
def __init__(self):
self.nodes = set()
self.edges = defaultdict(list)
self.distances = {}
def add_node(self, value):
self.nodes.ad... |
def twoSum(nums: list, target: int) -> list:
"""
QUESTION:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to
target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can... |
def main():
field = 3 # ex: 2^(3)
powers = [1,2,3,4,5,6] #x^1, x^2, x^3, x^4 ...
classes = []
for x in powers:
c = []
c.append(x)
for y in powers:
if x != y:
if y not in c and calc(field, x, y):
c.append(y)
c.sort()
... |
from random import *
import time
choices = ["Rock", "Paper", "Sicssors"]
computer = choices[randint(0, 2)]
print("welcome in our game")
time.sleep(1)
print("please choose paper, rock or scissors")
time.sleep(1)
print("If you want exit type 'x'")
time.sleep(1)
P_result = 0
C_result = 0
while True:
player = input(... |
"""
Example of bubble sort.
"""
def float_largest_to_top(data, array_size):
changed = False
# notice we stop at array_size-2 because of expr. k+1 in loop
for k in range(array_size - 1):
if (data[k] > data[k + 1]):
data[k], data[k+1] = data[k + 1], data[k]
changed = True;
re... |
#!/bin/python3
def convert(x):
return {
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
10: "ten",
11: "eleven",
12: "twelve",
13: "thirteen",
14: "for... |
#!/bin/python3
from copy import deepcopy
def bomberMan(n, grid):
global r, c
if n == 0 or n == 1:
return grid
if (n - 3) % 2 == 1 or n == 2:
for row in grid:
for i in range(c):
row[i] = 'O'
return grid
result = deepcopy(grid)
states = []
for... |
import sys
from math import sqrt
class Distance:
@staticmethod
def euclideanDistance(xCoor, yCoor):
"""This function check the euclidean distance"""
return sqrt((xCoor - 0) ** 2 + (yCoor - 0) ** 2)
try:
if __name__ == "__main__":
x = int(sys.argv[1])
y = int(sys.argv[2])
... |
from weather import Weather
from enum import Enum, auto
def getConditions():
weather = Weather()
conditions = weather.get_weather_conditions()
return conditions
# Format and print out the details for each day.
def format_condition_printout(conditions):
if not isinstance(conditions, dict):
r... |
import makeBigList
def merge_sort( thelist):
#the base case when the size of thelist =1
if len(thelist)==1:
return thelist
first_half = merge_sort(thelist[0:len(thelist)/2])
second_half = merge_sort(thelist[len(thelist)/2:len(thelist)])
return merge_2_list(first_half,second_half)
def merge_... |
for i in range(1,11):
for j in range(1,i+1):
print(j,end="")
print()
for i in range(1,11):
for j in range(1,i+1):
print(1,end="")
print() |
class Stack_Implementation:
def __init_(self,stack_old):
self.stack_old=stack_old
def push_fun(self,value):
self.stack_old=[10,20,30,40]
print("The stack before pushing new element is: ",self.stack_old)
self.stack_old.append(value)
print("The stack after pushing new element is: ",self.stack_old)
def po... |
w = float(input())
h = float(input())
i = w/(h*h)
if i < 20:
print('PESO BAJO')
if 20 <i < 25:
print('NORMAL')
if 25 <i < 30:
print('SOBRE PESO')
if 30 <i < 40:
print('OBESIDAD')
if i >= 40:
print('OBESIDAD MORBIDA')
|
from timeit import default_timer as timer
# Selection Sort
file2 = open('20k.txt', 'r')
sortedLines = file2.readlines()
sortedLines.sort() # Using a library Function, to sort the array, this will be used to check my implementation
start = timer()
file1 = open('20k.txt', 'r')
Lines = file1.readlines()
#Implementing S... |
import hashlib
cipher = hashlib.sha3_256()
print(cipher.name)
print(cipher.digest_size)
cipher.update("hello".encode(encoding="utf-8"))
# # -- python 3 encoding --
# # string is encoded as Unicode by default
# print('1 >> ----')
# print (type('我好'))
# print(str.encode('''我好'''))
# a=b'\xe6\x88\x91'.decode... |
from random import random
from random import seed
from prompt_toolkit import prompt
class Player():
def __init__(self, name):
self.player_name = name
class Roll():
def __init__(self, name):
self.name = name
self.rolls_i_can_beat = []
self.rolls_that_beat_me = []
def __... |
""" Assignment 6
Create a dictionary of waypoints.
Each waypoint should itself be a dictionary.
Write a loop that will print the name of each city on a new line.
Location Data:
WP1
locale: London
lat: 51.5074° N
lon: 0.1278° W
WP2
locale: Paris
lat: 48.8566° N
lon: 2.3522° E
WP3
locale: New York
lat: 40.7128° N
l... |
""" Assignment 7
Write a short script that will get a name from the user.
Find the length of the name.
If the length is lower than 5 print "Under".
If the length is more than 5 print "Over".
If the length is exactly 5 print "Five".
Try to use 'if', 'else' and 'elif' exactly once each.
Also, try not to evaluate the le... |
""" Assignment 1
Write a short script that will get some information from the user, reformat
the information and print it back to the terminal. """
# Possible Answer
fav_movie = input("What is your favorite movie? ")
print(f"Your favorite movie is: {fav_movie}.")
|
""" Assignment 15
1. Complete the log_this decorator such that it will print the output of the
following `square` function when it is called.
Stretch
1. Make sure the help feature of `square()` still works properly.
2. Write the decorator in such a way to allow for an arbitrary number of
positional and keyword argume... |
trau_profile = {
'name': 'Trau',
'job': 'Thuc tap sinh',
'org': 'Trung tam khoa hoc VN',
}
william_profile = {
'name': 'William',
'job': 'Thuc tap sinh',
'org': 'Trung tam khoa hoc VN',
}
tre_profile = {
'name': 'Tre',
'job': 'Tro ly robot',
'org': 'Trung tam khoa hoc VN',
}
profiles... |
import random
# Ask the user for three adjectives
adjectives = input('Give me three adjectives to describe a cat, separated by a comma: ')
# Split the adjectives into a list separated by a comma and print the list
x = adjectives.split(", ")
# Shuffle using random
random.shuffle(x)
print(x)
# Assign three variables ... |
# NUMBER = 12
# snake_case = 6
# number = 'five'
# number = 5
# print(number)
# a = 1
# b = 2
# a = b
# b = 15
# a = b
# print(a)
# a, b = 1, 2
# a, b = b, a
#
# print(a)
# p = print
#
# p('this thing')
def pretty_print(x):
return '({}) {}-{}'.format(x[:3], x[3:6], x[6:])
def something():
phone1 = input('P... |
"""
Contains a series of functions and custom classes,\n
concerning the base of linear algebra,
Matrices and Vectors
Here are the operations:
-- Vectors :
** Vector Dot
** Vector Cross (3D ONLY)
** Vector Addition and Subtraction
** Vector-Scalar Operations
-- ... |
def has_negatives(a):
"""
YOUR CODE HERE
"""
# Your code here
result = []
negatives = {}
a.sort()
for num in a:
if num < 0:
negatives[-num] = num
if num > 0 and num in negatives:
result.append(num)
# print(negatives)
# print(result)
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 15 10:13:42 2019
@author: ChemGrad
"""
"""
# Scope and lifetime of variable
def scopeFunc():
x = 10
print("The value inside function: ", x)
return x
x = 20
scopeFunc()
print("The value outside function: ", x)
def prime(n):
if n < 2:
return F... |
import itertools
case_1 = [0, 3, 0, 1, -3]
# Read the input file
matrix = []
with open("input.txt", "r") as f:
for line in f:
#print(line)
tmp = int(line)
matrix.append(tmp)
#tmp = list(line)
#tmp[-1] = tmp[-1].strip()
#tmp = map(int, tmp)
#matrix.append(tmp)
#
print(matrix)
def maze_jumps(list_... |
def divide(sq):
x,y = shape(sq)
TWO, THREE = 2,3
if y != x:
print "ERR(NOOP): Not expecting {} by {} square.".format(x,y)
return sq
if x % 2 == 0 and y % 2 == 0:
WIDTH = TWO
elif x % 3 == 0 and y % 3 == 0:
WIDTH = THREE
sql = sq.split("/")
rows = []
for row in range(0,x,WIDTH):
... |
from collections import defaultdict
def turing_machine(start, limit):
n,c = 0,0
tape = defaultdict(int)
state = start
while c < limit:
if state == 'A':
if tape[n] == 0:
tape[n] = 1
state = "B"
n+=1
else:
tape[n] = 0
state = "C"
n-=1
eli... |
#Viet cuong trinh tinh cước taxi
# Km đâu là 5000
# 200 m tiep theo là 1000
#Neu lon hon 30km thi moi km se them 3000Đ
while True:
km = int(input("nhap vao so km ma nguoi đi="))
s1 = 5000
if( km == 1):
print(" sô tiền phải trả 1km là =",float(s1))
elif( km >= 30):
print("tong so tien >3... |
print("==============Chuong trinh cau hoi trac nghiem===================")
def switch_funcion(choice):
chi = {
1: "Ban tra loi đung",
2: "ban tra loi sai",
}
return chi.get(choice,"Moi ban chon lai")
print (switch_funcion(1))
print("===========cAU HOI TRAC NGHIE=======")
print("==Chua Gie su sinh ra... |
a = input(" nhap vao chuoi:")
print("chuoi duoc dao la:", a[:: -1])
#cách 2
b = input(" nhap vao ten bat ki:")
for i in range(1,len(b) + 1):
print(b[-i], end=' ')
|
#'''viet chương trin in ra hình chữ nhật có ích thước m x n'''
# m: chieu ngang - n la chieu doc
#In ra tam giac
n= int(input("nhap vao n="))
for i in range(1, n+1):
for j in range(1, i+1):
print("*", end = "")
print()
#in ra hinh chu nhât
n1= int(input("nhap vao n1="))
m= int(input("nhap vao m="))... |
x = "phan thanh chi"
y = 'chi' in x
print(y)
print("do dai chuoi",len(x) -1 )
a =10
b =30
c = a+ b
print('Tong cua no la %d + và %d la %d ' %(a,b,c))
s = f" {a:} {b:} {c}"
print (s)
s1 = 'toi yeu'
s2 = 'lap trinh'
print('{} khong the {}'.format(s1,s2))
# Định dạng chuỗi
#chuoi
#print('Die vao a = {} dien vao b={}... |
def select_name_of_player_with_shortest_name():
return """SELECT name
FROM players
ORDER BY LENGTH(name) ASC
LIMIT 1;"""
def select_all_new_york_players_names():
return """SELECT players.name
FROM players JOIN teams ON players.team_id = teams.id
WHERE... |
import hashlib
text = input("Enter a String : ")
encoded_text = text.encode()
hash_object = hashlib.md5(encoded_text)
md5_hash = hash_object.hexdigest()
print("Code : ",md5_hash) |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 22 19:08:36 2020
@author: mnm
"""
####################
## EXAMPLE: while loops
## Try expanding this code to show a sad face if you go right
## twice and flip the table any more times than that.
## Hint: use a counter
####################
#n = input("You a... |
from strings import *
from classes import *
from options import *
# User Option numbers and their meanings
QUIT_PROGRAM_NO= 0
READ_BICYCLE_INFO_NO = 1
DISPLAY_WITH_SERVICE_INFO_NO = 2
DISPLAY_SELECTED_BIKE_INFO_NO = 3
ADD_BICYCLE_NO = 4
DO_BICYCLE_MAINTENANCE_NO = 5
RIDE_A_BIKE_NO = 6
# A global State, keeps track of ... |
board=[[0,0,0,7,0,0,0,0,3],
[0,9,6,0,0,0,0,0,0],
[2,0,0,8,5,0,0,0,0],
[1,7,0,2,0,4,0,3,6],
[0,6,0,0,7,0,0,4,0],
[0,8,2,6,0,3,5,1,0],
[0,0,0,0,1,7,0,0,8],
[0,0,0,0,0,0,2,5,0],
[9,0,0,0,0,2,0,0,0]]
def solve(grid):
find = find_empty(grid)
if not find:
retu... |
def euclidean_dist(x, y):
if (len(x) == 0 or len(y) == 0 or len(x) != len(y)):
return 0
return ((y[0]-x[0])**2 + (y[1]-x[1])**2) ** (1/2)
def manhattan_dist(x, y):
if (len(x) == 0 or len(y) == 0 or len(x) != len(y)):
return 0
answer = 0
for i in range(len(x)):
answer += abs(... |
#!/usr/bin/python
from __future__ import print_function
import sys
def StairCase(n):
for i in xrange(n+1) :
for j in xrange(n-i) :
print (' ',end='',sep='')
for k in xrange(i) :
print ('#',end='',sep='')
print ('\n',end='',sep='')
_n = int(input());
StairCase(_n)
|
from sklearn.neighbors import KNeighborsClassifier
from sklearn import datasets
import matplotlib.pyplot as plt
dataset = datasets.load_digits()
clf = KNeighborsClassifier(n_neighbors=3)
X,Y = dataset.data[:-10], dataset.target[:-10]
clf.fit(X,Y)
print('Prediction:',clf.predict(dataset.data)[-9])
plt.imshow(dataset.i... |
import random
async def get_color() -> int:
"""
Generates a random hexadecimal color.
Returns:
color: int - a hexadecimal number.
"""
# Generate a random color
color = "%06x" % random.randint(0, 0xFFFFFF)
# Convert to int for it to work
color = int(color, 16)
return colo... |
def var(n,s,g):
sum=n+s+g
print(sum)
print("average",sum/3)
n=int(input("any number"))
s=int(input("any number"))
g=int(input("any number"))
var(n,s,g)
|
def divisible(limit):
i=0
sum=0
while i<=limit:
if i%3==0 and i%5==0:
sum=sum+i
i=i+1
print(sum)
limit=int(input("any number"))
divisible(limit)
|
import threading
import time
def run(n):
print('task:', n)
time.sleep(2)
print('task done:', n)
start_time = time.time()
for i in range(10):
t = threading.Thread(target=run, args=(i,))
# t.setDaemon(True)
t.start()
print('cost:', time.time()-start_time)
print("all thread is done", threading.... |
# importing the needed libraries
from sklearn.metrics import accuracy_score
from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
import numpy as np
import pandas as pd
# reaading the data
irisData = pd.read_csv('Iris.csv')
print(irisData) # chec... |
def calculator(num1, num2, operator):
'''
recieve input from user of two numbers and an operator and compeletes the task
Asks user for an equation, each input seperated by a space. Depending on the operator the user gives,
The function will either add(+), subtract(-), multiply(*), divide(/), integer division(//), ... |
# coding:utf-8
import tkinter as tk
class Ball:
def __init__(self,x,y,dx,dy,color):
self.x=x
self.y=y
self.dx=dx
self.dy=dy
self.color=color
def move(self,canvas):
self.erase(canvas)
self.x=self.x+self.dx
self.y=self.y+self.dy... |
# Strings Exercise 1: Uppercase a String
s = ("this is a string. is it upper or lower case?").upper()
print(s)
# Strings Exercise 2: Capitalize a String
s = ("this is a string. Is it upper or lower case?").capitalize()
print(s)
# Strings Exercise 3: Reverse a String
def reverse(s):
str = ""
for i in s:
str = ... |
raw_input = input("What is your name? ")
name = str(raw_input)
print ("Hello, " + raw_input +"!")
|
# encoding: UTF-8
# Autores: Irma Gómez, Victor Curiel, Francisco Arenas
# Introduction to graph theory (Binary Tree implementation)
class Nodo():
#Constructor
def __init__(self, valor):
self.valor = valor
self.nodoIzquierda = None
self.nodoDerecha = None
class BinaryTree(... |
import numpy as np
from sigmoid import sigmoid
def lrCostFunction(theta, X, y, _lambda):
#LRCOSTFUNCTION Compute cost and gradient for logistic regression with
#regularization
# J = LRCOSTFUNCTION(theta, X, y, lambda) computes the cost of using
# theta as the parameter for regularized logistic reg... |
import numpy as np
from computeCostMulti import computeCostMulti
def gradientDescentMulti(X, y, theta, alpha, num_iters):
#GRADIENTDESCENTMULTI Performs gradient descent to learn theta
# theta = GRADIENTDESCENTMULTI(x, y, theta, alpha, num_iters) updates theta by
# taking num_iters gradient steps with l... |
import numpy as np
import math
def multivariateGaussian(X, mu, sigma2):
#MULTIVARIATEGAUSSIAN Computes the probability density function of the
#multivariate gaussian distribution.
# p = MULTIVARIATEGAUSSIAN(X, mu, Sigma2) Computes the probability
# density function of the examples X under the mu... |
from plotData_ex2 import plotData
import matplotlib.pyplot as plt
import numpy as np
from mapFeature import mapFeature
def plotDecisionBoundary(theta, X, y):
#PLOTDECISIONBOUNDARY Plots the data points X and y into a new figure with
#the decision boundary defined by theta
# PLOTDECISIONBOUNDARY(theta, X,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.