text stringlengths 37 1.41M |
|---|
values = [0,1]
def fill_to(number):
start = len(values)
for index in range(start, number+1):
values.append(values[index-2] + values[index-1])
def fib(number):
if len(values) > number:
return values[number]
fill_to(number)
return values[number]
|
"""
Modelar: un auto
atributos:
- una velocidad, al iniciar esta parado
puede:
- puede ver su velocidad
- puede acelerar una determinada velocidad
- puede frenar
"""
velocidadAuto = [10]
def verVelocidad() -> int:
"""Devuelve la velocidad ... |
# // A. Way Too Long Words
# // time limit per test1 second
# // memory limit per test256 megabytes
# // inputstandard input
# // outputstandard output
# // Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
# // Let's consider a w... |
# Given integers a and b, determine whether the following pseudocode results in an infinite loop
# while a is not equal to b do
# increase a by 1
# decrease b by 1
# Assume that the program is executed on a virtual machine which can store arbitrary long numbers and execute forever.
def isInfiniteProcess(a, b):
... |
# D.A.N_3002 Đơn giản 100 Điểm
# Giới hạn ký tự: 3000
# Cho mảng arr chứa các số nguyên. Bạn hãy tính tổng các phần tử ở các vị trí là số nguyên tố trong mảng arr. Biết các vị trí trong mảng đếm bắt đầu từ 1.
# Ví dụ:
# Với arr = [1, 2, 3, 4, 5, 6, 7] thì sumPrimeIndex(arr) = 17.
# Giải thích: các vị trí 2, 3, 5 7 l... |
# You are working on a brand new dictionary. Instead of adding weird contractions for various parts of speech (like v, n, adj, adv, etc.), you decided to provide far more useful information: you put an article before each noun (you haven't chosen between definite and indefinite articles yet, so you use a, an or the), t... |
# Given a string, find the number of different non-empty substrings in it.
# Example
# For inputString = "abac", the output should be
# differentSubstringsTrie(inputString) = 9.
# They are:
# "a", "b", "c",
# "ab", "ac", "ba",
# "aba", "bac",
# "abac"
def differentSubstringsTrie(inputString):
def addNode(l... |
# Find the smallest integer that is divisible by all integers on a given interval [left, right].
# Example
# For left = 2 and right = 4, the output should be
# smallestMultiple(left, right) = 12.
from fractions import gcd
def smallestMultiple(left, right):
res = left
for i in range(left,right+1):
res... |
# A. I Wanna Be the Guy
# time limit per test1 second
# memory limit per test256 megabytes
# inputstandard input
# outputstandard output
# There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
# Little ... |
# A. Beautiful Year
# time limit per test2 seconds
# memory limit per test256 megabytes
# inputstandard input
# outputstandard output
# It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
# Now you are suggeste... |
# A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
# He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
# Input
# The fir... |
# A. HQ9+
# time limit per test2 seconds
# memory limit per test256 megabytes
# inputstandard input
# outputstandard output
# HQ9+ is a joke programming language which has only four one-character instructions:
# "H" prints "Hello, World!",
# "Q" prints the source code of the program itself,
# "9" prints the lyrics of ... |
# A. Boring Apartments
# time limit per test1 second
# memory limit per test256 megabytes
# inputstandard input
# outputstandard output
# There is a building consisting of 10 000 apartments numbered from 1 to 10 000, inclusive.
# Call an apartment boring, if its number consists of the same digit. Examples of boring ap... |
# John has just entered a college, and should now pick several courses to take. He knows nothing, except that number x is a bad luck for him, which is why he won't even consider courses whose title consist of x letters.
# Given a list of courses, remove the courses with titles consisting of x letters and return the re... |
# Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
# Note, that during capitalization all the letters except the first one remains unchanged.
s = input()
a = [i for i in s]
a[0] = a[0].upper()
print("".join(a))
|
# Define a multiplication table of size n by m as follows: such table consists of n rows and m columns. Cell on the intersection of the ith row and the jth column (i, j > 0) contains the value of i * j.
# Given integers n and m, find the number of different values that are found in the table.
# Example
# For n = 3 a... |
# Given a square matrix, calculate the absolute difference between the sums of its diagonals.
# For example, the square matrix is shown below:
# 1 2 3
# 4 5 6
# 9 8 9
# The left-to-right diagonal = . The right to left diagonal = . Their absolute difference is .
# Function description
# Complete the function in ... |
def restoreString(str, indices):
d = {}
res = ""
for i in range(len(indices)):
d[indices[i]]= str[i]
for i in sorted(d.keys()):
res+=d[i]
return res
#Best solution:
def shuffleString(s,indices):
return ''.join([s[indices.index(counter)] for counter in list(range(len(s)))])
... |
# this line prints out a statement
print ("I will now count my chickens:")
#this line counts hens and roosters
print ("Hens", 25.0 + 30.0 / 6.0)
print ("Roosters", 100.0 - 25.0 * 3.0 % 4.0)
#this line counts eggs
print ("Now I will count the eggs:")
#this line does some math
print(3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.... |
# assigns this variable to 10
types_of_people = 10
# assigns a variable of x to this phrase
x = f"There are {types_of_people} types of people."
# assigns variable binary to a string
binary = "binary"
# assigns variable to a string
do_not = "don't"
# creates a variable assigned to a string concatenation
y = f"Those who ... |
from abc import ABC, abstractmethod
__copyright__ = "Copyright © 2020 RPS Group, Inc. All rights reserved."
__license__ = "See LICENSE.txt"
__email__ = "patrick.tripp@rpsgroup.com"
class StorageService(ABC):
""" Abstract base class for cloud storage.
It defines a generic interface to implement
"""
... |
""""Ejercicio 3: Imprimir una columna de asteriscos,
donde su altura se recibe como parámetro"""
#funcion
def asterix(a):
for i in range (0,a):
print( "*")
#programa
alt=int(input("ingrese altura de columna:"))
print=asterix(alt) |
"""Ejercicio 1: Dados dos parámetros numéricos,
calcular y devolver el resultado de la multiplicación
de ambos utilizando sólo sumas."""
#funcion sumulti
def sumulti (a,b):
suma=0
for i in range(0,b):
suma=suma+a
return suma
#programa
nro1=int(input("ingrese nro 1: "))
nro2=int(inpu... |
#TRABAJO PRACTICO Nº 2
#Ejercicio 1
#Paso 1: Introducir dos variables de enteros
nro1=int(input("Ingrese un numero: "))
nro2=int(input("Ingrese otro numero: "))
#Paso 2: Operar variables
suma=nro1+nro2
dif=nro1-nro2
#Paso 3: Devolver resultado
print("La suma entre ", nro1, " y ", nro2, "es: ", suma)
p... |
#Ejercicio 4: Invertir aquellos valores ubicados en posiciones impares de una lista.
def dolist():
listex=[]
nro=int(input("ingrese nro: "))
while nro!=-1:
if nro>0 and nro<21:
listex.append(nro)
else:
print("nro no valido")
nro=int(input("ingrese n... |
nro=int(input("ingrese nro positivo (-1 para salir): "))
binario="."
while nro!=-1:
if nro>=0:
if nro>=2:
if nro%2==0:
binario="0"+ binario
nro=nro//2
else:
binario="1" + binario
nro=nro//2
else:
... |
#ENCUESTA
#defino iteración
i=1
#defino consumidor
costumer=1
#defino valores de verdad a y b
a=0
b=0
#cantidades
aa=0
bb=0
justa=0
justb=0
none=0
both=0
while i<=100:
print("Bienvenido cliente Nro", costumer,"!")
acca=int(input("Acepta A? Si=1 / No=0: "))
if acca==1:
a=1
... |
"""
EJERCICIO EXTRA FUNDAMENTOS-
Leer dos listas de numeros M y N , ambas ordenadas de menor a mayor.
Generar e imprimir una tercera lista que resulte de intercalar todos los elementos de M y N.
La nueva lista también debe quedar ordenada, sin usar ningun m... |
# -------------------- Section 3 -------------------- #
# ---------- Part 1 | Patterns ---------- #
print(
'>> Section 3\n'
'>> Part 1\n'
)
# 1 - for Loop | Patterns
# Create a function that will calculate and print the first n numbers of the fibonacci sequence.
# n is specified by the user.
#
# NOT... |
C = input('來自哪個國家:')
Y = input('請書輸入年齡:')
Y = int(Y)
if C == '台灣':
if Y >= 18:
print('可以考駕照')
else:
print('你還不能考駕')
elif C == '美國':
if Y >= 16 :
print('可以開車')
else :
print('不能開車')
|
'''
@version: 1.1
@since: 21.03.2015
@author: Alexander Kuzmin
@return: None
@note: print a table with frequencies of letters in sorted order
'''
from sys import stdin
from operator import itemgetter
from collections import Counter
__author__ = 'Alexander Kuzmin'
def getSortedTableWithFrequencies... |
'''
@version: 1.0
@since: 07.04.2015
@author: Alexander Kuzmin
@note: Tools for processing a text: tokenizing, writing probabilities, generating and testing.
'''
#import enum # there are no such module in the contest
import argparse
import unittest
import random
import sys
from collections import Coun... |
import pandas as pd
from types import MethodType
ATTRIBUTES = {'loc', 'iloc', 'ix', 'index', 'shape', 'values'}
def _operator(op):
def func(self, *args, **kwargs):
operations = self._operations + [(op, args, kwargs)]
return Where(operations)
return func
class Where(object):
"""
Usage ... |
# set ====================================================================
# l = [1,2,3,5,6,7,8]
# d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
# d2 = dict({'Michael': 95, 'Bob': 75, 'Tracy': 85})
# # print(d,d2)
# s = set(l)
# # print(s.pop(), s.remove())
# print(l.pop(1), l.remove(8))
# print(l)
a = {1,2,3,0,4}
b = {... |
# type()函数可以查看一个类型或变量的类型,Hello是一个class,它的类型就是type,而h是一个实例,它的类型就是class Hello。
# 我们说class的定义是运行时动态创建的,而创建class的方法就是使用type()函数。
# type()函数既可以返回一个对象的类型,又可以创建出新的类型,比如,我们可以通过type()函数创建出Hello类,而无需通过class Hello(object)...的定义:
# 要创建一个class对象,type()函数依次传入3个参数:
# 1. class的名称;
# 2. 继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
#... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import pyautogui, time
# 获取焦点
pyautogui.click(200,200)
pyautogui.typewrite('hello world!', 0.1)
pyautogui.typewrite(['a', 'b', 'left', 'left', 'X', 'Y'], 0.1)
pyautogui.keyDown('shift')
pyautogui.press('4')
pyautogui.keyUp('shift')
def commentAfterDelay():
# pyautog... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
my_list = [12, 5, 13, 8, 9, 65, 1, 2,6]
# def bubble(bad_list):
# length = len(bad_list) - 1
# sorted = False
# while not sorted:
# sorted = True
# for i in range(length):
# if bad_list[i] > bad_list[i+1]:
# sorte... |
# test __str__ __repr__====================================
# class Student(object):
# def __init__(self, name):
# self.name = name
# def get_name(self):
# return self.name
# def __str__(self):
# return 'Student object (name: %s)' % (self.name)
# def __repr__(self):
# re... |
# source.py for Algorithms - Project 1
#
# This program implements a simple asymmetric cryptography system for use
# in cybersecurity applications
#
# @author Ross Adams, Longtin Hang, and Riley Williams
import math
import random
def test_prime_brute_force(p=10):
if p == 2:
return... |
# basic print string
print("myBeautifulString")
# passing an array
print(["m", "y", "A", "r", "r", "y"])
# splitting the array as positional arguments
print(*["m", "y", "A", "r", "r", "y"])
# printing the array as one string
print(*["m", "y", "A", "r", "r", "y"], sep="")
# printing two lines as one string
print(*["... |
if __name__ == "__main__":
xo=str(input("Ingrese el valor de la semilla: "))
n=int(len(xo)/2)
if len(xo)%2==0: #Si el modulo 2 del tamaño de la semilla es cero entonces...
veces=int(input("Ingrese la cantidad de numeros a generar: "))
for i in range(veces):
d=len(xo)
... |
#!/usr/bin/env python3
import sys
from datetime import datetime
found = False
data = []
frequency = 0
loops = 0
duplicates = []
duplicates.append(frequency)
def calc_freq(total, arg ):
if arg.startswith("+"):
total = total + int(arg.lstrip('-'))
elif arg.startswith("-"):
total = total - int(... |
s1 = input().strip()
s2 = input().strip()
s1 = s1.replace(s2.upper(), '').replace(s2.lower(), '')
print("result: {}".format(s1))
|
a = input()
cnt=0
for n in a :
if n.isupper() and n!="A" and n!="E" and n!="I" and n!="O" and n!="U":
cnt=cnt+1
print(cnt)
|
def isPrime(num):
if not num.isdigit():
return False
elif int(num) == 1:
return False
elif int(num) == 2:
return True
else :
for i in range(2,int(num)):
if int(num) % i == 0:
return False
return True
|
x=int(input())
if(x<=15):
y=4*x/3
print("{:.2f}".format(y))
else:
y=x*2.5-17.5
print("{:.2f}".format(y))
|
# example of a loop
# for i in [2,4,5,6,7]:#using actual values
# print("i = ",i)
#
# for i in range(10):#cycles through the range, from 0 for 10 values not to 10!
# print("i = ", i)
#
#
# for i in range(2,10):#cycles through the range, from 2 for 10 values not to 10!
# print("i = ", i)
#
# using modulus
... |
# we'll provide different outputs dependent on age
# 1 - 18 > Important
# 21, 50, > 65 > Important
# All others > Not Important
# Receive age and store in age
age = eval(input("Enter age: "))
# and : If both are true it returns true
# or : If either are true it returns true
# not : Converts true to false
# if state... |
''' Project Euler 0046
====================
'''
import eulerlib as lib
import math
N = 33
def f(k: int):
return 2 * k * k
def is_prime(n: int):
try:
return is_prime.cache[n]
except KeyError:
p = lib.is_prime(n)
is_prime.cache[n] = p
return p
is_prime.cache = {}
def f... |
'''
Created on Dec 7, 2020
@author: RICKY
'''
import math
def Inputkalimat (kalimat):
temp = float(input(kalimat))
return temp
# Dapatkan nilai T
def HitungNilaiT(s1,s2,s3):
NilaiT = 0.5*(s1+s2+s3)
return NilaiT
# Hitung Luas Segitiga :
def HitungLuasSegitiga(t,s1,s2,s3):
LuasSegitiga = math.sqr... |
'''
Created on Nov 2, 2020
@author: RICKY
'''
bil1 = 70
bil2 = 80
bil3 = 90
if bil1 <90 :
print("nilai bil1 < 90")
if bil2 < bil3:
print("nilai bil2 < nilai bil3")
elif bil1 > 90 :
print("nilai bil1 > 90")
if bil1 < bil3 :
print("nilai bil1 < nilai bil3")
#Operator Logika "and"... |
'''
Created on Nov 19, 2020
@author: RICKY
'''
# Bilangan Fibonanci
# 1,1,2,3,5,8,13,dst
n = int(input('Masukkan bilangan ke-n Fibonnaci : '))
x = 1
y = 1
z = 0
fib = []
for i in range(n+1):
x = y
y = z
z = x + y
fib.append(z)
for j in range(i):
... |
'''
Created on Nov 23, 2020
@author: RICKY
'''
n = int(input("Masukkan Angka :"))
if (n-1)%2 == 0 and n >= 5:
for i in range (n):
if i == 0 or i == n -1 :
print("* "*n)
else:
print("* "+" "*(n-2)+"*")
else:
print("Angka masukkan angka yang s... |
'''
Created on Nov 19, 2020
@author: RICKY
'''
#Program N! atau N faktorial
while True:
n = int(input("Masukkan bilangan anda :"))
if n < 0:
print("bilangan tidak boleh negatif")
faktorial = 1
i = n
while i >= 1 :
print (i,end=" x ")
faktorial *= ... |
# Simple analysis of the Collatz Conjecture
import random
import matplotlib.pyplot as plt
def collatz_function(n):
if(n % 2 == 0):
n = n/2
else:
n = (3 * n + 1)
return n
def collatz_several():
n = random.randrange(1, 1000, 1)
org = n
print(n)
counter = 0
plt.fi... |
#!/usr/bin/python -tt
# Expense Calculator
class Expense_Calculator(object):
def Expenses(self, Age, Retirement_Age, Inflation, Current_Expenses):
self.Future_Expenses={}
for x in range(Age,Retirement_Age+1):
if x==Age:
self.Future_Expenses[Age]=Current_Expenses
else:
self.Future_Expenses[x]=self.F... |
#!/usr/bin/env python
"""
Renames a dataset file by appending _purged to the file name so that it can later be removed from disk.
Usage: python rename_purged_datasets.py purge.log
"""
from __future__ import print_function
import os
import sys
assert sys.version_info[:2] >= ( 2, 4 )
def usage(prog):
print("usage... |
number = input('Введите целое число n: ')
print(int(number)+int(number+number)+int(number+number+number))
|
#Taking inputs
print("Enter the number of lines \nof the triangle you want to print:", end="")
n = int(input())
while True:
print("Press 1 for upwards pointing triangle \n"
"or"
"\nPress 0 for downwords pointing triangle", end=":")
b = int(input())
if b==1 or b==0:
brea... |
#This is a Demo File which shows you how to use Math101.py
#Some new functions are available although I will be adding new functions soon
from Math101 import isPrime,factorial,isPallindrome,GCD,LCM
#Taking Input
n = int(input('Enter the No'))
# Using isPrime() Function
if isPrime(n) == True:
print('Prime No')
el... |
#-*- coding:UTF-8 -*-
import sys
import thread
import socket
import time
def socket_server_run():
msocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname()
port = 9001
print 'host = ' ,host ,' <> port ',port
msocket.bind((host,port))
msocket.listen(10)
... |
x = "There are %d types of people." % 10 # variable x
binary = "binary" #variable binary
do_not = "don't" #variable do_not
y = "Those who know %s and those who %s." % (binary, do_not) #variable y, String inside string #1
print x
print y
print "I said: %r" % x #print string using %r String inside string #2
pr... |
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print "Wait there's not 10 things in that list, let's fix that."
#return a list of the sections in ten_things, using ' ' as the delimiter
#call split with ten_things and ' '
stuff = ten_things.split(' ') # split(ten_things, ' ')
more_stuff = ["Day", "Night", "... |
import math
first_number = int(input())
second_number = int(input())
if second_number > 1:
result = math.log(first_number, second_number)
else:
result = math.log(first_number)
print(round(result, 2))
|
#Exercise 8 LPTHW: Printing, Printing
# Initialize a string variable that has variable placeholders. Use .format as an easy way to create strings
formatter = "{} {} {} {}" # Initialize a string variable that has variable placeholders.
print(formatter.format(1,2,3,4)) #The .format function allows arguments (the numbe... |
# Exercise 7 LPTHW: More Printing
print("Mary had a little lamb.")
print("It's fleece was white as {}".format('snow')) #format function inserts argument in variable placeholder
print("And everywhere that Mary went.")
print("." * 10) # what did that do? Added 10 periods to the end....
end1 = "C"
end2 = "h"
end3 = "e"... |
#Exercise 12 LPTHW: Prompting People
#Instead of printing the prompt before the input line, use he prompt argument in input([prompt])
age = input("How old are you? ")
height = input("How tall are you? ")
weight = input("How much do you weigh in lbs? ")
print(f"So, you're {age} old, {height} tall and {weight} heavy."... |
import random
def weighted_choice(weights):
"""
The following is a simple function to implement weighted random selection in Python.
Given a list of weights, it returns an index randomly, according to these weights
:param weights: list of weights
:return: the index with the probability
"""
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
寻找“完美数”
"""
import math
def main():
for num in range(1,10000):
sum = 0
for factor in range(1, int(math.sqrt(num))+1):
if num % factor == 0:
sum += factor
if (factor > 1) and (num / factor != factor):
sum += num / factor
if num != 1 and sum == num... |
from darts.dart import Dart
# Here is all the logic required to set the optimal goals for a given score left and given number of darts in hand.
# For scores in range(60, 159), the target scores are hardcoded
# to reduce redundant calculations and ensure optimal targets.
def hardcoded_dart(score):
assert score i... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# auth : pangguoping
user_file = open('user.txt','r') #保存用户名密码
message_dict = { }
#下面for循环是把用户名密码转换为字典
for i in user_file:
line = i.strip()
line_list = line.split()
message_dict[line_list[0]] = line_list[1]
user_file.close()
counter = 0 #定义一个计数器
last_name = ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auther: pangguoping
import sys
import os
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(base_dir)
sys.path.append(base_dir)
from modules.menu import menu_show
while True:
user = input("\033[1;32;40mPlease input your name:\033[0m")
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#list __init__,内部
'''
# 1、set,无序,不重复序列
#创建
#方法一:
s1 = {"123","456"}
print(type(s1))
#方法二:
s2 = set() #创建空集合
#方法三:
#列表转换为集合
li = [11,22,11,22]
s3 = set(li)
print(s3)
#二、操作集合
#1.集合添加元素
s = set()
s.add(123)
print(s)
#A中存在,B中不存在
s1 = {11,22,33}
s2 = {22,33,44}
s3 = s1.di... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auther: pangguoping
'''
from xml.etree import ElementTree as ET
tree = ET.parse('xo.xml')
root = tree.getroot()
print(root)
for child in root:
print(child)
print(child.tag,child.attrib)
for gradechild in child:
#print(gradechild)
print(gradec... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
message_dict = { }
user_file = open('user.txt','r')
f=open('black_user.txt','r')
user_name = input("please input your name:")
user_passwd = input("please input your password:")
while True:
line = f.readline()
if user_name in line:
print('your name is black... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Auther: pangguoping
import sys,os
# base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print(base_dir)
# sys.path.append(base_dir)
#
# print(sys.path)
from modules.shopping import show_shopping_list
#from moprintlist import print_list
from modules.pri... |
#gives us randoms
import random
potential_words = ["example", "words", "someone", "can", "guess"]
word = random.choice(potential_words)
#to test: print(word)
#converts the word to lowercase
word = word.lower()
#make it a list of letters for someone to guess
current_word = list(word) #the number of letters should ma... |
# Given an array of integers, find the first missing positive integer in linear time
# and constant space. In other words, find the lowest positive integer that does not exist in the array.
# The array can contain duplicates and negative numbers as well.
# For example, the input [3, 4, -1, 1] should give 2. The input... |
listOfList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for rowIndex in range(0,3):
for colIndex in range(0,3):
print( listOfList[rowIndex][colIndex], end=' ')
print()
|
import turtle
def draw_square(shape):
for i in range(4):
shape.forward(200)
shape.right(90)
def draw_fractal():
screen = turtle.Screen()
screen.bgcolor("red")
fractal = turtle.Turtle()
fractal.shape("arrow")
fractal.speed(10)
fractal.color("white")
for i in range(36):
... |
a=[1,12,15,26,38]
b=[2,13,17,30,45]
def median(a):
if len(a)%2==0:
return (a[len(a)//2-1]+a[len(a)//2])/2
else :
return (a[len(a)//2])
def findmedian(a,b):
if len(a)==2:
m=(max(a[0],b[0])+min(a[1],b[1]))/2
return m
m1 = median(a)
m2 = median(b)
if m1=... |
import random
print("welcome to stone-paper-scissor game with computer!!","*****************************",sep="\n")
print("you can press 0 whenever you want to quit")
print("let's start the game")
while True:
print("press 1,2,3 for indicating stone,paper,scissor respectively!!")
turn=int(input("it's y... |
t = int(input())
word_list = []
for _ in range(t):
s = input()
word_list.append(s)
for _ in range(t):
if len(word_list[_]) == 1:
print(f"Case #{_ + 1}: 0")
else:
letter = 26 * [0]
vowel, consonant, max_vowel, max_consonant = 0, 0, 0, 0
for i in word_list[_]:
... |
def area(base, height):
'''(number, number) -> float
Return the area of triangle with given base and height.
>>>area(10, 40)
200.0
>>>area(3.4, 7.5)
12.75
'''
return base * height / 2
|
x = 15
y = 3
z = "this is a string"
a = "hello"
b = "world"
c = "again"
myList = [1,12,3,45,5]
def myPrint(words):
print(words, ", ok.")
myPrint("are you")
def myFunction(start, vList, step):
for i in range(start,len(vList),step):
print(vList[i])
def myRecursiveFunction(start, vList, step):
... |
import numpy as np
import math
import matplotlib.pyplot as plt
from scipy.stats import norm
plt.style.use('bmh')
import matplotlib
matplotlib.rc('lines',linewidth=3)
matplotlib.rc('font',size=16)
# revenue we make from each ticket sold ($)
revenue_per_ticket = 250
# cost of a voucher ($)
cost_per_voucher = 800
# prob... |
import sys
answer = []
hint = []
guess = []
wrongAns = []
score = 0
heart = 11
def chooseCategory(number):
category = ""
if number == "1":
category = "astronomy"
elif number == "2":
category = "fastfood"
elif number == "3":
category = "africa"
readFile(category)
def readFil... |
# Massive + methods + SLICE
massive.append(var) #| в кінець
massive.insert(index, var) #| на місці індекса вставити елемент
massive.remove(var) #| видалити елемент з масиву
massive.clear() #| очистити
massive.pop() #| повертає останній елемент і видаляє його з масиву
massive.index(var) #| п... |
# CLASSES
# Method
method.__doc__ # Doc
method.__name__ # Ім'я методу
method.__class__ # Class в якому визначений метод
method.__func__ # Object of func що реалізує даний метод
method.__self__ # Силка на екземпляр, асоціований з даним методом
# None - для незв'язаних методів
# Class
c.__do... |
import tkinter as tk
class Question:
def __init__(self, main):
self.entry1 = tk.Entry(main, width = 10, font = 15)
self.button1 = tk.Button(main, text = " Check ")
self.label1 = tk.Label(main, width = 20, font = 15)
self.entry1.grid(row = 0, column = 0)
self.button1.grid... |
# addition
2 + 3 # 5
# subtraction
3 - 2 # 1
# multiplication
2 * 3 # 6
# division
3 / 2 # 1.5
# python 2.7
# 3 / 2 = 1
# 3.0 / 2 = 1.5
# 3 / 2.0 = 1.5
# 3.0 / 2.0 = 1.5
# modulus (remainder after division)
4 % 2 # 0 (4 / 2 is 2 with no remainder)
7 % 3 # 1 (7 / 3 is 2 with a remainder of 1)
# floor div... |
import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
"""Tests for the class Employee"""
def setUp(self):
"""Create base employee."""
self.employee = Employee("Nelson", "Ripoll", 50000)
def test_give_default_raise(self):
"""Give raise using default a... |
# -*- coding: utf-8 -*-
"""Logistic Regression Classification for machine learning.
In statistics, logistic regression, or logit regression, or logit model is a
regression model where the dependent variable (DV) is categorical. This project
covers the case of a binary dependent variable—that is, where it can take
only... |
# -*- coding: utf-8 -*-
"""Support Vector Machine (SVM) classification for machine learning.
SVM is a binary classifier. The objective of the SVM is to find the best
separating hyperplane in vector space which is also referred to as the
decision boundary. And it decides what separating hyperplane is the 'best'
because... |
# -*- coding: utf-8 -*-
"""K-Means unsupervised classification for machine learning.
K-means clustering is a unsupervised method to cluser or group the data.
K-means allows you to choose the number (k) of categories/groups and
categorizes it automatically when it has come up with solid categories.
This algorithm is u... |
import numpy as np
import matplotlib.pyplot as plt
y0 = 1972
n0 = 0.0025
year_predicted = np.arange(1972, 2013, 2)
num_predicted = np.log10(n0) + ((year_predicted - y0) / 2) * np.log10(2)
year_observed = [1972, 1974, 1978, 1982, 1985, 1989, 1993, 1997, 1999, 2000, 2003, 2004, 2007, 2008, 2012]
num_observed = [0.0025,... |
def quicksort(A, p, r):
"""A: array to be sorted
p: left index
q: right index"""
if len(A) == 1:
return A
if p < r:
"""q is partitioning index, A[q] is not at right place"""
q = partition(A, p, r)
"""Separately sort elements before and after partition"""
quick... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Helper functions to reduce code reuse and misc other uses
"""
from urllib.parse import quote
def create_url(token, url, customerid):
""" Creates the url for sending data to NodePing
Formats the url based on whether or not the
customerid is None
:ty... |
"""Given a string, return a string where for every char in the original, there are two chars. Eg.
double_char(The) = TThhee"""
def double_func(user_input):
new_string = ""
for char in user_input:
new_string += char * 2
return new_string
print double_func(raw_input("Enter the string :"))
|
# -*- coding:utf-8 -*-
# author:"Xianglei Kong"
class People:
school = "CUIT"
def __init__(self,name,gender,age):
self.name = name
self.gender = gender
self.age = age
class Teacher(People):
def __init__(self,name,gender,age,level,salary):
super().__init__(name,gender,age)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.