text stringlengths 37 1.41M |
|---|
"""
This is a demo task.
Write a function:
def solution(A)
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−... |
import turtle
import random
turtle.screensize(canvwidth=500, canvheight=500)
def main():
value = 0
turtle.setpos(0, 0)
iteration = 1
while True:
targetX = random.randint(-400, 400)
targetY = random.randint(-400, 400)
value += find(targetX, targetY)
print(... |
# Problem Set 2019 - Problem 8
# Peter McGowan
# Started 2019-03-10
# Write a program that outputs today’s date and time in the format ”Monday, January 10th 2019 at 1:15pm”.
from datetime import datetime as dt # import datetime module
i = dt.now() # current datetime is set as value of i
def suffix(d): # if statemen... |
from bitarray import bitarray
"""
This class performs the PCY algorithm
"""
class PCY:
#Constructor that takes in the threshold percentage and the name of the file
def __init__(self, thresholdPercentage, fileName):
self.thresholdPercentage = thresholdPercentage
self.file = open(file... |
#!/usr/bin/env python3
def divide(a:float, b:float):
try:
# Intentionally raise an error.
x = a / b
except Exception as e:
# Except clause:
print("- Error occurred")
raise e
else:
print("-- Hi, this is the else block!")
return x
finally:
#... |
#!/usr/bin/env python3
lista = [ "nose", "tampoco", 100 ]
lista_nueva = list()
lista_nueva02 = list()
print('='*10)
try:
val = element
lista_nueva.append(val)
print("-- Dentro del try", val)
val = val + 20
lista_nueva02.append(val)
except Exception as e:
print("-- except", val, e)
continue
... |
import calendar
yy = 2020
mm = 11
yy = int(input("Enter year:"))
mm = int(input("Enter month:"))
print(calendar.month(yy,mm))
bye = input("To 'exit' the progrm type Exit: ")
|
# 序列指元素有序的排列并且通过下标偏移量访问到它一个或多个元素
# 序列分为字符串“abc”,列表[ 0, 'adad'],元组 ( "aaa","ccc")
# 随便输入年份判断生肖星座
chinese_zodiac = "鼠牛虎兔蛇马羊猴鸡狗猪"
# 通过下标输出元素
print(chinese_zodiac[0])
# 通过下标输出多个元素
print(chinese_zodiac[0:4])
# 从后往前输出
print(chinese_zodiac[-1])
# 判断元素是否在序列中 元素 in 序列
print('人' in chinese_zodiac)
print('猪' in chinese_zodiac)
... |
# 映射类型:字典 dict
# 字典包含哈希值和指向的对象 {'哈希值':对象}
# 建立一个空对象
dict1 = {}
print(type(dict1))
# 如何给字典增加值
dict2 = {'x': 1, 'y': 2}
dict2['z'] = 3
print(dict2)
# 统计生肖和星座
chinese_zodiac = "猴鸡狗猪鼠牛虎兔龙蛇马羊"
zodiac_name = (u'摩羯座', u'水瓶座', u'双鱼座', u'白羊座', u'金牛座', u'双子座', u'巨蟹座', u'狮子座', u'处女座', u'天秤座', u'天蝎座', u'射手座')
zodiac_days = (
... |
def split(string, pattern):
result = []
arr_of_index = []
if pattern in string:
if string[0] != pattern and string[-1] != pattern:
string = pattern + string + pattern
elif string[0] != pattern and string[-1] == pattern:
string = pattern + string
elif string[0]... |
from list import list
def isalpha(string):
alphabet = list('qwertyuiopasdfghjklzxcvbnm')
for i in string:
if i.lower() not in alphabet:
return False
else: return True
|
from random import randint
def generate_random_matrix(n):
return [[randint(-100, 100) for j in range(n)] for i in range(n)]
def print_formatted_matrix(matrix, text):
print(text)
print('\n'.join([''.join(['{:4}'.format(j) for j in i]) for i in matrix]))
print('\n\n')
|
from logic.count_polinomic_words import count_polinoms
from string_func.split import split
def main():
string = input("Enter a string: ")
print('Number of polinomic words in string:', count_polinoms(split(string, ' ')))
if __name__ == '__main__':
main()
|
def alghoritm(number):
result = []
while True:
if number == 1:
break
if number <= 0:
raise Exception("Number do not fit the task.")
if number % 3 == 0 and number != 6:
number /= 3
result.append(3)
else:
number -= 5
... |
import sys
date=input("Enter the date: ")
dd,mm,yy=date.split('/')
t_date=7
t_month=1
t_year=2020
dd=int(dd)
mm=int(mm)
yy=int(yy)
if (yy>t_year):
print("Sorry ,cannot check for a future date.")
sys.exit(0)
elif ((yy==2020) and (mm>t_month)):
print("Sorry ,cannot check for a future date... |
'''
Find if Given number is power of 2 or not.
More specifically, find if given number can be expressed as 2^k where k >= 1.
Input:
number length can be more than 64, which mean number can be greater than 2 ^ 64 (out of long long range)
Output:
return 1 if the number is a power of 2 else return 0
Example:
Input :... |
n = int(input())
steps = input()
level = 0
valley = 0
if steps[0] == "U":
level+=1
else:
level-=1
for i in range(1,len(steps)):
if steps[i] == "U":
level += 1
else:
level -= 1
if level == 0 and steps[i]=="U":
valley += 1
print(valley)
|
def caseChange():
string = input("Enter any sentence: ")
print(string.swapcase()) |
# OOP (Object Oriented Programming)
class Student:
default_gpa = 2.0
def __init__(self, name, major, gpa, is_on_probation):
self.name = name
self.major = major
self.gpa = gpa
self.is_on_probation = is_on_probation
def __init__(self, name, major, gpa, is_on_probation):
... |
# Lopez Chaidez Luis Enrique DDSIV
def ordenar(number1, number2):
"""Function that determines what number is bigger
Args:
number1 ([type]): [description]
number2 ([type]): [description]
Returns:
[type]: [description]
"""
if number1 == number2:
print(str(number1) + '... |
#luis Enrique Lopez Chaidez DDSIV
#Crea una tupla con valores ya predefinidos del 1 al 10,
# pide un índice por teclado y muestra el valor correspondiente del índice de la tupla.
nombres = ('Ana','Enzo','Eric','Eva','Hugo','Iván','Juan','Lara','Leo','Raúl')
cycle = True
while cycle:
try:
print(nombres[int... |
with open('pi_millions.txt') as file_object:
content = file_object.readlines()
print("This is SSSSSSS")
pi_number = ''
for s in content:
pi_number += s.strip()
#print(pi_number)
birthday = input("Enter your birthday, format:ddmmyyyy: ")
if birthday in pi_number:
print("Hurray! Your birthday appears in the... |
class Investment:
def __init__(self, principal, interest):
self.principal = principal
self.interest = interest
def value_after(self, n):
valueAfter = int(self.principal) * ((1 + (int(self.interest)/100)) ** int(n))
return str(valueAfter)
def __str__(self):
return ... |
import random
all_lessons = ('语文', '数学', '英语', '美术', '思品', '手工', '体育', '科学', '书法',)
var_lessons = []
for row in range(1,6):
row_data = []
for col in range(1,3):
if col == 1:
row_data.append(row)
else:
row_data.append(random.choice(all_lessons))
#print(row_data)
... |
#################################################################
#################### PROBLEM 04 #################################
#################################################################
"""
Write a program to convert the time inputted in minutes into hours and remaning minutes.
"""
## SOLUTION
time = i... |
#Variaveis.
vCartao = float(input('Quanto dinheiro há no seu cartão :'))
vPassagem = float(input('Quanto custa uma passagem :'))
dUso = float(input('Quantos vezes em um dia você utiliza este meio de transporte :'))
#Calculo de quantas passagens é possível utilizar.
print('O total de passagens que podem ser utilizadas é... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import turtle
import random
# Crea una ventana y un objeto Turtle
window = turtle.Screen()
window.bgcolor('black')
pen = turtle.Turtle()
pen.speed(0)
pen.hideturtle()
# Lista de colores para los corazones
colors = ['r... |
#!/usr/bin/env python
import sys
from Queue import PriorityQueue
def boolean_retrieval(inverted_list, q_words):
words, ret = [], []
for word in q_words:
if word not in inverted_list:
return ret
words.append(word)
n = len(words)
# current index for each id
idx = [0] * n
... |
# Introduction to Programming, Task 15: CapStone Project II
# Megan van Zyl, 23/04/2019
# Python code to make use of nested loops to create a number pyramid
for i in range (1, 10): #number of rows
for j in range(1, i + 1): #number of columns
print(i * j, end=" ")
print("\n") ... |
from sys import stdin
class MatrixError(BaseException):
def __init__(self, m1, m2):
self.matrix1 = m1
self.matrix2 = m2
class Matrix:
def __init__(self, matrix):
# создание копии
self.M = list(map(list, matrix))
def __str__(self):
s = list()
for row in se... |
from math import sqrt, fabs
a = float(input())
b = float(input())
c = float(input())
# Дискриминант
d = b**2 - 4*a*c
if d >= 0:
d = sqrt(d)
x1 = (-b - d) / 2 / a
x2 = (-b + d) / 2 / a
if fabs(x1 - x2) < 1e-60:
print(x1)
else:
print(x1, x2)
# elif d == 0:
# x1 = -b / 2 / a
# ... |
n = int(input())
va = n == 1 or (n > 20 and ((n-1) % 10 == 0))
vy0 = n == 2 or n == 3 or n == 4
vy2 = ((n-2) % 10 == 0)
vy3 = ((n-3) % 10 == 0)
vy4 = ((n-4) % 10 == 0)
vy = vy0 or (n > 20 and (vy2 or vy3 or vy4))
if va:
print(n, 'korova')
else:
if vy:
print(n, "korovy")
else:
print(n, "kor... |
"""
Creates a convolutionaly neural network (CNN) in Tensorflow and trains the network
to identify the facial emotion in an input image.
"""
import tensorflow as tf
from cvision_tools import detect_face, crop_face, convert_to_gray, resize_with_pad, over_sample, under_sample
from CohnKanadeDataset import CohnKanadeDa... |
def solution(numbers, hand):
pos = {1: [0, 0], 2: [0, 1], 3: [0,2], 4: [1, 0], 5: [1,1], 6: [1,2], 7: [2,0], 8: [2,1], 9: [2,2], "*": [3, 0], 0: [3, 1], "#": [3, 2]}
pair = {1: "L", 4: "L", 7: "L", 3: "R", 6: "R", 9: "R"}
answer = ''
left, right = pos["*"], pos["#"]
for number in numbers:
if... |
### TLE 발생
# s = input()
# p = input()
#
# idxs = []
# for i, sub in enumerate(s):
# if sub == p[0]:
# idxs.append(i)
#
# for idx in idxs:
# if s[idx: idx+ len(p)] == p:
# print(1)
# break
# else:
# print(0)
### 통과한 풀이
# import re
#
# s = input()
# p = input()
#
# pattern = re.comp... |
def check(x, y, type, columns, beams):
# 기둥인 경우
if type == 0:
if y == 0 or (x, y) in beams or (x - 1, y) in beams or (x, y - 1) in columns:
return True
# 보인 경우
else:
if (x, y - 1) in columns or (x + 1, y - 1) in columns or ((x - 1, y) in beams and (x + 1, y) in beams):
... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
app = Flask(__name__)
def connect_to_db(app):
"""Connect the database to our Flask app."""
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///lifelogger'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.app ... |
#Написать функцию, которая принимает на вход две строки
#Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0
#Если строки одинаковые, вернуть 1
#Если строки разные и первая длиннее, вернуть 2
#Если строки разные и вторая строка 'learn', возвращает 3
#Вызвать функцию несколько раз, передавая ... |
#!/usr/bin/python3
with open('12.in') as f:
instructions = [(i[0], int(i[1:])) for i in f]
angle_map = {0: 'E', 90: 'N', 180: 'W', 270: 'S'}
class Boat:
def __init__(self):
self.angle = 0
self.loc = [0, 0]
def action(self, instr):
if instr[0] == 'E':
self.loc[0] += ins... |
#!/usr/bin/python3
import pandas as pd
import numpy as np
def get_fuel(array):
fuel = np.floor(array / 3) - 2
if fuel < 0:
return 0
return fuel
data = pd.read_csv('input-1')
fuels_1 = np.floor(data['numbers'] / 3) - 2
print(sum(fuels_1))
fuel_total = 0
for module in data['numbers']:
fuel ... |
def squareEach(nums):
entry = 0
for i in nums:
nums[entry] = i**2
entry = entry+1
def main():
print('This program squares numbers that you enter.')
nums = input('Please enter your numbers separated by comma: ')
nums = nums.split(',')
... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 3 04:14:08 2016
@author: kiaph
"""
from graphics import *
from button import Button
from dieview import DieView
def window():
pointA = Point(125,75)
pointB = Point(125,175)
pointC = Point(125,275)
pointD = Point(350,150)
pointE = Point(500,15... |
from math import *
def squareEach(nums):
entry = 0
for i in nums:
nums[entry] = i**2
entry = entry + 1
def main():
print("Square a list of numbers. ")
nums = input("Enter a list of numbers seperated by a space: ")
nums = nums.split()
entry = 0
for i in nums:
nums[... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 27 18:05:23 2016
@author: kiaph
"""
def main():
print("This program calculates the numeric value of a name.")
""" Ask for the name to be calculated to numeric value"""
name = input("Enter your name: ")
name.lower()
""" Index the alphabet""" ... |
def main():
hours = eval(input("Please input the number of hours: "))
#print(hours)
wage = eval(input("Please input the hourly wage: "))
#print(wage)
if hours < 40:
print("The total amount earned is", hours*wage)
else:
ovrtime = hours - 40
print("Overtime is", ovrtime,"ho... |
from graphics import *
def main():
win = GraphWin()
shape = Rectangle(Point(50,50),Point(100,100))
shape.setOutline("red")
shape.setFill("red")
shape.draw(win)
center = Point(100,100)
for i in range(10):
p = win.getMouse()
c = shape.getCenter()
dx = p.getX() - c.getX(... |
def main():
grade = ["F++++","F","D","C","B","A"]
score = input("Enter your score on the quiz 0-5: ")
print("You made a", grade[score] ," on your quiz.")
main()
|
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 4 13:15:32 2016
@author: kiaph
This small script will sum numbers from 0 to your desired value n.
"""
def main():
print(" This program will sum numbers starting from 0 ending at n. ")
n = eval(input("Please enter a value for n: "))
total = 0
... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 4 07:05:26 2016
@author: kiaph
"""
"""
def printfile():
#fname = input("Enter filename: ")
fname = 'UserNames.prn'
infile = open(fname, "r")
data = infile.read()
print(data)
print("------------------------------------------------------------------... |
import graphics
from graphics import Rectangle
from graphics import Point
from graphics import Text
def main():
win = graphics.GraphWin()
shape = Rectangle(Point(75,75),Point(125,125))
shape.setOutline('Red')
shape.setFill('Red')
shape.draw(win)
for i in range(10):
p = win.getMouse()
... |
import re
import six
# Default Luhn check digits (base-10)
DIGITS = '0123456789'
def luhn_checksum(number, chars=DIGITS):
'''
Calculates the Luhn checksum for `number`
:param number: string or int
:param chars: string
>>> luhn_checksum(1234)
4
'''
length = len(chars)
number = ... |
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("edward favorite language is " +
favorite_languages['edward'].title() + ".")
print("\n#6.1")
My_Friend ={
'First_Name': 'Muhammad', 'Last_Name': 'Ali',
'Age': 26, 'City': 'Karachi',
}
print("My F... |
# Exercise #1
# name1 = raw_input("What is your name?")
# name2 = raw_input("What is your partner's name?")
#
# if name1 > name2:
# print "My name is greater!"
# elif name2 > name1:
# print "Their name is greater."
# else:
# print "Our names are equal!"
# Exercise #2
# date = raw_input("What is the date?")... |
list = [11,3,7,2,22,34,9,0,65]
def sort(listName):
for index in range(len(listName) - 1, 0, -1):
for secondIndex in range(index):
if(listName[secondIndex] > listName[secondIndex + 1]):
temp = listName[secondIndex]
listName[secondIndex] = listName[secondIndex + 1]
list... |
#利用urllib模組的urlretrieve做下載,帶入第一個參數為URL,第二個參數為檔案名稱
from selenium import webdriver
import urllib.request
from bs4 import BeautifulSoup
chrome_path = "D:\PycharmProjects\selenium_driver_chrome\chromedriver.exe" #chromedriver.exe執行檔所存在的路徑
driver = webdriver.Chrome(chrome_path) #開啟Chrome瀏覽器
driver.get("https://www.ptt.cc... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 2 23:07:21 2021
@author: orkun.yuzbasioglu
"""
from KMeans import KMeans, generate_data
# Training data generation
sample_count_per_class = 200 # number of data samples for each cluster
training_data = generate_data(sample_count_per_class) # generate data us... |
# Uses python3
import sys
def fibonacci_partial_sum_naive(from_, to):
sum = 0
current = 0
next = 1
for i in range(to + 1):
if i >= from_:
sum += current
current, next = next, current + next
return sum % 10
def fibonacci_sum_naive(n):
if n <= 1:
return n... |
# Uses python3
def calc_fib(n):
if (n <= 1):
return n
return calc_fib(n - 1) + calc_fib(n - 2)
def get_fibonacci_fast(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return current
if _... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 5 11:34:31 2019
@author: DFSCHMIDT
"""
import numpy as np
import math
from scipy.special import ellipkinc, ellipeinc
from numpy.random import random_sample as rand
def create_ellipsoid(ellipsoid, npoints=1000):
"""
Create... |
# -*- coding: utf-8 -*-
import os
import threading
from abc import abstractmethod, ABCMeta
__author__ = "Romain Mormont <romainmormont@hotmail.com>"
__version__ = "0.1"
class Logger(object):
"""A base class loggers. A logger is an object which print or not the messages it is passed according to
the verbosity... |
nota1=float(input("Digite a primeira nota do aluno: "))
nota2=float(input("Digite a segunda nota do aluno: "))
media=(nota1+nota2)/2
print("A média entre {:.2f} e {:.2f} é: {:.2f}".format(nota1,nota2,media)) |
print(-=-*20)
print("Analisador de Triangulos")
print(-=-*20)
primeiro= float(input("Primeiro Segmento: "))
segundo= float(input("Segundo Segmento: "))
terceiro= float(input("Terceiro Segmento: "))
if primeiro< segundo + terceiro and segundo< primeiro + terceiro and terceiro< primeiro+segundo:
print("Os segmentos... |
num = int(input("Primeiro valor: "))
num2 = int(input("Segundo valor: "))
if num > num2:
print("O primeiro valor é maior")
elif num < num2:
print("O segundo valor é maior")
elif num == num2:
print("Não existe valor maior, os dois são iguais") |
print("="*15)
print("10 TERMOS DE UMA PA")
print("="*15)
termo1 = int(input("Primeiro termo: "))
razao = int(input("Razão: "))
decimo= termo1+(10-1)*razao
count = 1
while count <=10:
print("{}".format(termo1), end= ' -> ')
termo1 += razao
count +=1
print("ACABOU") |
def sum_square_even_root_odd(nums):
list=[]
for num in nums:
if num%2==0:
list.append(num**2)
else:
list.append(num**0.5)
return round(sum(list),2) |
nota1= float(input("Primeira nota: "))
nota2= float(input("Segunda nota: "))
media = (nota1+nota2)/2
print("Tirando {} e {}, a média do aluno é {}".format(nota1,nota2,media))
if media<5.0:
print("O aluno está REPROVADO")
elif media>=5.0 and media<6.9:
print("O aluno está em RECUPERAÇÃO")
elif media>=7.0:
... |
numero = int(input("Digite um número"))
unidade= numero % 10
dezena = numero // 10 % 10
centena = numero // 100 % 10
milhar = numero // 1000 % 10
print("Unidade: {}".format(unidade))
print("Dezena: {}".format(dezena))
print("Centena: {}".format(centena))
print("Milhar: {}".format(milhar)) |
'''Exercício Python 055: Faça um programa que leia o peso de cinco pessoas. No final,
mostre qual foi o maior e o menor peso lidos.'''
lista=[]
for i in range (0,5):
lista.append(float(input("Digite o peso: ")))
print("O menor peso lido foi {}".format(min(lista)))
print("O menor peso lido foi {}".format(max(li... |
'''Exercício Python 064: Crie um programa que leia vários números inteiros pelo teclado.
O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada.
No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag).'''
num = int(input("Digite um númer... |
import time
import random
def jogada(jogador):
if jogador == 0:
return "pedra"
elif jogador == 1:
return "papel"
elif jogador ==3:
return"tesoura"
print('Suas opções:')
print("[0] PEDRA")
print("[1] PAPEL")
print("[2] TESOURA")
jogador = int(input("Qual é a sua jogada?"))
computado... |
print("="*15)
print("10 TERMOS DE UMA PA")
print("="*15)
termo1 = int(input("Primeiro termo: "))
razao = int(input("Razão: "))
decimo= termo1+(10-1)*razao
for i in range(termo1,decimo,razao):
print("{}".format(i), end= ' -> ')
print("ACABOU") |
import string
from random import *
characters = string.ascii_letters + string.punctuation + string.digits
password = "".join(choice(characters) for x in range(randint(7, 14)))
print("Şifreniz Bu;")
print("Your password is here;")
print(password) |
def MaxLenList(array, unique_array=[], final_array=[]):
unique_array = list(set(map(lambda x : x[0], array)))
final_array = sorted([max(filter(lambda x : i in x, array)) for i in unique_array])
return [(i,len(i)) for i in final_array]
array = ["aa", "bbbb", "b", "ffffff", "fff", "wwwwwwww", "wwww"... |
'''
2019年6月26日21:14:42
通过这个 pyqt5 工程来学习 pyqt5
顺便作为未来写工程时候的参考
https://github.com/maicss/PyQt5-Chinese-tutorial/blob/master/hello_world.md
这里面的教程很棒,很感谢
'''
'''
In this example, we create a simple
window in PyQt5.
'''
# sys模块包含了与Python解释器和它的环境有关的函数
# 这里引入了PyQt5.QtWidgets模块,这个模块包含了基本的组件
import sys
from PyQt5.QtWidgets imp... |
def countPrimes(t):
# '''
# 1부터 t까지의 수 중에서 소수의 개수를 반환합니다.
# '''
testArr = [1]*(t+1)
testArr[0],testArr[1] = 0,0
count = 0
for i in range(2, t+1):
# print("this is testArr[",i,"]:",testArr[i])
if testArr[i] == 1:
j = 2
count = count + 1
wh... |
from datetime import datetime
from elasticsearch import Elasticsearch
from typing import List
import json
document_text = """The easiest way to learn how to use Streamlit is to try things out yourself. As you read through this guide, test each method. As long as your app is running, every time you add a new element to... |
Keys = []
shuffle_arr = [[]]
reduct_arr = [[]]
def map(filename,filepath):
A = []
f = open(filename,"r")
lines = f.read().split('\n')
for line in lines:
A.append((line, 1))
return A
def shuffle(lines):
for w in lines:
key, val = w
if not Keys.__contains__(key):
... |
from math import *
class X:
def __init__(self, x, y):
self.x = x
self.y = y
class Y:
def __init__(self, z):
self.z = z
objX = X(-4.5, 0.75*10**(-4))
objY = Y(0.845*10**2)
def show(X, Y):
print(' x = ', X.x,'\n', 'y = ', X.y,'\n', 'z = ', Y.z,'\n')
show(objX, objY)
def sol... |
"""
Utility functions to deal with vectors in n-dimensional space.
"""
import numpy as np
# Utility functions
def hstack(v, n):
"""Return array with vector v in each of the n columns"""
return np.kron(np.ones((n, 1)), v).T
def row_product(vec, arr):
"""
Multiply the rows of `array` by the elements ... |
# Name: Janae Dorsey
# File: bumper.py
#
# Purpose: This program will create a simulation with two "cars" that change direction when they collide or when they
# hit a wall.
#
# Certification of Authenticity:
# I certify that this lab is entirely my own work.
from graphics import *
from random import randint
import mat... |
# -*- coding:utf-8 -*-
def gradient(x,y):
theart0 = 0
theart1 = 0
# learning rate define 0.5
learningRate = 0.01
for i in range(100000):
sum0 = 0
sum1 = 0
for j in range(len(x)):
print(len(x))
sum0 += theart0 + theart1*x[j] - y[j] #从1加到m
p... |
import pandas as pd
import operator
# Read the dataframe
df = pd.read_csv('statistics.csv')
# Same values, excluding the values for unrecognised files
df_filtered = df.loc[df['Predicted sentence'] != "unknownvalueerror"]
# WER calculation
#~~~~~~~~~~~~~~~~~~~
print("\n" + "~" * 30)
print("WER calculation")
print("... |
def Pivot(arr,low,high):
pi = arr[high]
index = low - 1
for j_index in range(low,high):
if arr[j_index] < pi:
index = index + 1
arr[index], arr[j_index] = arr[j_index],arr[index]
arr[index + 1],arr[high] = arr[high],arr[index + 1]
return index + 1
def Quick_Sort(ar... |
class Person:
def __init__(self, first, last):
self.firstname = first
self.lastname = last
def getName(self):
return self.firstname + " " + self.lastname
def __str__(self):
return self.firstname + " " + self.lastname
class Employee(Person):
def __init__(sel... |
# numbers=(10, 2, 3, 4, 5, 6)
# print(any(numbers))
# print(max(numbers))
# print(min(numbers))
# print(len(numbers))
# print("sorted:")
# print(sorted(numbers))
# print("sum:")
# print(sum(numbers))
# n=(10, 4, 3, 8, 5, 6)
# print("kortejni max", max(n))
# print("kortejni min", min(n))
# print(max(n)+min(n))
# n=(10... |
# Дано 3 числа. Визначити чи всі числа непарні. Числа вводяться з клавіатури
def check(digit):
if digit % 2 != 0:
print(digit, " is odd.")
else:
print(digit, " is even.")
first = int(input("Enter first digit: "))
second = int(input("Enter second digit: "))
third = int(input("Enter third digi... |
import math
import argparse
import sys
# credit_principal = 'Credit principal: 1000'
# final_output = 'The credit has been repaid!'
# first_month = 'Month 1: paid out 250'
# second_month = 'Month 2: paid out 250'
# third_month = 'Month 3: paid out 500'
#
# # write your code here
#
# # print(credit_principal)
# # pr... |
import input
def isTargetText(some_text):
uppers = some_text[1:4] + some_text[5:8]
lowers = some_text[0] + some_text[4] + some_text[8]
if uppers.isupper() == True and lowers.islower() == True:
return True
else:
return False
def findInBlock(lots_of_text):
i = 0
results = ''
while i < len(lots_of_text) - 8:
... |
import input
def calculate_wrapping_paper(l, w, h):
side_1 = l * w
side_2 = w * h
side_3 = l * h
smallest = min(side_1, side_2, side_3)
return 2*side_1 + 2*side_2 + 2*side_3 + smallest
def calculate_ribbon(l, w, h):
dimensions = [l, w, h]
dimensions.sort()
wrap = dimensions[0]*2 + dimensions[1]*2
cubic_feet ... |
import input
from itertools import permutations
def process_input(puzzle_input):
data = puzzle_input.split('\n')
cities = []
processed = {}
for datum in data:
datum = datum.split(' ')
processed[datum[0] + ' to ' + datum[2]] = int(datum[-1])
if datum[0] not in cities:
cities.append(datum[0])
if datum[2] ... |
import csv
import abc
class Calibrator(abc.ABC):
def __init__(self):
self.horizontal = 0
self.depth = 0
def process_input(self, input_file):
with open(input_file) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
instruction = row[0].split()[0]
amount = int(ro... |
string = input('Enter the word you want to check : ').lower()
reversed_string = string[::-1]
if reversed_string == string :
print('It is a palindrome')
else :
print('It is not a palindrome')
|
def extraLongFactorals(n):
total = n
while n > 1:
total *= n-1
n -= 1
print(total)
return total
if __name__ == "__main__":
extraLongFactorals(25) |
# Starting with traditional Hello World! greet.
print("Hello world!")
#Simple add method
def add(number1,number2):
return number1 + number2
#test input numbers
num1 = 5
num2 = 8
print(F'Add {num1} and {num2}')
print(F'{num1} + {num2} = {add(num1,num2)}')
person1 = {"name": "Pradeep", "age": 36, "g... |
def get_rank(string):
"""
Parses a string representing a rank. Returns a string in the correct form
for the lookup table. Returns None if the input could not be parsed.
"""
if "ace" in string or string=="a":
return "A"
if "king" in string or string=="k":
return "K"
if "queen"... |
#斐波那契数列数列
#使用递归求出斐波那契数列数列的第N个值
#时间复杂度为指数阶
def Fib_seq(n):
if (n < 1):
return -1;
if n == 1 or n == 2 :
return 1;
return Fib_seq(n - 1) + Fib_seq(n - 2)
#设置一个长度为N的数组,初始化数组的每个值为-1
#设置下标为0及1的值为1
#使用循环,取数组数列的前俩项之和,赋值个当前项
#时间复杂度为O(n),相比Fib_seq时间负载度大大降低
#空间复杂度为O(n)
def Fib_seq1(n):
if n < 1... |
class Nutrition:
def __init__(self, age, weight, height, gender):
self.age = age
self.weight = weight
self.height = height
self.heightMeters = self.height/100
self.gender = gender
self.BMI = self.weight / (self.heightMeters * self.heightMeters)
print("Nutritio... |
# #range()范围练习
# for value in range(1,10):
# print(value)
#
# #范围转数字列表练习
# numbers=list(range(1,10))
# print(numbers)
#
# #奇数链表创建,加步长
# odd_numbers=list(range(1,10,2))
# print(odd_numbers);
#
# #以下是数字列表及范围处理的几种写法
# squares=[]
# for value in range(1,10):
# square=value**2
# squares.append(squ... |
def stringList(data):
if(data==data[::-1]):
print(data+" is a pallindrome")
else:print(data+" Sorry . is not a pallindrome")
#a=input("Please give a String: ")
stringList("madam")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from operator import itemgetter
import sys
current_word = None
current_count = 0
word = None
# input comes from STDIN
for line in sys.stdin:
# удаляем проблемы в начале и конце строчки
line = line.strip()
# разбиваем каждую по символу таба
# чтобы по... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.