text stringlengths 37 1.41M |
|---|
"""
# Student class is defined with two different object
class student:
def __init__(self, name, age, subject_1, subject_2, subject_3):
self.name = name
self.age = age
self.sub1 = subject_1
self.sub2 = subject_2
self.sub3 = subject_3
@staticmethod
def marks(numb):
... |
# Machine Learning Project
__author__ = 'Eslam Hamouda'
import math
from _operator import itemgetter
import json,sys
#Genres Action | Romance | Horror | Mystry | Sci-Fi
# dummy dataset copied from the IMDb top 250 film with some fabrications.
dataset = dict()
# load the dataset from json file.
with open("recommendati... |
"""
Have you ever played "Connect 4"? It's a popular kid's game by the Hasbro company. In this project, your task is create a Connect 4 game in Python.
Before you get started, please watch this video on the rules of Connect 4:
https://youtu.be/utXzIFEVPjA
Author: Ivan Komlev
Date: 2020-10-14
GitHub: https://github.co... |
# iterate backwards using char array
def urlify(s, length):
num_spaces = s[:length].count(' ')
url_index = length + 2 * num_spaces - 1
for i in xrange(length - 1, -1, -1):
if s[i] == ' ':
s[url_index] = '0'
s[url_index - 1] = '2'
s[url_index - 2] = '%'
... |
class Dog():
def __init__(self,name):
self.name = name
def speak(self):
return self.name + " says woof!"
class Cat():
def __init__(self,name):
self.name = name
def speak(self):
return self.name + " says meow!"
niko = Dog("niko")
felix = Cat("felix")
print(niko.speak())#... |
import math
# 1 can of paint can cover 5 square meters of wall
wall_height = int(input("Input the height of wall: "))
wall_width = int(input("Input the width of wall: "))
coverage = 5
def paint_calc(height,width,cover):
area = height * width
num_of_cons = math.ceil(area/cover)
print(f"You'll need {num_of_c... |
# https://github.com/Pierian-Data/Complete-Python-3-Bootcamp/blob/master/05-Object%20Oriented%20Programming/02-Object%20Oriented%20Programming%20Homework.ipynb
# Problem 1 計算兩座標的距離 & 斜率
# Fill in the Line class methods to accept coordinates as a pair of tuples and return the slope and distance of the line.
#solution ... |
# # Practice_6: Use a Debugger
# def mutate(a_list):
# b_list = []
# for item in a_list:
# new_item = item * 2
# b_list.append(new_item)
# print(b_list)
# mutate([1,2,3,5,8,13])
"""
Use a Debugger 題目分析
def mutate(a_list):
b_list = []
for item in a_list:
new_item = item * 2
b_list.append(new_item... |
def format_name(f_name,l_name):
"""Take a first and last name and format it to return the title
case version of the name"""
if f_name == "" or l_name == "":
return "You didn't provide valid inputs."
formated_f_name = f_name.title()
formated_l_name = l_name.title()
#print(f"{formated_f_na... |
def func():
return 1
print(func())#1
def hello():
return "Hello"
print(hello())#Hello
print(type(hello))#<class 'function'>
greet = hello
print(type(greet))
print(greet())#Hello
|
"""
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
You've visited Russia 2 times.
You've been to Moscow and Saint Petersburg.
"""
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris","Lille","Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin","Hamburg","Stu... |
from art import logo
print(f"\033[31m{logo}\033[00m")
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def caesar(plain_text,shift_amount,direction_side):
word = ""
if direction == "decode":
shift_amount *= -1
... |
name = input("What's your character's name? ")
print("Your character's name is", name, "\n", end="")
game = input("Would you like to begin the game? Enter Yes or No: ")
print(game)
"Yes" == "yes"
"No" == "no"
if game == "yes":
print(name)
elif game == "no":
quit()
else:
print("Please enter yes or no."
#Y =... |
#a = '*'
#b = 0
#while b < 5:
#b = b + 1
#print(a)
#a = a + '*'
#a = '*'
#b = 0
#while b < 5:
#b = b + 1
#print(a)
#a = a + '*'
x = 0
y = 0
r = 25
n = 2*r
while y < n:
x = 0
while x < n:
if (x-r)**2 + (y-r)**2 < r**2:
print('*', end="")
else:
... |
def prime(n):
l = [0]*n
p = 2
while p < n:
if l[p] == 0:
q = 2*p
while q < n:
l[q] = 1
q = q + p
p = p + 1
result = []
i = 2
while i < n:
if l[i] == 0:
result.append(i)
i = i + 1
return result
#print(prime(200))
|
graph={
'A':['B','C'],
'B':['D','E'],
'C':['F','G'],
'D':['H','I'],
'E':['J','K'],
'F':['L','M'],
'G':['N','O'],
'H':[],
'I':[],
'J':[],
'K':[],
'L':[],
'M':[],
'N':[],
'O':[],
}
def dls(start,goal,path,level,maxD):
print("\nCurrent lev... |
#Hello there!!!....myself Rakesh pandey
#Building a TicTacToe game!!!
import os
from time import sleep
#define board
board=[" "," "," "," "," "," "," "," "," "]
def printboard():
print(" ---- " * 3)
print("|", board[0], " ", "|", board[1], " ", "|", board[2], " ", "|")
print(" ---- " * 3)
print("|", ... |
username=input("enter the user name\t")
password=input("Enter the password\t")
hidden_password=len(password)*"*"
print(f"yeah! your username is {username} \n your secret password is\t{hidden_password}")
|
# .endswith() => metnin parametrede gönderdiğiniz değer ile bitip bitmediğini True / False değer olarak döner.
metin = "murat vuranok"
sonuc = metin.endswith("ok")
if sonuc:
print("metin ok kelimesi ile bitmektedir.")
else:
print("metin ok kelimesi ile bitmemektedir.")
#Ternary kullanımı
print("metin ok k... |
import datetime
now = datetime.datetime.now()
print(str(now))
#2019-07-21 10:21:20.236668
print(repr(now))
#datetime.datetime(2019, 7, 21, 10, 22, 2, 890202
class Personel:
def __init__(self,isim):
self.FirstName = isim
def __repr__(self):
return "Personel ( '{}', '{}' )".format(self.FirstN... |
# Dısarıdan aldığı ismi ve soyisime göre mail adresi oluşturan metot. (isim.soyisim@bilgeadam.com)
# Kulanıcı 2. parametreye değer girmeyebilir.
def Mail(a,b = None):
mail = ""
if b is None:
mail ="{}@bilgeadam.com".format(a)
else:
mail = "{}.{}@bilgeadam.com".format(a,b)
print(mail)
... |
# Mantıksal Operatorler
#----------------------
# and => Sorguya katılan her bir koşulun sağlanması
# or => Sorguya katılan herhangi bir koşulun sağlanması
# not => Sorgula olumsuzlık katar; True ise False, False ise True döndürür.
user_name = input("Lütfen kullanıcı adınızı giriniz : ")
if user_name == "admin" : ... |
try:
number = int(input("Lütfen birinci sayiyi giriniz : "))
number2 = int (input("Lütfen ikinci sayiyi giriniz : "))
toplam = number+number2
fark = number-number2
bolum = number/number2
carpim = number*number2
print("Sayilarin toplamı : ",toplam,
"\nSayıların farkı : ",fark,
... |
# Tanımlama şekli
# Bir dizinin maksimum index değeri, eleman sayısının bir eksi değeridir.
sehirler = ["ankara","edirne","eskisehir","istanbul","kars","kayseri","istanbul"] #List
# eleman sıra no : 1,2,3,4,5,6,7
# eleman index no : 0,1,2,3,4,5,6
print(sehirler[0])
index = len(sehirler)-1
print(sehir... |
#Şifrenin 3 defa yanlış girilmesi durumunda kullanıcıyı uyaran uygulama
#password = "abc123"
#fail_count = 0
#for i in range(3):
# password_user = input("Şifrenizi giriniz : ")
# if (password==password_user):
# print("Giriş Sağlandı")
# break
# else:
# print("Hatalı şifre girdiniz.")
# ... |
def fib1(n):
"""in tabe ozve n om donbale fibonachi ra midahad"""
if n==1 or n==2:
return 1
return fib1(n-1)+fib1(n-2)
list1=[]
def fib2(n):
"""in tabe listi az n ozve avval donbale fibonachi ra midahad"""
i=n
while n:
if fib1(n) not in list1:
list1.append(fib1(n))
... |
'069'
a=('Germany','France','UK','Spain','Italy')
print(a)
b=input('\nplease enter one of the vountries above: ')
i=0
for name in a:
if b.upper()==name.upper():
print(i)
i+=1
'070'
j=0
c=int(input('now enter a number (from 0 to 4): '))
for value in a:
if j==c:
print(value)
j+=1
'071'
sp... |
# Comparison of the Kalman filter and the histogram filter.
# 06_f_kalman_vs_histogram_filter
# Claus Brenner, 29 NOV 2012
from distribution import *
from math import sqrt
from matplotlib.mlab import normpdf
from pylab import plot, show, ylim
def move(distribution, delta):
"""Returns a Distribution that h... |
#coding:utf-8
import random
import time
def regiun():
'''生成身份证前六位'''
#列表里面的都是一些地区的前六位号码
first_list = ['360881','360802','120101','130102','440881','110100','110101','110102','110103','110104','110105','110106','110107','110108','110109','110111']
first = random.choice(first_list)
return first
def... |
try:
a = 5/0
print(a)
except ZeroDivisionError as err:
print('Ты тупой - делишь на ноль')
print('123')
while True:
try:
number = int(input("Введите число:"))
print("Число умноженное на 5: {0}".format(number*5))
print("10 делим на {0} = {1} ".format(number, 10/number... |
print("Good boys")
p = 5
print(p)
b = p
print(b, p)
p = 'Halid'
b = 'Gadzhi'
d = "50"
p = 5
p = p * 10
p = str(p) + d
boo = False
h = 'Halid'
g = (h + ' ') * 10
print(b[::-1], p, g[:-1])
print(len(h))
str1 = "кошки, собаки,арбузы, грызуны"
lis = str1.split(',')
print(lis)
lis2 = ['halid','... |
name = 'Абдурахман'
age = 14
coolness = 20.3
print(name + " красавчик " + "Его возраст: " + str(age)
+ " Он крут на " + str(coolness) + "%")
print("%10.7s красавчик. Его возраст %10.5d лет. \
Его крутость %10.2f%%" % (name, age,coolness))
print("{0:ы^20s} красавчик. Его возраст {0} лет. \
Его крутость {0}%".... |
import random
def get_card(player):
while True:
yield player.pop()
def play(player1,player2):
k = 0
global player1_count, player2_count
for card1, card2 in zip(get_card(player1), get_card(player2)):
k += 2
print(card1,card2)
if card1[0] > card2[0]:
... |
menu = {
"breakfast": {
'hours': '8:00',
'items': [ 'Яихница','Чай']
},
'lunch': {
'hours': '12:00',
'items': ['Шамбургер', 'Суп', 'Компот']
}
}
print(menu)
import json
menu_json = json.dumps(menu)
print(menu_json)
with open('menu.json','wt',encoding='utf-8') as f1:
f1.write(menu_json)
me... |
price = {"энергия":1542,"отопление":1542,"горячая вода":92}
def show_price(usluga):
print("цена на {0} = {1}".format(usluga, price[usluga]))
def est_usluga(usluga):
if usluga in price:
return True
else:
return False |
class Chert:
count = 0
@classmethod
def show_count(cls):
print("У нас на районе {0} черта".format(cls.count))
def __init__(self,name,hair,strengh):
self.name = name
self.hair = hair
self.heeyar = True
self.strengh = strengh
self.__jagua... |
import sqlite3
def create_db():
curs.execute("""CREATE TABLE IF NOT EXISTS questions
(type VARCHAR(50) PRIMARY KEY,
question VARCHAR(250))""")
ins = "INSERT OR REPLACE INTO questions VALUES(?, ?)"
curs.execute(ins,('shmot','За шмот поясни?'))
curs.execute(ins,('age','Сколько тебе есть?'))... |
example=input("Give input: ")
def pal(example):
b=example[::-1]
if example==b:
return "True"
return "false"
print(pal(example)) |
import mysql.connector # to connect python to a mysql database
import requests # will allow us to send HTTP requests to get HTML files
from requests import get
from bs4 import BeautifulSoup # will help us parse the HTML files
import pandas as pd # will help us assemble the data into a DataFrame to clean and analyze it
... |
# Listing_8-4.py
# Copyright Warren & Carter Sande, 2013
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version $version ----------------------------
# A loop using range()
for looper in range (1, 5):
print looper, "times 8 =", looper * 8
# 运行为times 8 = 8
# times 8 = ... |
""" Write a function that computes the volume of a sphere given its radius.
Formula is 4/3 pi r^3 """
from math import pi
def vol(rad):
return (4/3)*pi*(rad**3)
print(vol(2))
""" Write a function that checks whether a number is in a given range (inclusive of high and low) """
def ran_check(num,low,high):
re... |
""" SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order
spy_game([1,2,4,0,0,7,5]) --> True
spy_game([1,0,2,4,0,5,7]) --> True
spy_game([1,7,2,0,4,5,0]) --> False """
from os import truncate
def spy_game(nums):
code = [0,0,7,'x']
for num in nums:
... |
"""Create a dictionary and perform some modifications to it"""
birthmonths = {
'Radhila' : 'August',
'Akash' : 'March',
'Anjali' : 'Jan',
'Saahil' : 'April'
}
print('Anjali\'s birth month is:', birthmonths['Anjali'])
del birthmonths['Radhila']
print('The number of contents in the dictionary is:', (... |
#!/Users/Radhika/Documents/Udemy/anaconda/bin/python
"""WAP that prints the numbers from 1 to 100, but
- for multiples of 3 print “Fizz” instead of the number and
- for the multiples of 5 print “Buzz” and
- for numbers which are multiples of both 3 and 5 print “FizzBuzz”"""
for x in range (1,100+1):
if ((x %... |
def celsius_to_fahrenheit(celsius):
fahrenheit = celsius * 9/5 + 32
print("{}°C to {}°F".format(celsius, fahrenheit))
def fahrenheit_to_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
print("{}°F to {}°C".format(fahrenheit, celsius))
def menu():
print("Program do konwersji temperatury w r... |
class MailChimpBaseException(Exception):
pass
class MailChimpError(MailChimpBaseException):
""" Represents an error returned from the MailChimp API. """
def __init__(self, message, code):
MailChimpBaseException.__init__(self, message)
self.code = code
class MailChimpGroupingNotFound(MailCh... |
import sys
import math
def draw(l1,l2,w1,w2):
for i in range(len(w2)):
o=[]
for j in range(len(w1)):
if i == l2:
o.append(w1[j])
elif j == l1:
o.append(w2[i])
else:
o.append(" ")
print(' '.join(o))
# Auto-generated code below aims at helping you parse
# the standard input according to the p... |
#!/usr/bin/python2
"""
Reads one or more hex encoded values from a file (split by newlines),
writes them to the specified subdir using the SHA1 of the contents as
the file name.
"""
import os
import sys
import hashlib
def main(args=None):
if args is None:
args = sys.argv
if len(args) != 3:
p... |
# receive integer
number = int(input())
# write a function if the number is perf or not
def is_number_perfect(num=number):
is_perfect = False
if num < 0:
return "It's not so perfect."
summary_of_divisors = 0
for numbers in range(1, num):
if num % numbers == 0:
s... |
distance_in_meters = int(input())
kilometres = distance_in_meters / 1000
print(f"{kilometres:.2f}")
|
data = input()
targeted_cities = {}
# {'Tortuga': [345000, 1250], 'Santo Domingo': [240000, 630], 'Havana': [410000, 1100]}
while not data == "Sail":
city, population, gold = data.split("||")
population = int(population)
gold = int(gold)
if city in targeted_cities:
targeted_cities[city][... |
student_academy = {}
n = int(input())
sum_of_grades = 0
best_students = {}
for _ in range(n):
student_name = input()
grade = float(input())
if student_name not in student_academy:
student_academy[student_name] = []
student_academy[student_name].append(grade)
for student, grades in ... |
percent_number = int(input())
def loading_bar(percent=percent_number):
list_of_percents = []
list_of_percent_in_str = ""
if percent < 100:
for number in range(1, percent + 1):
if number % 10 == 0:
list_of_percents.append("%")
for element in list_of_per... |
first = int(input())
second = int(input())
third = int(input())
forth = int(input())
summary = first + second
summary1 = int(summary / third)
result = summary1 * forth
print(f"{result:.0f}") |
list_of_employee_happiness = list(map(lambda num: int(num), input().split(" ")))
# [1, 2, 3, 4, 2, 1]
happiness_improvement_factor = int(input())
multiplying_happiness = list(map(lambda num: num * happiness_improvement_factor, list_of_employee_happiness))
# [3, 6, 9, 12, 6, 3]
filtered = list(filter(lambda n... |
first_number = int(input())
second_number = int(input())
def factorial_division(num1=first_number, num2=second_number):
first_number_factorial = 1
second_number_factorial = 1
for number1 in range(1, num1 + 1):
first_number_factorial *= number1
for number2 in range(1, num2 + 1):
... |
n_in_str = input()
result = n_in_str.split(" ")
numbers_list = []
opposite_list = []
for index in result:
numbers_list.append(int(index))
for numbers in numbers_list:
opposite_list.append(numbers * (-1))
print(opposite_list) |
our_neighborhood = list(map(int, input().split("@")))
# 10, 10, 10, 2
command = input()
cupid_location = 0
house_count = 0
is_mission_successful = True
while not command == "Love!":
jump = command.split()[0]
length_of_jump = command.split()[1]
cupid_location += int(length_of_jump)
if cupid_loc... |
test_data = [ [1], [1, 2], [3, 4] ]
def backtrack(data, data_index, result=[], current_res=[], target_len=3):
if len(current_res) == target_len:
result.append(','.join(map(str, current_res)))
return
if data_index >= len(data):
return
for i in range(len(data[data_index])):
current_res.append(data[data_inde... |
#!/usr/bin/python
def trims(s):
while s[:1] == ' ':
s = s[1:]
while s[-1:] == ' ':
s = s[:-1]
return s
#
print(trims(' heloo '))
|
class Matrices:
def matrix(self, rows):
rows = int(rows)
# let's hope there won't be wrong column input
return [[float(j) for j in input().split()] for i in range(rows)]
def multiply_by_const(self):
rows, columns = input('Enter size of matrix: ').split()
print(... |
"""
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: "ab-cd"
Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo... |
# coding:utf-8
"""
685. Redundant Connection II
Hard
769
210
Add to List
Share
In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no pare... |
# Quiz 1 - Plot J(theta_0, theta_1)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
# the error function
def J(a, b):
# test data
data = np.array([[0.5, 0.9], [0.3, 0.7], [1.1, 2.3], [2.0, 4.3], [3.5, 6.8], [4.1, 8], [0, 0.1], [5.8, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 17 10:53:15 2019
@author: andrewpauling
"""
def snowfall(idx):
"""
snowfall from maykut and untersteiner 1971
"""
snow = 0
if idx <= 118 or idx >= 301:
snow = 2.79e-4
elif idx >= 119 and idx <= 149:
snow =... |
import threading
lock=threading.Lock() #创建一个线程锁(互斥锁)
num=100
#买票
def sale(name):
lock.acquire() #设置锁
global num
if num>0:
num=num-1
print(name,"卖出一张票,还剩",num,"张票")
lock.release() #释放锁
#程序执行时,程序本身就是一个线程,叫主线程
#手动创建的线程,叫子线程
#主线程的执行中,不会等待子线程执行完毕,就会直接执行后面的代码
#售票窗口(2个线程)
while 1==1:
if num>0:
ta=threading.Thre... |
# -------------------------Python 运算符-------------------------------
# 什么是运算符?
# 本章节主要说明Python的运算符。举个简单的例子 4 +5 = 9 。 例子中,4 和 5 被称为操作数,"+" 称为运算符。
# Python语言支持以下类型的运算符:
# 算术运算符
# 比较(关系)运算符
# 赋值运算符
# 逻辑运算符
# 位运算符
# 成员运算符
# 身份运算符
# 运算符优先级
# ------Python算术运算符------
# 以下假设变量: a=10,b=20:
# + 加 - 两个对象相加 a + b 输出结果 30
# - 减 -... |
"""Contains a tool for converting decimal numbers to binary strings"""
def dec2bin(x, num_dig, wrap_in_quotes=True):
s = bin(x)
s = s.replace("0b", "")
assert(num_dig >= len(s))
if len(s) < num_dig:
num_zeros = num_dig - len(s)
s = "0" * num_zeros + s
if wrap_in_quotes:
ret... |
'''
Created on 11.01.2018
@author: tfuss001
'''
def dreh(lst):
if len(lst) == 1:
return lst
else:
print(str(lst[1:]) + "+" + str(lst[0]))
return dreh(lst[1:]) +[lst[0]]
lst=[1,2,3,4,5]
print(dreh(lst))
|
# Copyright (c) Vera Galstyan Jan 2018
numbers = list(range(1,10))
for number in numbers:
if number == 1:
print("1st")
elif number == 2:
print("2nd")
elif number == 3:
print("3rd")
else:
print(str(number) + "th") |
"""
Axis class
==========
Axis is a named ordered collection of values.
For these doctests to run we are going to import numcube.Axis and numpy.
>>> from numcube import Axis
>>> import numpy as np
Creation
--------
To create an Axis object, you have to supply it with name and values. Name must be a string,
values mus... |
#!/usr/bin/env python3
"""deep NN performing binary classififcation"""
import numpy as np
class DeepNeuralNetwork:
"""Deep Neural Network Class"""
def __init__(self, nx, layers):
"""nx is number of input values"""
if type(nx) is not (int):
raise TypeError("nx must be an integer")... |
#!/usr/bin/env python3
"""function calculates the integral of a polynomial"""
def poly_integral(poly, C=0):
"""function calculates the integral of a polynomial"""
coIndex = 0
dePoly = []
try:
if len(poly) < 1:
return None
except TypeError:
return None
# code chec... |
#!/usr/bin/env python3
"""function adds two arrays, element-wise"""
def add_arrays(arr1, arr2):
"""add arrays if same size"""
if len(arr1) != len(arr2):
return (None)
newList = []
for i in range(len(arr1)):
newList.append(arr1[i] + arr2[i])
return (newList)
|
#!/usr/bin/env python3
"""
calculates the specificity each class in a confusion matrix
"""
import numpy as np
def specificity(confusion):
"""
confusion is a confusion numpy.ndarray of shape (classes, classes)
classes is the number of classes
"""
for m in range(confusion.shape[0]):
negfp =... |
#!/usr/bin/env python3
"""
Initialize cluster centroids for K-means
"""
import numpy as np
def initialize(X, k):
"""
Initialize cluster centroid for K-means
:param X: np.ndarray, shape(n, d)
contains data set used for K-means
:param k: pos integer containing the num clusters
:retu... |
#!/usr/bin/env python3
"""
Function determines if a markov chain is absorbing
"""
import numpy as np
def absorbing(P):
"""
determines if a markov chain is an absorbing chain
:param P: np.ndarray, (n,n), transition matrix
n: num of states in the markov chain
:return: True or False
"""
if ... |
#!/usr/bin/env python3
"""
function that calculates cost of NN using L2
"""
import numpy as np
def l2_reg_cost(cost, lambtha, weights, L, m):
"""
cost: cost of the network without L2 regularization
lambtha: regularization parameter
weights: dictionary of weights and biases (numpy.ndarrays) of NN
L... |
#!/usr/bin/env python3
"""
calculates the marginal probability of obtaining the data
"""
import numpy as np
from scipy import math, special
def intersection(x, n, P, Pr):
"""
calculates the intersection of obtaining this data
with the various hypothetical probabilities
"""
factor = math.factoria... |
#!/usr/bin/env python3
"""function normalizes(standardizes) a matrix"""
import numpy as np
def normalize(X, m, s):
"""
X is numpy.ndarray of shape (d, nx) to normalize
m is numpy.ndarray of shape (nx,) contains features of X
s is numpy.ndarray of shape (nx,) contains Std Dev of X
d id the num of ... |
#!/usr/bin/env python3
"""
Function that calculates the definiteness of a matrix
"""
import numpy as np
def definiteness(matrix):
"""
calculates definiteness of a matrix
:param matrix: list of lists
:return: the string: Positive definite,
Positive semi-definite, Negative semi-definite,
Negativ... |
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5)
student_grades = np.random.normal(68, 15, 50)
"""data format"""
bin_edges = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
plt.hist(student_grades, align='mid', bins=bin_edges, edgecolor='black')
"""graph design"""
plt.ylabel(... |
#!/usr/bin/env python3
"""Class represents a binomial distribution"""
class Binomial:
"""Class represents a binomial distribution"""
def __init__(self, data=None, n=1, p=0.5):
"""Binomial distribution"""
if data is None:
if n <= 0:
raise ValueError("n must be a posi... |
#!/usr/bin/env python3
"""Class represents a normal distribution"""
class Normal:
"""Class represents a normal distribution"""
def __init__(self, data=None, mean=0., stddev=1.):
"""Normal Distribution"""
if data is None:
if stddev <= 0:
raise ValueError("stddev mus... |
#!/usr/bin/env python3
""" Write script that displays the up coming launch"""
import requests
if __name__ == '__main__':
# need url
url = "https://api.spacexdata.com/v4/launches/upcoming"
# request url
launchData = requests.get(url).json()
# set date type for unbound value comparison
date = fl... |
# https://www.hackerrank.com/challenges/python-string-formatting
def print_formatted(number):
# your code goes here
l = len(bin(number)[2:])
for i in range(1,number+1):
i_octal = oct(i)[2:]
i_hex = hex(i)[2:].swapcase()
i_bi = bin(i)[2:]
i_str = str(i)
print(i_str.rju... |
import random
s=["самовар", "весна", "лето"]
w=random.choice(s)
word=list(w)
l=random.choice(w)
lett=word.index(l)
word[lett]='?'
print(''.join(word))
a=input('Введите букву:')
if a==l:
print('Победа!')
print('Слово:', w)
else:
print('Увы!Попробуйте в другой раз.')
print('Слово:', w)
|
#Se crea la clase padre, donde ésta misma tomará posteriormente los métodos para las clases hijas .
class Juego:
__vidas = 0
#Método constructor, el cual contiene la palabra init, seguida de sus respectivos atributos, con sus reglas para crear el mismo método.
def __init__(self, vidas):
self.__vida... |
import random
# controlled by player
class Rocket(object):
ver_velocity = 0
hor_velocity = 0
max_speed = 3
def __init__(self, x, y):
self.weapon = 'red'
self.x = x
self.y = y
def move(self, ver, hor):
if ver != 0 or self.ver_velocity !=0:
if ver != 0 and... |
import os #used for path making
import io #used for encoding option when writing
from make_articles_dico import make_articles_dico
from scrape_article_content import scrape_article_content
papers_dico = {"huffingtonpost" : 'http://huffingtonpost.com'}
def scraping(papers_dico):
#make_articles_dico=fct : (paper_... |
#!/usr/bin/env python
# coding: utf-8
# # Lab 07: The Internet
#
# - **Name**: Colton R. Crum
# - **Netid**: ccrum
# ## Activity 1: SpeedTest
#
# For the first activity, you are to measure the speed of various networking technologies by using the [SpeedTest] website. You are to use the following three connection ... |
def main():
message = 'GUVF VF ZL FRPERG ZRFFNTR'
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for key in range(len(letters)):
translated = ''
for symbol in message:
if symbol in letters:
num = letters.find(symbol)
num = num - key
if nu... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 29 10:11:50 2014
@author: 11111042
"""
def buscar(n):
list1 = ["Life","The Universe","Everything","Jack","Jill","Life","Jill"]
count = 0
for i in range(1,len(list1)):
if count<len(list1) and list1[count]!=n:
count = count + 1
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 22 10:01:03 2014
@author: 11111042
"""
def quickSort(lista):
menorLista = []
pivotLista = []
mayorLista = []
if len(lista) <= 1:
return lista
else:
pivot = lista[0]
for i in lista:
... |
# -*- coding: cp1252 -*-
def main():
nombre = input("Ingrese su nombre: ")
password = input("Ingrese su clave: ")
if nombre == "Andrea" and password == "12345":
print ("Bienvenida", nombre)
elif nombre == "Fred" and password == "Rock": #else_ if es lo mismo que elif
print ("Bienvenido", nombre)
else:
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 15 10:20:52 2014
@author: 11111042
"""
def buscarSecuencial(lista, n):
listaAuxiliar = []
for i in range(0,len(lista)):
if lista[i] == n:
listaAuxiliar.append(i)
return listaAuxiliar
def buscarRecursivo(lista, n, indice):
if indic... |
from weatbag import words
class Tile:
def __init__(self):
self.challenge_completed = False
self.minutes = "40"
def describe(self):
print("You see two children who you notice now are a boy and a girl.\n"
"They are playing and running around a raft.\n")
if not self.... |
import projection_virtual_side
def sort_asterix(pattern, convert=str):
"""
Function to create a sorting function for a given pattern using a callable to convert what ever is found with asterix.
Parameters
----------
pattern : str
Pattern to sort for.
If there is no asterix in the... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 6 17:00:45 2018
@author: wmy
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
import math
import sklearn
import sklearn.datasets
from opt_utils import load_params_and_grads, initialize_parameters, \
forward_propagation, backward_pro... |
# by eric
# 2018-08-16
# inspired by cheetah software
import numpy as np
import matplotlib.pyplot as plt
from math import pi, sin
def circular(y0, yf, x):
if (x<0) | (x>1):
print('phase out of range')
y = y0 + (yf - y0) * (sin((x - 0.5)*pi) + 1)/2
return y
class FootSwingTrajectory:
def _... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.