text stringlengths 37 1.41M |
|---|
class tree_node:
def __init__(self,data=None):
self.data=data
self.left=None
self.right=None
def append(self,data):
if(self.data is None):
self.data=data
self.right=None
self.left=None
else:
temp=tree_node(data)
... |
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
self.parent=None
self.height=1
self.size=1
class AVL:
def __init__(self):
self.head=None
def node_size(self,node):
if node:
return 1+self.node_siz... |
#!/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 deleteMatches():
"""Remove all the match records from the d... |
#!/usr/env python
aeronaves = []
aeroportos = []
def menu(titulo, opcoes):
while True:
print("=" * len(titulo), titulo, "=" * len(titulo), sep="\n")
for i, (opcao, funcao) in enumerate(opcoes, 1):
print("[{}] - {}".format(i, opcao))
print("[{}] - Retornar/Sair".form... |
import random
qas = [
('What is the brand name for acetaminophen? ', 'Tylenol'),
('What is the brand name for lacosamide? ', 'Vimpat'),
('What is the brand name for levetiracetam? ', 'Keppra')
]
random.shuffle(qas)
numRight = 0
for question, rightAnswer in qas:
answer = input(question + '')
if... |
#! /usr/bin/python
import socket
import sys
import argparse
host = 'localhost'
data_payload = 4098
backlog = 5
def echo_server(port):
"""A simple echo server"""
# Create socket object
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# Enable reuse address
sock.setsockopt(socket.SOL_SOCKET,... |
'''
DATA FRAME INDEXING AND LOADING
'''
import os
import pandas as pd
os.chdir ("/home/samrat/Documents/Git/PYTHON/PANDAS")
df = pd.read_csv('DATA-FILES/olympics.csv')
df.head()
#Changing the index to column0 AND skipping the 1st row.
df = pd.read_csv('DATA-FILES/olympics.csv', index_col=0, skiprows=1)
print (df.head(... |
import numpy as np
import pandas as pd
1. determining the m, n from a linear combination of a set of basis vectors.
lincom = np.array([19,29,54])
set_of_vectors = np.array([[1,2,3], [4,5,6], [1,2,6]])
np.linalg.solve(set_of_vectors, lincom)
2. Doing a Linear Transformation of a matrix of 6 vectors. Just multiply th... |
import os
path="/home/samrat/Documents/Git/PYTHON/APP-DATASC-PYTHON-COURSERA-SPEC/COURSE3-ML/WEEK2"
os.chdir(path)
import numpy as np
import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
np.set_... |
'''
1. As Prof Raghavan said, each row of a data frame is an object of the same type. The type of each of the objects is determined by the type of the columns. The schema of the columns is determined by the constituent series'.
2. A DataFrame by definition is a collection of series. Each column is a series. So if you ... |
'''
BOOLEAN MASK - AN ARRAY. Multiple conditions can be connected to give a complex query.
'''
import os
import pandas as pd
os.chdir ("/home/samrat/Documents/Git/PYTHON/PANDAS")
#Changing the index to column0 AND skipping the 1st row.
df = pd.read_csv('DATA-FILES/olympics.csv', index_col=0, skiprows=1)
#changing the ... |
'''
NOTE 1 - DIFFERNCE BETWEEN LISTS AND ARRAY -
1. ARRAY IS HOMGENEOUS
2. ARRAY IS MULTI DIMENSIONAL BY DEFAULT.
3. LISTS SHOW UP AS COMMA SEPARATED ITEMS. ARRAYS ARE NOT SEPERATED BY COMMAS
4. VECTORIZED CODE CAN BE WRITTEN ONLY WITH NUMPY AND NOT WITH LIST
5. COMPUTATIONS ARE FASTER IN NUMPY
6. EVERY ARITHMETIC OPER... |
#Unlike C, python does not convert automatically the character to ascii number.
import numpy as np
try:
data = input ("Enter name")
numeric_data = int(data)
except:
numeric_data = -1
print (numeric_data)
np.arange(5)
|
import sqlite3, sys
class Phonebook(object):
def __init__(self):
try:
c.execute('CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT, phone TEXT unique)')
except:
pass
print('Welcome to the Phonebook')
def addEntry():
name = input('Введите ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 27 12:34:02 2018
@author: datacore
"""
# plot feature importance manually
from numpy import loadtxt
from xgboost import XGBClassifier
from matplotlib import pyplot
# load data
dataset = loadtxt('stockdata.csv', delimiter=",")
print(dataset)
# split data into X and y
X = ... |
__author__ = 'mohammadsafwat'
def binarySearchRecursive(alist, item):
if len(alist) == 0:
return False
else:
midpoint = len(alist) // 2
if alist[midpoint] == item:
return True
else:
if item < alist[midpoint]:
return binarySearchRecursive(a... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python3
"""This defines the structure of a UCT"""
import copy
import random
class UCT(object):
"""Tree definition but not including expand, select, simulate and backup"""
def __init__(self):
# common tree structure
self.state = None # Board informatio... |
import sys,pygame #Importar para la creacion de la vetana
import Image #Importar para trabajar con imagene (PIL)
from sys import argv #Importar para trabajar con argumentos de terminal
#def main: se crea la ventana y se carga la imagen ya en escala de grises
def main(image):
ancho,altura,new_image=escala_grises(i... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.sum = 0
def getSum(self, root: TreeNode, current: int):
if root.lef... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from typing import List
class Solution:
def longestConsecutive(self, num: List[int]) -> int:
if not num:
return 0
num_first = {}
for n in num:
if n + 1 in num_first:
num_first[n + 1] = False
if ... |
'''
Algorithm to discover if a string is a palyndrome or not
'''
class Palyndromes(object):
@staticmethod
def is_palyndrome(s):
r = s[::-1]
return s == r
def is_palyndrome(a_string):
if len(a_string) > 0:
return False
else:
reversed = a_string[::-1]
if reversed == a_strin... |
#!/usr/bin/python
# -*- coding: ascii -*-
'''
AVL (Adelson-Velsky and Landis) Tree: A balanced binary search tree where the height of the two subtrees (children) of a node differs by at most one.
Look-up, insertion, and deletion are O(log n), where n is the number of nodes in the tree.
(Definition from http://xlinux... |
# -*- coding: utf-8 -*-
from date import TOTAL_NUMS
from query import QUERY
total_num = 0
for k, v in(TOTAL_NUMS.items()):
total_num = total_num + v
total_num2 = 0
for k, v in(QUERY.items()):
total_num2 = total_num2 + 1
if total_num == total_num2:
print("match: ", total_num)
else:
print("not match: ", ... |
# Name: Kevin Nakashima
# Class: CPSC 223P
# Date: 02/07/2017
# File: Binary2Text.py
# converts a binary set to a string
#Imports=======================================================================
#T2B===========================================================================
def Bin2Text(binary):
tex... |
#!/usr/bin/env python3
"""
This is a quick function that can work out the distance between two GPS
coordinates.
"""
import sys
from math import asin, cos, radians, sin, sqrt
if len(sys.argv) != 5:
print("Usage: distance lat1 lon1 lat2 lon2")
sys.exit(1)
lat1 = float(sys.argv[1].strip().strip(","))
lon1 = flo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 23:54:49 2018
@author: apple
"""
week = [30,39,34,35,37,30,40]
for i in range(0,6):
if i == 2:
print('周三:',end='')
print(week[i])
|
import smtplib
from email.message import EmailMessage
from getpass import getpass
from collections import defaultdict
if __name__ == "__main__":
name = input("Name: ")
n = get_user_input(f"Hi, {name}!\nHow many products do you want to add to the shopping list? ", int)
shopping_list = defaultdict(int)
f... |
import random
import string
# Satunnaisuus
print(random.randint(1, 10))
# Nopan heittäminen
print("Silmäluku: ", random.randint(1,6))
# Toinen vaihtoehto, kuten edellinen
print("Silmäluku: " + str(random.randint(1,6)))
# Kolikon heittäminen
a = ["kruuna", "klaava"]
print("Tulos: " + random.choice(a))
# Salasanan a... |
from collections import Counter
import csv
import matplotlib.pyplot as plt
import numpy.numarray as na
import parse
MY_FILE = "../data/sample_sfpd_incident_all.csv"
def visualize_days():
"""Visualize data by day of week"""
# grab our parsed data that we parsed earlier
data_file = parse.parse(MY_FILE, ",")
# m... |
'''
At the start of the game the user selects class, based on that selection the users hero will be assigned
attributes correlating to the type of hero. Attributes determine the hero's ability to use certain spell and weapons
and also determine the amount of health that the character has at the start of the game.
'''
... |
import pymongo
'''
The ArmorDB class directly queries the MongoDB database for all the Armor specifications. We import the
pymongo plugin to incorporate MongoDB with python.
We initially setup a client to run mongoDB, then we specify which Database we will be accessing
via (db = client.armory). Where client.armory sp... |
ch=0
stack=[]
while ch!=4:
print "Stack Operation"
print "1. PUSH"
print "2. POP"
print "3. DISPLAY"
print "4. QUITE"
ch=int(raw_input('Enter your choice : '))
if ch==1:
n=int(raw_input('Enter number to PUSH : '))
stack.append(n)
elif ch==2:
... |
# -*- coding: utf-8 -*-
# Создайте списки:
# моя семья (минимум 3 элемента, есть еще дедушки и бабушки, если что)
from typing import List, Tuple, Union
my_family = ['father', 'mother', 'son']
# список списков приблизителного роста членов вашей семьи
my_family_height = ['father', 183], ['mother', 165], ['son', 95]
... |
# This program import the insect_class_polymorphism module here
# The isinstance() function is incorporated here
import insect_class_polymorphism as ic
def find_member(member):
if isinstance(member, ic.Insect): # isinstance method
print(member)
else:
print(member,' isn\'t an instance of Insect')
def creat... |
# 1: Preprocessing
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))])
# 2: Model
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, ker... |
"""
py实现递归算法
function recursive(input):
if input <= 0:
return input
else
output = recursive(input - 1)
return output
"""
def get_fib(position):
if position == 0 or position == 1:
return position
return get_fib(position-1) + get_fib(position - 2)
#Test cases
print(get_f... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
u'描述了之前未接触的类的相关知识'
#私有变量,以__开头就是私有变量,但同时不要以__防止被视为类似于__name__的特殊变量
'''
class MyClass(object):
def __init__(self,name,data):
self.__name = name
self.__data = data
def print_data(self):
print '%r : %r'%(self.__name,self.__data)
cc = MyClass('sawyer... |
# -*- coding: UTF-8 -*-
'''
def print_two(*args):
arg1 , arg2 = args
print "arg1: %r, arg2: %r" %(arg1 , arg2)
'''
def print_again(a1 , a2):
print "a1: %r , a2: %r" %(a1 , a2)
def print_none():
print "is ok."
def print_two(*args): #它的功能是告诉 python
a1 , a2 = args #让它把函数的所有参数都接受进来,然后放到名字叫 args 的... |
#Exercício: Faça um nome que leia o nome de uma pessoa e mostre uma mensagem de boas-vindas.
nome = input("Digite seu nome: ")
print("É um prazer em te conhecer,{}.".format(nome))
|
#Exercício: Faça um algoritmo que leia o preço de um produto e mostre seu novo preço com 5% de desconto.
preco = float(input("Digite o valor do produto: "))
desconto = preco - (preco * 0.05)
print("O valor a ser pago é R${:.2f}, já está com o desconto aplicado.".format(desconto)) |
"""
ชื่อDiscord = ม.6 ภูมิ ภูมิระพี ระยอง
ชื่อนามสกุล = นายภูมิระพี เสริญวณิชกุล
Email = phumrapeesoen1@gmail.com
ชั้น = ม.6
"""
import random
Questions = ["รักพ่อแม่ไหม?", "เคยช่วยพ่อแม่รดน้ำต้นไม้ไหม?", "เคยช่วยคนตาบอดข้ามถนน?", "ให้อาหารปลาไหม?", "เคยช่วยครูยกของไหม?"]
random.shuffle(Questions) # เรี... |
import unittest
from itertools import combinations
"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,a2 + b2 = c2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.Find the product abc.
"""
def is_pythagorean_triangle(... |
from graphics import Point, Line, GraphWin, Text
from math import sin, cos, radians
def vect(point, theta):
length = .00005
x = point.x + (length * cos(theta))
y = point.y + (length * sin(theta))
return Point(x, y)
def main():
win = GraphWin("map", 1000, 800)
win.setCoords(-88.357, 41.786, -8... |
"""Read in data from a text file and process it using the algorithm.
Current output line format:
TIME, LAT, LON, CALC_BEARING, HEADING, STATUS
"""
# import tracker as track
import header
class Transcriber:
"""docstring for Transcriber."""
def __init__(self, filename):
"""Constructor."""
sel... |
"""Provides bearinga nd coords classes."""
import math
import gps
class Bearings:
"""Object that stores bearing calculated from GPS position."""
# This should not initialize with an initial bearing
def __init__(self, bear=0):
"""Constructor."""
self.b = [bear]
def add_bearing(self, b... |
'''
ID: 2010pes1
TASK: dualpal
LANG: PYTHON3
'''
def convert(n,i,nums):
lst = []
st = ''
while i>0:
lst.append(nums[i%n])
i = (i - (i%n))/n
for i in range(len(lst)):
st += lst[len(lst)-1-i]
return st
# filter solutions that are already palindromic in one base (ex: base 2)
# ... |
class person:
def __init__(self,n,a,g):
self.name=n
self.age=a
self.gender=g
def display(self):
print("Name:",self.name)
print("Age:",self.age)
print("Gender:",self.gender)
class publications:
def __init__(self,no_rp,no_of_books,no_art):
self.no_rp=no... |
a=input("Enter file name to read:")
b=input("Enter file name to write:")
f1=open(a,mode='r')
f2=open(b,mode='w')
str=f1.read()
f2.write(str)
f1.close()
f2.close()
with open("two.txt",mode='r') as f:
fstr=f.read()
print("The contents in the file two is:\n ")
print(fstr)
|
n=int(input("Enter a number:"))
rev=0
while n!=0:
rev=rev*10+n%10
n=int(n/10)
print(f"Reverse={rev}")
|
#dict={x:2*x for x in range(1,10)}
d={}
for i in range(1,10):
d[i]=i*2
print(d) |
class name(Exception):
def __init__(self,name):
self.name=name
def display(self):
print(f"Hello {self.name} :)")
try:
uname=(input("Enter the name:"))
raise name(uname)
except name as r:
r.display() |
a=input("Enter the file name:")
with open(a,mode='r') as f:
str=f.read()
l=str.split()
k=len(l)
print(f"Number of words ={k}") |
import re
ch=input("Enter a word:")
k=len(ch)
str=""
l=re.findall(".",ch)
if(ch[k-1]=='f'):
l.pop()
for i in l:
str+=i
str+="ves"
elif(ch[k-2]=='f'):
l.pop()
l.pop()
for i in l:
str+=i
str+="ves"
elif(ch[k-1]=='y'):
l.pop()
for i in l:
str+=i
str+="ies"
el... |
s=int(input("Enter the salary:"))
g=input("Enter the gender(m/f):")
r=0
if(s<=10000):
r=2
if(g=="m"):
r=r+5
elif(g=='f'):
r=r+10
s+=(r*s)/100
print("Salary=",s)
|
ch=int(input("Area:\n1.rectange\n2.triangle\n3.circle\n4.square\nEnter choice:"))
if (ch==1):
a = int(input("Enter length:"))
b = int(input("Enter breadth:"))
area=a*b
print("Area of rectangle=",area)
elif(ch==2):
a = int(input("Enter length:"))
b = int(input("Enter breadth:"))
area=(a*b)/2
... |
jedi=(input("Name a jedi master: "))
if jedi.upper()=="YODA":
print("Jedi Master, he is!")
|
from bitterdispute.variable import Variable
import numpy as np
import math
def sin(x):
"""Defines what happens when sin operations performed on
a Variable() object or a constant value. Includes calculation of first and second derivative.
"""
try:
new_x = Variable(name=x.name, value=np.sin(x.val... |
class QuizBrain:
"""
...
"""
# ...
def __init__(self, question_list, question_number=0, score=0):
self.current_question_number = question_number
self.question_list = question_list
self.user_score = score
# def next_question(self):
# if self.current_ques... |
import pandas as pd
import quandl
class Stockobj():
"""
By Ben Rogojan
Date: 2018-09-25
A class used to represent a stock and the data for
its stock prices in a set data range
Attributes
----------
StockTicker : str
Represents the 1-5 character ti... |
from maze import Maze
from maze import Map
class DepthLimited(Maze):
def __init__(self, x, y):
Maze.__init__(self, x, y)
self._map = self.m
def create_node(self, x, y):
self._map.visit(x, y, self.win, "blue")
def check_neighbours(self, b):
neighbours = []
mp = se... |
#INDEX ERROR
import sys
a = "abcde"
n = input()
print(a[n]) #BUG, IndexError
print(a[-7]) #BUG, IndexError
print(sys.argv[0])
print(sys.argv[1]) #BUG, IndexError
a_list = ['a', 'b', 'mpilgrim', 'z', 'example']
print(a_list[-6]) #BUG, IndexError
print(a_list[-3])
a_list.append(['c','d','e'])
print(a_list[5][3]) #... |
#Python number to check if number is armstrong or not
def check_armstrong_number(num):
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit**3
temp//= 10
if sum == num:
print(num, 'Is armstrong number')
else:
print(num, 'Is not armstrong n... |
#_*_ coding: utf-8 _*_
#test data
'''
Complete the countingValleys function in the editor below.
It must return an integer that denotes the number of valleys Gary traversed.
BONUS:
If we represent _ as sea level, a step up as /, and a step down as \,
'''
#n: the number of steps Gary takes
nn = 8
#s: a string descri... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 15 11:09:05 2018
@author: mclower
"""
import numpy as np
n=6
p1=5
p2=3
def f(n,p1,p2):
Sum=0
for ii in range(n):
if(ii % p1 == 0):
Sum= Sum +ii
elif(ii % p2==0):
Sum=Sum +ii
return Sum
X=f(n,p1,p2)
print(X)
|
import unittest
from InventoryAllocator import InventoryAllocator
##########################################
# INSTRUCTIONS FOR TESTING #
##########################################
# #
# run the following code: #
# #
# $ python InventoryAllocatorTest.py #
# #
#######... |
from tkinter import *
#importing tkinter module.
root = Tk() #creating the master.
frame = Frame(root) #creating the frame.
frame.pack()
bottomframe = Frame(root) #creating the bottom frame.
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text="Red", fg="red") #creating th... |
from datetime import datetime
class Account:
def __init__(self, first_name, last_name,phone_no,bank):
self.self.first_name = first_name
self.last_name = last_name
self.phone_no = phone_no
self.bank = bank
self.balance = 0
self.withdraw_summary = []
se... |
# sorted()相当于for i in 括号里的参数,把i排序,key=相当于把i加工一下,按加工之后的排序,但是最后排序结果还是原来的i
# 结果里面只有排序好的i
# sort和sorted一样,只是sorted返回新的列表,sort排序原来的对象
# 按照键排序
l3 = sorted({1: 'D', 5: 'B', 2: 'B', 4: 'E', 3: 'A'}.items(),key = lambda item:item[0])
print('l3',l3)
l2 = sorted([1,5,3,2],key=lambda item:item**2)
l4 = sorted([1,5,3,2],reverse=... |
# Good morning! Write a function called reverseNumber that reverses a number.
# Input Example:
# 12345
# 555
# Output Example:
# 54321
# 555
def reverse(num):
newNum = ''
for n in str(num):
newNum = n + newNum
return int(newNum)
print(reverse(12345)) |
def code(invoerstring):
ascistring = ""
for letter in invoerstring:
ascistring = ascistring + chr(ord(letter)+3)
return ascistring
naam = str(input("Naam: "))
beginst = str(input("Beginstation: "))
eindst = str(input("Eindstation: "))
invoerstring = str(naam + beginst + eindst)
print(code(invoerst... |
from tkinter import *
from tkinter.messagebox import showinfo
root = Tk()
label = Label(master=root,
text='Hello World',
background='white',
foreground='blue',
font=('Helvetica', 16, 'bold italic'),
width=20,
height=3)
label.pack()
def hallo():
grondtal = int(entry.get())
kwadraat = grondtal ** 2
tekst = ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 4 21:21:19 2019
@author: Bowton
"""
import math
import numpy as np
import matplotlib.pyplot as plt
def getArea(): #gets user input for the length of the wind farm
#then calculates the area and returns length and area
length = in... |
graph = {
'A':['B','C'],
'B':['A','C','D'],
'C':['A','B','D','E'],
'D':['B','C','E','F'],
'E':['C','D'],
'F':['D']
}
def BFS(graph,s):
stack = []
stack.append(s) #节点栈
seen = set() #已输出队列
seen.add(s)
while (len(stack) > 0):
vertex = stack.pop() #后进先出
... |
print('{}'.format("format this string"))
fname="abhishek"
lname="sawant"
print('{}....{}'.format(fname,lname))
#Use format to align the output and give width
print(format(fname,"<50s"))
print(format(fname,">50s"))
#Fill Empty spaces
print(format(fname,"@<50s"))
print(format(fname,"$>50s"))
#Form... |
sample=()
print(type(sample))
sample= 25,35,45
print(sample)
sample = (25,65,45,[90,"check",5.5])
print(sample)
sample=((3,4,5),(4,5,6),(5,6,7))
print(sample)
print(sample[1][1])
#creating tuples from list and sets
scores = [25,35,45]
sample=tuple(scores)
print(sample)
scores = {25,35,45}
sample=t... |
lengthOfList=int (input("Enter the length of list :- "))
list=[]
for i in range(lengthOfList) :
list.insert(i,int (input("Enter element in list:-")))
print(list)
sliceStart=int(input("Slice Start :- "))
sliceEnd=int(input("Slice End :- "))
list=list[sliceStart:sliceEnd]
list.sort()
print(list) |
import threading
import time
def callMeForEachThread(threadName,delay):
counter=0
while counter <= 10:
print(threadName," ",str(counter))
time.sleep(delay)
counter+=1
thread1=threading.Thread(target=callMeForEachThread,args=("Thread1",1))
thread2=threading.Thread(target=callM... |
"""
Given 1->2->3->4, you should return the list as 2->1->4->3
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# ... |
"""
minimum swaps
"""
def minimumSwaps(arr):
count = 0
i = 0
l = len(arr)
sorted_arr = sorted(arr)
while i < l:
n = arr[i]
pos = sorted_arr.index(n)
if (i != pos):
arr[i], arr[pos] = arr[pos], arr[i]
count += 1
i -= 1
i += 1
... |
# fb phone interview 1 - donna
# input: list of pairs of integers, for example [(1,2), (5,6), (7,3), ...]
# input: a non-negative integer "K"
# output: the "K" points from the input that are closest to the origin (0,0)
# for example: if K=2, [(1,2), (7,3)]
# first solution that I thought of right off the bat
# time ... |
import string
def idcheck(s):
print "idcheck start!"
letters = string.ascii_letters
digits= string.digits
s_l=len(s)
if s_l >0 :
if (s[0] in letters) == False and s[0] != "_":
return False
i=1
while i < s_l:
if (s[0] in letters) == False and s[0]... |
import turtle as t
def rectangle(horizontal, vertical, color):
t.pendown()
t.pensize(1)
t.color(color)
t.begin_fill()
for counter in range(1, 3):
t.forward(horizontal)
t.right(90)
t.forward(vertical)
t.right(90)
t.end_fill()
t.penup()
def arm(color):
t.p... |
import pygame
# Globals
size = width, height = 458, 458
rows = cols = 9
tileSize = width//rows
white = (255,255,255)
black = (0,0,0)
grey = (220,220,220)
#Function
def backtrack(board, screen, animate):
solved = False
for row in range(9):
for col in range(9):
if board[row][col][1] == 0:
... |
'''Задание1. Найти сумму и произведение цифр трехзначного числа,
которое вводит пользователь.
https://drive.google.com/file/d/1YlUtqLMn-ZPQXjRHXaQ0omqdbkv3rtnn/view?usp=sharing'''
abc = int(input('Введите целое трехзначное число: '))
a = int(abc / 100)
b = int((abc - (100*a)) / 10)
c = int(abc - (a*100) - (b * 10))... |
import sys
from random import randint
from turtle import forward, left, speed
speed('slowest')
for idx, argument in enumerate(sys.stdin):
if idx == 0:
# In case of the first argument -the Python program name- do nothing in
# this iteration, jump over it with `continue`
continue
turtle_... |
def tic_tac_toe():
board = [1, 2, 3, 11, 12, 13, 21, 22, 23, 4, 5, 6, 14, 15, 16, 24, 25, 26, 7, 8, 9, 17, 18, 19, 27, 28, 29,
31, 32, 33, 41, 42, 43, 51, 52, 53, 34, 35, 36, 44, 45, 46, 54, 55, 56, 37, 38, 39, 47,
48, 49, 57, 58, 59, 61, 62, 63, 71, 72, 73, 81, 82, 83, 64, 65, 66, 74, ... |
def sort(values):
for m range(len(values)):
for n in range(m, len(values)):
if (values[m] > values[n]):
temp = values[m]
values[m] = values[n]
values[n] = temp
y = raw_input().rstrip()
yList = list(y)
sort(yList)
print("".join(yList))
|
candyInStore = ["Snickers", "Kit Kat", "Sour Patch Kids", "Juicy Fruit", "Sweedish Fish", "Skittles", "Hershey Bar", "Skittles", "Starbursts", "M&Ms"]
allowance = 5
selectedCandy = []
#for i in range(len(candyInStore)):
#print("[" + str(i) + "] " + candyInStore[i])
for candy in candyInStore:
print ("[" + str... |
fname = input("Enter file name: ")
fh = open(fname)
#fh = open('romeo.txt')
lst = list()
lst2 = []
for line in fh:
#print(line.rstrip())
lst += line.split()
#print(sorted(lst))
for item in lst:
if item not in lst2:
lst2.append(item)
print(sorted(lst2))
|
import random
from functools import wraps
import csv
class Deck():
def __init__(self):
""" This should populate our card deck"""
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
values = ["A" ,"2", "3", "4","5", "6", "7", "8", "9", "10", "J", "Q", "K"]
self.card_list = []
for suit in suits:
for value... |
def flip(x):
if x == 0:
return 1
if x == 1:
return 0
def Scramble(binary):
msgBinary = binary
key = "e81e38192bfd4B7e"
msgBinaryList = list(msgBinary)
keyList = list(key)
numRange = range(0,16)
#Get the numeric values of the key
for x in numRange:
keyList... |
#This contains all the functions relating to the binary decoding of a file
def splitString(numberString):
tempString = str(numberString)
outStringPiv0 = numberString[:4]
outStringPiv1 = numberString[4:]
outString0 = outStringPiv0[:2]
outString1 = outStringPiv0[2:]
outString2 = outStri... |
i=int(raw_input())
if i<0:
print "Negative"
elif i>0:
print "Positive"
else:
print "Zero"
|
import time
import datetime
'''
input: Epoch format date
processing: convert Epoch format date to human readable time.
Output: human readable date and time.
'''
def epotchToDateTime(data):
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data))
'''
input: human readable date and time.
processing: convert ... |
from copy import deepcopy
from queue import Queue
import time
class Problem(object):
def __init__(self, initial, goal):
self.initial = initial
self.goal = goal
def actions(self, state): #goes through actions of the current node being observed to generate its children
action_list = []
... |
#Exercise 7 - Get first list of numbers and create a second list and store only even numbers from first list
#Create a list with random numbers
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#Create another list with only even numbers taken from list 1
b = [number for number in a if number % 2 == 0]
print(b)
... |
#Get a string as input from user and reverse the string and store it in different variable
def reverse_v4(x):
y = x.split()
y.reverse()
return " ".join(y)
#Get user input
test1 = input("Enter a sentence: ")
#Print test result
print (reverse_v4(test1))
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root: return []
allPaths = []... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
longestDiameter = 0
def dept... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
totProfit = 0
for i in range(1, len(prices)):
if prices[i-1] < prices[i]:
totProfit += prices[i] - prices[i - 1]
return totProfit
# 1 3 4 5 6 7
"""
for each... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.