text stringlengths 37 1.41M |
|---|
##https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/ZquE8/utrienniaia-probiezhka
##
##Утренняя пробежка
##В первый день спортсмен пробежал X километров, а затем он каждый день увеличивал пробег
##на 10% от предыдущего значения (для решения задачи разрешается использовать числа с запятой,
#... |
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/VQiXk/ughadai-chislo-2
# Угадай число - 2
# Август и Беатриса продолжают играть в игру, но Август начал жульничать.
# На каждый из вопросов Беатрисы он выбирает такой вариант ответа YES или NO,
# чтобы множество возможных задуманных чисе... |
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/9G2HO/minimal-nyi-dielitiel/submission
# Минимальный делитель
# Дано целое число, не меньшее 2. Выведите его наименьший натуральный делитель, отличный от 1.
def minimalDivisor(n):
if (n % 2 == 0):
return 2
sqrt = in... |
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/s9LoW/kolichiestvo-slov-v-tiekstie
# Количество слов в тексте
# Во входном файле записан текст. Словом считается последовательность
# непробельных символов идущих подряд, слова разделены одним или большим числом
# пробелов или символам... |
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/ydk0B/zamiechatiel-nyie-chisla-4/
# Замечательные числа - 4
# Даны два четырёхзначных числа A и B. Выведите все четырёхзначные числа на
# отрезке от A до B, запись которых является палиндромом.
def is_palindrome(obj) -> bool:
... |
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/4S9Z3/slozhnyie-protsienty/submission
# Сложные проценты
# Процентная ставка по вкладу составляет P процентов годовых, которые
# прибавляются к сумме вклада через год. Вклад составляет X рублей Y копеек.
# Определите размер вклада через ... |
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/5zNLl/chietnyie-i-niechietnyie
# Четные и нечетные
# Даны три целых числа A, B, C. Определить, есть ли среди них хотя бы одно четное и хотя бы одно нечетное.
def isSameParity(x, y):
return (x - y) % 2 == 0
x = int(input())
y ... |
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/g7wXJ/sosiedi-odnogho-znaka/submission
# Возрастает ли список?
# Дан список. Определите, является ли он монотонно возрастающим(то есть верно
# ли, что каждый элемент этого списка больше предыдущего).Выведите YES, если
# массив монотонн... |
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/qoori/vtoraia-sprava-tsifra
# Вторая справа цифра
# Дано натуральное число. Найдите цифру, стоящую в разряде десятков в его десятичной записи
# (вторую справа цифру или 0, если число меньше 10).
number = int(input())
print((number //... |
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/OIAiF/liesienka/
# Лесенка
# По данному натуральному n≤9 выведите лесенку из n ступенек, i-я ступенька
# состоит из чисел от 1 до i без пробелов.
def print_progression(n):
for i in range(1, n + 1):
print(i, end='')
... |
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/sfB26/zabastovki
# Забастовки
# Политическая жизнь одной страны очень оживленная. В стране действует K
# политических партий, каждая из которых регулярно объявляет национальную
# забастовку. Дни, когда хотя бы одна из партий объявляет ... |
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/9FHfN/prokhodnoi-ball
# Проходной балл
def find_prev_bigger_element(decreasing_list, index):
for i in range(index - 1, -1, -1):
if i >= 0 and decreasing_list[i] > decreasing_list[index]:
return decreasing_lis... |
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/kX4tZ/dlina-posliedovatiel-nosti
# Длина последоваательности
# Программа получает на вход последовательность целых неотрицательных чисел,
# каждое число записано в отдельной строке. Последовательность завершается числом 0,
# при считы... |
# Diffie-Hellman key exchange
# https://docs.python.org/3.6/library/secrets.html#module-secrets
import secrets
def dh_keygen(p, g):
""" Given prime p and generator g,
generates a private_partial_key and the public_partial_key that is used to exchange in an insecure channel
Keyword arguments:
p, ... |
# -*- coding: utf-8 -*-
import random
class BattleUnit(object):
def __init__(self):
self.strength = 1
def calucHurt(self, attacker, skillStrength):
# 是否暴击
dr = self.doRoll(attacker)
if dr:
if self.isPlayer():
return skillStrength * attacker.stre... |
price_list = []
number_of_items = int(input('Please enter the number of items:'))
while number_of_items < 0:
print('Please enter a valid number of items')
number_of_items = int(input('Please enter the number of items:'))
for i in range(1, number_of_items + 1):
current_price = float(input('Please enter the... |
#!/usr/bin/python3
def first():
animal,vegetable,mineral = 'cat','broccoli','gold'
print("Here is an {0} a {1} a {2}".format(animal,vegetable,mineral))
print(animal)
print(vegetable)
print(mineral)
first()
def prompt():
val = raw_input("Enter something to repeat: ")
print("You entered : {... |
import sqlite3;
class database_accessor:
conn = sqlite3.connect("mydatabase1.db");
cursor = conn.cursor();
def create_table(self,table):
if table == "stocks":
self.cursor.execute("CREATE TABLE stocks (company text,id text,price integer,stocks_amount integer)");
... |
# CTI- 110
# M5HW3- Factorial
# Laura Saunders
# 10/21/2017
def main():
# This program will ask the user for a nonnegative integer and use it to calculate the factorial of that number.
integer = int( input("Enter a nonnegative integer? "))
factorial = 1
for number in range(1, integer... |
# CTI- 110
# M5LAB1- Shapes
# Laura Saunders
# 10/21/2017
import turtle
def main():
for i in range(0,4):
turtle.forward(50)
turtle.left(90)
for i in range(0,3):
turtle.forward(50)
turtle.left(120)
main()
|
# Node list is
# None or
# Node(value, rest), where rest is the rest of the list
class Node:
def __init__(self, value, rest):
self.value = value
self.rest = rest
def __eq__(self, other):
return ((type(other) == Node)
and self.value == other.value
and self.rest == othe... |
'''
힙
https://blex.me/@baealex 참고함
'''
class Heap:
def __init__(self):
self.heap=[]
def __str__(self):
return str(self.heap)
def insertElement(self, data):
self.heap.append(data)
if len(self.heap)>1:
node=len(self.heap)-1
while True:
... |
'''
1259번
팰린드롬수
'''
while True:
word=list(input())
if word==['0']:
break
if word==list(reversed(word)):
print("yes")
else:
print("no") |
def encode(code):
result = []
count = 1
letter = None
for position in xrange(len(code)):
try:
current = code[position]
next = code[position+1]
if current == next:
count += 1
letter = current ... |
#this is the class for bank
import sys
import random
class Bank():
def __init__(self, accounts):
self.accounts = accounts
def getBalance(self,accountNum):
return self.accounts[accountNum]
def deposit(self,account,amount):
self.accounts[account] += amount
return self.accounts[account]
def withdraw(s... |
def is_pallindrome(word):
reversed_word = ''.join(reversed(word))
if word == reversed_word:
return True
return False
pallindrome = "racecar"
print(f"Is {pallindrome} a pallindrome: {is_pallindrome(pallindrome)}")
|
import cv2
#Face and Smile Classifiers.
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
smile_detector = cv2.CascadeClassifier('haarcascade_smile.xml')
#Grab a Webcam Feed.
webcam = cv2.VideoCapture(0)
while True:
#Read current frame from Webcam.
successful_frame_read, frame = we... |
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import pandas as pd
df = pd.read_csv("D:\\china_gdp.csv")
print(df.head(10))
plt.figure(figsize=(8,5))
x_data, y_data = (df["Year"].values, df["Value"].values)
plt.plot(x_data, y_data, 'ro')
plt.ylabel('GDP')
plt.xlabel('Year')
plt.... |
import PIL
import os, sys
from PIL import Image
print("Witaj w Pythoshopie! Program ten umożliwia Ci między innymi przeskalowanie Twojego obrazu!\n")
print()
imageFile=input("Wpisz nazwę pliku, który chcesz przeskalować (np. zabawny_pies.jpg):\n")
obrazek=Image.open(imageFile)
'''obrazek.show() #shows your image... |
import math
year_type = input()
holidays = int(input())
weekends_home_town = int(input())
weekends_sofia = 48 - weekends_home_town
volleyball_sofia = 3 / 4 * weekends_sofia
volleyball_home_town = weekends_home_town
volleyball_holidays = 2 / 3 * holidays
volleyball_total = volleyball_sofia + volleyball_h... |
"""Load text-based data onto MySQL database.
Example:
$ python data_to_mysql.py data.sum foo_db bar_table -u user -p
"""
import sys
import sqlconnector
import pandas as pd
import peeweedb
def dict2sql(db, table, data):
"""
Write a (1, n) dictionary (single row dictionary) to mySQL.
Parameters:
-... |
# Throwing Cards Away #1110
# Dalton Lima 07/28/17
# https://www.urionlinejudge.com.br/judge/en/problems/view/1110
# More problems @github.com/daltonbr/uri
import sys
# Input is a ordered deck of n cards numbered 1 to n
# with card 1 at the top and card n at the bottom
# The following operation is performed as long ... |
class StackPyList(object):
"""Stack implementation using Python lists."""
def __init__(self):
self._data = list()
def __str__(self):
return str(self._data)
def __len__(self):
return len(self._data)
def top(self):
if is_empty(self):
raise IndexError('i... |
x = int(input())
ans = 0
ans += (x//500)*1000
x -= 500 * (x//500)
ans += (x//5)*5
print(ans) |
y = int(input())
if y%400==0:
print("YES")
elif y%100==0:
print("NO")
elif y%4==0:
print("YES")
else:
print("NO") |
a, b = list(map(int, input().split()))
def gcd(a, b):
return gcd(b, a%b) if b else a
def lcm(a, b):
return a*b//gcd(a, b)
print(lcm(a, b)) |
class Dice:
def __init__(self, top=1, front=2, left=4, right=3, back=5, bottom=6):
self.d = {"TOP":top, "FRONT":front, "LEFT":left, "RIGHT":right, "BACK":back, "BOTTOM":bottom}
def roll_x(self):
self._roll("TOP", "FRONT", "BOTTOM", "BACK")
def roll_y(self):
self._roll("FRONT", "LEFT", "BACK", "RIG... |
n = int(input())
a = list(map(int, input().split()))
def insertionSort():
for i in range(1, n):
v = a[i]
j = i-1
while j>=0 and a[j]>v:
a[j+1] = a[j]
j -= 1
a[j+1] = v
print(" ".join(map(str, a)))
print(" ".join(map(str, a)))
insertionSort() |
s = list(input())
if s[0]=="A":
s[0] = "a"
flag = False
for i, ele in enumerate(s[2:-1], 2):
if ele == "C":
s[i] = "c"
flag = True
break
if flag and str(s).islower():
print("AC")
else:
print("WA")
else:
print("WA") |
s = input()
t = input()
m = "atcoder@"
for a, b in zip(s, t):
if a==b or (a=="@" and b in m) or (b=="@" and a in m):
continue
else:
print("You will lose")
exit()
print("You can win") |
n = int(input())
a = input().replace(" ", "")
m = int(input())
b = input().replace(" ", "")
if a<b:
print(1)
else:
print(0) |
s = input()
flag = True
for i, e in enumerate(s):
if i%2==0 and e not in "RUD":
flag = False
elif i%2==1 and e not in "LUD":
flag = False
if flag:
print("Yes")
else:
print("No") |
n = int(input())
if n<60:
print("Bad")
elif n<90:
print("Good")
elif n<100:
print("Great")
else:
print("Perfect") |
s = list(input())
n = len(s)
srev = list(reversed(s))
a = s[:(n-1)//2]
arev = list(reversed(a))
b = s[(n+3)//2-1:]
brev = list(reversed(b))
if s == srev and a == arev and b == brev:
print("Yes")
else:
print("No")
|
n = int(input())
if n==2:
print("WANWAN")
else:
print("BOWWOW") |
from string import ascii_lowercase, ascii_uppercase
a = input()
if a in ascii_lowercase:
print("a")
else:
print("A") |
s = input()
num = set("1234567890")
ans = False
for e in s:
if e in num:
ans = True
if ans:
print("leet")
else:
print("Noleet") |
class Dice:
def __init__(self, top=1, front=2, left=4, right=3, back=5, bottom=6):
self.d = {"TOP":top, "FRONT":front, "LEFT":left, "RIGHT":right, "BACK":back, "BOTTOM":bottom}
def roll_x(self):
self._roll("TOP", "FRONT", "BOTTOM", "BACK")
def roll_y(self):
self._roll("FRONT", "LEFT", "BACK", "RIG... |
s = input()
a = "WBWBWWBWBWBW"
a = a*3
if s==a[0:20]:
print("Do")
elif s==a[2:22]:
print("Re")
elif s==a[4:24]:
print("Mi")
elif s==a[5:25]:
print("Fa")
elif s==a[7:27]:
print("So")
elif s==a[9:29]:
print("La")
elif s==a[11:31]:
print("Si") |
#!/usr/bin/env python
#
import sys
from collections import defaultdict
# Time complexity: O(n)
# Mem complexity: O(n)
def is_anagram(l1, l2):
d = defaultdict(lambda: 0)
for c in l1:
d[c] += 1
d2 = defaultdict(lambda: 0)
for c in l2:
d2[c] += 1
for c, n in d.items():
if n != d2[c]:
return... |
#!/usr/bin/env python
#
import sys
# time complexity: O(n)
# mem complexity: O(n)
def one(s):
return ''.join([ s[i] for i in range(len(s)-1, -1, -1) ])
# time complexity: O(n)
# mem complexity: O(1)
def two(l):
for i in range(0, len(l)):
j = len(l) - i - 1
if i >= len(l)/2:
break
l[i], l[j] = ... |
def tower_builder(n_floors):
'''
https://www.codewars.com/kata/576757b1df89ecf5bd00073b
'''
tower = []
max_size = (n_floors - 1) * 2 + 1
for i in range(n_floors):
stars = 2 * i + 1
spaces = (max_size - stars) // 2
floor = ' ' * spaces
floor += ... |
def dfs(adj, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
yield start
for child in adj[start] - visited:
yield from dfs(adj, child, visited)
#return visited
def dfs_iter(adj, start):
visited, stack = set(), [start]
while stack:
... |
def ccw(u, v, w):
'''
Returns a positive number if u -> v -> w is a counter-clockwise angle
a negative number if u -> v -> w is a clockwise angle
zero if u -> v -> w are colinear
'''
return (v[0] - u[0]) * (w[1] - u[1]) - (v[1] - u[1]) * (w[0] - u[0])
def is_convex(points):
... |
import random
def shuffle(arr, left=0, right=None):
'''
Shuffles arr[l:r+1] unbiasedly with Fisher-Yates algorithm
Note that the interval includes both l and r
'''
if not right:
right = len(arr) - 1
while right - left:
idx = random.randint(left, right)
arr[right], arr... |
"""
Assumes no negative weights
Time Complexity: O(V + E log V)
Space Complexity: O(V)
"""
import heapq
def dijkstra(adj, start):
path = {vertex: -1 for vertex in adj}
dist = {vertex: float('inf') for vertex in adj}
dist[start] = 0
pq = [(0, start)]
while len(pq) > 0:
lenght, vertex = h... |
from tkinter import *
def win1():
# creating login window
window = Tk()
photo = PhotoImage(file="shield-logo.gif")
imgLabel = Label(window, image=photo)
imgLabel.photo = photo
imgLabel.place(relx=.1,rely=.1,anchor=CENTER)
logoLabel = Label(window, text="IVY LEAGUE UNIVERSITY", font=("... |
#ASSIGNENT IF STATEMENTS
#funtion to check equality between 3 numbers
def equalityTest(a,b,c):
a=int(a)
b=int(b)
c=int(c)
if (a==b or a==c or b==c) :
check=True
else:
check= False
print(check)
equalityTest("1",2,2)
|
a = int(input('first number: '))
b = int(input('second number: '))
m = 1
for n in range(2,min(a,b)):
if (a%n == 0) & (b%n == 0):
m = n
print(f'The greatest common divisor of {a} and {b} is:{m}')
print(f'The least common multiple of {a} and {b} is:{(a*b)//m}')
|
# Prime number within 100, not include 1
for i in range(2,101):
p = True
for j in range(2,i-1):
if i%j == 0:
p = False
break
else:
continue
if p == True:
print(f'{i} is a prime number')
|
def lengthOfLongestSubstring(s):
last_appear = {}
start=0
longest=0
for index,letter in enumerate(s):
if letter in last_appear and last_appear[letter] >=start:
start = last_appear[letter]+1
else:
longest = max(longest, ... |
import os
def signup():
input1 = input("Enter Username: ")
input2 = input("Enter Password: ")
users = open('user.txt', 'a')
users.write("\n{0},{1}".format(input1, input2))
def login(user_info):
us_input = input("Enter Username: ")
pw_input = input("Enter Password: ")
users... |
#!/usr/bin/env python3
"""Programm that catenates"""
import os
import sys
def main():
args = sys.argv[1:]
if len(args) < 1:
print('Usage: {} FILE'.format(os.path.basename(sys.argv[0])))
sys.exit(1)
file = args[0]
if not os.path.isfile(file):
print('{} is not a file'.form... |
#!/usr/bin/env python3
import os
import sys
def main():
args = sys.argv[1:]
# #If there are no argument
if len(args) != 1:
print('Usage: {} FILE [NUM_LINES]'.format(os.path.basename(sys.argv[0])))
sys.exit(1)
# #If first argument is not a file
file = args[0]
if not os.path.isfile(fi... |
from heapq import heappush, heappop
class Node:
"""A node in a graph"""
# How do we handle difference distance functions?
def __init__(self, id, neighbors={}):
self.id = id
self.neighbors = neighbors
self.previous = None
self.shortest_distance = None
def __str__(self)... |
PI = {}
BESTLEN = 0
BESTVAL = 0
def next_collatz(n):
if n % 2 == 0:
return n/2
else:
return 3*n + 1
def collatz_length(num):
if num == 1:
return 0
if not num in PI:
PI[num] = 1 + collatz_length(next_collatz(num))
return PI[num]
for i in xrange(1, 1000000):
... |
# https://www.geeksforgeeks.org/single-neuron-neural-network-python/
# Python program to implement a
# single neuron neural network
# import all necessery libraries
from numpy import exp, array, random, dot, tanh
# Class to create a neural
# network with single neuron
class NeuralNetwork():
def __init__(sel... |
import time
# A fake comment
# Add to dev
seconds = 50
minutes = 59
hours = 12
ampm = 1
text_ampm = ""
while 1==1:
print(hours,":",minutes,":",seconds,text_ampm)
seconds = seconds +1
time.sleep(1)
if seconds == 60:
seconds = 0
minutes = minutes +1
if minutes == 60:
minutes... |
import graph
from depth_first_search import depth_first_search
def Kruskal(G, w):
'''
Implementation of Kruskal's algorithm for obtaining the minimum
spanning tree of a weighted undirected graph.
[G]: graph.Graph instance. undirected and connected.
If not connected we get a forest in... |
"""
This module implements a Convolutional Neural Network in PyTorch.
You should fill in code into indicated sections.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
class ConvNet(nn.Module):
"""
This class implem... |
#Wayne Swamber Jr
#1419882
print("Davy's auto shop services")
print("Oil change -- $35")
print("Tire rotation -- $19")
print("Car wash -- $7")
print("Car wax -- $12")
print()
#services = {'Oil change': 35, 'Tire rotation': 19, 'Car wash': 7, 'Car wax': 12}
print("Select first service:")
first_service = input()
print... |
#!/usr/bin/env python3
import pandas as pd
def growing_municipalities(df):
increase_df = df[df["Population change from the previous year, %"] > 0]
proportion = increase_df.shape[0] / df.shape[0]
print("Proportion of growing municipalities: {0:.1f}%".format(proportion))
return proportion
def main(... |
#!/usr/bin/env python3
import pandas as pd
def best_record_company():
df = pd.read_csv("src/UK-top40-1964-1-2.tsv", sep="\t")
df = df.groupby("Publisher")
woc_sum = df["WoC"].sum().sort_values()
print(woc_sum)
print(df)
best_df = df.get_group(woc_sum.index[-1])
print(best_df)
return b... |
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
def to_grayscale(image):
w=np.array([0.2126, 0.7152, 0.0722]).reshape(1, 1, 3)
a = image * w
return a.sum(axis=2)
def to_red(image):
image2=image.copy()
image2[:,:,[1,2]] = 0
return image2
def to_green(image):
... |
#!/usr/bin/env python3
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
def fit_line(x, y):
model = LinearRegression(fit_intercept=True)
# model.fit(x[:, np.newaxis], y)
model.fit(x.reshape(-1, 1), y) # Equivalent, Single feature, -1 means infer from th... |
#!/usr/bin/env python3
import pandas as pd
import numpy as np
def missing_value_types():
df=pd.DataFrame([["United Kingdom", np.nan, None],
["Finland", 1917, "Niinistö"],
["USA", 1776, "Trump"],
["Sweden", 1523, None]... |
#!/usr/bin/env python3
import pandas as pd
def suicide_fractions():
df = pd.read_csv("src/who_suicide_statistics.csv")
df["Suicide fraction"] = df["suicides_no"] / df["population"]
result = df.groupby("country").mean()
return result["Suicide fraction"]
def info(df, name):
print("\n%s" % name)
... |
#!/usr/bin/env python3
import numpy as np
def first_half_second_half(a):
m = int(a.shape[1]/2)
# print(m)
b, c = a[:, 0:m], a[:, m:]
d = np.sum(b, axis=1) > np.sum(c, axis=1)
print(b, c, d)
return a[d]
def main():
a = np.array([[1, 3, 4, 2], [2, 2, 1, 2]])
print(first_half_second_half... |
#!/usr/bin/env python3
import math
def main():
# enter you solution here
shape_list = ["triangle", "rectangle", "circle"]
while True:
shape = str(input("Choose a shape ({0}, {1}, {2}): ".format(shape_list[0], shape_list[1], shape_list[2])))
if not shape:
break
elif sha... |
# Question 1
def hello_name(user_name):
print("hello_" + user_name +"!")
# Question 2
odd_numbers = []
n = 1
while len(odd_numbers) < 100:
if n % 2 == 1:
odd_numbers.append(n)
n += 1
for odd_number in odd_numbers:
print(odd_number)
# Question 3
def max_num_in_list(a_list):
return(max(a_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 取一个list或tuple中的部分元素
# 笨办法:
L1 = ('Jeremy', 'Sarah', 'Micheal', 'Steve', 'Adam')
L2 = ['Jeremy', 'Sarah', 'Micheal', 'Steve', 'Adam']
print(L1[0], L1[2], L1[4])
# 好办法:切片
print(L2[0:3])
# 从0开始,0可以省略
print(L2[:3])
# 可以从任意位置开始,只要不超过范围
print(L2[1:3])
# 也可以倒着来:
print(L2[-3:])... |
# Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
sum = 0
count = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") :
continue
pos = line.find(':')
#print pos
#print line[pos+1:]
string = line[pos+1:]
#print "Copy of... |
name = raw_input("Enter file:")
if len(name) < 1 :
name = "mbox-short.txt"
handle = open(name)
wordsl = list()
#count = -1
for line in handle:
line = line.rstrip()
if not line.startswith('From ') : continue
words = line.split()
# print words[1]
# count = count + 1
# wordsl[count] = word... |
import sqlite3
import weather_forecast
def get_planned_scheme():
"""function for getting the planned
network scheme specified by user"""
con = sqlite3.connect('temp_db.db')
with con:
cur = con.cursor()
cur.execute("SELECT scheme FROM temp_db")
while True:
row = cur.fetch... |
# Given an array of non-negative integers, you are initially positioned at the first index of the array.
# Each element in the array represents your maximum jump length at that position.
# Determine if you are able to reach the last index.
# Example 1:
# Input: [2,3,1,1,4]
# Output: true
# Explanation: Jump 1 step ... |
# Given two strings text1 and text2, return the length of their longest common subsequence.
# A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" wh... |
"""AOC Day 3"""
import pathlib
import time
def read_input(input_path: str) -> list:
"""take input file path and return appropriate data structure"""
with open(input_path, 'r') as input_file:
lines = list()
for line in input_file.readlines():
lines.append(line.strip())
retur... |
# import the necessary packages
from sklearn.feature_extraction.image import extract_patches_2d
class PatchPreprocessor:
def __init__(self, width, height):
# store the target width and height of the image
self.width = width
self.height = height
def preprocess(self, image):
# e... |
def get_formatted_name(first_name, last_name, middle_name =''):
'''Return a full name, nice formatted'''
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('j... |
guests = ['Ben', 'Els', 'Stijn', 'Sofie', 'Juan', 'Sophie']
print(guests)
message = "Dag " + guests[0] + ", Graag nodig ik je uit voor een etentje!"
print (message)
not_present = guests.pop(4)
print ("\n" + not_present + " kan niet aanwezig zijn.")
print (guests)
guests.insert(4,'Pierre')
print (guests)
#sort metho... |
from random import choice
from place import *
class Generator(object):
# Hopefully this stuff will load from DB in the future
descriptions = ["a hallway", "a dark room", "a class room",
"a lecture hall", "a janitor's closet",
"a supply closet", "a staircase"]
direc... |
import turtle # change the RGB colors
def draw_circle(turtle, color, size, x, y):
turtle.penup()
turtle.color(color)
turtle.fillcolor(color)
turtle.goto(x,y)
turtle.begin_fill()
turtle.circle(size)
turtle.end_fill()
turtle.pendown()
tommy = turtle.Turtle()
tommy.shape("turtle")
tommy.... |
# 1. stack
# An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g.
# Algorithm:
# 1. Initialize a stack S.
# 2. Process each bracket of the expression one at a time.
# 3. If we encounter an opening b... |
# A python program to test all keywords below
#here are the keywords
'''
False class is return None continue
for True def from while and
not with as elif if or
else import pass break in raise
'''
from math import sin as alias
# c... |
import datetime
import os
import shutil
from pathlib import Path
print('This Script will back up a valid source file path: ')
print('The program works by copying the input directory to a specified destination path: ')
source_path = Path(input(' Please enter the source c:file path: '))
if not source_path.exists():
... |
def myCount(s):
flag = 1
count = 0
for i in range(0,len(s),1):
if s[i]==' ' or s[i]== '\n' or s[i]== '\t':
flag=1
elif flag == 1:
count = count+1
flag = 0
return count
if __name__ == '__main__':
print(myCount('One two three\n ... |
def non_repeated(string):
if (len(string)>2):
my_res = string[0]
index = 0
for i in range(1,len(string),1):
if string[i] != my_res[index]:
index = index + 1
my_res = my_res + string[i]
print(my_res)
else:
print("Ente... |
from itertools import product
from app.buttons import *
class Level(object):
# Object to hold and solve a calculator level
def __init__(self,level_data):
# General constructor
self.goal = level_data.goal
self.moves = level_data.moves
self.start = level_data.start
self.buttons ... |
class bst(object):
def __init__(self):
self.__parent=None
self.__root=None
self.__left,self.__right=None,None
def __len__(self):
if self.__root==None:
return 0
return len(self.__left)+len(self.__right)
def insert(self,x):
if x==None or self.__root==x:
return
if self.__root==None:
self.__ro... |
__author__ = 'Turtle'
print("Hi I'm new to this")
print("I'm going to try to make the number 10 turn into the number 5")
var1 = 10
print(var1)
var2 = 5
print(var2)
print("So We'll take var1 and subtract var2 from it!")
var1 - var2
print(var1 - var2)
print("Now that we did that let's try to make it turn into 15!")
var3 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.