text stringlengths 37 1.41M |
|---|
"""
Task 11:
Given a binary tree, you need to compute the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between
any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
... |
"""
Parses the argument lexicon by Somasundaran, Ruppenhofer & Wiebe (2007):
http://people.cs.pitt.edu/~wiebe/pubs/papers/sigdial07.pdf
http://mpqa.cs.pitt.edu/lexicons/arg_lexicon/
Span identification task: Encodes whether a given token is contained in a
phrase that matches a rhetorical pattern.
Technique classificat... |
"""
1. List: sorted function and sort method are quite different!
"""
li = [9, 3, 2, 0, 33, 22, -98, 1]
s_li = sorted(li, key=abs, reverse=True) # Sorted function returns a new variable and it does NOT affect the original list, the key/reverse argument are optional.
print("sorted varialbe:\t", s_li)
li.sort(reverse=T... |
'''Создать список с оценками учеников разных классов школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...]
Посчитать и вывести средний балл по всей школе.
Посчитать и вывести средний балл по каждому классу.'''
import math
def my_round(x):
return int(x + math.copysign(0.5, x))
school_journal= [{'school_c... |
numbers = []
numbers2 = []
numbers3 = []
limit1 = int(input("Write 1st desired upper limit here: "))
limit2 = int(input("Write 2nd desired upper limit here: "))
limit3 = int(input("Write 3rd desired upper limit here: "))
def make_list_for(limit, list):
for val in range(0, limit):
list.append(v... |
# this line prints a string
print("I will now count my chickens:")
# this line prints a string followed by the result of a sum
print("Hens", 25.0 + 30.0 / 6.0)
print("Roosters", 100.0 - 25.0 * 3.0 % 4.0)
# this line prints a string
print("Now I will count the eggs:")
# this line prints a sum
print( 3.0 + 2.0 + ... |
# -*- coding: utf-8 -*-
import numpy as np
def estimateGrad(fun, x, delta):
""" Given a real-valued function fun, estimate its gradient numerically.
Inputs are:
-fun: a function of one variable
-x: an input, represented as a sparse vector
-delta: a small real value
Output is:
... |
class Riddle:
def __init__(self, question, correctAnswer, timesToTry):
self.question = question
self.correctAnswer = correctAnswer
self.timesToTry = timesToTry
def activate(self):
print("Welcome")
print("You are locked in this room...")
print("To proceed to the ... |
"""Demo of how to pop up plots asynchronously using separate processes."""
from __future__ import print_function
# https://gist.github.com/dwf/1222883
from multiprocessing import Process
import time
import sys
import matplotlib.pyplot as plt
import numpy as np
def demo():
i = 0
processes = []
while True:
... |
from __future__ import division
from builtins import range
from random import random
from time import time, sleep
import pylab as plt
def simulateTime(stable = 0, rand = 100):
"""
Simulates process.
:param stable: stable time over
:param rand: value of time to randomize
:return: Dtime # time durat... |
import math
pw = ""
pwFile = open("common.txt", 'r')
listOfCommons = pwFile.readlines()
def errorMsg():
msg = ""
if length == 0:
msg += "You need at least 6 characters\n"
if uppercase == 0:
msg += "You need at least 1 uppercase letter\n"
if lowercase == 0:
msg += "You need at lea... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 18 10:50:10 2020
@author: hussa
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
# Question 4 #################################################################
# Equation for field due to ring of charge
def dE_field(z):
# E = 2pi*r*z... |
t = int(input())
for _ in range(t):
string = input()
ballCount = 0
for i in string:
if i == 'N'or i == 'W' or i == 'D':
continue
else:
ballCount += 1
over = int(ballCount / 6)
ball = ballCount%6
if over == 0 and ball !=0:
if ball > 1:
... |
my_list = [0, 1, 2, 3, 4, 5]
for item in my_list:
print("Item : "+str(item))
my_list = [0, 1, 2, 3, 4, 5]
for i,item in enumerate(my_list):
print("Item : "+str(i)+" = "+str(item))
family = ['anik','mona','rajdon','halim']
for i,data in enumerate(family):
print(str(family[i])+" = "+str(data))
my_dict ... |
class Node:
def __init__(self, data):
self.data = data
self.nextAddress = None
class LinkedList:
def __init__(self):
self.hade = None
# def printList(self):
# tmp = self.hade
# while(tmp != None):
# print(tmp.data)
# tmp = tmp.nextA... |
class Student:
perc_raise = 1.6
def __init__(self, first, last, grade):
self.first = first
self.last = last
self.grade = grade
self.email = first + '.' + last + '@gmail.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
def ap... |
Number = 4
'''This program finds numbers divisible by 4'''
for a in range(101):
if a % 4 == 0:
print(a, "is divisible by 4")
else:
print(a, "is not divisible by 4")
|
def target_factors_of_triangle(number):
factors = 0
test_number = 0
while factors < number:
test_number += 1
test_triangle = triangle(test_number)
# This IF makes it a little faster
# assuming that a non-mult of 2 would never have the most factors
# Is that true? I don't know.
if test_triangle % 2 == 0:
... |
def sum_even_fibs(maxInt):
lastVal = 1
currentVal = 2
sum = 0
while currentVal < maxInt:
if currentVal % 2 == 0:
sum += currentVal
lastVal, currentVal = currentVal, lastVal + currentVal
return sum
if __name__ == "__main__":
maxInt = input("Please enter the maximum number you wish to sum to: ")
print sum_... |
print("Good morning world!")
print("It's time for day two of python drills. yay!")
numberOne = 1
addition = 1 + 1
subtraction = 5 - 4
multiplication = 5 * 5
division = 10 / 2
exponentiation = 5 ** 5
numList = list(range(0,15))
print(numList)
puppies = ['puppy', 'doggie', 'stutler', 'good boy', 'poochie']
for puppy in p... |
def ft_len(sstr):
l = 0
for i in sstr:
l += 1
return l
def ft_analysis(sstr):
print(sstr[2])
print(sstr[ft_len(sstr) - 2])
print(sstr[0], sstr[1], sstr[2], sstr[3], sstr[4], sep="")
i = 0
while i != ft_len(sstr) - 2:
print(sstr[i], end="")
i += 1
... |
import mysql.connector
from mysql.connector import MySQLConnection, Error
print("hello")
print("""Please enter any choice
========= L FOR LOGIN
========= R FOR REGISTER
========= A FOR ADMIN LOGIN
========= Q for quit the Menu""")
choice = input("enter your choice = ")
try:
myconnection = mysql.connector.connec... |
import numpy as np
import pandas as pd
import csv
from math import sqrt
import matplotlib.pyplot as plt
import itertools
df2 = pd.read_csv('Salary.csv') #read_csv vs DataFrame gets it in the form we want to pull out X and Y columns
df2.head()
X = df2.iloc[:, :-1].values
Y = df2.iloc[:, -1].values
def mean(values):
... |
from random import *
word_list = ["Mac n Cheese", "Pizza", "Penne Vodka", "Empanadas ", "Grilled Cheese", "Icecream"]
#Generates a random integer.
x = randint(0, len(word_list)-1)
print(word_list[x])
|
nums = [123,1232,4,4,68,83,1,24,43,75,634]
sum = 0
#iterate through a list
for e in nums:
sum = sum + e
print(sum)
person = {
'name': 'Daniyar',
'age': 22,
'height': 188.5,
'students': ['Ibra', 'Yaroslav'],
}
for k,v in person.items():
print(k,v)
sum = 0
for i in range( len(nums) ):
sum... |
# Drone Control Py by Drone Team 2-1
# Sprint Week Project #1, November 2020
# Python program for sending user commands to the Tello Drone
import tello_abridged
# TODO: Track if drone is in the air or not
#Connect to the drone
t = tello_abridged.Tello()
t.connect_and_initialize()
# List of valid commands the tello ... |
temperature_c = input('please key in Celsius temperature:')
temperature_f = float(temperature_c) * 9 / 5 + 32
print("Fahrenheit", temperature_f)
|
import pygame
from pygame.draw import *
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
SUN_BORDER = (255, 255, 128)
SUN_COLOR = (255, 255, 192)
SKY = (0, 255, 255)
WATER = (22, 80, 68)
GRAY = (32, 32, 32)
def draw_sun(x, y, r):
line(screen, SUN_COLOR, (x-r, y), (x+r, y), r//10)
line(screen, SUN_COLOR, (x, y-r), (x, y+r)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 13 17:16:27 2020
@author: willik37
"""
play = "y"
last_number = 0
while play == "y":
x = int(input("How many numbers?"))
x+=last_number
for i in range (last_number, x):
# Debug code here
print(f'{last_number}: last_numb... |
"""\
Stopwatch - a convenience class for timing things.
>> s = Stopwatch()
>> ... # do something you want timed
>> duration = s.duration()
"""
from datetime import datetime
class Stopwatch(object):
def __init__(self):
self.start()
def start(self):
self._start = datetim... |
def q_sort_all(array):
q_sort(array, 0, len(array) - 1)
def q_sort(array, i, k):
if i < k:
pivot = partition(array, i, k)
q_sort(array, i, pivot-1)
q_sort(array, pivot+1, k)
def partition(array, left, right):
pivot_index = choose_pivot(left, right)
pivot_value = array[pivot_i... |
import matplotlib.pyplot as plt
def drawGraph(data,xID,yID, xLabel,yLabel):
for point in data:
x=point[xID]
y=point[yID]
plt.scatter(x, y, color="blue")
plt.xlabel(xLabel)
plt.ylabel(yLabel)
plt.show() |
__author__ = "ipetrash"
# https://docs.python.org/3.4/tutorial/inputoutput.html#reading-and-writing-files
# http://pythonworld.ru/tipy-dannyx-v-python/fajly-rabota-s-fajlami.html
# Открыть файл в режиме чтения
with open("foo.txt", mode="r") as f:
print(f.read())
print()
# Открыть файл в режиме чтения и построч... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# SOURCE: https://docs.python.org/3/library/csv.html#csv.DictWriter
# SOURCE: https://stackoverflow.com/a/3087011/5909792
import csv
items = [
{"name": "bob", "age": 25, "weight": 200},
{"name": "jim", "age": 31, "weight": 180},
]
ke... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# EN: Least Common Multiple.
# RU: Наименьшее общее кратное (НОК).
def gcd(a, b):
"""Нахождение НОД"""
while a != 0:
a, b = b % a, a # Параллельное определение
return b
if __name__ == "__main__":
a, b = 7006652, 11230... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# SOURCE: https://github.com/szabgab/slides/blob/914d15bb55cb0e335afcb72b6af0fa2aa9ed356f/python/examples/pil/draw_rectangle_with_rounded_corners.py
# TODO: append alpha
from PIL import Image, ImageDraw
def round_corner(radius, fill):
"... |
# coding=utf-8
__author__ = "ipetrash"
import argparse
def create_parser():
parser = argparse.ArgumentParser(
description="Find the longest word in a string, separated by spaces."
)
return parser
if __name__ == "__main__":
create_parser().parse_args()
string = input("Input string: ")... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
"""
Вам дана последовательность строк.
В каждой строке замените все вхождения нескольких одинаковых букв на одну букву.
Буквой считается символ из группы \w.
Sample Input:
attraction
buzzzz
Sample Output:
atraction
buz
"""
# Пример использов... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# SOURCE: Design Patterns: Builder — Строитель
# SOURCE: https://ru.wikipedia.org/wiki/Строитель_(шаблон_проектирования)
from abc import ABC, abstractmethod
# "Product"
class Pizza:
def __init__(self):
self._dough = ""
sel... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# SOURCE: https://github.com/barseghyanartur/transliterate
import transliterate
def make_transliterate(text: str) -> str:
try:
return transliterate.translit(text, reversed=True)
except transliterate.exceptions.LanguageDetectionE... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
def make_transliterate(text: str) -> str:
symbols = (
"абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ",
"abvgdeejzijklmnoprstufhzcss_y_euaABVGDEEJZIJKLMNOPRSTUFHZCSS_Y_EUA",
)
tr = {ord(a): ord(b) f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# SOURCE: https://github.com/mozman/svgwrite/blob/master/examples/ltattrie/color_triangles_function.py
import math
# pip install svgwrite
import svgwrite
from svgwrite import rgb
def create_svg(name):
width = 900
height = 900
fon... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# pip install nltk
import nltk
text = "Ай да А.С. Пушкин! Ай да сукин сын!"
sentences = nltk.sent_tokenize(text)
print(f"Before ({len(sentences)}): {sentences}")
# Before (3): ['Ай да А.С.', 'Пушкин!', 'Ай да сукин сын!']
sentences = nltk.sen... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# SOURCE: https://docs.python.org/3.6/library/socketserver.html#socketserver-tcpserver-example
import socketserver
import sys
sys.path.append("..")
from common import send_msg, recv_msg
HOST, PORT = "localhost", 9090
class MyTCPHandler(soc... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
import datetime as dt
def generate_range_dates(start_date, end_date) -> list:
date_1 = min(start_date, end_date)
date_2 = max(start_date, end_date)
# Сразу добавляем стартовую дату
items = [date_1]
while date_1 < date_2:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
from datetime import datetime
check_hours, check_minutes = 16, 29
dt = datetime.now()
check_dt = dt.replace(hour=check_hours, minute=check_minutes)
if dt > check_dt:
print(dt - check_dt)
else:
print(check_dt - dt)
# 0:38:00
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
from datetime import datetime
def get_age(text: str) -> int:
date_text = text.split()[0]
dt = datetime.strptime(date_text, "%d/%m/%Y")
years_delta = datetime.today() - dt
return years_delta.days // 365
if __name__ == "__main_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
import random
from pathlib import Path
file_name = Path(__file__).parent / "abusive words.txt"
with open(file_name, encoding="utf-8") as f:
WORDS = f.readlines()
def get_words(number, chain_length=2):
random.shuffle(WORDS)
random_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# Functors
class Foo:
def __call__(self):
return 1
class MySum:
def __call__(self, *args):
return sum(args)
class MyPow:
def __call__(self, a, b):
return a**b
class Bar:
def __init__(self, start_val... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# «Если Алиса будет кидать монетки до тех пор, пока не получит решку, следующую за орлом, а Боб – до тех пор,
# пока не получит две решки подряд, то Алисе в среднем потребуется четыре броска монеты, в то время как Бобу – шесть.»
from random imp... |
__author__ = "ipetrash"
# Sort / Сортировка
# https://wiki.python.org/moin/HowTo/Sorting
import random
l = [x for x in range(20)]
random.shuffle(l)
print("List: %s" % l)
l.sort()
print("Sorted list: %s" % l)
l.sort(reverse=True)
print("Reversed Sorted list: %s" % l)
print()
m = [x for x in range(20)]
random.shuf... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# SOURCE: https://www.pyimagesearch.com/2015/02/09/removing-contours-image-using-python-opencv/
# pip install opencv-python
import cv2
import numpy as np
def is_contour_bad(c):
# approximate the contour
peri = cv2.arcLength(c, True)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
def get_num(text: str) -> int:
return int("".join(filter(str.isdigit, text)))
def natural_sorted(items: list) -> list:
return sorted(items, key=get_num)
def natural_sort(items: list):
items.sort(key=get_num)
if __name__ == "__ma... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
"""
Скрипт для вывода имен без повторений.
"""
from print_statistic_all_names import get_all_names
first_name_list = [name[1] for name in get_all_names(split_name=True)]
print("Total:", len(first_name_list))
unique_first_name_list = list(se... |
__author__ = "ipetrash"
def fibo_1(n):
f = [0, 1]
for i in range(2, n + 1):
f.append(f[i - 1] + f[i - 2])
print(f)
def fibo_2(n):
a, b = 0, 1
print(a, b, end=" ")
for i in range(2, n + 1):
a, b = b, a + b
print(b, end=" ")
if __name__ == "__main__":
# Fibo / Фиб... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
from tkinter import *
root = Tk()
root.title("Шашки")
canvas = Canvas(root, width=700, height=700)
canvas.pack()
def square():
y = 0
while y < 700:
x = 0
while x < 700:
canvas.create_rectangle(x, y, x + 88... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# SOURCE: http://www.nerdparadise.com/programming/pygame/part1
# pip install pygame
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
game_active = True
is_blue = True
x = 100
y = 100
clock = pygame.time.Clock()
while... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
import csv
from io import StringIO
text = """\
id;name;address;zip
1;vasya;moscow;11111
2;oleg;sochi;22222
"""
# Variant 1
csv_reader = csv.reader(text.splitlines(), delimiter=";")
for row in csv_reader:
print(row)
print()
# Variant 2
cs... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# Very-very simple calc
def calc(expr):
operator_function = {
"-": lambda x, y: x - y,
"+": lambda x, y: x + y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y,
}
nums = list()
opers = list()
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
import copy
from dataclasses import dataclass
@dataclass
class Button:
value: bool
is_clicked: bool = False
def activate(buttons: list[Button], index: int):
button = buttons[index]
if button.is_clicked:
return
but... |
from mas_evaluator import value_from_ast
from Queue import *
import math
import operator
'''Given a root node of an expression tree for an answer this code will traverse the tree and outputs a dictionary of possible wrong answers obtained via one mistake. For each of these mistakes we record as the value for that key ... |
def check_version(v1,v2):
if v1==None or v2==None or len(v1)==0 or len(v2)==0:
return 0
l1 = [int(i) for i in v1.split(".")]
l2 = [int(i) for i in v2.split(".")]
while(len(l1)<len(l2)):
l1.append(0)
while(len(l1)>len(l2)):
l2.append(0)
i=0
while i<len(l1) an... |
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
a = head
b = None
if a.next != None:
b = head.next
while b.next!=None and b.next.next!=None:
b = b.next.next
a = a.next
... |
#Valo Mara
#vmara2
#CS 111 Lab Monday at 3:00
#Writing text on pictures
file = pickAFile()
pic = makePicture(file)
addText(pic,20,(getHeight(pic)-20),"...What?",white)
pic.show()
writePictureTo(pic,file)
#-5 for not re-prompting for a new filename to save new picture. Program saves by overwriting original picture. |
########################################################################
# Exercises 3.5 - #04
#
# Traverse the graph of Problem 1 by breadth-first search and construct
# the corresponding breadth-first search tree. Start the traversal at
# vertex 'a' and resolve ties by the vertex alphabetical order.
#
# Problem 1 gr... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
def get_pair(arr, n):
colors = {}
pairs_count = 0
for i in arr:
if i in colors.keys():
colors[i] += 1
else:
colors[i] = 1
if colors[i] % 2 == 0:
pairs... |
def check_keep_playing(game):
keep_playing = input("Do you want to try the other game? -> (Yes/No)")
if keep_playing == "No":
print("Well, it was a pleasure!")
if keep_playing == "Yes":
if game == 1:
game = 2
run_game(game)
elif game == 2:
game = 1
run_game(game)
def run_game(g... |
# coding:utf-8
# 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
#
# 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。
#
# 示例 1:
#
# 输入: [1,2,3,1]
# 输出: 4
# 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
# 偷窃到的最高金额 = 1 + 3 = 4 。
# 示例 2:
#
# 输入: [2,7,9,3,1]
# 输出: 12
# 解释: 偷... |
# coding:utf-8
# 你有一个单词列表
# words
# 和一个模式
# pattern,你想知道
# words
# 中的哪些单词与模式匹配。
# 如果存在字母的排列
# p ,使得将模式中的每个字母x# 替换为# p(x)
# 之后,我们就得到了所需的单词,那么单词与模式是匹配的。
#
# (回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。)
#
# 返回# words中与给定模式匹配的单词列表。
# 你可以按任何顺序返回答案。
# 示例:
#
# 输入:words = ["abc", "deq", "mee", "aqq", "dkd", "ccc"], ... |
# coding:utf-8
# 给定一个用字符数组表示的 CPU 需要执行的任务列表。其中包含使用大写的 A - Z 字母表示的26 种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。CPU 在任何一个单位时间内都可以执行一个任务,或者在待命状态。
#
# 然而,两个相同种类的任务之间必须有长度为 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。
#
# 你需要计算完成所有任务所需要的最短时间。
#
# 示例 1:
#
# 输入: tasks = ["A","A","A","B","B","B"], n = 2
# 输出: 8
# 执行顺序: A... |
# coding:utf-8
# 给定一个整数数组# A,返回其中元素之和可被# K# 整除的(连续、非空)子数组的数目。
#
#
#
# 示例:
#
# 输入:A = [4, 5, 0, -2, -3, 1], K = 5
# 输出:7
# 解释:
# 有# 7# 个子数组满足其元素之和可被# K = 5
# 整除:
# [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
#
# 提示:
#
# 1 <= A.length <= 30000
# -10000 <= A[i] <= 10000
# 2 <= K <= 10000
... |
"""
Provide a class to maintain the state of an evolving game, including
validation of actions, detection of draws, and optionally maintaining
a game log.
NOTE:
This board representation is designed to be used internally by the referee
for the purposes of validating actions and displaying the result of the game.
Each ... |
import tkinter as tk
ob = tk.Tk()
ob.title('calculator')
text = tk.Entry(ob,width=120, borderwidth=2)
text.grid(row=0, column=0, columnspan=4)
def on_click(n):
first = text.get()
text.delete(0, tk.END)
text.insert(0, str(first)+ str(n))
def addition():
first = text.get()
... |
"""This is a proof of concept for the quiz, sans the webpage"""
from collections import namedtuple, defaultdict, deque
import json
import random
from pymongo import MongoClient
from pprint import pprint
import os
#LOAD DATABASE
db_user = os.environ.get('QUIZDB_USER')
db_password = os.environ.get('QUIZDB_PASSWORD')
... |
'''
You are given a string S. Suppose a character 'c' occurs consecutively X times in the string. Replace these consecutive occurrences
of the character 'c' with (X,c) in the string.
For a better understanding of the problem, check the explanation.
Sample Input
1222311
Sample Output
(1, 1) (3, 2) (1, 3) (2, 1)
'''
... |
'''
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
'''
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
... |
string = input("Enter a noun ")
string_1= input("this is it ")
string_3= input ("keyboard not found press f1 ")
print("this is just a test function " + string + "that does all the cool stuff " + " in python")
friends =["Kevin", "talha"]
numbers = [1,2,3,4,5,6]
##friends.extend(numbers)
print(friends)
friends.append... |
print "hello friends"
testlist = []
testdict = {}
testdict = {
1: 'pants',
2: 'shoes'
}
testlist = ['peanuts', testdict, 'rabbits']
for l in testlist:
print l
for i in range(10):
print i
|
"""
Bubble Sort
"""
def sort(collection):
"""
Bubble Sort
:param collection: Input Array
:return: None
"""
collection_len = len(collection)
for outer_idx in range(collection_len):
is_sorted = True
for inner_idx in range(collection_len-outer_idx-1):
if collectio... |
# -*- coding: utf-8 -*-
"""Create one-mode ("unipartite") projections from bipartite graphs.
"""
import networkx as nx
# Copyright (C) 2011 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
__author__ = """Ari... |
lista=[]
for i in range(6):
elemento=input("Ingrese el nombre del equipo")
lista.append(elemento)
for i in range(6):
for j in range(6):
if i != j:
print ("Local: ", lista[i]," Visita: ", lista[j])
|
# Examining the shape of the data set
df = pd.read.csv('CC_card.csv')
df.head()
df.shape
##
# Once the labeled fraud file is read in
# Import pandas and read csv
import pandas as pd
df = pd.read_csv("creditcard_data.csv")
# Explore the features available in your dataframe
print(df.info())
# Count the occurrences of... |
#write a function that converts number to roman numerals
# function mySample(298) --> CCXCVIII
x=298
x=str(x)
print(len(x))
print(x[0])
def roman_numeral_converter(num):
num=str(num)
length_of_num = len(num)
f=num[1] + length_of_num
digitValue=[1000,900,600,500,400,100,90,60,50,40,11,10,9,8,7,6,5,4,3,... |
# it is task 4 exercise
def compare(x, y):
if (x > y):
return 1
elif (x < y):
return -1
else:
return 0
|
def insertionSort(inputArray):
size = len(inputArray)
for i in range(0, size):
for j in range(i, 0, -1):
if inputArray[j] < inputArray[j-1]:
inputArray[j], inputArray[j-1] = inputArray[j-1], inputArray[j]
else:
break;
return inputArray
data... |
""" 04 - Utilizando funções e listas faça um programa que receba
uma data no formato DD/MM/AAAA e devolva uma string no formato
DD de mesPorExtenso de AAAA. Opcional: valide a data e retorne
'data inválida' caso a data seja inválida. """
data = input('Digite a data no formato dd/mm/aaaa: ')
def mesExtenso(x):
... |
#Liam Hurt's Python Homework 4
#Python v2.7.10
#11/18/18
import random
#Checks for an enter/return or a q
def check_string_input():
while True:
inputVal = raw_input("Return or Enter to continue, q to exit >")
if inputVal.lower() == "q":
return "e"
elif not inputVal.strip() or ... |
# __author__ = 'admin'
# -*- coding: utf-8 -*-
"""
from threading import Thread, Lock
# define a global variable
some_var = 0
lock = Lock()
class IncrementThread(Thread):
def run(self):
# we want to read a global variable
# and then increment it
global some_var
lock.acquire()
... |
__author__ = 'admin'
# -*- coding: utf-8 -*-
def extendlist(val, lista=[]):
lista.append(val)
return lista
list1 = extendlist(10)
list2 = extendlist(123, [])
list3 = extendlist('a')
print("list1 = %s" % list1)
print("list2 = %s" % list2)
print("list3 = %s" % list3)
"""
# 输出结果为:
list1 = [10, 'a']
list2 = [12... |
class Node:
def __init__(self, value = None,next = None,prev =None):
self.prev = prev
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
n1 = Node(2)
n2 = Node(3)
n3 = Node(4)
n4 = Node(5)
LL = LinkedList()
LL.... |
from pandas import Series
from pandas import DataFrame
# Arithmetic Operations on Series
# Both series are having same no of items
print("On Series\n")
series1 = Series([1, 2, 3, 4, 5])
series2 = Series([100, 200, 300, 400, 500])
print(series1 + series2)
print("\n")
# Both series are having different elements
series1... |
from pandas import Series
se1 = Series([1,2,3,4,5])#Series is kinda like a list but with some exceptions
print(se1)
print(se1[2])
se2 = Series([100,200,300],index = ['a','b','c']) #one of the exception is that you can specify custom indexes
print(se2)
print(se2['b']) # printing using the custom index |
'''
Pid manager assignment.
'''
# lets us use a random numnber
import random
# built in threading library for python
import threading
# lets us use the sleep function
import time
MIN_PID = 300
MAX_PID = 5000
#creates an array of size 5001 (0-5000)
pid_map = [None] * (MAX_PID + 1)
mutex=threadin... |
#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
return psycopg2.connect("dbname=tournament")
def reportTournaments():
"""Returns a list of tournaments register... |
a = "apple banana mango"
b = "banana fruits mango"
ls = []
a1 = a.split()
b1 = b.split()
for i in a1:
if i not in a1[a1.index(i) + 1:]:
if i not in b1:
ls.append(i)
for i in b1:
if i not in b1[b1.index(i) + 1:]:
if i not in a1:
ls.append(i)
print(ls)
|
# Liste des nouveauté en Python 3.8
# https://www.python.org/dev/peps/pep-0569/
# Quelques une des features les plus importantes:
# Le Morse n'est pas mort:
# Walrus operator
# Il permet l'affectation d'une valeur á une variable même si celle-ci n'as pas été déclarer.
a = [1, 2, 3, 4]
if (n := len(a)) > 3:
print... |
# =============================================================================
# 7.3.1 相关系数基础 by 王宇韬&肖金鑫
# =============================================================================
# 注意,在下面的代码运行过程中,如果是用pycharm运行程序,需要把生成的图片关掉,才能继续执行下面的程序
import random
import numpy as np
import matplotlib.pyplot as plt
from scipy.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygame
from configuraciones import *
def Historia(pantalla):
pygame.init()
pygame.display.flip()
fin = False
#TEXTO
title = "MARIO RELOAD"
l1 = "Mario es un fontanero enamorado de su princesa: Peach."
l2 = "Lastimosamente, Peach se encuentra secuestrada, ... |
import random
pass_len = int(input("ENTER THE DESIRED LENGTH OF THE PASSWORD: "))
pass_chars = (
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X',
'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',... |
#This program will determine the calculation of a sales prediction.
#6.15.19
#CTI-110 P2T1 - Sales Prediction
#Marceia Patterson
#Get the projected total sales
total_sales = float(input("Enter the projected sales: "))
#Calculate the profit as 23 percent of total sales.
profit = total_sales*0.23
#Display t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.