text stringlengths 37 1.41M |
|---|
#Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать.
#Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать,
#есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет".
#Вслед за тем игрок должен попробовать отгадать слово.
#Ко... |
# Задача 3. Вариант 8
# Напишите программу, которая выводит имя "Борис Николаевич Бугаев",
# и запрашивает его псевдоним. Программа должна сцеплять две
# эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
# # Egorov V. I.
# 24.02.2016
name = "Борис Николаевич Бугаев"
psname = "Андрей Бе... |
# Задача 5, Вариант 8
# Напишите программу, которая бы при запуске
# случайным образом отображала название одного
# из семи дней недели.
# Карамян Н.Г.
# 22.05.2016
input ("Жмак......\n")
import random
day = random.randint(1, 7)
if (day) == 1:
print ("Понедельник")
elif (day) == 2:
print ("Вторник")
elif ... |
#Задача 12. Вариант 15.
#1-50. Разработайте игру "Крестики-нолики". (см. М.Доусон Программируем на Python гл. 6).
# Mitin D.S., 28.05.2016, 14:53
X="X"
O="O"
EMPTY=" "
TIE="Ничья"
NUM_SQUARES=9
def display_instruct():
print('''
Привет, студент! Давай поиграем в крестики-нолики! Вводи число от 0 до 8. Числа соответст... |
# Задача 6. Вариант 11.
#Создайте игру, в которой компьютер загадывает название
# одного из девяти действующих вокзалов Москвы, а игрок должен его угадать.
# Kurchatov N. V.
# 11.04.2016
import random
x=random.randint(1,9)
if x==1:
name="Белорусский"
elif x==2:
name = "Казанский"
elif x==3:
name = "Киевский"
eli... |
# Задача 12. Вариант 49.
#Разработайте игру "Крестики-нолики"
#Valkovskey M.A.
size = 3
board = [ 0 ] * size * size
pics = [' . ', ' x ', ' o ']
def print_board (board):
print()
for num in range(size):
print(' ' + str(num +1) + ' ', end='')
print()
index = 1
letter = 97
for cell in board:
... |
# Задача 2. Вариант 45
# Напишите программу, которая будет выводить на экран наиболее понравившееся вам
# высказывание, автором которого является Эзоп. Не забудьте о том, что автор
# должен быть упомянут на отдельной строке.
# Goman D.V.
# 29.03.2016
print ('Невсегда будет лето.')
print ('\n\t\tЭзоп')
input ('\n\n... |
# Задание 4. Вариант 10.
# Напишите программу, которая выводит имя, под которым скрывается Уильям Сидни
# Портер. Дополнительно необходимо вывести область интересов указанной
# личности, место рождения, годы рождения и смерти (если человек умер),
# вычислить возраст на данный момент (или момент смерти). Для хранения вс... |
print ("Герой нашей сегодняшней программы - Аврора Дюпен")
name = input ('Под каким именем мы знаем этого человка? Ваш ответ: ')
print ("Всё верно: Аврора Дюпен - " + name + "!")
|
#Задача 7. Вариант 22
#Разработайте систему начисления очков для задачи 6, в соответствии с которой игрок получал бы большее количество баллов за меньшее количество попыток.
#Rudich A.C.
#31.03.2016
print('Угадайте имя одного из двух братьев, легендарных основателей Рима, которую загадал компьютер')
import random
a = ... |
# Задача 2. Вариант 20.
# Напишите программу, которая будет выводить на экран наиболее понравившееся
#вам высказывание, автором которого является Овидий. Не забудьте о том, что
#автор должен быть упомянут на отдельной строке.
# Titov I. V.
# 02.06.2016
print("Происхождение человека есть , по видимому одно из самых сл... |
#Задача №3 Вариант 34
#Напишите программу, которая выводит имя "Александр Михайлович Гликберг", и
запрашивает его псевдоним. Программа должна сцеплять две эти строки и
выводить полученную строку, разделяя имя и псевдоним с помощью тире.
#Novikova J. V.
#26.04.2016
print ("Герой нашей сегоднящней программы - Але... |
#Задача5.Вариант40.
#Напишите программу, которая бы при запуске случайным образом отображала название одного из четырнадцати гражданских чинов, занесенных в Петровскую «Табель о рангах» .
#Zinovieva Z.M.
#31.03.2016
impot random
n=random.randint(1,14)
elif n==1:
print("Канцлер")
elif n==2:
print("Вице-Канцл... |
# Задача 3. Вариант 15.
# Напишите программу, которая выводит имя "Лариса Петровна Косач-Квитка", и запрашивает его псевдоним.
# Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
# Mitin D.S.
# 05.03.2016, 23:14.
print('Введите псевдоним Ларисы Петровны "К... |
# Задача 7. Вариант 50.
#Разработайте систему начисления очков для задачи 6, в соответствии с которой
#игрок получал бы большее количество баллов за меньшее количество попыток.
# Alekseev I.S.
# 15.05.2016
import random
print("Программа случайным образом загадывает название одной из республик СССР, а игрок должен ... |
# Задача 9. Вариант 31.
# 1-50. Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет". Вслед за тем игрок должен попроб... |
# Задача 5. Вариант 39.
# Напишите программу, которая бы при запуске случайным образом отображала название одной из четырех основных мастей лошадей.
# Korotkova D.S.
# 26.03.2016
print("Одной из основны мастей лошадей является:")
import random
mast=("Вороная масть","Гнедая масть","Рыжая масть","Пегая масть")
B=ran... |
# Задание 4. Вариант 27.
# Напишите программу, которая выводит имя, под которым скрывается Доменико
# Теотокопули. Дополнительно необходимо вывести область интересов указанной
# личности, место рождения, годы рождения и смерти (если человек умер), вычислить
# возраст на данный момент (или момент смерти). Для хранения в... |
# Задача 6. Вариант 45
# Создайте игру, в которой компьютер загадывает название одного из семи чудес
# света, а игрок должен его угадать.
# Goman D.V.
# 29.03.2016
import random
n = random.randrange(7)
chudo = ('Пирамида Хеопса', 'Висячие сады Семирамиды', 'Статуя Зевса в Олимпии',
'Храм Артемиды в Эфесе', '... |
#Задача 6. Вариант 46
#Создайте игру, в которой компьютер загадывает название одной из трех стран, входящих в
#военно-политический блок "Антанта", а игрок должен его угадать.
#Gryadin V. D.
import random
print("Попробуй угадать,какую страну входящую в Антанту я загадал")
a = random.choice(['Россия','Англия','Франц... |
#Задача 9. Вариант 1.
#Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет". Вслед за тем игрок должен попробовать отга... |
import sys
import json
import requests
def convert(amount, base, to):
url = f'https://api.ratesapi.io/api/latest?base={base}&symbols={to}'
response = requests.get(url).json()
return float(response['rates'][to])*float(amount)
if __name__ == "__main__":
if len(sys.argv) == 4:
amount = sys.argv... |
# Add "Hello" and "Goodbye" buttons
###################################################
# Student should add code where relevant to the following.
import simplegui
# Handlers for buttons
def print_hello():
print("Hello")
def print_goodbye():
print("Goodbye")
# Create frame and assign callbacks to event ... |
# Vector addition function
###################################################
# Student should enter code below
def add_vector(u, v):
u1, u2 = u
v1, v2 = v
return [u1 + v1, u2 + v2]
###################################################
# Test
print(add_vector([3, 4], [5, -1]))
print(add_vector([4, 3], [... |
year = 1
numberOfSlowWumpuses = 1000
numberOfFastWumpuses = 1
print(year, numberOfSlowWumpuses, numberOfFastWumpuses)
while numberOfSlowWumpuses >= numberOfFastWumpuses:
numberOfSlowWumpuses *= 2
numberOfSlowWumpuses *= 0.6
numberOfFastWumpuses *= 2
numberOfFastWumpuses *= 0.7
year += 1
print(ye... |
# Counter with buttons
###################################################
# Student should add code where relevant to the following.
import simplegui
counter = 0
# Timer handler
def tick():
global counter
print counter
counter += 1
# Event handlers for buttons
def start_handler():
timer.start()
... |
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
fh = open(name)
email_histogram = {}
for line in fh:
# find line that starts with “From”
if line.startswith("From "):
words = line.split()
# who sent the message
# words = [0]From [1] stephen.marquard@uct.ac.za Sat ... |
"""
Exercise 5: (Advanced) Change the socket program so that it only shows
data after the headers and a blank line have been received. Remember
that recv receives characters (newlines and all), not lines.
"""
import socket
import re
web_address = input('Enter - ')
if len(web_address) < 1 : web_address = 'http://data... |
n = 100
numbers = range(2, n)
results = []
while numbers != []:
results.append(numbers[0])
numbers = [n for n in numbers if n % numbers[0] != 0]
# print(len(results))
print(range(2, 16, 3))
print(range(15, 2, -3))
print(range(2, 18, 3))
## 168 |
# Prime number lists
###################################################
# Student should enter code below
start = 1
end = 13
prime_list = []
for val in range(start, end + 1):
# If num is divisible by any number
# between 2 and val, it is not prime
if val > 1:
for n in range(2, val):
... |
hours = float(input("Enter Hours: "))
rate_per_hour = float(input("Enter Rate: "))
pay = hours * rate_per_hour
print("Pay: ", pay) |
import operator
fruit = {"oranges": 3, "apples": 5, "bananas": 7, "pears": 2}
print("Fruit Before: {}".format(fruit))
# Sorts by Name
print("Fruit After: {}".format(sorted(fruit.items(), key=operator.itemgetter(0))))
# Sort by values
print("Fruit After: {}".format(sorted(fruit.items(), key=operator.itemgetter(1))))
pr... |
c = float(input("Give a temperature in celsius: "))
f = (c * 9/5) + 32
print(f) |
"""
The program will prompt for a URL, read the JSON data from that URL using
urllib and then parse and extract the comment counts from the JSON data,
compute the sum of the numbers in the file.
"""
import json
import urllib.request, urllib.parse, urllib.error
import ssl
# Ignore SSL certificate errors
ctx = ssl.c... |
p = True
q = True
print(not(p or not q))
p = True
q = False
print(not(p or not q))
p = False
q = True
print(not(p or not q))
p = False
q = False
print(not(p or not q))
|
t = input()
while(t):
t -= 1
colors = raw_input().split()
case1 = colors[0:2]
case2 = colors[2:4]
case3 = colors[4:]
tempcase1 = list(set(case1).intersection(case2))
tempcase2 = list(set(tempcase1).intersection(case3))
if(len(tempcase2)>0):
print "YES"
else:
... |
def print_arr(arr):
for a in arr:
print a,
print ""
return
t = input()
while(t):
t -= 1
n,m = map(int,raw_input().split())
works = range(1,n+1)
done = list(map(int,raw_input().split()))
for work in done:
try:
works.remove(work)
except:
... |
def substrings(string):
subs = []
for a in range(len(string)+1):
for b in range(a):
subs.append(string[b:a])
return subs
def diffrk(string):
return string.count('r')-string.count('k')
t = raw_input()
arr = substrings(t)
for a in arr:
print a,diffrk(a)
|
prime = [2]
def isprime(num):
if num<2:
return False
elif num == 2:
return True
for a in prime:
if num % a == 0:
return False
prime.append(num)
return True
def primes(num):
for i in range(max(prime)+1,num+1):
flag = 1
for j in... |
def suminv(n):
tmp = 0
for a in range(1,n+1):
tmp += 1.0/(a+1)
return tmp
frac = input()
while(frac):
n = 1
while(suminv(n)<frac):
n += 1
print str(n) + ' card(s)'
frac = input()
|
def isPal(x):
return x == x[::-1]
t = input()
while(t):
t -= 1
string = raw_input()
count = 0
for a in range(len(string)):
for b in range(a+1,len(string)+1):
if(isPal(string[a:b])):
count += 1
print count
|
def has_negatives(a):
nums = {}
result = [] #Need to return a list of nums with negs
#Loop through each number in the list
for num in a:
#need to check if the absolute value of our number is in our dict..
if nums.get(abs(num)):
#If if is, we can add it to our result list
... |
# Реализовать дескриптор валидации для атрибута email. Ваш дескриптор должен проверять формат email
# который вы пытаетесь назначить.
class EmailDescriptor:
def __init__(self):
pass
# self.email
def __get__(self, instance, owner):
return self.email
def __set__(sel... |
import sys
import math
import cmath
#python program that hosts multiple calculators for simple applications
def quad1(a, b, c):
d = (b**2) - (4*a*c)
x = (-b + math.sqrt(d))/(2*a)
return x
def quad2(a, b, c):
d = (b**2) - (4*a*c)
x = (-b - math.sqrt(d))/(2*a)
return x
number = 0
while number != "... |
import pandas as pd
import numpy as np
import requests
import os
def sanitize_characters(raw, clean):
for line in input_file:
out = line
output_file.write(line)
sanitize_characters(input_file, output_file)
def standardize_text(df, text_field):
df[text_field] = df[text_field].str.replace(r"h... |
import os
def savePlainTextToFile(data, fileName):
print "Creating file"
f = open(fileName, 'w')
f.write( str(data) )
f.close()
print "File has been created"
return
def saveItemsOnFile(items, file):
f = open(file,'w')
for i in items:
f.write(removeNonAscii(i) + '\n')
f.close()
return
def deleteFi... |
"""
Rules for the game environment(s) and the basic player actions.
All environments are grid-based cellular automata with discrete evolution.
Agents can perform actions within/upon the environments outside of an
evolutionary step. Therefore, an environment is primarily responsible for
three things:
1. maintaining en... |
mid_score = float(input('Enter Midterm Score (30) : '))
if(mid_score >30 or mid_score<0):
print('Error Midterm score | enter again')
mid_score = 0.0
final_score = float(input('Enter Final Score (30) : '))
if(final_score >30 or final_score<0):
print('Error Final Score | enter again')
final_score = 0.0
... |
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run find-rectangles
# This mission is an adaptation of the "Rectangles" game (fromSimon Tatham's Portable Puzzle Collection). If you are lost or just want to play, the game is availablehere.
#
# You have to divide a rectangular grid into recta... |
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run shortest-knight-path
# Sofi found a chess set in the supply closet on the robots ship. She has decided to learn how to play the game of chess starts by attempting to understand how the knight moves.Chess is played on a square board of eight... |
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run army-units
# You are the developer of the new strategy game and you need to add the soldier creation process to it. Let's start with the 2 types - AsianArmy and EuropeanArmy (each of them will be a subclass of the Army - class with the methods... |
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run army-battles
# In the previous mission - Warriors - you've learned how to make a duel between 2 warriors happen. Great job! But let's move to something that feels a little more epic - the armies! In this mission your task is to add new classes... |
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run wrong-family
# Michael always knew that there was something wrong with his family. Many strangers were introduced to him as part of it.
#
# Michael should figure this out. He's spent almost a month parsing the family archives. He has all fath... |
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run the-highest-building
# The main architect of the city wants to build a new highest building.
# You have to help him find the current highest building in the city.
#
#
#
# Input:Heights of the buildings as a 2D-array.
#
# Output:The number ... |
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run eaten-go-stones
# A quite unbelievable event has occurred several years ago, in the spring of 2016 - the computer programAlphaGo, developed by Google DeepMind, won against the world's best player in theGo gamewith the result 4-1. Until the ver... |
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run friends
# pre.example { border: 1px solid #aaa; border-radius: 3px; background: #eee; margin-left: 20px; padding: 5px; overflow: auto; } p.indent { margin-left: 20px; }For the mission"H... |
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run straight-fight
# A new unit type won’t be added in this mission, but instead we’ll add a new tactic -straight_fight(army_1, army_2). It should be the method of the Battle class and it should work as follows:
# at the beginning there will be a ... |
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run 88th-puzzle
# p.quote-source { float: right; font-size: 10px; }Dr. Emmett Brown: If my calculations are correct, when this baby hits 88 miles per hour... you're gonna see some serious shit.
#
# ===
#
# Marty McFly: He... |
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run matrix-transpose
# In linear algebra, the transpose of a matrixAis another matrixAT(also writtenA′,Atr,tAorAt) created by any one of the following equivalent actions:
#
# reflectAover its main diagonal (which runs from top-left to b... |
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run ryerson-letter-grade
# Given the grade percentage for the course, calculate and return the letter grade that would appear in the Ryerson’s grade transcript, as defined on the pageRyerson Grade Scales. The letter grade should be returned as a s... |
#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run how-much-gold
# Our Favorite Trio has found a mysterious metal bar. This bar appears to be made of various metal including gold, iron, copper and tin. The bar does not contain any other metal except these. We do not know the quantity ... |
# 1. Дано целое число (int). Определить сколько нулей в этом числе.
########################################################################
value = 20020025876055505
value_str = str(value)
zero = value_str.count('0')
print("В числе ", value, "находится", zero, "нулей")
###############################################... |
#!/usr/bin/python3
def change_int(num):
num += 5
print("Inside the function with num changed to : " + str(num))
#main
myNum = 5
print("Inside the main function with num being: " + str(myNum))
print("calling the change int function")
change_int(myNum)
print("now my int is : " + str(myNum))
|
#!/usr/bin/python3
#
# longestRun.py
#
# Description: given a number, find the longest sequence of 1s given its binary representation
#
# Created: 12/14/2019
#
# Developer: codex040
#
# Version: 1.0
#
######################### Function definition #########################
def longestRun(num):
# validate the inpu... |
#sort.py
#given an array which consists of three unique values, sort them in
#increasing order
########################################################################
#Function definitions
########################################################################
def sortNums(nums):
#check if there are any number ... |
#!/usr/bin/python3
'''
binary search
implement binary search
created: 09/03/2020
version: 1.0
'''
######################## Function Definition ####################
def binary_search(numbers, target, is_sorted = False):
#local variables
s = 0 #start of the list
e = len(numbers) - 1 #end of the list
#... |
"""
longestSubstr.py
given a string, find the longest substring with no repeating characters
"""
def findLongestSubstr(textStr):
if len(textStr) <= 1:
return
subStr = set(textStr[0])
i = 1
startPos = 0
longestSubstrLen = 1
longestSubstring = textStr[0]
while i < len(textStr):
if textStr[i] not in subSt... |
#!/usr/bin/python3
'''
schedule_tasks.py
A task is a some work to be done which can be assumed takes 1 unit of time. Between the same type of tasks you must take at least n units of time before running the same tasks again.
Given a list of tasks (each task will be represented by a string), and a positive integer n... |
#two_sum.py
#given a list and a target "k" find if there are two numbers in the list
#that can add up to the target
#function definition
def two_sum(list, k):
#iterate through the list and check if a pair exists
for i in range(0,len(list)):
diff = k - list[i]
if diff in list[i:]:
return True
#at this point... |
class Demo:
name = ""
#assign val by constructor
def __init__(self, name):
self.name = name
#get val by method
def func(self):
print("My name is "+self.name)
ob = Demo("Harshil")
ob.func()
|
# Arithmetic Operators => +, -, //, *, %
# Comparison operators => ==,!=,<=,=>,<,>
# Logical operators => and, or, not
# Assignment operators => =,+=,-=,*=,/=,//=
# Membership Operators => in, not in
# Identity Operators => is, is not
print(2+3)
print(2>=3)
if 4 % 2 == 0:
print("modulo is 0")
a = 2
b = 3
a *= b
... |
print("break---->")
for i in range(1,6):
if i == 3:
break
print(i)
print("continue---->")
for i in range(1,6):
if i == 3:
continue
print(i) |
import nltk
from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize
from textblob import TextBlob
text=("My name is Adithya! What about yours? It is a very beautiful day today.")
tokenized_text=sent_tokenize(text)
print(tokenized_text)
#breaks paras into sentences.
text=("My name is Adithya! ... |
'''
OpenCV provides the bilateralFilter() function to apply the bilateral filter on the image. The bilateral filter can reduce unwanted noise very
well while keeping edges sharp. The syntax of the function is given below
src- It denotes the source of the image. It can be an 8-bit or floating-point, 1-channel image.
d... |
from unittest import TestCase
from collections import defaultdict, namedtuple
from shopping_basket.pricer import BasketPricer
class TestBasketPricer(TestCase):
def setUp(self):
self.basket = defaultdict(int)
self.catalogue = {
"Baked Beans": 0.99,
"Biscuits": 1.20,
... |
# FontLab script to generate OpenType feature substitution code for selected glyphs
# works with simple ligatures and alternates.
# Does not attempt to decode multiple-feature glyphs such as "f_f_i.alt"
# as there is no single clear right input set for that
#
# by Thomas Phinney, open source under Apache 2.0 license
f... |
import RPi.GPIO as GPIO
from time import sleep
# GPIO Pins, needs to be fixed later, as 1-6 are obviously not valid
# TODO: All the turn sleeps are probably wrong, will fix as soon as circuit is built
Motor_ONE_A = 1
Motor_TWO_A = 2
Motor_ONE_B = 3
Motor_TWO_B = 4
Motor_THREE_A = 5
Motor_THREE_B = 6
def forward():
... |
"""
This was written the 26th of January 2017.
The code aims to determine the exact composition of a molecule and displays the number of the consisting atoms.
An example is shown at the end.
@author: Tarek Samaali
"""
import re
class Stack :
"""
The stack will be useful when dealing with brackets, curlies an... |
import sys
import struct
import numpy
import matplotlib.pyplot as plt
from PIL import Image
# Decompose a binary file into an array of bits
def decompose(data):
#the array of bits we will fill
v = []
#Length of the file. Will be used in the nex loop
fSize = len(data)
#add the header onto the string. This will... |
from linked_list.linked_list import LinkedList, Node
def test_import():
assert LinkedList
# Code Challenge 06
# Add a node to the end of the linked list
def test_append():
node = Node(0)
link = LinkedList(node)
link.insert_node(4)
link.append(10)
actual = str(link)
expected = f'{{ 4 }} -... |
# T.J. Flesher
# Info 2900
# P. Phillips
# Lab2A - Try Looping
# Fahrenheit to Celsius or Celsius to Fahrenheit Converter
#display instructions
print("Enter 'C' to convert a Celsius temperature to Fahrenheit")
print("or")
print("Enter 'F' to convert a Fahrenheit temperature to Celsius")
#get user input
... |
#!/usr/bin/python
'''
###############################################
Sockets
File: server.py
Usage: python server.py <port>
Description: Starts a TCP connection to exchange messages with clients connected to the same port.
Python modified from my IRC chatbot.
C modified from my CS344 encryption/decryption ... |
#Advent of Code '17
#Day 12b: Digital Plumber
import re
#read input
file = open('input12.txt','r')
input = file.read().split('\n')
file.close()
#list of which we have found to be connected
connected = []
for x in range(0, len(input)):
input[x] = input[x].split(' ')
connected.append( False )
... |
#Advent of Code 18a
# Duet
file = open('input18.txt','r')
#file = open('inputTest.txt','r')
input = file.read().split('\n')
file.close()
registerLetters = 'abcdefghijklmnop'
registerLetterLength = len( registerLetters )
registerValues = []
for letter in registerLetters:
registerValues.append( 0 )
def getR... |
#Advent of Code '17
#Day 16b Permutation Promenade
def getIndex( value ):
for x in range(0,len(programs) ):
if programs[x] == value:
return x
print("get Index found nothing")
return -1
def spin( size ):
global programs
size = len(programs... |
#Import dependencies
import os
import csv
import pandas as pd
#Bring in CSV file
budget_data = os.path.join("budget_data_1.csv")
csv_path = "raw_data/budget_data_1.csv"
#Create dataframe
pd.read_csv(csv_path)
budget_df = pd.read_csv(csv_path)
#Find total month count
month_counts = budget_df["Date"].value_counts()
... |
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def inorderTraversal(root):
if root:
inorderTraversal(root.left)
print(root.data, end = ' ')
inorderTraversal(root.right)
def morris_traversal(root):
cur... |
#!/usr/bin/python
import math
class AKEncoderDecoder:
def __init__(self):
pass
def ak_encoder(self, raw_string, pass_key):
encoded_str = ""
for char in raw_string:
converted_char = ord(char)
if converted_char >= 65 and converted_char <= 122:
converted_char -= 64
else:
... |
#! /usr/bin/env python3
# **************************************************************************** #
# #
# ::: :::::::: #
# generator.py ... |
#! /usr/bin/env python3
from FileLoader import FileLoader
import pandas as pd
def howManyMedalsByCountry(df, name):
country = df.loc[df['Team'] == name]
dic = {}
for index, row in country.iterrows():
dic[row['Year']] = {'G': 0, 'S': 0, 'B': 0}
if row['Medal'] == 'Gold':
... |
#! /usr/bin/env python3
import sys
def main():
if len(sys.argv) < 2:
return 0
list = sys.argv[:0:-1]
for each in list:
for letter in each[::-1]:
if letter.isupper():
sys.stdout.write(letter.lower())
else:
sys.stdout.write(letter.upper())
if each != sys.argv[1]:
sys.stdout.wr... |
#! /usr/bin/env python3
import pandas as pd
class FileLoader:
@staticmethod
def load(path):
data = pd.read_csv(path)
print("Loading dataset of dimensions "
+ "{} x {}".format(data.shape[0], data.shape[1]))
return data
@staticmethod
def display(df,... |
# coding=utf-8
"""
This module provides functions for working with and resolving data from a CSV file.
"""
import os
import csv
import itertools
from cards.templatefield import TemplateField, fields
from cards.markdown import markdown
from cards.util import FileWrapper, lower_first_row
from cards.warning import War... |
"""
Write two Python functions to find the minimum number in a list.
The first function should compare each number to every other number
on the list. O(n^2). The second function should be linear O(n).
"""
from time import time
from random import randint
def minNum1(nums):
start = time()
minNum = nums[0]
... |
"""
Write recursive algorithm that rolves the Tower of Hanoi problem.
Explanation:
The key to the simplicity of this algorithm is that we make two
different recursive calls. The first recursive call moves all but
the bottom disk on the initial tower to an intermediate pole. The
next line simply moves the botto... |
import time
def sumOfN2(n):
start = time.time()
theSum = 0
for i in range(1, n+1):
theSum = theSum + i
end = time.time()
print(theSum, end - start)
return theSum, end - start
def sumOfN3(n):
start = time.time()
theSum = (n * (n+1)) / 2
end = time.time()
return the... |
"""Implementation of palindrom checker."""
from deque import Deque
def check(expr):
chars = Deque()
for char in expr:
chars.addRear(char)
while chars.size() > 1:
char_one = chars.removeFront()
char_two = chars.removeRear()
if char_one != char_two:
return Fal... |
class PrioQueue:
def __init__(self, Listlen):
self.data = []
for i in range(Listlen):
self.data.append(-1)
self.Length = 0
self.Front = -1
self.Back = -1
def add(entry):
if self.Back == -1:
self.data[0] = entry
self.Back = 0
else:
newlist = []
for j in range(self.Length):
... |
class MyClass:
"""A simple example class"""
i = 12345
def __init__(self):
self.new = 7
def f(self):
return 'hello world'
sample = MyClass()
sample.i = "hello"
print(sample.new) |
class Curso:
def __init__(self,IdCurso,Descripcion,IdEmpleado):
self.IdCurso = IdCurso
self.Descripcion = Descripcion
self.IdEmpleado = IdEmpleado
def Guardar(P_Id,P_Descripcion,P_IdEmpleado):
curso = Curso(P_Id,P_Descripcion,P_IdEmpleado)
lstCurso = []
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.