text stringlengths 37 1.41M |
|---|
plus = 0
for i in range(1,101):
if i%3 == 0:
plus += i
print(plus) |
import sys
sys.stdin = open('input.txt', 'r')
T = int(input())
for tc in range(1, T + 1):
str1 = list(set(input()))
str2 = list(input())
# 값 초기화
largest_value = 0 # 가장 큰 값을 저장하자!
largest_alphabet = '' # 가장 큰 값의 알파벳을 저장하자!
# str1을 돌면서 알파벳을 꺼내오자
for char in str1:
#str2에 들어있는 char를 ... |
import re
# the function should return the strings "invalid" or "valid" based on the email ID entered
def checkmail(email):
return 'valid' if re.search(r'^[a-zA-Z0-9]+@[a-z]+.[a-z]{2,3}$', email) else 'invalid'
# email='pgajjar@gmail.com'
# print("email: " + email + " : " + checkmail(email))
# email='pgajjar@gm... |
import sys
from six import StringIO
from random import randint
import numpy as np
import gym
from gym import spaces
# default : easy board
BOARD_SIZE = 10
NUM_MINES = 9
# cell values, non-negatives indicate number of neighboring mines
MINE = -1
CLOSED = -2
def board2str(board, end='\n'):
"""
Format a board... |
#-------------------------------------------------------------------------------
# Name: demo_string_templates.py
# Purpose: Demonstrate how the string.Template class works
# Author: David Viljoen
# Created: 06/02/2018
#---------------------------------------------------------------------------... |
# Python program to convert decimal to binary
# Function to convert Decimal number
# to Binary number
class decToBinary:
counter = 0
bin_list = []
@staticmethod
def decimalToBinary():
print("Enter the {0} th number that will be converted binary number ...".format(decToBinary.counter)... |
""" test_values.py creates user-defined n amount of values to be passed into each instance of the Intercept class in interceptor.py
Each value represents the value for each variable at every second passed in the simulation. In real life application,
speed and distance values would be calculated by live GPS data once ev... |
class Book:
def __init__(self, name, lst_update, cre_date, r_lst):
self.name = name
self.last_update = lst_update
self.creation_date = cre_date
self.recipes_list = r_lst
def get_recipe_by_name(self, name):
"""Print a recipe with the name `name` and return the instance"""... |
import simplegui
import random
secret_number = 0
def input_guess(guess):
'''
Input your number to guess the secret number
'''
print('Guess was {}'.format(int(guess)))
guess = int(guess)
if guess == secret_number:
label1.set_text('{} is Correct.\nYou may play another game. The... |
#13) Escreva um programa que leia números inteiros do teclado.
#O programa deve ler os números até que o usuário digite 0 (zero).
#No final da execução, exiba a quantidade de números digitados, assim como a soma e a média aritmética.
numero = 1
soma = 0
quant = 0
while numero != 0:
numero = int(input('Digi... |
# Modifique o programa abaixo para imprimir de 1 até o número digitado pelo usuário, mas,
# dessa vez, apenas os números ímpares.
fim = int(input("Digite o último número a imprimir: "))
x = 1
while x <= fim:
print(x)
x = x + 2
|
'''
Framework for mathematical functions that GUI relies on to perform
data transfer equation.
'''
def convert_to_bits(dataset_size, data_total):
'''
Convert given amount of data to bits.
'''
bits = 0
if dataset_size == 'KB':
bits = (data_total * 1024) * 8
elif dataset_size == 'M... |
nem = input("Add meg a nemed:(fiú:m/lány:f)")
if nem == "f":
kor = int(input("Hány éves vagy?: "))
if kor >= 10 and kor <= 12:
print("Gratulálok, játszhatsz a csapatban. ")
else:
print("Sajnálom, nem téged keresünk!")
else:
print("Sajnálom, nem téged keresünk!") |
import MainScript
import numpy as np
flag = False
c = 0
sud = np.zeros(81).reshape((9, 9))
while flag == False:
for c in range(9):
row = input('Enter one row: ')
count = 0
for i in row:
sud[c, count] = int(row[count])
count += 1
print(sud)
repeat = input('I... |
from queue import Queue
import copy
import numpy as np
import time
boardSize = int(input("Board Size: "))
que = Queue()
goalStates = 0
exploredStates = 0
#defining board data structure
initial_state = {
"board": [],
"numQueens": 0,}
#define goal state
goal_state = {
"numQueens": boardSize}
#generate an ... |
import sqlite3
from sqlite3 import Error
import requests
html = 'https://www.celestrak.com/NORAD/elements/cubesat.txt'
name = input("Enter Name: ")
DATA = ["","","","","","","","","","","","","","","","","","",""]
TLESIZE = [[0,23],[26,30],31,[33,34],[35,37],[38,40],[42,43],[44,55],[57,66],[68,75],[78,84],[88,... |
class Solution:
def calculateTax(self, levels, salary):
#Approach: Iterative // linear traversal
#Time Complexity: O(n) // or O(1) if n is fixed
#Space Complexity: O(1)
#where, n is the number of levels
remaining = salary
prev_level = 0
total_tax = 0
... |
"""
src.population
~~~~~~~~~~~~~~~
deals with all population operations like create population of some specific size,
select the best chromosomes out of a populations and save all of the best scores out of all rounds,
new_population creates new improved population and circle of life just calls every function by order
i... |
#nested function accessing a nonlocal variable
def print_output(msg):
def output():
print(msg)
output()
print_output("Hello world!")
#return output function instead of calling it
def print_output(msg):
def output():
print(msg)
return output
another=print_output("Hello Hell... |
'''
1. create
1. add new single dataset (via console)
2. read
1. show all datasets
2. show single dataset
3. update
1. update single dataset
4. delete
1. delete all
2. delete single row
5. save/export
6. end program
'''
#Function to display a simple Menu
def show_main_menu():
print("What wou... |
## ACTIONS ##
def you_died(why):
print(f"{why} Game over!")
exit(0)
## END ACTIONS ##
## CHARACTERS ##
def guard():
actions_dict = {
"check": "It appears the guard is still sleeping. You need to get to that door behind him. What are you waiting for?",
"sneak": "You approac... |
def fun():
print("In fun()")
def add(a, b=0):
return a + b
def fun2(*, n1=1, n2): # keyword only arguments
pass
def fun3(*names, msg="Hello"):
for n in names:
print(msg, n)
def fun4(a=10, *b):
print(a)
print(b)
def kwargs(n1, n2, *args):
print(n1,n2)
print(args)
kwar... |
# Print numbers from 1 to 10
for n in range(1, 11):
print(n, end=" ")
else:
print("\nOver\n")
for n in range(10, 0, -1):
print(n, end=" ")
|
def operation(n1, n2, task):
return task(n1, n2)
def add(a, b):
return a + b
def mul(a, b):
return a * b
print(operation(10, 20, add))
print(operation(10, 20, mul))
|
d = {10: "Abc", 20: 'Def', 15: "Pqr"}
for t in sorted(d.items(), key=lambda t: t[1]):
print(t)
st = "Java Programming"
for c in filter(lambda ch: ch.isupper(), st):
print(c)
for c in filter(str.islower, st):
print(c)
|
# Brady Madden
# Sort the CSV data in ncaa_tournament_data2.csv alphabetically by team, separated by tournament year
import csv
from operator import itemgetter
with open('ncaa_tournament_data2.csv', 'r') as f:
data = [line for line in csv.reader(f)]
filename = ""
files = []
list = []
for line in data:
if len(... |
"""
Name: Runs a Google Analytics API query
Developer: Matt Clarke
Date: June 8, 2020
Description: Passes a payload to the Google Analytics reporting API and returns the data.
"""
import math
import pandas as pd
def run_query(service, view_id: str, payload: dict, output: str = 'df'):
"""Runs a query against the ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 2 20:48:10 2020
@author: Vinod NK
"""
import csv
import matplotlib.pyplot as plt
numerial_col_1 = []
numerial_col_2 = []
numerial_col_3 = []
def Average(lst):
return sum(lst) / len(lst)
first = True
with open('broadway.csv', 'r') as file:
reader = csv.reader(... |
import time
print('***КАЛЬКУЛЯТОР***')
print()
firstn = float(input("Введите первое число: "))
secondn = float(input("Введите второе число: "))
mathact = input('Выберите математическое действие(+,-,*,/): ')
equals = float(0)
if (mathact == "+"):
equals = firstn + secondn
print(firstn, '+', second... |
from abc import ABC, abstractmethod
from datetime import date, timedelta
from stats.support.tools.format import FormatTime
class StampTime(ABC):
"""Represent abstraction of time stamp interface."""
@abstractmethod
def today(self) -> str:
pass
@abstractmethod
def yesterday(self) -> str:
... |
#!/usr/bin/env python
import argparse
import emoji
import itertools
import random
import re
import sys
emoji_list = sorted(emoji.EMOJI_UNICODE.items())
def emoji_ord(emoji):
""" Get emoji's index """
for i, e in enumerate(emoji_list):
if e[1] == emoji:
return i
def ord_emoji(n):
"""... |
def sum_subarray(array, sum):
map = {}
curr_sum = 0
for i in range(len(array)):
curr_sum += array[i]
if curr_sum == sum:
print('sum is between 0 to', i)
if curr_sum - sum in map:
print(f'it exist between {map[curr_sum - sum ]+1} to {i}')
map... |
from time import sleep
secend = 0
mineute = 0
hour = 0
while True:
secend += 1
print(hour,":",mineute,":",secend)
sleep(1)
if secend == 59:
mineute += 1
secend = 0
if mineute == 59:
hour += 1
mineute = 0
|
def Comma_Code(spam):
print('Practising displaying list with and condition')
final = ''
for i in range(len(spam)):
if i == len(spam)-2:
final += spam[i]+', and '
elif i == len(spam)-1:
final += spam[i]
else:
final += spam[i]+', '
... |
import random
print('Welcome to Guess Number Game ')
print('I am thinking of a number between 1 and 20. ')
randomNumber = random.randint(1,20)
for guessCount in range (1,7):
guessNumber = int(input('Take a Guess. '))
if guessNumber < randomNumber :
print('Your guess is too low ')
... |
import string
class Rule:
def __init__(self):
self._name = ""
self._listfact = []
self._conclusion = None
def setname(self, name=string):
self._name = name
def getname(self):
return self._name
def setconclusion(self, fact):
self._concl... |
n=input("Enter a num")
if n=0 or n=1:
print("Enter a valid input")
else:
fact=n*(n-1)
print("factorial of num is",num fact(num)) |
def fun1(str):
return str[::-1]
str12='kobi'
print(fun1(str12))
x=input('enter name:')
print(fun1(x)+fun1(x)+fun1(x)) |
def f1 (x,y):
sum=0
# for i in range (y):
sum=int(x**y)
return sum
x=int(input('enter number:'))
y=int(input('enter number:'))
print(f1(x,y)) |
def func(str):
str1=''
for i in str:
if i!='a':
str1+=i
return str1
str='aabgfdadf'
print(func(str))
|
class Tree:
def __init__(self, data):
''' Initialise tree
'''
self.children = []
self.data = data
def add_child(self, data):
''' Tree, NoneType -> Tree
Add child with data in Tree
Return Tree with data
'''
for child in self.childr... |
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from stage1 import read_all_test_files
from stage2 import merge_cleanup
from stage3 import improve_dataset
# Stage 5/5: Visualize it!
# Steps 1-8 are the same as in the previous stage.
# Requirements:
# 1. Read the CSV files with datasets.
#... |
diasMes = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
nombre = input('¿Como te llamas? ')
print('Hola ', nombre)
print('Los próximos Juegos Olímpicos son en Tokyo el 24 de Julio del 2020, introduce la fecha de hoy y te diré cuantos días faltan: ')
strAno= input ('¿En qué año estamos? ')
strMes = input('¿... |
import numpy as np
class Deque:
def __init__(self, capacidade):
self.capacidade = capacidade
self.inicio = -1
self.final = 0
self.numero_elementos = 0
self.valores = np.empty(self.capacidade, dtype=int)
def __deque_cheio(self):
return (self.inicio == 0 and self.... |
'''
Desenvolva uma operação para transferir elementos de uma pilha P1 para uma pilha
P2 (cópia).
'''
import numpy as np
class Pilha:
def __init__(self, capacidade):
self.capacidade = capacidade
self.topo = -1
self.valores = np.empty(self.capacidade, dtype=int)
def pilha_cheia(self):
if self.topo ... |
import copy
class MyMatrix:
def __init__(self, matrix=[]):
self.dim = None
self.rows = None
self.cols = None
self.matrix = matrix
def __del__(self):
self.matrix.clear()
del self
def input_matrix(self, word=''):
dim = [int(i) for i in input(f'Enter... |
import time
def search(lst,x):
#start = time.time()
for idx, item in enumerate(lst):
if item == x:
end = time.time()
return idx
return -1
def binary_search_iter(lst, x):
#start_time = time.time()
start = 0
end = len(lst) - 1
while start <= end:
mid = ... |
#
# Created by Yevhenii Ganusich
#
class Node:
# Node class constructor
def __init__(self, val):
self.val = val
self.leftChild = None
self.rightChild = None
# Iteratively insert the value in the tree
def insertIter(root, val):
newNode = Node(val) # make a new node with new valu... |
# 숫자형실습문제.py
#numeric_ex.py
#1번
print( '{0:=^50}'.format( '1번' ) )
velocity = input( 'Input velocity : ' )
distance = input( 'Input distance : ' )
#time = eval( distance + '/' + velocity )
time = int(distance) / int(velocity)
print()
print( 'velocity : {0:<6.2f}'.format( float( velocity ) ) )
print( 'di... |
# 문자열실습문제.py
# 1번 답안
print( '{0:=^50}'.format( '1' ) )
s = 'hong gil dong201912121623210'
name = s[ :s.rfind( 'g' ) + 1 ]
birthday_index = s.rfind( 'g' ) + 1
birthday = s[ birthday_index: birthday_index + 9 ]
idnumber = s[ s.rfind( 'g' ) + 1: ]
print( 'Name : ' + name )
print( 'Birthday : ' + birthday[ :... |
#!/usr/bin/env python3
import requests
import xml.etree.ElementTree as ET
from config import ecb_url, cube, symbols
def parse_currency_args(currency):
"""
checks if we got symbol, not three letter currency name
:param currency: user input symbol or three letter currency name
:return: currency symbol... |
import copy
import math
class Sudoku():
def __init__(self, lista):
self.tablero = lista
self.tam = len(self.tablero)
self.zona = int(math.sqrt(self.tam))
# Guarda las coordenadas de los numeros que no se pueden borrar
self.no_borrable = []
for i in range(self.tam)... |
# set a M*N matrix's row and column to 0 if it has 0 in it
def setzero(l,m,n):
row = []
col = []
for i in xrange(m):
for j in xrange(n):
if l[i][j] == 0:
row.append(i)
col.append(j)
for i in row:
for j in xrange(n):
l[i][j] = 0
for j in col:
for i in xrange(m):
l[i][j] = 0
# 1.8 determine ... |
class Node:
def __init__(self, val):
self.val = val
self.next = None
def print_list(head):
while head is not None:
print head.val,
head = head.next
print ''
# 2.1 Remove duplicates from linked list
def remove_dup(head):
Prev = None
Curr = head
Next = None
d = []
while Curr is not None:
Next = Curr.n... |
def isunique(s):
a = [0 for i in xrange(256)]
for l in s:
if a[ord(l)] == 1:
return False
a[ord(l)] ^= 1
return True
a = 'abcdefgd'
print isunique(a) |
def edit_dist(X,Y,m,n):
if m == 0 or n ==0:
return m+n
elif X[m-1] == Y[n-1]:
return edit_dist(X,Y,m-1,n-1)
else:
return 1 + min( edit_dist(X,Y,m,n-1), edit_dist(X,Y,m-1,n), edit_dist(X,Y,m-1,n-1) )
def edit_dist_m(X,Y,m,n):
c = [ [0 for i in xrange(n)] for j in xrange(m) ]
... |
# 8.4 write a method to compute all permutations of a string
def permutation(s):
n = len(s)
l = list(s)
if n == 1:
return [l]
elif n== 2:
return [l, [l[1],l[0]]]
elif n>2:
l = []
perm = permutation(s[:n-1])
for i in range(n):
for item in perm:
l.append(item[:i] + [s[n-1]] + item[i:] )... |
"""Measurements using spatial objects."""
import numpy as np
from skspatial.objects import Vector
from skspatial.typing import array_like
def area_triangle(point_a: array_like, point_b: array_like, point_c: array_like) -> np.float64:
"""
Return the area of a triangle defined by three points.
The points... |
n = 0
for c in range (0, 6):
n2 = int(input("Digite um valor: "))
if n2 % 2 == 0:
n += n2
print("A soma dos número pares é: {}".format(n)) |
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
print('As notas são {} e {}, a média entre elas é {:.1f}.'.format(n1, n2, (n1 + n2)/2)) |
nota1 = float(input('Digite a nota da primeira nota '))
peso1 = float(input('Digite o peso da primeira nota '))
nota2 = float(input('Digite a nota da seugundo nota '))
peso2 = float(input('Digite o peso da segundo nota '))
media = (nota1/peso1+nota2/peso2)/2
print('A média das duas notas é:', media)
|
s = float(input("Digite seu salário: "))
if s > 1250:
aumento = 0.10
else:
aumento = 0.15
aumentoReais = s * aumento
print("Seu aumento foi de {}%, que equivale a R$:{:.2f} e com isso seu salário será de R$:{:.2f}.".format(aumento * 100, aumentoReais, s + aumentoReais)) |
t = int(input("Digite qual tabuada você quer: "))
n = 0
for c in range(0, 11):
print("{} * {} = {}".format(t, n, t * n))
n += 1 |
import math
c1 = float(input('Digite o tamanho do cateto '))
c2 = float(input('Digite o tamanho do outro cateto '))
h = math.hypot(c1,c2)
print("O valor da hipotenusa é {:.2f}".format(h)) |
# -*- coding: utf-8 -*-
def fertilizer_calculator():
"""Python program for determining fertalizer needed for a given square foot area and a known NPK ratio"""
while True:
"""Get Input from the user, error handling in case something other than a number is entered)
Inputs are assigned var... |
print ("I love python")
print("I'm excited to learn a new language")
print("We are finally done with the first year of school")
name = input ("What is your name? ")
print("your name is " + name)
question = input ("do you love python? ")
print =(""+question) |
__author__ = 'yueeong'
'''
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
UPPERLIMIT = 1000
def allinone():
sum = 0
therange = range(1,UPPERLIMIT,1)
for i in ... |
#!/usr/bin/env python3
import sys
def add_path():
from os.path import normpath, join, exists, dirname, abspath, realpath
libdir = normpath(join(dirname(realpath(__file__)), ".."))
if exists(join(libdir, "tbar")):
sys.path.insert(0, libdir)
# sys.argv[0] = os.path.abspath(__file__)
return
... |
second = int(input('Please input the seconds:'))
time = {'days':0,'hours':0,'minutes':0,'seconds':0}
if second < 60:
time['days'] = 0
time['hours'] = 0
time['minutes'] = 0
time['seconds'] = second
elif 60 <= second < 3600:
time['days'] = 0
time['hours'] = 0
time['minutes'] = second//60
time['seconds'] = second%... |
# calculate_paint_volume computes the number of gallons of paint required
# calculate_labor_hours computes the hours of labor required
# calculate_paint_cost computes the cost of the paint
# calculate_labor_cost computes the labor charges
# total_cost computes the total cost of the paint job
def calculate_paint_volume... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 18 11:09:33 2016
@author: Mebius
"""
#linear_search.linear_search is now search here
from linear_search import linear_search as search
#from binary_search import binary_search as search
import random
class ICSList:
def __init__(self, l=[]):
sel... |
single_digit_numbers = input('please input:')
length = len(single_digit_numbers)
Sum = 0
i = 0
for i in range(0,length):
Sum = Sum + int(single_digit_numbers[i])
print(Sum)
|
a={"cap_a":8}
b={"cap_b":5}
c={"cap_c":3}
for key, value in a.items():
def_a = value
for key, value in b.items():
def_b = value
for key, value in c.items():
def_c = value
print(f"You have an {def_a} litre jug full of water and two smaller jugs are empty,\nOne that contains {def_b} litres and the ot... |
# n!
# nCm = --------------
# m! (n - m)!
def custom_method(n, m):
n_factorial = n
m_factorial = m
n_m_factorial = n - m
for i in range(1, n):
n_factorial *= i
for i in range(1, m):
m_factorial *= i
for i in range(1, n - m):
n_m_factorial *= i
... |
# importing the requests library
import requests
# importing csv module
import csv
from io import StringIO
import pandas as pd
import datacompy
import json
# csv file name
filename = "something.csv"
# initializing the titles and rows list
fields = []
rows = []
# api
_id = "id"
env = "base url"
status = "sta... |
"""
Title: Number of ones in binary representation.
Given an integer, write a function to compute the number of ones in
the binary representation of the number.
Execution: python OnesInBinary.py
For more details, check out http://www.byte-by-byte.com/onesinbinary
"""
import unittest
def ones_binary(x: int):
... |
"""
Title: Reverse Stack
Given a stack, reverse the items without creating any additional data structures.
Execution: python ReverseStack.py
For more details, check out http://www.byte-by-byte.com/reversestack/
"""
import unittest
def reverse(stack):
if stack == []:
return stack
tmp = stack.pop()
... |
"""
Title: 0-1 Knapsack
Given a list of items with values and weights, as well as a max weight, find
the maximum value you can generate from items where the sum of the weights is
less than the max.
Execution: python Knapsack.py
For more details, check out http://www.byte-by-byte.com/01knapsack/
"""
import unittest
... |
# Note: This Queue class is sub-optimal. Why?
class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 19 21:35:56 2017
@author: Don Gass
Decided to try out a homebrew function :-)
"""
def howmanybars(money):
"""
Given an amount of money (as int), return the number of chocolate bars you
can get, where each bar costs $1 and contains a coupon. 10 coup... |
import math
def encrypt(plian, step=2):
cipher = ""
for i in range(0, step): # int(round((len(plian)/step)+.4))
for j in range(i, len(plian), step):
if (plian[j].isalpha()):
cipher += plian[j]
print cipher
def decrypt(cipher, step=2):
plian = ""
p... |
def solve(text, count):
if len(text) == 1:
return count // 2
# split chars into first part & last part & middle parts & joint parts
first_ch = text[0]
# Endpoints exclusive
first_index = -1
middle_index = -1
for i, ch in enumerate(text):
if ch == first_ch:
cont... |
#
# Your previous Python 3 content is preserved below:
#
# def say_hello():
# pr('Hello, World')
#
# for i in range(5):
# say_hello()
#
#
# #
# # Your previous Python 2 content is preserved below:
# #
class myxrange:
def __init__(self, *args):
if len(args) == 1:
self.start = 0
... |
#!/bin/python
import math
import os
import random
import re
import sys
def is_balanced(s):
stk = []
if len(s)%2:
return 'NO'
else:
opening_br = {'[': 1, '{': 1, '(': 1}
closing_br = {']': 1, '}': 1, ')': 1}
for x in s:
if x in opening_br:
stk.ap... |
def sh(nums):
first = None
second = None
for num in nums:
if first is None or first < num:
# print(num)
second = first
first = num
elif second is None or (second < num and num != first):
second = num
return second
nums = [2, 3, 6, 6, 5]
p... |
# https://www.hackerrank.com/challenges/angry-children-2/problem
#!/bin/python3
import math
import os
import random
import re
import sys
INT_MAX = sys.maxsize
# Complete the angryChildren function below.
def array_avg(arr):
return int(sum(arr)/len(arr))
def unfairness(arr):
n = len(arr)
w = 0
for i i... |
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('inputTotal.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Now we split the image to 140 firmas, each 250x250 size
cells = [np.hsplit(row,4) for row in np.vsplit(gray,35)]
# Make it into a Numpy array. It size will be (4,35,250,... |
import os
import ticTacToe as tTT
import hangman as hm
import wordCounter as wC
import phoneBook as pB
import owls as o
import wordLadder as wL
import removeFromString as rFS
import higherLower as hL
import rockPaperScissors as rPC
import facts as f
programs = ("Tic Tac Toe(2 player), Hangman, Word Counter, Phone boo... |
import sys, re
spreadsheet = open('D2.in','r')
# Calculate Row Difference.
def rowDifference(row):
i = 0
j = 0
vals = row.split()
for i in range(0, len(vals)):
for j in range(i+1, len(vals)):
if (int(vals[i]) % int(vals[j]) == 0):
return int(vals[i])/int(vals[j... |
# coding: utf-8
import re
def read_file(filename):
with open(filename) as f:
content = f.readlines()
return content
data = read_file("data.txt")
reg_exp = r"(\d+)-(\d+) (\w): (\w+)"
# part 1
def check_reg_match(m):
lower_bound = int(m[1])
upper_bound = int(m[2])
return lowe... |
i = '2'
if not(i):
print '1'
else:
print '2' |
# To help you get started, we've provided a sample paragraph that you can use when testing your code.
# Your game should consist of 3 or more levels, so you should add your own paragraphs as well!
start_game_message = '''Welcome to the very first Python program NicoBlc wrote! It is a word replacement game.
How to play... |
"""Demonstrating the use of SQL in python with SQL alchemy."""
import sqlalchemy as sa
import pandas as pd
if __name__ == '__main__':
engine = sa.create_engine('sqlite:///flight.db')
connection = engine.connect()
print(pd.read_sql('readings', connection))
# an example of updating the table
sql ... |
def es_maximo_o_minimo(a,b,c):
if (a==0):
print ('No es una funcion cuadratica')
else:
xv=-b/(2*a)
yv=a*((-b/(2*a))**2)+b*(-b/(2*a))+c
if (a<0):
print('El valor es un maximo en {},{}'.format(xv,yv))
else:
print('El valor es un minimo en {},{}'.format(xv,yv))
es_maximo_o_minimo(1,0,2)
|
def potencia(b,n):
if n<=0:
return 1
if n%2==0:
p=potencia(b,n/2)
return p*p
else:
p=potencia(b,(n-1)/2)
return p*p*b
print(potencia(5,3))
|
a=2
b=0
def division():
try:
if a==2:
return b
numero=a/b
except:
print('quisiste dividir por cero')
raise
finally:
print('chau')
division()
|
def most_resul():
for i in range (5):
print(i*i)
def most_resul_2():
for i in range(2,6):
print(i,2**i)
most_resul()
most_resul_2()
|
class Pila:
def __init__(self):
self.items=[]
def __str__(self):
valor=""
for elemento in self.items:
valor+=str(elemento)+","
return valor
def apilar(self,x):
self.items.append(x)
def desapilar(self):
if self.esta_vacia():
raise ValueError("La pila esta vacia")
return self.items.pop()
def esta... |
def naiveSoln(arr,k):
max_sum = 0
n = len(arr)
for i in range(n-k+1):
curr_sum = 0
for j in range(i,i+k):
curr_sum += arr[j]
max_sum = max(curr_sum,max_sum)
return max_sum
def efficientSol(arr,k):
curr_sum = 0
n = len(arr)
for i in ... |
# -*- coding: utf-8 -*-
from sys import argv
from os.path import exists
script, from_file, to_file = argv
# print "Copying from %s to %s" % (from_file, to_file)
# We could do these two on one line too, how?
# in_file = open(from_file) # 写完open就及时写close
# indata = in_file.read() # 这个不用写close
# indata = open(from_fi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.