text stringlengths 37 1.41M |
|---|
import cv2
import matplotlib.pyplot as plt
import numpy as np
#programa coordenada de bordes funciona y investigar como funciona tanto filtro
#https://bretahajek.com/2017/01/scanning-documents-photos-opencv/
imagen = cv2.imread("papel.jpg")
rows, cols, channel = imagen.shape
print([rows,cols])
#img = np.resize( img,... |
numbers = [5, 10, 7, 9]
for i in range(len(numbers)):
numbers[i] = pow(numbers[i],3)
print("Original Numbers:", numbers)
print("Min:", min(numbers))
print("Max:", max(numbers))
print("Sum:", sum(numbers))
print("Changed Numbers:", numbers)
|
"""
第三章
3-2 自行連接LED
從"machine"匯入"Pin"類別的方式
在第16腳接LED
"""
#從"machine"匯入"Pin"類別
from machine import Pin
#匯入"time"模組才能執行sleep()
import time
#在16腳輸出高電位
led = Pin(16, Pin.OUT)
#腳16輸出高電位(亮燈)
led.value(1)
#腳16輸出低電位(不亮燈)
led.value(0)
for i in range(3):
led.value(0)
time.sleep(0.5)
led.value(1)
time.sle... |
def RemoveVowels(str):
if not str:
return ""
if str[0] in ['a','e','i','o','u','A','E','I','O','U']:
return RemoveVowels(str[1:]) #it recursively looks at the rest of the string
else :
return str [0] + RemoveVowels(str[1:]) #it adds the character and recursively looks at the rest of... |
from typing import List, Dict, Tuple, Union
class Activities:
def __init__(self):
self.count = int(input())
self.activities = self.initialize_activities()
self.cameron_calendar = []
self.jamie_calendar = []
def initialize_activities(self):
activities = [[*[int(val) for ... |
#I'm getting the name of the file and converting it to a string (even though it is a string already)
#this is just for consistency in the code
print ("enter the name of the file you would like to decrypt")
fileName = input()
fileName = str(fileName)
#now I am opening the file, this time in read mode.
sensitiveFil... |
#!/usr/bin/python3
"""
Returns the perimeter of the island described in grid
"""
def island_perimeter(grid):
"""
Returns the perimeter of the island described in grid
"""
cnt = 0
perim = 0
while cnt < len(grid):
mv = 0
while mv < len(grid[0]):
if grid[cnt][mv] == 1... |
# def is called a function
def print_hello_world():
print("Hello")
print("World")
def print_multiples_of_six():
a = 6
print("6 x 1 =", a * 1)
print("6 x 2 =", a * 2)
print("6 x 3 =", a * 3)
print("6 x 4 =", a * 4)
print("6 x 5 =", a * 5)
print("6 x 6 =", a * 6)
print("6 x 7 =",... |
from PIL import Image
import sys
#######################################################
# gets the legth of the message in bits
# @param message - the message to encode
# @return - the length of the message in bits
#######################################################
def getLength(message):
# check ... |
#!/usr/bin/env python3
import random
print('please enter the Dice you want to roll in the Format ndx,')
print('where n is the count of dices, and x is the number of possible values of the dice, e.g. 2d6')
diceRaw = input()
diceList = diceRaw.split("d")
diceFaces = int(diceList[1])
diceCount = int(diceList[0])
diceOut ... |
# part 1 function definition
# with optional arguments - as discussed together
def format_name(first_name, last_name, middle_name=None):
if middle_name:
full_name = f"{first_name.title()} {middle_name.title()} {last_name.title()}"
else:
full_name = f"{first_name.title()} {last_name.title()}"
... |
class Composer:
""" Defining a class for composers"""
def __init__(self, name, nationality, period):
self.name = name
self.nationality = nationality
self.period = period
def youtube(self):
return (f'{self.name} is currently playing on my computer.')
Bach = Composer('J.S Bach', 'German', 'Baro... |
'''
Create a function called 'americanize' that takes a string as argument,
transforms it into ALL CAPS, and then prints it as a subliminal part
of the american flag. E.g.:
|* * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO|
| * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO|
|* * * * * * * * * * OOOOOOOOOOOOOOOOOOOOOOOOO|
| ... |
#!/usr/bin/env python
# coding=utf-8
# 我自己的方法就是找到之字形输出的规律
# 更好的方法,是更改index来输入每个字符
class Solution(object):
"""docstring for """
# def convert(self, s, numRows):
# s_num = len(s)
# n = 2 * numRows - 2
# l = []
# if s_num <= numRows or numRows == 1 or numRows == 0:
# r... |
class solution(object):
"""docstring for solution"""
#方法1
def countBits(self,num):
cout=[0]
for x in range(num+1):
cout.append(bin(x).count('1'))
return cout
#方法2,x&(x-1)计算1的个数
def countBits(self,num):
cout=[]
num1=0;
for x in range(num+1):
while x:
x=x&(x-1)
num1+=1
cout.append(num1)
... |
# coding: utf-8
import sqlite3
# 入力の変数を宣言
dbName = input('作るデータベースの名前を入力してください' + '\n')
tbName = input('作るテーブルの名前を入力してください' + '\n')
# DBの作成とDBを操作するための変数を宣言
conn = sqlite3.connect(dbName + '.db')
curs = conn.cursor()
# テーブルを作成し、カラムは値・テキストが2つ
curs.execute('CREATE TABLE ' + tbName + ' (userID INTEGER, lastName TEXT, f... |
# Goncalo Botelho Mateus, 99225
def eh_tabuleiro(tab):
# eh_tabuleiro: universal -> booleano
"""
A funcao recebe um argumento de qualquer tipo e devolve True se for um
tabuleiro e False caso contrario, sem nunca gerar erros.
"""
if type(tab) is tuple and len(tab) == 3:
for tup in tab:
... |
def compare(str, sample):
i = 0 #нумератор строки
j = 0 #нумератор шаблона
if(str == ""): #проверка для пустой строки
for s in sample:
if(s != "%"):
return "NO"
length = len(sample) #найдем длину сэмпла
k = 1
while k < length: #превращяем все ряды процентов в ... |
from abc import ABC, abstractmethod
class AbstractArray(ABC):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def print(self):
pass
@abstractmethod
def create(self, n):
pass
def __del__(self):
print('Deleted!')
class Array(AbstractArray):
d... |
# 최빈값 구하기
def solution(array):
answer = 0
counter = {}
# 1. 빈도수 확인 (배열을 돌면서)
for number in array:
counter[number] = counter.get(number, 0) + 1 # 1개 추가
# 결과
# counter = {
# 1: 1,
# 2: 1,
# 3: 3,
# 4: 1,
# }
print(counter)
... |
def sortLexo(words):
words.sort()
print(words[0])
A = []
string = input()
for i in range(0,len(string)):
if string[i] not in A:
A.append(string[i])
B = []
for i in A:
new_str = string.replace(i,"")
B.append(new_str)
sortLexo(B)
|
import numpy as np
import random
N = random.randint(1, 10)
A = np.random.randint(0, 100, (N, N))
print("Матрица:\r\n{}".format(A))
a = np.diagonal(A, 1)
a_sum = a.sum()
print("Элементы которые выше главной диагонали: \n" + str(a) + "\nИх сумма = " + str(a_sum))
b = np.diagonal(A, -1)
b_sum = b.sum()
pri... |
#Classe Bola: Crie uma classe que modele uma bola:
#Atributos: Cor, circunferência, material
#Métodos: trocaCor e mostraCor
class Bola:
def __init__(self,cor,circunferencia,material):
self.cor = cor
self.circunferencia = circunferencia
self.material = material
def troca... |
#Classe Pessoa: Crie uma classe que modele uma pessoa:
#Atributos: nome, idade, peso e altura
#Métodos: Envelhercer, engordar, emagrecer, crescer. Obs: Por padrão, a cada ano que nossa pessoa envelhece, sendo a idade dela menor que 21 anos, ela deve crescer 0,5 cm.
class pessoa:
def __init__(self,nome,idade... |
def twodimrecursive(mat, verbose=True):
import logging
if verbose:
logging.getLogger().setLevel(logging.DEBUG)
else:
logging.getLogger().setLevel(logging.INFO)
def depth(mat):
checks = []
depths = []
logging.debug(f'Entering {mat}')
... |
player_height = float(input("請輸入球員身高(公尺):"))
player_weight = float(input("請輸入球員體重(公斤):"))
player_bmi = player_weight / player_height**2
bmi_label = None
if player_bmi > 30:
bmi_label = 'Obese'
if player_bmi <= 30 and player_bmi > 25:
bmi_label = 'Overweight'
if player_bmi <= 25 and player_bmi > 18.5:
... |
# Define functions for pop toc here
# write some pseudo code
# write a function if the number is divisible by 3
# def div_3(number):
# return number%3 == 0
def div3(num):
if num%3 == 0:
return True
else:
return False
# write a function if the number is divisible by 5
def div5(num):
... |
"""
programmer: me
program: double for loop
"""
for i in range(5):
print(i)
for j in range(20):
print(j)
print("Done!")
print("\n")
'''
programmer: me
program: average test score
'''
num_people = int(input("How many people are taking the test? "))
test_per_person = int(input("How many tests are be... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import shuffle, choice
class EpithetManager:
"""" Class for managing epithets."""
""" Dictionary for names(keys) and epithets. """
dict_epithets = {}
""" Current number of used epithets. """
counter = 0
""" Total number of epithets ... |
import streamlit as st
# To make things easier later, we're also importing numpy and pandas for
# working with sample data.
import numpy as np
import pandas as pd
header = st.beta_container()
dataset = st.beta_container()
features = st.beta_container()
model_training = st.beta_container()
st.title('Analysi... |
"""
Small, reusable utility functions to be used in other parts of the program.
"""
from sys import stdin
from contextlib import contextmanager
import operator
from string import ascii_lowercase
def contained(string, charset):
"""
Does a string only contain characters from this set?
"""
return set(s... |
import util
def minify(path):
"""
Remove whitespace from a data file. Outputs to stdout to be redirected.
"""
with util.read_file_or_stdin(path) as f:
while True:
c = f.read(1)
if not c: break # EOF
if c.isspace(): continue # remove whitespace
... |
'''
手绘中国象棋
'''
from tkinter import *
root = Tk()
root.title("中国象棋棋盘手绘")
can =Canvas(root,width =400, height =450)
can.create_line((0,2),(400,2),width=2)
for i in range(10):
can.create_line((0,i*50),(400,i*50),width=2)
can.create_line((3,0),(3,450),width=2)
for i in range(8):
can.create_line((i*50,0),(i*50,200),wid... |
#For loops in python
list1 = [["Aman", 1], ["Shubham", 3], ["Rohit", 6], ["Vikram", 10]] #This is list of list
tp = ("Aman", "Shubham", "Rohit", "Vikram") #tuple
# print(list1[0], list1[1], list1[2])
print("\n")
#Using list
for item, lollypop in list1:
print(item, "eats", lollypop ,"lollypops")
pr... |
#Exercise 1
#Create a dictionary and take input from the user and return the meaning og the word from the dictionary
print("***WELCOME TO THE MINI PYTHON DICTIONARY***")
d1 = {"Master":"गुरुजी", "Buisness":"व्यापार", "Yourself":"स्वयं", "Intrested":"इच्छुक"}
Search = input("Enter your word:- ")
b = Search.capitalize(... |
# If Else & Elif Conditionals in Python
var1 = 6
var2 = 56
var3 = int(input())
if var3 > var2:
print("Greater")
elif var3 == var2:
print("Equal")
else:
print("Lesser")
list1 = [5,6,7,8]
if 5 in list1:
print("Yes 5 is in the list")
if 13 not in list1:
print("No it's not in the list")
print(15 ... |
frequency = 0
found = False
seen = set()
while not found:
with open("input.txt") as f:
for line in f:
seen.add(frequency)
if line[0] == '-':
frequency -= int(line[1:])
else:
frequency += int(line[1:])
if frequ... |
import generatedata
import random
# Calculate the edge name for two points
def gen_name(point_a, point_b):
edge_name = [point_a[0], point_b[0]]
if (point_a[0] > point_b[0]):
edge_name = [point_b[0], point_a[0]]
return edge_name
# Calculate the euclidean distance
def calc_dist(point_a, point_b):
... |
from threading import Thread
from threading import Lock
i = 0
def someThreadFunction1(lock):
# Potentially useful thing:
# In Python you "import" a global variable, instead of "export"ing it when you declare it
# (This is probably an effort to make you feel bad about typing the word "global")
global i
... |
#Rotten tomatoes
from rottentomatoes import RT
import Main
import sqlite3
import json
api = '43h3hy2a4r6cuf3h3d4tzkqy'
def details(movie,detailinfo):
movie_data = RT(api).search(movie)
json_data = json.loads(movie_data)[0]
detail = json_data[detailinfo]
print detail
class Rottentomatoes(Main.Datafetch)... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
'''
We are going to predict the closing stock price of the day of a corporetion using the past 60 days stock prices.
the coperation will be facebook here.
'''
# In[1]:
#importing all the needed libraries
import math
import numpy as np
import pandas as pd
from sklear... |
n = int(input('How many numbers = '))
x = int(input('x = '))
y = int(input('y = '))
import random
A = [x, x, y]
print(A)
if n < 3:
print('Error')
exit(0)
for i in range(3, n):
A.append(A[i - 2] + (A[i - 1] / (2 ** (i - 1))) * A[i - 3])
print('\n{0}' .format(A)) |
"""
This is a base class for wine data set
"""
from abc import ABCMeta
from abc import abstractmethod
class Dataset(metaclass=ABCMeta):
""" __init__:
path is the prefix of the file and will be formatted by subset"""
def __init__(self, path, subset='train'):
# assert subset in ['train', 'eval']... |
print("Hello World")
message = 'Hello "1" World'
print(message)
message = "hello 'python' world"
print(message)
message = message.title()
print(message)
message = message.upper()
print(message)
message = message.lower()
print(message)
print("----------------------------------------------")
message2 = "I will print"
m... |
def main():
# write code here
receipt = []
total = 0
entered = input("Item (enter \"done\" when finished): ")
while entered != "done":
item_details = {}
item_details["name"] = entered
item_details["price"] = float(input("Price: "))
item_details["quantity"] = int(inp... |
#!/usr/bin/python
import random
loccities = ["Phoenix","San Diego","Ontario","Burbank","Los Angeles","Orange County","Las Vegas","San Jose","San Francisco","Oakland"]
forcities = ["Phoenix","London","Rome","Frankfurt","Tokyo","Manila","Madrid","Beijing","Shanghai","Paris","Barcelona","Hong Kong","Singapore","Cancun",... |
def check(str):
print(str)
print(str[::-1])
str1=raw_input("enter the string:")
check(str1)
|
# Inheritance
class Food:
def __init__(self, name, price):
self.name = name
self.price = price
print(f"{self.name} Is Created From Base Class")
def eat(self):
print("Eat Method From Base Class")
class Apple(Food):
def __init__(self, name, price):
super().__init_... |
# PracticalSliceEmail
name = input("Enter Your Name: ")
email = input("Enter Your Email: ")
userName = email[:email.index("@")]
print(f"Hello {name} Your Email Is {email} And UserName Is {userName}") |
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import random
import math
# declare global variables
low = 0
high = 100
secret_number = 0
num_... |
import pandas as pd
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
from flask import Flask, redirect, url_for, request
excel_file = "/home/arjun/Desktop/flask_proj/movies1.xlsx"
df = pd.read_excel(excel_file, sheet_name="movies")
flag = 0
name = df["movie_title"]
genre = df["genres"]
actor1 = df["actor_1_... |
def get_answer():
sum_of_squares = 0
square_of_sum = 0
for i in range(101):
sum_of_squares += i ** 2
square_of_sum += i
square_of_sum = square_of_sum ** 2
dif = square_of_sum - sum_of_squares
return dif
if __name__ == '__main__':
print(get_answer()) |
'''3-1. Names: Store the names of a few of your friends in a list called names. Print
each person’s name by accessing each element in the list, one at a time.'''
# names = ['Friend 1', 'Friend 2', 'Friend 3']
# print(names[0])
# print(names[1])
# print(names[2])
'''3-2. Greetings: Start with the list you used in Exer... |
# Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
# Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
def maxSub(nums):
if len(nums)... |
# Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
# Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?
def missingNo(nums):
return sum(i for i in range(len(nums)+... |
# Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
# You may assume that the array is non-empty and the majority element always exist in the array.
## Hint: What data structure can keep track of two data at the same time?
## Hint: How do yo... |
"""
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You ma... |
# 1.1 Implement an algorithm to determine if a string has all unique characters. What if you
# can not use additional data structures?
# def uniqueChars1(str):
# mydict = {}
# for each in str:
# if each not in mydict:
# mydict[each] = 1
# else:
# mydict[each] += 1
# ... |
#!/usr/bin/python
"""
This is the code to accompany the Lesson 3 (decision tree) mini-project.
Use a Decision Tree to identify emails from the Enron corpus by author:
Sara has label 0
Chris has label 1
"""
import sys
import time
sys.path.append("../tools/")
from email_preprocess import prepr... |
import time
# 当此模块作为程序入口时(模块名为"__main__时可以使用")
if __name__ == "__main__":
def getNumbers(a):
a += "#"
r = list()
innumber = False
iBegin = 0
for i in range(len(a)):
ch = a[i]
if 48 <= ord(ch) <= 57:
if not innumber:
... |
A = []
for i in range(1,27):
A.append(i)
print(A) |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
smallH = sma... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
current = head
while ... |
class User:
bank_name = "First National Dojo"
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 1000
def make_deposit(self, amount):
self.account_balance += amount
return self
def make_withdrawl(self, amount):
sel... |
# Libraries needed to be imported
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
import matplotlib as mpl
## Method to plot Climate (Warming) Stripes and/or Time Series (if asked) :
def plot_stripes(Tmax, Tmin, t, station_name, plot_tseries):
"""
A Python function that take... |
names = ["Вася", "Маша", "Петя", "Валера", "Саша", "Даша"]
def find_person(name):
while len(names) > 0:
if names.pop(0) == name:
print( name + ' нашелся')
break
else:
print( name + ' не нашелся')
find_person('Саша')
find_person('Кирилл')
|
def insertionSort(ar):
var =ar[-1]
found = False
for i in range(-1, -len(ar)-1, -1):
if i == -len(ar) and found == False:
ar[0] = var
found = True
print " ".join(map(str, ar))
if(found == False):
ar[i] = ar[i-1]
if(ar[i-1] < var):
ar[i] = var
found = True
print " ".join(map(str, ... |
def panagram(sen):
sen = sen.lower()
string = "abcdefghijklmnopqrstuvwxyz"
for char in string:
if char not in sen:
return False
return True
"""
sen = sen.lower()
dic = {}
for key in range(97,123):
dic[key] = False
for char in sen:
if ord(char) in dic:
dic[ord(char)] = True
var =True
for in... |
#!/usr/bin/env python3
"""Derive happiness in oneself from a good day's work"""
def poly_derivative(poly):
"""Derivative func"""
if len(poly) == 1:
return [0]
elif not isinstance(poly, list):
return None
elif len(poly) == 0:
return None
else:
return [poly[i] * i for... |
#!/usr/bin/env python3
"""Concatenate along axis function"""
def cat_matrices2D(mat1, mat2, axis=0):
"""Concatenates two matrices along specific axis
Args:
mat1 ([int]): a list of elements.
mat2 ([int]): a list of elements.
axis (int, optional): Defaults to 0.
"""
new_matrix =... |
#!/usr/bin/env python3
"""Initialize Poisson"""
class Poisson:
"""Represents a poisson distribution"""
def __init__(self, data=None, lambtha=1.):
"""Constructor method"""
if data is None:
if lambtha <= 0:
raise ValueError("lambtha must be a positive value")
... |
"""Sabes si es par o impar"""
Variable=17
if(Variable%2==0):
print("Si es par")
else:
print("Es impar")
"""Calculo de año biciesto o no"""
Año=2000
if(Año%4==0):
print("Su año tiene 366 dias , por lo tanto",Año, "es biciesto")
else:
print("Su año tiene 365 dias , por lo tanto",Año,"no es biciesto")
... |
# -*- coding: utf-8 -*-
import numpy as np
def make_batches(size, batch_size):
"""
Returns a list of batch indices (tuples of indices).
:param size: Size of the dataset (number of examples).
:param batch_size: Batch size.
:return: List of batch indices (tuples of indices).
"""
nb_batch =... |
enemy = {
'loc_x': 70,
'loc_y': 50,
'color': 'green',
'health': 100,
'name': 'Vasya'
}
print(enemy)
print("Location X = " + str('loc_x'))
print("Location Y = " + str('loc_y'))
print("His name is: " + enemy['name'])
enemy['rank'] = 'Admiral'
print(enemy)
del ene... |
class Hero():
def __init__(self, name, level, model):
self.name = name
self.level = level
self.model = model
self.health = 100
def show_hero(self):
if(self.health == 0):
print( "Hero destroyed!!!")
else:
description = (self.name + " Level ... |
from pyspark import SparkConf, SparkContext
import collections
def parse_data(line):
line_split = line.split(",")
age = int(line_split[2])
num_friends = int(line_split[3])
return (age, num_friends)
conf = SparkConf().setMaster("local").setAppName("FriendsByAge")
sc = SparkContext(conf=conf)
lines = ... |
#!/usr/bin/env python
from ADCDACPi import ADCDACPi
import time
import RPi.GPIO as GPIO
#The ADC DAC Pi uses GPIO pin 22 to control the LDAC pin on the DAC. For normal operation this pin needs to be kept low. To do this we will use the RPi.GPIO library to set pin 22 as an output and make it low.
GPIO.setwarnings... |
"""Find the sum of all the primes below 2 000 000"""
import time
start_time = time.time()
def is_prime(n):
# 1 is not a prime
if n <= 1:
return False
# If n is 2 or 3, it's prime
if n <= 3:
return True
# Check if n is divisible by 2 or 3
if n % 2 == 0 or n % 3 == 0:
re... |
import math
from time import time
start_time = time()
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i ** 2 <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
re... |
print "making the circles out of square"
import turtle
def draw_square():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.shape("circle")
brad.color("yellow")
brad.speed("normal")
j = 0
while(j<36):
i = 0
while(i<4):
brad.forward(... |
"""Users test model."""
# Django
from django.db.utils import IntegrityError
from django.test import TestCase
# Model
from users.models import User
class CreateUserTestCase(TestCase):
"""
Evaluate that the User model allows us to
create a user correctly.
"""
def setUp(self):
self.alan = ... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import f
from scipy.stats import norm
'''
This program performs an ANOVA F test followed by individual t tests
'''
def main():
# Input parameters
Nminusk = 10000
kminus1 = 2
step = 0.001
# Integrate the F-distribution to ... |
friends = ['Dylan','Van','Ify','Ben', 'Jermaine']
message = "Hello " + friends[0] + ". " + "How are you?"
print(message)
message = "Hello " + friends[1] + ". " + "How are you?"
print(message)
message = "Hello " + friends[2] + ". " + "How are you?"
print(message)
message = "Hello " + friends[3] + ". " + "How ar... |
"""
Python AST implementation of the parser
For this implementation to work each syntax in extensions to define
python_ast_name which is assigned a string of the class in python's ast module
for example addition and subtraction is implemented with BinOp so you'd do
class Addition(Node):
python_ast_name = "BinOp"... |
class Node (object):
UNSET_INDEX = -1
def __init__(self, weight):
self.index = Node.UNSET_INDEX
self.weight = weight
self.activate()
def __repr__(self):
return "<Node %s>" % self.get_index()
def get_index(self):
return self.index
def get_weight(se... |
import math
import re
def mainGame():
print("What range is your number in:")
numberChecking = True
while ( numberChecking ):
try:
numberRange = input()
minNumber, maxNumber = [int(x)for x in sorted(re.findall('\d+', numberRange)) ]
break
except ValueErr... |
import unittest
from seconds import Secs
class TestPush(unittest.TestCase):
def test_convert_to_secs(self):
# From minutes to seconds
print("From minutes:")
print(f" 2 minutes = {Secs('2m')}")
print(f" 5 minutes = {Secs('5 mins')}")
print(f" 10 minutes = {Secs('10 m... |
import numpy as np
from sklearn.datasets import load_iris
from sklearn import tree
# load_iris() will load all 150 rows of data from the
# iris wikipedia table
iris = load_iris()
# These are the indices of the test data we will be using
test_idx = [0, 1, 2, 50, 51, 52, 100, 101, 102]
print("The features are: " + str... |
# coding=utf-8
'''Escribe un programa que pida por teclado dos números y
que calcule y muestre su suma solamente si:
-los dos son pares
-el primero es menor que cincuenta
-y el segundo está dentro del intervalo cerrado 100-500.
En el caso de que no se cumplan las condiciones, en vez de la suma ha de
visualizars... |
# coding=utf-8
'''Escribe un programa que pida por teclado una cantidad de dinero y
que a continuación muestre la descomposición de dicho importe en el menor
número de billetes y monedas de 100, 50, 20, 10, 5, 2 y 1 euro.
En el caso de que alguna moneda no intervenga en la descomposición no se
tiene que visualiz... |
# coding=utf-8
'''Lee por teclado 5 números enteros positivos, y escribe cuál es el mayor de los números introducidos.'''
numeroA = int(input('Introduce un número entero positivo:'))
numeroB = int(input('Introduce un número entero positivo:'))
numeroC = int(input('Introduce un número entero positivo:'))
numeroD = int... |
# example 4.5
import random # you must add this at the top of your program to use the random functions
def main():
answer = random.randint(1, 10)
guess = 0
tooHigh = 0
tooLow = 0
valid = False
print("Guess a number between 1 and 10!")
while guess != answer:
valid = Fals... |
def reverseString(inputString):
return inputString[::-1]
# if __name__ == "__main__":
# print(reverseString("apple"))
# print(reverseString("nope"))
# print(reverseString("1234"))
|
# Regular expressions
import re
# Use Inflect for singular-izing words
import inflect
# Gensim for learning phrases and word2vec
import gensim
# For some reason, inflect thinks that there is a singular form of 'mass', namely 'mas'
# and similarly for gas. Please add any other exceptions to this list!
p = inflect.eng... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
get_ipython().run_line_magic('matplotlib', 'inline')
#
# # Tensors
# --------------------------------------------
#
# Tensors are a specialized data structure that are very similar to arrays
# and matrices. In PyTorch, we use tensors to encode the inputs and
# outpu... |
#!/usr/bin/env python
# coding: utf-8
# # Linear Regression in 1D - Prediction
# ## Simple linear regression - prediction
#
# In[1]:
import torch
w = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(-1.0, requires_grad=True)
def forward(x):
y=w*x+b
return y
# In[3]:
x=torch.tensor([1.0])
yhat=fo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 30 09:01:46 2020
@author: student
"""
# FLAMES game
n1=input("Enter the name").lower().replace(" ","")
n2=input("Enter the name").lower().replace(" ","")
d1=list(set(n1)-set(n2))
d2=list(set(n2)-set(n1)) #removing matchning letters
c=d1+d2 ... |
'''
Створіть масив А [1..7] за допомогою генератора випадкових чисел і виведіть його на екран.
Збільште всі його елементи в 2 рази.
Огороднік Марина Олександрівна, І курс, група 122А
'''
import numpy as np # імпортуємо бібліотеку numpy для роботи з масивами
from random import randint # імпортуємо функцію randin... |
# Научите Анфису отвечать на вопрос «Анфиса, как дела?» случайным образом.
# Для этого напишите функцию how_are_you() без параметров (да-да, функции могут не иметь параметров, это нормально).
# Пусть она возвращает случайный ответ из списка answers. Можете и сами дописать варианты :)
# здесь подключите библиотеку rand... |
# На основе заготовленного кода напишите функцию print_friends_count() для вывода количества друзей.
# Аргументом сделайте friends_count. Вызовите эту функцию не менее трёх раз с разными аргументами от 1 до 20.
def print_friends_count(friends_count):
if friends_count == 1:
print('У тебя 1 друг')
elif 2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.