text stringlengths 37 1.41M |
|---|
# create a simple list
a = ['a', 'b', 'c', 'x', 'y', 'z']
# iterate through list, using enumarate to retrieve index and item
for index, item in enumerate(a):
print("index", index, ", ", "item", item)
|
string = input("Введите текст: ")
length = len(string)
lower = upper = 0
for i in string:
if i.islower():
lower += 1
elif i.isupper():
upper += 1
per_lower = lower / length * 100
per_upper = upper / length * 100
print("%% строчных букв: %.2f%%" % per_lower)
print("%% прописных букв: %.2f%%" % p... |
# Input : A collection A = {a1, . . . , an}, indices l, r
# Output: An array A' containing all elements of A in nondecreasing order
A = [2, 4, 1, 6, 5, 3]
def quick_sort(array, left, right):
index = partition(array, left, right)
if left < index - 1:
quick_sort(array, left, index - 1)
if index < ri... |
def reverse_word(word):
res = ""
for letter in range(len(word) - 1, -1, -1):
res += word[letter]
return res
if __name__ == "__main__":
inpt = input("Enter yout sentence: ")
string = ""
for symbol in inpt:
if symbol not in ":.,;-!?":
string += symbol.lower()
re... |
import copy
def calculate(number):
"""
function calculates number of elements, the highest and the lowest, their sum, average and median
>>> calculate([1, 2, 3, 4, 5])
([1, 2, 3, 4, 5], 5, 15, 1, 5, 3.0, 3)
>>> calculate([2, 4, 6, 7, 3])
([2, 4, 6, 7, 3], 5, 22, 2, 7, 4.4, 4)
>>> calculate(... |
from copy import deepcopy
def make_board(n):
""" int -> list
Returns a list, filled with zeros, representing a board
"""
column = [0 for i in range(n)]
board = [column[:] for i in range(n)]
return board
def print_result(n, lst_of_results):
""" int, list -> None
This function is used ... |
#Problem 1
def get_position(ch):
"""
str -> int
Return a positon of letter in alphabet. If argument is not a letter function
should return None.
>>> get_position('A')
1
>>> get_position('z')
26
>>> get_position('Dj')
"""
if not isinstance(ch, str): return None
if le... |
def make_board():
"""
returns a list, representing 8*8 board
"""
return [[0 for i in range(8)] for i in range(8)]
def print_board(board):
"""
Prints a board
"""
for i in board:
for j in i:
print(j, end=" ")
print()
def convert_postition(pos):
"""
s... |
def calculate_expression(expression):
"""
str -> int
Return the result of arithmetic calculations in expression entered as text.
>>> calculate_expression("Скільки буде 8 відняти 3?")
5
>>> calculate_expression("Скільки буде 7 додати 3 помножити на 5?")
22
>>> calculate_expression("Скільк... |
import math
def level(nodes):
return math.ceil(math.log(nodes+1,2))
def leveltwo(nodes):
if nodes > 0:
return math.floor(math.log(nodes,2))+1
return 0
for i in range(20):
print(str(i)+" nodes, level: "+str(level(i))+"function 2 says its level: "+str(leveltwo(i))) |
import random
import numpy as np
class Network:
# Input parameter
# sizes: list in which each element is the number of neurons in each layer.
def __init__(self, sizes):
self.num_layers = len(sizes)
self.sizes = sizes
self.biases = [np.random.randn(y) for y in sizes[1:]]
# There is one bias for each no... |
class Restaurant:
def __init__(self, seatings):
self.seatings = seatings
self.tables = [None for _ in range(0, seatings)]
def seat(self, guest):
is_table_available = not all(self.tables)
if is_table_available:
idx = next(i for i, t in enumerate(self.tables) if t is ... |
n=int(input('Enter num: '))
if n%2!=0:
for i in range (1,n+1):
for j in range (1,n+1):
if (i==n//2+1 or j==n//2+1):
print('*',end=' ')
else:
print(' ',end=' ')
print()
else:
print('Entered wrong input')
'''
Enter num: 7
... |
candies=list(map(int,input().split()))
a=[]
extra_c=int(input('Enter extra candies:'))
for i in candies :
if i+extra_c>=max(candies):
a.append(True)
else:
a.append(False)
print(a)
'''
2 4 1 5 3
Enter extra candies:3
[True, True, False, True, True]
'''
|
n=int(input('Enter an odd num: '))
if n%2!=0:
for i in range(1,n+1):
for j in range(1,n+1):
if(i==1 or i==n or i==n//2+1 or j==1 or j==n or j==n//2+1):
print('*',end=' ')
else:
print(' ',end=' ')
print()
else:
print('You have ent... |
# 打开文件:open()
# 输入:read()
# 输入一行: readline()
# 文件内移动 seek()
# 输出write()
# 关闭文件close()
# file1 = open('name.txt', 'w')
# file1.write('ddddd')
# file1.close()
#
# file2 = open('name.txt')
# print(file2.read())
# file2.close()
#
# file3 = open('name.txt', 'a')
# file3.write('bbbb')
# file3.close()
file4 = open('name.txt... |
#列表
l = [3, 2, 3, 7, 8, 1]
print(l.__sizeof__())
l.count(3) #2 表示统计列表 / 元组中 item 出现的次数
l.index(7) #3 index(item) 表示返回列表 / 元组中 item 第一次出现的索引
# list.reverse() 和 list.sort() 分别表示原地倒转列表和排序(注意,元组没有内置的这两个函数)。
l.reverse() #l [1, 8, 7, 3, 2, 3]
l.sort() #l [1, 2, 3, 3, 7, 8]
# 元组
tup = (3, 2, 3, 7, 8, 1)
tup.count(3) #2
tup... |
# Pandas库数据预处理和清洗
# pip3 install pandas 安装命令
import numpy as np
from numpy import nan
from pandas import Series, DataFrame # 最重要的库
import pandas as pd
# series基本操作
data = Series([4, 5, 6, 7])
print(data)
# 输出结果,第一位为索引位置
# 0 4
# 1 5
# 2 6
# 3 7
# dtype: int64
print(data.index) # RangeIndex(start=0, sto... |
def sieve(n):
not_prime = []
prime = []
for i in xrange(2, n+1):
if i not in not_prime:
prime.append(i)
for j in xrange(i*i, n+1, i):
not_prime.append(j)
return prime
print "Till which integer you want to do the primality test?"
x = int(raw_input(">"))
pri... |
import random
print ("===============BEM AO VINDO AO JOKENPÔ================")
print('''
[ 1 ] JOGAR
[ 2 ] REGRAS
[ 3 ] SAIR
''')
opcao = int(input(""))
if opcao == 3:
exit (1)
if opcao == 2:
print ('''[ Pedra ganha da tesoura (amassando-a ou quebrando-a) ]
[ Tesoura ganha do papel (cortando-o) ]
[ Papel ganha... |
salario = float(input("Digite o salário do funcionário: "))
if salario>1250: aumentado = salario*1.10
else: aumentado = salario*1.15
print ("O salário do funcionário com aumento é igual a: R$ {:.2f}".format(aumentado)) |
celsius = float(input("Digite a temperatura em °C: "))
fahrenheit =( ((celsius * 9)/5)+32 )
print (f"A temperatura {celsius:.1f}°C equivale a {fahrenheit:.1f}°F") |
import emoji
import math
num = int(input("Digite num: "))
print (f"A raiz de {num} = {math.sqrt(num):.2f}")
print(emoji.emojize('Python is :thumbs_up:', use_aliases=True)) |
num = int(input("Digite o numero a ser convertido: "))
print('''Escolha a base para qual deseja converter:
[ 2 ] Binário
[ 8 ] Octal
[ 16 ] Hexadecimal
''')
base = int(input("Base a qual deseja converter: "))
while base != 2 and base != 8 and base != 16:
print("\nVocê escolheu uma opção inválida!!!"... |
from datetime import date
ano = int(input('Digite o ano que deseja saber se é bissexto: '))
if ano == 0: date.today().year
if ano%100 == 0 and ano%4 == 0:
print ("Ano não bissexto\n")
else:
if ano%4 != 0:
if ano%400 != 0:
print ("Ano não bissexto\n")
else: print ("Ano bissexto\n"... |
test = input ("Digite alguma coisa: ")
print ("O tipo primitivo desse valor é", type(test))
if test.isspace(): print ("O seu texto só possui espaços ")
if test.isnumeric(): print ("Você digitou um numero")
if test.isalpha(): print ("Você digitou uma letra ou frase")
if test.isupper(): print ("O seu texto está em MAISC... |
nome = (str(input("Digite seu nome completo: "))).strip()
print ("Nome em maiúsculo: ", nome.upper())
print ("Nome em minúsculo: {}".format(nome.lower()))
#separa o nome em razão do espaço entre as palavras, logo após junta sem espaços e calcula o length
print (f'Tamanho do nome, sem contar espaços: {len("".join(nome.s... |
form = dict() # formulario para cada pessoa
cadastro = list()
while True:
print()
form['Nome'] = str(input('Nome da pessoa: '))
sexo = str(input("Sexo[M/F]: ")).upper().strip()
while sexo not in 'MF':
print('\033[31;1m'+'Responda apenas M ou F !!'+'\033[0;0m')
sexo = str(input("Sexo[M/... |
import math
num = float(input("Digite um numero qualquer: "))
print ("A parte inteira desse numero é {}".format(math.trunc (num))) |
nome = []
idade = []
sexo = []
soma = 0
maior = 0
mulh_menos_vinte = 0
nome_mais_velho = ''
for i in range (1, 5):
print ("-"*5, i, "ª PESSOA","-"*5)
nome.append(str(input("Qual o nome da pessoa: ").strip()))
idade.append(int(input("Qual a idade da pessoa: ")))
sexo.append(str(input("Qual o sexo da pe... |
import random
num_alunos = (int(input("Quantos alunos irão participar: ")))
num_sorteados = (int(input("Quantos alunos deseja sortear: ")))
i = 0
alunos = []
for i in range (1,num_alunos+1):
alunos.append (input(f"Digite o nome do aluno {i}: "))
selected = random.sample (alunos, k=num_sorteados)
ordem = 1
prin... |
from datetime import date
dia_nasc = int(input("Qual o dia de nascimento do atleta? "))
mes_nasc = int(input("Qual o mês de nascimento do atleta? (em numero): "))
ano_nasc = int(input("Qual o ano de nascimento do atleta? "))
ano_atual = int(date.today().year)
mes_atual = int(date.today().month)
dia_hoje = int(date.to... |
usertime = float(input("Tell me a word in english: "))
if usertime = cat:
print("gato")
elif usertime = dog:
print("perro")
elif usertime = horse:
print("caballo")
else
print("no entiendo")
|
# Check memory with sys.getsizeof()
import sys
mylist = range(0, 10000)
print(sys.getsizeof(mylist))
# Woah… wait… why is this huge list only 48 bytes?
# It’s because the range function returns a class that only behaves like a list. A range is a lot more memory efficient than using an actual list of numbers.
# You c... |
"""
Students have become secret admirers of SEGP. They find the course exciting and the professors amusing. After a superb Mid Semester examination its now time for the results. The TAs have released the marks of students in the form of an array, where arr[i] represents the marks of the ith student.
Since you are a... |
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import requests
#GPIO SETUP
sensor_pin = 20
relay_pin = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor_pin, GPIO.IN)
GPIO.setup(relay_pin, GPIO.OUT)
# test the sensor to find out if the soil is moist
def get_sensor(sensor_pin):
# see if sensor has detected moisture... |
""" argdeco.main -- the main function
This module provides :py:class:`~argdeco.main.Main`, which can be used to create main
functions.
For ease it provides common arguments like `debug`, `verbosity` and `quiet`
which control whether you want to print stacktraces, and how verbose the logging
is. These arguments will ... |
from XmlGenerator import XmlGenerator
from CalculateAlpha import CalculateAlpha
import math
class Controller (object):
"""
Controller acts as the singleton class that hides
implementation details of the alpha and pi.
It generates the XML file and create DTD.
In encapsulate the object of class Cal... |
class calculator():
def __init__(self):
self.user_input1 = 0
self.user_input2 = 0
self.calc_total = 0
self.running = True
def ask_user_input(self):
user_input_1 = int(input('Enter a number: '))
self.input1 = user_input_1
user_input_2 = int(input('Enter a... |
# -*- coding: utf-8 -*-
"""
mnist_loader
-----------------------------
A library to load the MNIST image data. For detail of the data structures that ara returned,
see the doc string for "load_data" and "load_data_wrapper". In practice "load_data_wrapper"
is the function usually by our neural network code
"""
import ... |
from tetris_lookahead import possible_locations
from tetris_board import *
def score(board, hold, queue, active, can_hold, board_func, place_func, depth):
if depth == 0:
return board_func(board)
moves = []
for x, y, s, m in possible_locations(TetrisPiece(active, 4, 19, 0), board):
test_bo... |
import MapReduce
import sys
"""
Assymetric Relationships in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
# Implement the MAP function
def mapper(record):
# YOUR CODE GOES HERE
ori_record=record[:]
record.sort()
k... |
# iamprudhvi
class BSTNode:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
def insert_node(root, data):
if root is None:
node = BSTNode(data)
root = node
else:
if data < root.data:
if root.left is... |
# You are in an infinite 2D grid where you can move in any of the 8 directions
# (x,y) to
# (x-1, y-1),
# (x-1, y) ,
# (x-1, y+1),
# (x , y-1),
# (x , y+1),
# (x+1, y-1),
# (x+1, y) ,
# (x+1, y+1)
# You are given a sequence of points and the order in which you ... |
# https://programmers.co.kr/learn/courses/30/lessons/42626?language=python3#
# 1차 풀이 (정확성 통과, 효율성 전부 실패) -> 소트에서 문제가 생기는 것으로 판단됨..
def solution(scoville, K):
def _make_two_to_one(a, b):
return a+(b*2)
if min(scoville) > K:
return 0
_shuffle = 0
scoville.sort()
while scovil... |
def cons(x, y):
"""s = list([x]) + list([y])"""
return [x] + list(y)
def car(x):
return x[0]
def cdr(x):
return x[1:]
def cadr(x):
return x[1]
def caddr(x):
return x[2]
def cadddr(x):
return x[3] |
import sqlite3
DATABASE = 'companydb.db'
def insertproduct(sellerid, itemid, qty, unit):
con1 = sqlite3.connect(DATABASE)
cur1 = con1.cursor()
cur1.execute("INSERT INTO availproducts (sellerid, itemid, qty, unit) values (?,?,?,?)", (sellerid, itemid, qty, unit))
con1.commit()
con1.close()
def fetchitemid(catego... |
import timeit
import numpy as np
def bubbleSort(arr):
if len(arr) == 1:
return arr
else:
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
arr[i+1], arr[i] = arr[i], arr[i+1]
return [arr[-1]] + bubbleSort(arr[:-1])
def test():
arr = list... |
# if condition:
# statement
# else:
# statement
#nested if exampal( if within "if")
user=input('Enter user name : ')
passward=input('Enter passward : ')
if user.upper()=='Ifte'.upper():
if passward=='123':
print('wellcome')
else:
print('invalid passward')
else:
print('invalid u... |
print('Main Menu')
print('='*20)
print('1. Additon')
print('2. Subtraction')
print('3. Multification')
print('4. Division')
print('5. Exit')
print('Enter Your Selection :',end=' ')
ch=input()
if ch=='1':
print('you have selected addition')
elif ch=='2':
print('you have selected subtraction')
elif ch=='3':
... |
# Quiz Quest Component 1 - have an integer checking function
# Int_check Function goes here
def int_check(question):
while True:
try:
response = int(input(question))
return response
# Error message
except ValueError:
print("Please enter an integer\n")
... |
import math
class CSensor(object):
sensor_number = 0
# the base class for the sensor
def __init__(self, name='sensor', x=0, y=0, heading=0):
self.name = name
self.x_base = x
self.y_base = y
if heading == 0:
self.heading = math.pi - math.atan2(self.x_base, self.... |
"""
The labyrinth has no walls, but pits surround the path on each side.
If a players falls into a pit, they lose.
The labyrinth is presented as a matrix (a list of lists): 1 is a pit and 0 is part of the path.
The labyrinth's size is 12 x 12 and the outer cells are also pits. Players start at cell (1,1).
The ex... |
import torch
"defines modules, which are like functions, some has trainable parameters"
import torch.nn as nn
"defines functions, equivalent to non-trainable modules"
import torch.nn.functional as F
class myModel(nn.Module):
"store all the trainable layers here"
def __init__(self):
nn.Module.__init__(self)
se... |
import sys
def parse_params(filename):
"""
Function to parse parameter file
:param filename: Parameter filename
:return: parameter values
"""
all_dicts = []
with open(filename) as f:
for line in f:
params = line.strip().split()
temp_dict = {"die": floa... |
"""
Date management
"""
from datetime import datetime
from typing import Sequence
from arrow import arrow
def relevant_days_between(start_date: datetime, end_date: datetime) -> Sequence[datetime]:
"""
Get the list of dates representing the weekdays between (including) two dates
:param start_date: Star... |
def main():
lista = []
brEl = int(input("Unesite broj elemenata: "))
for i in range(0, brEl):
unos = input(f"Unesite element {i}: ")
try:
lista.append(int(unos))
except:
print("Pogresan unos.")
lista.sort()
print(lista)
if __name__ == '__main... |
from math import sin, cos, sqrt
from random import uniform
import numpy as np
from calie.aux import angles
class Se2A(object):
"""
Class for algebra se2 quotient over equivalent relation given by exp.
To respect camel case convention and avoid confusion class for se(2) is called Se2A.
It is the quot... |
import fractions as fr
from scipy import misc
# ------------- auxiliary method for the BCH formula ----------------
def fact(n):
"""
Covers the predefined function factorial from scipy.misc
:param n:
:return: factorial of n type float
"""
return float(misc.factorial(n, True))
def bern(n):
... |
#coding:utf-8
'''
去掉重复的字母,使用lexicographical order找出最短的字串
'''
class Solution(object):
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
rs = {x:i for i, x in enumerate(s)}
res = ''
for j, y in enumerate(s):
if y not in res:
... |
digimon_stats=[["Attack",7], ["Defense",10],["S",4]]
#Use the Analyzer to get Digimon details.
print(digimon_stats[1])
#Use the Analyzer to get the numerical value for the Digimon's Speed (S)
#[2][1] is the 2nd list & 1st value inside digimon_stats, where counting is 0-based.
print(digimon_stats[2][1])
... |
# -*- coding: utf-8 -*-
"""
Dado un mensaje y un alfabeto, dar su codificación usando la técnica
de 'Move to Front'.
mensaje='mi mama me mima mucho'
alfabeto=[' ', 'a', 'c', 'e', 'h', 'i', 'm', 'o', 'u']
MtFCode(mensaje,alfabeto)=[6, 6, 2, 2, 3, 1, 1, 2, 2, 5, 2,
2, 4, 1, 4, 3, 2, 8, ... |
import sys
import copy
def handle_repeat(list_all):
first_list = list(copy.copy(list_all[0]))
for line in first_list:
if is_repeat_3(line,list_all):
first_list.remove(line)
return first_list
def file2list(vcf):
file_list = []
with open(vcf) as f:
for line in f:
... |
from datetime import datetime
fecha = "10 days 2021"
try:
objeto_fecha = datetime.strptime(fecha, '%d days after %Y')
fecha_normalizada = datetime.strftime(objeto_fecha, '%d/%m/%Y')
print("Funcionó el método 1")
print(fecha,'->', objeto_fecha, '->', fecha_normalizada)
except ValueError:
objeto_fecha =... |
import itertools
def permutations(string):
res = itertools.permutations(string)
print (res)
return [''.join(str) for str in (set(res))]
permutations('aabb') |
def perimeter(n):
#Fibonacci sequence
a=[]
a.append(1)
a.append(1)
for i in range(2,n+1):
a.append(a[i-1]+a[i-2])
#
return int(4*sum(a))
|
prime_numbers = 0
number = 2
while(prime_numbers <= 25):
counter = 0
for i in range(2,number):
if(number%i == 0):
counter = counter + 1
if(counter == 0):
prime_numbers = prime_numbers + 1
print(number)
number = number + 1 |
# ИКНиТО, 2-ой курс, ИВТ, Лазарев Игорь
x = []
y = []
n = int(input("Введите количество элементов: "))
for i in range(n):
x.append(float(input("Введите " + str(i + 1) + " элемент Х: ")))
y.append(float(input("Введите " + str(i + 1) + " элемент Y: ")))
print(x)
print(y)
x_sr = sum(x) / n
y_sr = sum(y) / n
x_kv... |
# This Program caluclates howmany tiles you will need
# When tiling a wall or floor in metres squared
length = float(input ("Enter Room Length: "))
width = float(input ("Enter Room Width: "))
#length = 4.3
#1width = 2.2
Area = length * width
needed = Area * 1.05
print ("You need ", needed ,"Tiles in metres s... |
from datetime import date
today = int(date.today().weekday())
print(today)
if today < 4:
print('Yes, unfortunately today is a weekday.')
else:
print('It is the weekend, yay!') |
def anagrams1(words):
anagrams = {}
for word in words:
alphaform = "".join(sorted(word.lower()))
#print(f'{word} {alphaform}')
if alphaform not in anagrams:
anagrams[alphaform] = []
anagrams[alphaform].append(word)
for key in anagrams:
print(anagrams[k... |
#Excercise : Dead Code 작성 주의!!
#Exception Handling : try/except 문 사용
astr = 'Hello bob'
#istr = int(astr) # 에러발생 : 형변환 불가능함 : int는 unsafe : ok,error 동시 존재 : error의 가능성이 있으면 error핸들링을 해줘야 함
try: #에러발생 여지가 있으면 넣어준다
istr = int(astr)
except: #에러발생시 적용
istr = -1
print('Fisrt', istr)
# try 중간 ... |
a=1
b=1
con=1
d=1
while con<=10:
while d<=10:
c=b/a
print c
b=b+con
d=d+1
print("la tabla de dividir es la siguiente:")
con=con+1
b=con
d=1
|
print("el inciso c del ejercicio 1")
def suma(x, y):
return x + y
a=raw_input("ingrese el primer numero")
b=raw_input("ingrese el segundo numero")
value=int(a)
value1=int(b)
print suma(value, value1)
print " "
|
# ------------------------------------------------------------------------------
# Name: CS_U2_Assg2.py
# Purpose: List Checker
# Author: Maryil.H
# Created: 27/03/2017
# ------------------------------------------------------------------------------
#Remove Redundants function
def remove_redundants(og_list... |
#
# Description: Find the collisions between birds
#
# Author: Ninad Dipal Zambare
#
level_one_birds = ["A", "B", "C", "D", "E"]
level_two_birds = ["B", "A", "E", "D", "C"]
collisions = {}
i=0
for bird1 in level_one_birds:
for bird2 in level_one_birds:
if bird1 != bird2 and not level_one_birds.index(bird2... |
import unittest
from Trees.printTree import TreeNode, Solution
class TestPrintTree(unittest.TestCase):
def testCase1:
#single node as tree
root = TreeNode(1)
self.answer = [['1']]
solution = Solution()
self.input = solution.printTree(root)
assert self.input == self.answer
def testCase2:
#2. fu... |
from numpy import sin, cos, pi
''' Classic Cartpole Task
Reference: Bartol, A., Sutton, R. S., & Anderson, C. W. (1983). Neuro-like adaptive elements that can solve difficult learning problems. IEEE Trans. Syst., Man, Cybern, 13, 834-846.'''
num_actions = 2
class Cartpole:
'''
states: [x, theta, d... |
# The definition for GridWorld -- the environment that the agent will continuously interact with
import numpy as np
class GridWorld:
def __init__(self):
self._num_rows = 5
self._num_cols = 5
self._state = (0, 0)
self._t = 0
self._terminal_states = {(self._num_rows... |
# 2-D tile coding
# It is used to construct (binary) features for 2-D continuous state/input space + 1-D discrete action spacce
# for linear methods to do function approximation
import math
import numpy as np
# The following three lines are subject to change according to user need
# -- numTilings, x_start, x_ra... |
score =int (input('请输入一个分数:'))
if 100 >=score>=90:
print('A')
elif 90 >score>=80:
print('B')
elif 80>score>=60:
print('C')
elif 60>score>=0:
print('D')
else:
print('输入错误!')
|
#!/usr/local/bin/python3
# Write a function that reverses characters in (possibly nested) parentheses
# in the input string.
# Input strings will always be well-formed with matching ()s.
# Example
# For inputString = "(bar)", the output should be
# reverseInParentheses(inputString) = "rab";
# For inputString = "f... |
#!/usr/local/bin/python3
def shapeArea(n):
sa = ((n -1) * (n -1)) + (n * n)
return sa
print(shapeArea(1))
|
def binaryToDecimal(binary):
decimal = 0
index = 0
while binary > 0:
lastDigit = binary % 10
binary = int(binary / 10)
decimal += (lastDigit * (2**index))
index += 1
return decimal
def decimalToBinary(decimal):
binary = ""
remainders = []
while decimal > 0:
remainders.append(str(decimal % 2))
deci... |
import json, urllib
import requests
import geopy.distance
API_KEY = 'AIzaSyC8m1yNa6eDGE5VLR1GjQ-5Mz_WyoM-5Kc'
#To be able to pass all locations in one call
def addLocations(content):
validArgument = ''
for locations in content:
validArgument += locations + '|'
return validArgument
#To return the latitude an... |
import random
import words
words = open('words.py').read().strip().split('", "')
word = random.choice(words)
print(word)
#On créer notre compteur pour chaque coup de l'utilisateur
compteur = 20
#On demande à l'utilisateur de rentrer une lettre
while compteur != 0 :
for i in word :
letter = input('Entre... |
class EmotionData:
def __init__(self, joy = -1, anger = -1, disgust = -1, sadness = -1, fear = -1):
self.joy = joy # float between 0 and 1
self.anger = anger
self.disgust = disgust
self.sadness = sadness
self.fear = fear
class ReviewData:
def __init__(self, s... |
import random
from plane import Plane, sign
class Environment:
def __init__(self):
self.plane = Plane()
def turbulence(self):
self.plane.current_angle += (random.random() -0.5) * 90
return self.plane.current_angle
def flight(self):
while True:
self.turbulence()... |
__author__ = 'warrickmoran'
#
# General Read/Write methods from Python 101
#
def file_read(filename):
"""
Read File Contents
"""
try:
with open(filename, 'r') as handler:
data = handler.readlines() # read ALL the lines!
print(data)
except IOError:
print("An I... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 18:19:15 2018
@author: Administrator
"""
class Tower:
"""Course-Week2:Simple Programs-4.Functions-Video:TowersofHanoi-method1
"""
def __init__(self):
self.counter = 0
def hanoi(self, n, a, c, b):
if n == 1:
... |
import re, math
from main import *
from collections import Counter
from start import *
WORD = re.compile(r'\w+')
def get_cosine(vec1, vec2):
intersection = set(vec1.keys()) & set(vec2.keys())
numerator = sum([vec1[x] * vec2[x] for x in intersection])
sum1 = sum([vec1[x]**2 for x in vec1.keys(... |
board=["-","-","-",
"-","-","-",
"-","-","-"]
game_still_going=True
#who win
winner=None
#turn of player
current_player="X"
def display_board():
print(board[0]+"|"+board[1]+"|"+board[2])
print(board[3]+"|"+board[4]+"|"+board[5])
print(board[6]+"|"+board[7]+"|"+board[8])
def play_game():
... |
A = [[0] * 10] * 10 # вроде бы это обычный список списков 10х10 состоящий из 0
A[0][0] = 1 # меняем элемент с индексом 0 в списке с индексом 0
print(A[1][0]) # печатаем элемент с индексом 0 в списке с индексом 1 |
# Ejercicio 024_Intro_BlockOrientation
# Donde se muestra como cambiar la direccion o orientacion del voxel
# Usamos de forma mas eficiente la variable blockType
# Connect to Minecraft
from mcpi.minecraft import Minecraft
mc = Minecraft.create()
# 53 es Oak Wood Stairs
blockType = 53
# Coordenadas iniciales
x = 10
y... |
## Basic feature extraction using text data
# Number of words
# Number of characters
# Average word length
# Number of stopwords
# Number of special characters
# Number of numerics
# Number of uppercase words
import pandas as pd
from nltk.corpus import stopwords
stop = stopwords.words('english')
## to increase the di... |
#!/usr/bin/env python3
"""Learn how to use tuples
Usage:
python3 tuples.py
"""
# tuples are defined with (), are immutable
# t is the global scoped object for this module
t = ("Norway", 4.953, 3)
def loop(tpl):
for item in tpl:
print(item)
print("length of the tuple is ", len(tpl))
print(__nam... |
'''
String 조작하기
1.글자합체
string + string
2.글자삽임(수술)
3.글자 자르기
'''
#1.글자합체
hphk ="happy" + "hacking"
print(hphk)
#2.글자삽입
name="hj"
age=27
text="안녕하세요. 제이름은 {}입니다. 나이는 {}세 입니다.".format(name, age)
print(text)
f_text= f"제이름은 {name}입니다. 나이는 {age}세 입니다."
print(f_text)
#3. 글자자르기
#string> "어떠한 글자들"[start:end]
text_name = ... |
import os
import csv
# Path to collect data from the Resources folder
election_csv = os.path.join('Resources', 'election_data.csv')
#read in the csv file
with open(election_csv,'r') as csvfile:
csv_reader = csv.reader(csvfile,delimiter = ',')
#skip header row
csv_header = next(csvfile)
#create lists... |
import unittest
from app.models import News
class NewsTest(unittest.TestCase):
def setUp(self):
'''
test to run before each test
'''
self.news_sources=News('abc-au', "ABC News",'https://abcnews.go.com')
def test_instance(self):
'''
test case to confirm the objec... |
# Python program for Dijkstra's single
# source shortest path algorithm. The program is
# for adjacency matrix representation of the graph
# Library for INT_MAX
import sys
class Graph():
def __init__(self, ver):
self.V = ver
self.graph = [[0 for colu in range(ver)]
for row in range(ver)]
def printSolu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.