text stringlengths 37 1.41M |
|---|
#Rotation of an image
import cv2
import matplotlib.pyplot as plt
def main():
imgpath = "C:\\Users\\Purneswar Prasad\\Documents\\misc\\4.2.01.tiff"
img1 = cv2.imread(imgpath, 1)
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
rows, columns, channels = img1.shape
R = cv2.get... |
if __name__ == "__main__":
from state import *
else:
from ..state import *
class GameState(State):
"""contains all info about a board state"""
number_of_players = 2
length = 4
stones = 2
squares = length * 2 + 2
def __init__(self, board=None, player=0, plys=0, handicap=-.... |
# Classes 1
print('####Classes_1#####')
## Clasess
class Employee_1:
#class variable
raise_amount = 1.10
num_of_employee = 0
# Constructor/ initialised
# self is an instance and others are arguments
def __init__(self, first, last, pay):
self.first = first # class variable
self.l... |
my_student = {'name': 'Vipul', 'age': '29', 'courses' : ['Math', 'CompSci']}
print(my_student)
print(my_student['name'])
my_student_new = {1: 'Vipul', 2: '29', 'courses' : ['Math', 'CompSci']}
print(my_student_new[2])
print(my_student.get('name'))
print(my_student.get('phone'))
print(my_student.get('phone', 'Not Fo... |
#Object programming
class parent:
#constructor
def __init__(self):
print("Our class is created")
#destructor
def __del__(self):
print("Our class is destructed")
#member function
#self is like void
def printParent(self):
print(self.value1)
... |
# Cauculadora de IMC
# Início do recebimento de dados
altura = float(input('Insira a sua altura em metro: '))
peso = float(input('Insira o seu peso, em kilograma: '))
# Fim do recebimento de dados
# Inicio do tratamento de dados
imc = peso/(altura**2)
# Fim do tratamento de dados
# Inicio das saídas para o usuá... |
import sys
import time
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation
# code reference: https://en.wikipedia.org/wiki/Maze_generation_algorithm
class robot_map(object):
def __init__(self, width=40, height=40, complexity=0.01, density=0.1):
self.width = w... |
def assym(a, g, p):
key = g ** a % p
return key
def valid(key_publ_s):
try:
i = False
file = open("allowed.txt", "r")
for line in file:
if line[0] == str(key_publ_s):
i = True
return i
except:
return False
def encode(st, key):
s... |
#find the target sum from an element from two lists
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
sL = sorted(nums)
for _ in range(len(nums)-1):
# print('nums', nums)
a = sL.pop(0) #2, sL = [3,4]
aInd = nums.index(a) #1
b = target - a #4
# print(a,b)
... |
"""
Converter for Minutia
- to bitstring and vice-versa
- from bitstring to int and vice-versa
"""
from bitstring import BitArray
from Minutia import MinutiaNBIS, MinutiaNBIS_GH
class MinutiaConverter:
def __init__(self, x_bit_length=11, y_bit_length=11, theta_bit_length=10, total_bit_length=32):
... |
def main():
arr = [6,4,7,8,10,12]
novelSort(arr,0,len(arr)-1)
print(arr)
def novelSort(arr,start,end):
if start >= end:
return arr
min_index = arr[start:end+1].index(min(arr[start:end+1])) + start
max_index = arr[start:end+1].index(max(arr[start:end+1])) + ... |
##https://www.geeksforgeeks.org/heap-sort/
import time
def main():
with open('input_10000.txt') as inputfile:
data = inputfile.read()
inputfile.close()
A = [int (i) for i in data.split()]
heapsize = 0
starttime = time.time()
heapsort(A)
endtime = time.time()
elap... |
import sys
import argparse
def setup_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
'--inputdata', type=str,
help='input a string for me to operate')
return parser
def expr(arr):
op = '+-*/'
stack =[]
while(len(arr)!=0):
for i in range... |
from collections import namedtuple
# Orientations
UP, RIGHT, DOWN, LEFT = range(4)
# Turning
TURN_LEFT, GO_STRAIGH, TURN_RIGHT = range(3)
def next(turn):
return (turn + 1) % 3
Cart = namedtuple("Cart", "x, y, orientation, next_turn")
def out_of_lane(cart):
raise Exception("out of lane", cart)
def horizont... |
import string
import sys
from string import printable
from Crypto.Cipher import AES
def first_half():
pt = 'aaaaaaaaaaaaaaaa'
val = len(pt) % 16
if not val == 0:
pt += '0' * (16 - val)
res = {}
for a in printable:
for b in printable:
for c in printable:
... |
import math
def number_of_divisors(number):
divisors = 0
for x in range(1, int(math.sqrt(number)) + 1):
if number % x == 0:
divisors += 1
if math.sqrt(number).is_integer():
return divisors * 2 - 1
return divisors * 2
number = 0
n = 1
while True:
number += n
n += 1
# print(number)
if number_of_divisors(... |
def sieve_of_sundaram(limit):
new_limit = limit // 2 - 1
boolean_list = [True] * new_limit;
i = 1
j = i
while (i + j + 2 * i * j < new_limit):
while (i + j + 2 * i * j <= new_limit):
boolean_list[2 * i * j + i + j - 1] = False
j += 1
i += 1
j = i
primes = [2]
for i in range(0, new_limit):
if boolea... |
"""Assume that when calling count_down on a smaller range it would
print the numbers of that range in decreasing order. """
# start <= end
def count_down(start, end):
if start == end:
return start
else:
print(end)
count_down(start, end - 1)
# start <= end
def count_up_and_down(start,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class SeqStorage(object):
def __init__(self, MAXSIZE):
"""
初始化线性表
:param MAXSIZE:
"""
self.MAXSIZE = MAXSIZE
self.data = [None] * self.MAXSIZE
self.length = 0
def show_list(self):
print(self.data)
... |
import turtle # importing our graphical library
turtle.speed(10) # Set speed of drawing
turtle.hideturtle() # Disable default turtle object
s = turtle.Screen() # Create a graphic window
s.bgcolor("black") # Set background color
turtle.pencolor("red") # Set drawing pen color
turtle.pensize(5) #Set drawing pen size... |
def generarBaseDatos():
listaPalabras = []
continuar = "si"
while continuar == "si":
listaPalabras.append(input("Ingrese una palabra: "))
continuar=input("Desea agregar otra palabra? (si/no): ")
return listaPalabras
def buscarPalabraAleat(listaPalabras):
impo... |
def exponenciar (base,exponente):
resultado = base
for i in range(1, exponente):
resultado = resultado * base
return resultado
base = int(input("base: "))
exponente = int(input("exponente: "))
resultado = exponenciar(base,exponente)
print(resultado)
|
#!/usr/bin/python
def displayPathtoPrincess(n,grid):
p0 = grid[0][0] == 'p'
p1 = grid[0][n-1] == 'p'
p2 = grid[n-1][n-1] == 'p'
p3 = grid[n-1][0] == 'p'
up_down = True
left_right = True
if p1:
left_right = False
elif p2:
up_down = False
left_right = Fa... |
#Tipos de dados:
# string(str) "assim"
# inteiro(int) 0 10 20 30 -10 -20 -30
# real(float) 10.50 1.4 2.5
# boolean(bool) true/false
#funcao type retorna o tipo do valor
print('Gabriel ',type('Gabriel'),sep=' ### ')
print('10 ',type(10),sep=' ### ')
print('10.5 ',type(10.5),sep=' ### ')
print('10 = 10 ',type(10==10),s... |
# Condições IF, ELIF, ELSE
#como não usa chaves, ele se considera pela qtd de espaços
#se for verdadeiro entra na condição if
if True:
print("verdadeiro.")
else:
print('não é verdadeiro')
#se for falso, entra na condição else
if False:
print("verdadeiro.")
else:
print('não é verdadeiro')
if Fals... |
#exibir algo na tela
print('hello world')
print(123456)
#argumento nomeado sep='any' que da replace espaço entre argumento
#argumento nomeado end='any' que da replace na quebra de linha
#print('Gabriel', 'Miranda', 16, 'anos')
print('Gabriel', 'Miranda', sep='-',end='\n# # # # # # # # #\n')
print('Gabriel', 'Miranda', ... |
# ===
# Program Name: harris-lab2-assign1.py
# Lab no: 2
# Description: Temperature Conversion App
# Student: Stacy Harris
# Date: 6/12/2020
# ===
import os.path
title = "Temperature Conversion Application"
print(title)
def main():
print("Would you like to convert from Fahrenheit to Centigrade or Centigrade... |
import pygame #importing pygame package
import sys #module helps to manipulate different parts (functions variables)
pygame.init() #initialize all imported pygame modules
#main interface
WINDOW_WIDTH = 1200
WINDOW_HEIGHT = 700
FPS = 20 # frames per second
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
ADD_NEW_FLAM... |
import pygame
from Helpers import write
from Helpers import color
def playGame(game):
game.clear_screen()
game.display_stats()
# Bet
# Money input from user
if game.betting:
write(game.screen, "BET", 54, color("black"), (game.width/2 - 20, game.height/2 - 54))
write(game.screen, str(game.bet), 48, color("bla... |
"""
I answered incorrectly during a interview on 9/20/19 with Pokemon/Karat.
I said there would be an error with printing f.count()
But the correct answer is that 10.
Is Apple instantiated first and its count saved and not overwritten by
According to here
https://www.programiz.com/python-programming/multiple-inherit... |
# DOCS
# https://docs.python.org/3.7/library/stdtypes.html#set
a = set([1, 2, 3, 4, 5, 6])
b = a
c = set([1, 3, 5])
d = set([1, 10])
print(b.issubset(c)) # False
print(c.issubset(b)) # True
print(b.issuperset(c)) # True
print(b.union(c)) # set([1, 2, 3, 4, 5, 6])
print(c.union(b)) # set([1, 2, 3, 4, 5, 6]) wh... |
"""
Given an int array of holes where 1 means a mole and 0 is no mole.
Find out the max number of moles you can hit with a mallet of width w.
http://leetcode.com/discuss/interview-question/350139/Google-or-phone-screen-or-whac-a-mole
"""
# ans = 4
holes1 = [0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0]
w1 = 5
holes2 = []
w2 = 1
h... |
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
longest = ''
adjuster = 0
#go in reverse order through a string
for ss in range(len(s),0,-1):
substring = s[0:ss]
palindrome = self.findPalindrome(substring)
print("ss: %d longest %s palindrome %s" % (... |
import pandas as pd
import matplotlib.pyplot as plt
# https://seaborn.pydata.org/tutorial.html
import seaborn as sns
table = pd.read_csv("soccerdata.csv")
print(table)
print(table.head())
print(table.head(10))
# print(table["Name"])
print(table.Name)
# sns.countplot(y=table.Nationality, palette=... |
print("Hello")
a=10
b=20
sum = a +b
print("sum is",sum);
#whatever we write in our program is by default part of main
print(__name__)#main |
"""
Unsupervised learning
We have data but no labels !!
Classification is numerically done by the model and we later name those classes
Output is not known for observations in DataSet
k-means clustering
k denotes no of classes we expect from our model
----------------------... |
# class Input:
#
# def __init__(self, input, weight):
# self.input = input
# self.weight = weight
class Perceptron:
def __init__(self, inputs=None):
self.inputs = inputs
print(">> Perceptron Created with Inputs")
print(inputs)
print("~~~~~~~~~~~~~~~~... |
#for i in range (1, 11):
#for i in range (1, 11,2):
for i in range (10, 0, -1):
print(">> i is:", i)
print("==========")
"""
show(num) => print num
"""
#creating or defining a function
#recursion -> executing same fnc again nd again from the same function
def show(num):
if num== 0:
return ... |
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn import metrics
# DataSet Description
# 1. Number of times pregnant
# 2. Plasma glucose concentration a 2 hours in an oral glucose tolerance test
# 3. Diastolic blood pressure (m... |
from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
# Initial Data
X = [1, 2, 3, 4, 5]
Y = [2, 4, 5, 4, 5]
# Lienar Regression : 1 Line of Code :)
data = stats.linregress(X, Y)
print(">> Slope is:", data[0])
print(">> Interceptor is:", data[1])
print(">> Equation of Line: y = {} + {... |
students = ["John", "Jennie", "Jim", "Jack", "Joe", ["Jim","Jack"]]
print(students, hex(id(students)))
newStudents = students + ["Fionna", "George"]
print(students, hex(id(newStudents)))
# Operation -> Concatenation in the same List
students = students + ["Fionna", "George"]
print(students, hex(id(students)))
someSt... |
import sqlite3
def create_connection(path):
""" This function connect to the path given
:param path: path to connect
:return: connection
:rtype: string
"""
try:
connection = sqlite3.connect(path)
print("Connection to DB successful!")
except sqlite3.Error as e:
... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a list node
# @return a tree node
def sortedListToBST(self, head):
cu... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param preorder, a list of integers
# @param inorder, a list of integers
# @return a tree node
def buildTree(self, preorder... |
#!/usr/bin/env python3
# coding: utf-8
"""
Maximize It!
https://www.hackerrank.com/challenges/maximize-it
"""
from itertools import product
if __name__ == '__main__':
line = input().split()
k, m = [int(x) for x in line[:2]]
l = []
for _ in range(k):
line = input().split()
l.append([i... |
#!/usr/bin/env python3
# coding: utf-8
"""
Hex Color Code
https://www.hackerrank.com/challenges/hex-color-code
"""
import re
if __name__ == '__main__':
re_rgb = re.compile(r'[ ,:(](#(?:[a-f0-9]{3}|[a-f0-9]{6}))[ ,;)]', re.I)
n = int(input())
for _ in range(n):
s = input()
for m in re.fi... |
#!/usr/bin/env python3
# coding: utf-8
"""
Detect HTML Tags, Attributes and Attribute Values
https://www.hackerrank.com/challenges/detect-html-tags-attributes-and-attribute-values
"""
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print(tag)
... |
#!/usr/bin/env python3
# coding: utf-8
"""
itertools.product()
https://www.hackerrank.com/challenges/itertools-product
"""
from itertools import product
if __name__ == '__main__':
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
print(*product(a, b))
|
import turtle
area = turtle.Screen()
area.setup(width=650, height=650)
area.bgcolor("black")
tr = turtle.Turtle()
tr.speed(10)
tr.fillcolor('yellow')
tr.begin_fill()
tr.circle(100)
tr.end_fill()
tr.goto(7, -20)
tr.color('white')
tr.circle(200)
tr.color('black')
tr.penup()
... |
import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud
def plot_character_words(character):
lines = pd.read_csv('scooby_doo_lines.csv')
lines = lines[lines['character'] == character] # Filter to character
lines = lines['line'] # Get the text data
lines = [l... |
'''
5. Convert 8 to a string
'''
result = str(8)
print(result) |
'''
X, Y, Z respresenting dimensins of cuboid along with integer N
print list of all possible
'''
x = int(input("Enter X"))
y = int(input("Enter Y"))
z = int(input("Enter Z"))
n = int(input("Enter N"))
coordinates = [] |
'''
4. Write a program which prompts the user for 10 floating-point numbers and calculates
their sum, product and average. Your program should only contain a single loop.
'''
print("Enter 10 floating-point numbers: ")
count = 0
float_list = []
sum = 0.0
product = 1.0
while count < 10:
number = float(input("Enter n... |
#defind a variable with a boolean value
it_is_tuesday = False
print("Which day is today")
#this is if statement starts a new block
if it_is_tuesday:
#this is inside the block
print("It's Tuesday")
#this is outside the block
print("Print this no matter what")
|
'''
1. Create a set whih contains the first four positive integers a and set b which contains
the first four odd positive integers
'''
a = {1, 2, 3, 4}
b = {5, 6, 7, 8}
print(a)
print(b)
'''
2. Create a new set c which combine the numbers which are in a or b (or both)
'''
c = a.union(b)
print(c)
'''
3. Create a set d w... |
class Solution:
def rotateString(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
ind = 0
while(ind != len(A)):
d = ind
ind = B[ind+1:].find(A[0])
if (ind == -1):
break
else:
... |
#全局变量指向没有改箭头,则不用加global
import threading
import time
#定义一个全局变量
g_nums = [11,12]
g_num = 12
def test1(temp):
temp.append(33)
print("---in test1 temp=%s----" % str(temp) )
def test2(temp):
print("----in test2 temp=%s----" % str(temp))
def main():
#target指定将来新线程去哪个函数执行代码
#args是调用函数,传的数据
t1 = thr... |
arquivo = open("entradaSintatico.txt", "r")
tokens = arquivo.read()
tokens = tokens.split(" ")
posInicial = 0
posFinal = 0
tempAtual = 0
tabSimb = []
verificacoes = []
cod3End = []
linhaCod = 1
def Z(ch, pos):
if ch == "var":
ch, pos = I(ch, pos)
ch, pos = S(ch, pos)
print("C... |
import random
list1=["snake","water","gun"]
value=random.choice(list1)
print("******Snake Water Gun Game******")
name=input("Please Enter your name: ".upper())
cu=0
cp=0
c=5
while c>0:
a = input("You Choice 1. for Snake 2. for Water 3.for Gun\n")
if a == "snake":
if a == value:
... |
import sys
import time
# import numpy as np
import pandas as pd
# import datetime as dt
CITY_DATA = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'}
months = ['all', 'january', 'february', 'march', 'april', 'may', 'june']
def get_filters():
... |
import requests
S = requests.Session()
URL = "https://en.wikipedia.org/w/api.php"
#Function to serach for the most similar page title to the keyword
def page_title(target):
PARAMS = {
"action": "opensearch", #Which action to perform.(Search the wiki using the OpenSearch protocol.)
"search... |
# -*- coding: utf-8 -*-
"""
remarks: commonly used functions related to intervals
NOTE
----
`Interval` refers to interval of the form [a,b]
`GeneralizedInterval` refers to some (finite) union of `Interval`s
TODO:
1. unify `Interval` and `GeneralizedInterval`, by letting `Interval` be of the form [[a,b]]
... |
# from __future__ import print_function
import collections #Deque. This is a higher performance version of a list. Faster when accessing first / last elements.
# ------------------------------------------------------------------------------------------------------------------------------------------------------
# Code ... |
def manhattan_from_zero(point):
return abs(point[0]) + abs(point[1])
def load_path_points():
instructions = input().split(',')
x, y = 0, 0
dirs = {'L': (-1, 0), 'R': (1, 0), 'U': (0, 1), 'D': (0, -1)}
path_points = set()
for instruction in instructions:
direction = dirs[instruction[0]... |
import random
import os
MENU = """ ++ P A S S W O R D G E N E R A T O R ++ by @djalocho
Choose a security level:
[1] - Low
[2] - Medium
[3] - High
Type a number [1-3] -> """
def num_input(message):
try:
number = int(input(message))
return num... |
def FindNumber():
#Pick a number and the program will guess your number in the least
#amount of attemtps as possible. Only '<', '>' or '=' can be used.
lo = 0
hi = 2
print("Input '<' if my guess is smaller, Input '>' if my guess is greater")
print("or input '=' if guess is correct")
hinum =... |
import numpy as np
import pandas as pd
df1=pd.DataFrame(np.arange(1,13).reshape(3,4),columns=list('abcd'))
df2=pd.DataFrame(np.arange(1,21).reshape(4,5),columns=list('abcde'))
df1.add(df2,fill_value=0) #两个表相加
frame=pd.DataFrame(np.arange(1,13).reshap(4,3),columns=list('bde'),index=['Shenzhen','Guangzhou','... |
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a+b
def subtract(a, b):
print "SUBSTRACTING %d - %d" % (a, b)
return a - b
def mulpiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a*b
def divide(a, b):
print "DIVIDING %d / %d" %(a, b)
return a/b
print "Let's do some math ... |
s=raw_input("Enter the string ")
s=s.split(" ")
s.sort()
print " ".join(s)
|
# Python3 program to add two numbers
num1 = 15
num2 = 12
num3 = 10
# Adding two nos
sum = num1 + num2 + num3
# printing values
print("Sum of {0} {1} and {2} is {3}" .format(num1, num2, num3, sum))
|
with open("input.txt") as file:
passports = file.read().split("\n\n")
fields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]
count = 0
for passport in passports:
flag = False
for field in fields:
if f"{field}:" not in passport:
flag = True
break
if flag:
con... |
"""
2520 is the smallest number that can be divided by each of the numbers from 1
to 10 without any remainder. What is the smallest positive number that is
evenly divisible by all of the numbers from 1 to 20?
LCM(x, y) = x * y / GCD(x, y) -> 1 * 20 / GCD(1, 20)
LCM(k1, k2, ..., kn) = LCM(...(LCM(LCM(k1, k2), k3)...), ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 10 08:00:59 2018
@author: Papun Mohanty
"""
from faker import Faker
import sqlite3
import time
# Creating Faker Object
faker_factory = Faker()
try:
conn = sqlite3.connect('human.db')
cursor = conn.cursor()
print("Opened database successfully"... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def setDemo(self):
# NLR : A B D C E G H F I
# LNR : D B A G E H C F I
# LRN : D B G H E I F C A
n1l = TreeNode('B')
n1l.left = TreeNode('D')
n1rl = TreeNode('E')
n1rl.left = TreeNode('G')
n1rl.right = Tr... |
# PROBLEM DESCRIPTION
# A permutation is an ordered arrangement of objects.
# For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
# If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
# The lexicographic permutations of 0, 1 and 2 are:
# 012 ... |
# PROBLEM DESCRIPTION
# You are given the following information, but you may prefer to do some research for yourself.
# 1 Jan 1900 was a Monday.
# Thirty days has September,
# April, June and November.
# All the rest have thirty-one,
# Saving February alone,
# Which has twenty-eight, rain or shine.
# And on leap years... |
from sys import stdin
"""
Nombre: Jhoan Sebastian Lozano
Código: 8931869
Código de honor del curso:
Como miembro de la comunidad académica de la
Pontificia Universidad Javeriana Cali me comprometo
a seguir los más altos estándares de integridad académica.
"""
def solve(M):
pascal = [ [1 for _ in range(... |
#Calculate a power of a number rised to other
def power(a,b):
if b==0:
return 1
else:
return a*power(a,b-1)
a=int(input("base: "))
b=int(input("exponent: "))
print(power(a,b))
#Perfect numbers between 1 and 1000
import math
def divisors(n):
divs = [1]
for i in range(2,... |
#!/usr/bin/env python
'''
For this exercise, draw a random number of randomly-sized sprites with a random color, random initial position, and random direction
'''
import sys, logging, pygame, random
assert sys.version_info >= (3, 4), 'This script requires at least Python 3.4'
logging.basicConfig(level=logging.CRITI... |
'''
@ Ting-Yi Shih
#Usage Example
from factory import Factory
Factory(source=[1,2,3], filename="factory_out", func=lambda x:str(x), num_workers=1).run()
source: a list/an iterator/a generator of items
filename: output filename
func: function that returns a string as the result of the item
can take either 1 argu... |
#Abhishek Khandelwal
def slope(q):
x0,y0 = lowest_point
x1,y1 = q
#print lowest_point,q
#print float(y0-y1)/(x0-x1)
return float(y0-y1)/(x0-x1)
n = int(raw_input("Enter number of Points"))
points = []
lowest_point = (100,100)
for i in xrange(n):
point = tuple(map(int,raw_input().split()))
p... |
# Mario recursion
from cs50 import get_int
def main():
height = get_int("Put the hight of the pyramid object: \n")
def mariostep(n):
if n == 0:
return
else:
mariostep(n - 1)
for i in range(n):
print("#", end = '')
print("", end... |
#code
def commonPrefix(s1, s2):
n1 = len(s1)
n2 = len(s2)
result = ""
i,j=0,0
while i<=n1-1 and j<=n2-1:
if s1[i]!=s2[j]:
break
result+=s1[i]
i+=1
j+=1
if result:
return result
else:
return -1
def prefix(s, l... |
userInput = int(input("Please input side length of diamond: "))
if userInput > 0:
for i in range(userInput):
for s in range(userInput -3, -2, -1):
print(" ", end="")
for j in range(i * 2 -1):
print("*", end="")
print()
for i in range(userInput, -1, -1):
... |
def LeftView(root, level, maxlevel):
if root is None:
return 0
else:
if maxlevel[0]<level:
print(root.data, end=' ')
maxlevel[0] = level
LeftView(root.left, level+1, maxlevel)
LeftView(root.right, level+1, maxlevel)
def printLeft(root):
... |
list1 = []
new_list = []
for _ in range(int(input())):
list2 = []
name = input()
score = float(input())
new_list.append(score)
list2.append(name)
list2.append(score)
list1.append(list2)
new_list.sort()
new_list = list(set(new_list))
new_list.sort()
print(new_list)
val = new_l... |
hashtable = [[], ] * 10
def checkPrime(n):
if n==1 or n==0:
return 0
for i in range(2, n//2):
if n%i==0:
return 0
return 1
def getPrime(n):
if n%2==0:
n+=2
while not checkPrime(n):
n+=1
return n
def hashFunction(key):
capacity ... |
def josephus(n, k):
ll = []
i=1
while i<=n:
ll.append(i)
i+=1
i=1
while len(ll)!=1:
index = (i+k)%n
ll.pop(index)
i+=1
return ll
def main():
T= int(input())
while(T>0):
nk = [int(x) for x in input().split(... |
# -*- coding: utf-8 -*-
import csv
class Contact:
def __init__(self,name, phone,email):
self.name=name
self.phone=phone
self.email=email
class ContactBook:
def __init__(self):
self._contacts=[]
def add(self, name,phone,email):
contact = Contact(name, phone, ema... |
import random
import matplotlib.pyplot as plt
# константы генетического алгоритма
POPULATION_SIZE = 100 # количество индивидуумов в популяции
MAX_GENERATIONS = 200 # максимальное количество поколений
P_CROSSOVER = 0.9 # вероятность скрещивания
P_MUTATION = 0.1 # вероятность мутации индивидуума
N_VECTOR = 2 # ко... |
class things(object):
def __init__(self, name, function, surface):
self.name = name
self.function = function
self.surface = surface
def description(self):
print(f"名字:{self.name},功能:{self.function},外貌:{self.surface}")
things1 = things("桌子", "陈放东西", "有四条腿")
things2 = things("椅子"... |
"""
一个回合制游戏,每个角色都有hp 和power,hp代表血量,power代表攻击力,hp的初始值为1000,power的初始值为200。
定义一个fight方法:
my_final_hp = my_hp - enemy_power
enemy_final_hp = enemy_hp - my_power
两个hp进行对比,血量剩余多的人获胜
"""
"""
一个回合制游戏,每个角色都有hp 和power,hp代表血量,power代表攻击力,hp的初始值为1000,power的初始值为200。
定义一个fight方法:
my_final_hp = my_hp - enemy_power
enemy_final_hp = en... |
# 面向对象
class House:
# 静态属性 -> 变量, 类变量, 在类之中, 方法之外
door = "red"
floor = "white"
# 构造函数,是在类实例化的时候直接执行
def __init__(self):
# 实例变量,是在类实例化的时候直接执行,以“self.变量名的方式去定义”,实例变量的作用域为这个类中的所有方法
self.door
self.yangtai = "大"
# 动态属性 -> 方法(函数)
def sleep(self):
# 普通变量,再类之中、方法之中... |
#figure &subplot
"""
numpy를 이용한 다양한 그래프 그리기
"""
from matplotlib import pyplot as plt
import numpy as np
from numpy.random import randn
fig = plt.figure()
sp1 = fig.add_subplot(2,2,1)
sp2 = fig.add_subplot(2,2,2)
sp3 = fig.add_subplot(2,2,3)
sp4 = fig.add_subplot(2,2,4)
sp1.plot([2,3,4,5], [81,93,91,97])
sp2.plot(ra... |
"""The unit test for runtime.ast"""
import unittest
from runtime import ast, env, lib
NULL_LITERAL = ast.Literal(env.Value(env.NULL))
INT_LITERAL = ast.Literal(env.Value(lib.INTEGER, 0))
TRUE_LITERAL = ast.Literal(env.Value(lib.BOOLEAN, True))
FALSE_LITERAL = ast.Literal(env.Value(lib.BOOLEAN, False))
STRING_LITERAL =... |
import math
x1, y1 = input().split()
x2, y2 = input().split()
x1 = float(x1)
x2 = float(x2)
y1 = float(y1)
y2 = float(y2)
dist = math.sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))
print("%.4f" % dist)
|
n = int(input())
horas = n / 3600
resto = n % 3600
minutos = resto / 60
resto = resto % 60
segundos = resto
print("%d:%d:%d" % (horas, minutos, segundos))
|
# 2. 두 수를 입력 받아서 두 수의 차이를 출력하는 프로그램
a=int(input("input : "))
b=int(input("input : "))
if a>b:
print(a-b)
else:
print(b-a)
|
people = ['홍', '이', '김', '이', '이', '김']
def max_count(people):
counts = {}
for i in people:
if i in counts:
counts[i] += 1
else:
counts[i] = 1
return counts
counts = max_count(people)
print(max(counts.values())) |
# 1. 두 수를 입력 받아서 큰 수를 출력하는 프로그램
a=int(input("input : "))
b=int(input("input : "))
if a>b:
print(a)
else:
print(b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.