text stringlengths 37 1.41M |
|---|
"""
Input Notation
c : clubs
d : diamonds
h : hearts
s : spades
1 : ace
2 : two
3 : three
4 : four
5 : five
6 : six
7 : seven
8 : eight
9 : nine
10 : ten
11 : jack
12 : queen
13 : king
Format:
Place suit first, then number for card inputs
suits are alphabetical
Numbers Array:
card - 1 = card number; Ace has ... |
def _compute_third(first, second):
""" Compute a third coordinate given the other two """
return -first - second
class HexVector:
""" Represents a Vector in Hex space """
def __init__(self, x=None, y=None, z=None):
""" Initialize the Hex Vector """
self.x = x if x is not N... |
print("-------------------------02")
def multiply(a,b):
return a * b
class TestMultiply:
@classmethod
def setup_class(cls):
print("--setup_class--")
@classmethod
def teardown_class(cls):
print("--teardown_class--")
def setup_method(self,method):
print("--setup_meth... |
class PriorityQueue:
def __init__(self):
# array sorted backwards
self.p_queue = []
def remove_minimum(self):
if(len(self.p_queue)==0):
return None
return self.p_queue.pop()
def insert(self,x):
for i in range(len(self.p_queue)):
if(self.... |
#Method reads in a file that contains n_grams in format:
#frequency word1 word2 ... word_n
#Method returns a 2D list of the words: [ [word1, word2, ... word_n], [word1, ....], ...]
#The 2D list is sorted based on the frequency of the n_grams, the most common ones at the front
#NOTE: the frequency is stored as a stri... |
import random
import time
from matplotlib import pyplot as plt
import numpy as np
def organizar(lista):
for a in range(0,len(lista)):
for b in range(0,a):
if lista[a]>=lista[b]:
aux=lista[a]
lista[a]=lista[b]
lista[b]=aux
#T(n)=n+n(n+1)/2+3n e... |
def adn(chain1, chain2):
'''Function which find the longest common subsequence between two chains'''
if(len(chain1) == 0 or len(chain2)==0):
return 0
if(chain1[len(chain1)-1] == chain2[len(chain2)-1]):
return adn(chain1[:len(chain1)-1], chain2[:len(chain2)-1]) + 1
return max(adn(chain1[:l... |
class GraphAl:
def __init__(self,size):
self.size = size
self.lista = [[] for i in range(size)]
def addArc(self, source, destination):
self.lista[source].append(destination)
self.lista[destination].append(source)
def isBicolorable(self, i):
visited = [""]... |
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle=="":
return 0
h = len(haystack)
n = len(needle)
if h < n:
return -1
for i in range(h... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
min = -float('Inf... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
point = ListNode(0)
save = point
... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def gener(self,list_):
length = len(list_)
if length==1:
return [TreeNode(list_[0])]
elif l... |
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
neg = 0 if numerator * denominator > 0 else 1
numerator, denominator = abs(numerator), abs(denominator)
not_the... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
sum = 0
cur = [root]
n... |
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
menu = 0
print("Välkommen till miniräknaren")
while menu < 5:
print(" 1 Räkna med +\n 2 Räkna med -\n 3 Räkna med *\n 4 Valfritt arbete om du vill\n 5 Avsluta")
menu = ... |
pos = 1
def search(arr,n):
l = 0
u = len(arr)-1
while l <= u:
mid = (l+u)//2
if arr[mid] == n:
globals()['pos'] = mid
return pos+1
else:
if arr[mid] < n:
l = mid+1
else:
u = mid-1
retu... |
def multiply_by2(li):
newlist=[]
for item in li:
newlist.append(item*2)
return newlist
print(multiply_by2([1,2,3]))
print(map(multiply_by2,[1,3,6]))
def multiply_by3(item):
return item*3
print(list(map(multiply_by3,[1,3,6])))
my_pets = ['alfred', 'tabitha', 'william', 'ar... |
def fizzbuzz(num):
if type(num) is int:
if num % 15 == 0:
return 'fizzbuzz'
elif num % 5 == 0:
return 'buzz'
elif num % 3 == 0:
return 'fizz'
else:
return num
raise TypeError("Input must be integer!")
def main():
f = open('fizz... |
# Task
# Given an array of integers , Find the maximum product obtained from multiplying 2 adjacent numbers in the array.
# Notes
# Array/list size is at least 2.
# Array/list numbers could be a mixture of positives, negatives also zeroes .
# Input >> Output Examples
# adjacentElementsProduct([1, 2, 3]); ==> return ... |
# Introduction and Warm-up (Highly recommended)
# Playing With Lists/Arrays Series
# Task
# Given an array of integers , Find the minimum sum which is obtained from summing each Two integers product .
# Notes
# Array/list will contain positives only .
# Array/list will always has even size
# Input >> Output Examples
#... |
def invert(list):
list_negative = [-x for x in list]
return list_negative
list = [1,2,3,4,5]
print(invert(list)) |
# While making a game, your partner, Greg, decided to create a function to check if the user is still alive called checkAlive/CheckAlive/check_alive. Unfortunately, Greg made some errors while creating the function.
# checkAlive/CheckAlive/check_alive should return true if the player's health is greater than 0 or fals... |
# Consider the word "abode". We can see that the letter a is in position 1 and b is in position 2. In the alphabet, a and b are also in positions 1 and 2. Notice also that d and e in abode occupy the positions they would occupy in the alphabet, which are positions 4 and 5.
# Given an array of words, return an array of... |
# Your task is to create functionisDivideBy (or is_divide_by) to check if an integer number is divisible by each out of two arguments.
# A few cases:
# (-12, 2, -6) -> true
# (-12, 2, -5) -> false
# (45, 1, 6) -> false
# (45, 5, 15) -> true
# (4, 1, 4) -> true
# (15, -5, 3) -> true
# Original c... |
# Given a string of digits confirm whether the sum of all the individual even digits are greater than the sum of all the indiviudal odd digits. Always a string of numbers will be given.
# If the sum of even numbers is greater than the odd numbers return: "Even is greater than Odd"
# If the sum of odd numbers is great... |
#Problem 4
#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
def palindromeProduct (numDigits):
numList = []
dig = 0
maxRange = 10**numDigit... |
print('''
Задание №10. Напишите скрипт, позволяющий определить надежность вводимого
пользователем пароля. Это задание является творческим: алгоритм
определения надежности разработайте самостоятельно.
''')
password = input('Введите пароль:')
if len(password) < 8:
print('Ненадежный пароль... |
print('''
Задание №6. Напишите программу, позволяющую ввести с клавиатуры текст
предложения и вывести на консоль все символы, которые входят в этот
текст ровно по одному разу.
''')
text = input('Введите текст: ')
for char in set(text):
if text.count(char)==1:
print(char)
input() |
# we can import modules to use later
import base64, sys
def new_accumulator(initial):
"""This is a function that returns a function (a closure)!"""
total = [initial]
def accumulator(x):
total[0] += x
print total[0]
return accumulator
class Greeter:
"""I am a docstring.
Th... |
# Lesson 6:
# Basic string operations (https://www.learnpython.org/en/Basic_String_Operations)
# based on lessons available at www.learnpython.org
# defining strings, w/ and w/o quotes
astring = "Hello world!"
astring2 = 'Hello world!'
print("single quotes are ' '")
# this prints out 12 because "Hello world!" is 12 ... |
# Lesson 4:
# Basic Operators (https://www.learnpython.org/en/Basic_Operators)
# based on lessons available at www.learnpython.org
# arithmetic operators
number = 1 + 2 * 3 / 4.0
print(number)
# modulo operator
remainder = 11 % 3
print(remainder)
# power operator (**)
squared = 7 ** 2
cubed = 2 ** 3
print(squared)
p... |
#WAP to enter hight of user in feets ans converts it into inches and cetimeter
#Height = int(input("Enter Height: "))
Height_ft = int(input("Enter Height in Feet: "))
Height_inch = int(input("Enter Height in Inches: "))
Height_inch= Height_inch + (Height_ft * 12)
Height_cm = int(Height_inch) * 2.54
print(... |
#WAP for Swapping using Third variable
x = input("Enter the variable :")
y = input("Enter the another variable :")
x, y = y, x
print ("After swapping: ")
print("Value of x : ", x)
print("Value of y : ", y) |
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(b)
print(np.dot(a.T, b))
A = np.array([[1, 2],
[3, 4]
])
B = np.array([[5, 6],
[7, 8]
])
print(np.matmul(A, B))
|
def square_of_sum(number: int) -> int:
"""
Calculate and return the square of sum for the argument *number*.
"""
return sum(i for i in range(number + 1))**2
def sum_of_squares(number: int) -> int:
"""
Calculate and return the sum of squares for the argument *number*.
"""
return sum(i**... |
def classify(number: int) -> str:
"""
Calculate factors and aliquot sum of a number. Return numbers category.
"""
if (number <= 0):
raise ValueError("number cannot be smaller or equal to zero")
factors = factorify(number)
aliquot_sum = aliquot(factors)
if aliquot_sum == number:
... |
#Program excercise of function return
#September 5, 2018
#Start of Function
def add(x,y):
return x + y
def multiply(x,y):
return x * y
def div(x,y):
return x / y
#End of Function
print("Welcome to Pogi's Calculator")
print("")
x = input("Enter First Number: ... |
from stack import LStack
operator = ['*', '/', '+', '-']
bracket = ['(', ')']
infix1 = ['3', '*', '(', '4', '+', '10', '/', '2', ')']
infix2 = ['3', '*', '(', '(', '4', '+', '10', ')', '/', '2', ')']
def is_number(x):
if x not in operator and x not in bracket:
return True
else:
return False
de... |
class Rectangle:
def __init__(self, a, b):
self.width = a
self.height = b
def getArea(self):
return self.width * self.height
if __name__ == '__main__':
res = Rectangle(3, 4)
print(res.getArea())
|
from typing import List
from random import randint
class Solution:
"""
@param a: an integer array
@return: nothing
"""
def selection_sort(self, a: List[int]):
n = len(a)
for i in range(n):
tmp = i
for j in range(i + 1, n):
if a[j] < a[tmp]:
... |
class Solution:
"""
@param n: an integer
@return: an integer f(n)
"""
def fibonacci_1(self, n: int) -> int:
a, b = 0, 1
for _ in range(n - 1):
a, b = b, a + b
return a
def fibonacci_2(self, n: int) -> int:
arr = [0, 1, 1]
for i in range(3, n ... |
from matplotlib import pyplot as plt
# the function to plot the loss of the training process
def plot_history(history):
hist_dict = history.history
loss_reg = hist_dict['loss']
plt.figure()
plt.plot(loss_reg, 'b')
plt.legend(['Training'])
plt.ylabel("Training loss")
plt.xlabel("Epoch")
... |
# basic engineering economics problems ... starting here...
"""
Created on Fri Aug 28 09:36:50 2020
@author: natezen
"""
# compare two alternatives using present worth
import numpy as np
# quick illustration of the IF PW of one alternative is better then...
PW1 = 10000
PW2 = 8000
if PW1>PW2:
pr... |
def cost_of_ground_shipping(weight):
if weight <= 2:
cost =+ (weight * 1.50) + 20
elif weight > 2 and weight <= 6:
cost =+ (weight * 3) + 20
elif weight > 6 and weight <= 10:
cost =+ (weight * 4) + 20
elif weight > 10:
cost =+ (weight * 4.75) + 20
return cost
premium_ground_shippin... |
a=int(input("enter the num"))
print(chr(a))
|
import math
a=int(input("enter a string "))
print(math.floor(a))
|
a=int(input("enter num"))
b=int(input("enter num"))
c=int(input("enter num"))
print(a*b%c)
|
n=int(input("enter n"))
a=int(input("enter a"))
d=int(input("enter d"))
s=0
for i in range(1,n+1):
s=s+(a+(i-1)*d)
print(s)
|
n=int(input("enter the num"))
b=1
for i in range(2,n):
if n%i==0 and n!=2:
b=0
if b==0:
print("yes")
else:
print("no")
|
s=input("enter the string")
b=len(s)//2
print(b)
for i in range(len(s)):
if i==b:
print(s[i])
s1=s.replace(s[i],'*')
print(s1)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 9 21:19:47 2019
@author: $PACEkiRK
"""
# -*- coding: utf-8 -*-
"""
Create a deck of 52 cards
Shuffle the deck
Ask the Player for their bet
Make sure that the Player's bet does not exceed their available chips
Deal two cards to the Dealer and two car... |
from matplotlib import pyplot as plt, animation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
ax.set(xlim=(-1, 1), ylim=(-1, 1))
string = 'Hello, how are you doing?'
label = ax.text(0, 0, string[0], ha='center', va='center', fontsize=20, color="Red")
... |
courses = ['English', 'Hindi', 'Marathi', 'Math']
print(courses)
courses.append('Science')
print(courses)
courses.insert(3, 'Social Science')
print(courses)
courses_2 = ['Art', 'commerce']
print(courses + courses_2)
courses.extend(courses_2)
print(courses)
popped = courses.pop()
print... |
"""
## Fulltime Week1 Quiz
* Write a function ```readcurrency(filename)```
that takes a filename as its argument.
* This function reads the lines of a file, which are of the form
```
USD 1.141911
```
Where the first value is a currency and the second value is the
Euro's value in that currency.
* Ret... |
import struct
from typing import Tuple
class Color:
"""An RGBA color object that can be created using RGB, RGBA, color name, or a hex_code."""
red: int
green: int
blue: int
alpha: int
def __init__(self, red: int, green: int, blue: int, alpha: int = 255) -> None:
self.red = red
... |
from collections import OrderedDict
class LRUCache(object):
def __init__(self, capacity=5):
if capacity < 1:
self.capacity = capacity
print("Capacity cannot less than 1")
return
self.capacity = capacity
self.cache = OrderedDict()
# Initialize c... |
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def __str__(self):
cur_head = self.head
... |
import numpy as np
class Interface():
def __init__(self):
self.DICIONARIO_SINAIS = {"a": "+", "b" : "-", "c" : "x", "d" : "÷"}
def imprimir_manual_fracao(self, sinal):
print(" a c")
print("--- ", self.DICIONARIO_SINAIS[sinal], " ---")
print(" b d")
... |
class Student:
def __init__(self,FirstName, LastName, GPA, Major, FacultyAdvisor):
self.FirstName = str(FirstName)
self.LastName = str(LastName)
self.GPA = float(GPA)
self.Major = str(Major)
self.FacultyAdvisor = str(FacultyAdvisor)
### Accessors
def getVals(self):... |
from gpiozero import LED
from time import sleep
import tkinter.font
import RPi.GPIO as GPIO
from tkinter import *
GPIO.setmode(GPIO.BCM)
yellow = LED(18)
red = LED(22)
blue = LED(27)
window = Tk()
window.title("TOGGLE LED")
myFont = tkinter.font.Font(family = 'Calibri'... |
# Word Jumble
#
# The computer picks a random word and then "jumbles" it
# The player has to guess the original word
import random
# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
HINT = ("Programming langauge this was written with?",
"What... |
# 'letters' and 'points' provided by Codecademy learning platform
letters = ["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"]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]
# build point diction... |
def adjacentElementsProduct(inputArray):
mult_res = 0
for i in range(len(inputArray) - 1):
mult = inputArray[i] * inputArray[i + 1]
if mult > mult_res:
mult_res = mult
return mult_res
inputArray = [3, 6, -2, -5, 7, 3, 9, 12, 100, -5]
print(inputArray)
result = adja... |
#!/usr/bin/env python3
from sys import stdin
import re
REDSTONE_CHAR = "\033[91m+\033[0m"
def print_map(positions: [(int, int)], width=4):
redstone_map = [[False for y in range(4)] for x in range(4)]
for position in positions:
x,y = map(int, position)
redstone_map[x-1][y-1] = True
for y ... |
monedas=[200,100,25,10,5,1]
vuelto=int(input('Cuanto es el vuelto que hay que devolver en centavos? '))
for i in range(len(monedas)):
if (vuelto/monedas[i])>=1:
cambioA=int(vuelto/monedas[i])
vuelto=vuelto%monedas[i]
print('Seran '+ str(cambioA)+' monedas de '+ str(monedas[i])+' centavos de dolar') |
print('Programa para devolver el vuelto en la menor cantidad de monedas posibles')
#Empiezo declarando las variables en centavos de dolar
A=1
B=5
C=10
D=25
E=100
F=200
#Le pido el dato a el usuario
vuelto=int((input('Cuantos centavos son de vuelto? ')))
#Hago los computos
if (vuelto/F)>1:
CambioF=int(vuelto/F)
vuel... |
from threading import *
import time
def doubles(numbers):
for i in numbers:
time.sleep(1)
print("doubles",2*i)
def square(numbers):
for n in numbers:
time.sleep(1)
print("square",n*n)
numbers=[1,2,3,4,5]
begintime=time.time()
doubles(numbers)
square(numbers)
print("... |
for i in range(65, 70):
for l in range(i):
print(' ', end='')
for k in range(i , 70):
print(chr(k), '', end='')
print('\n') |
str = input("Enter the string")
l = len(str)
p = l-1
index = 0
while index < p:
if str[index] == str[p]:
index = index + 1
p = p-1
print("String is a palindrome")
break
else:
print("string is not a palindrome")
break |
n=5
wx=n
wy=n
for x in range(1,n+1):
for y in range(1,n*2+1):
if(y==wx or y==wy):
print(wx,end="")
else:
print(" ",end="")
wx-=1
wy+=1
print() |
for i in range(3, 0, -1):
for j in range(i, 1, -1):
print(" ",end=" ")
for k in range(i, 4):
print("*",end=" ")
print(" ")
|
num=int(input("Enter the Number"))
sum=0
temp=num
while temp>0 :
dig=temp%10
sum= sum * 10 + dig
temp=temp//10
print(sum)
if sum== num :
print("palindrome")
else :
print("Not palindrome")
|
import functools
l=[1,3,6,4,3,5]
print("the sum of list element is :",end="")
print(functools.reduce(lambda a,b:a+b,l))
print("The maximumlement of the list:",end="")
print(functools.reduce(lambda a,b: a if a > b else b,l)) |
from threading import *
class even(Thread):
def run(self):
for i in range(10):
if (i % 2 == 0):
print(current_thread().getName(),i)
class odd(Thread):
def run(self):
for i in range(10):
if (i % 2 == 1):
print(current_threa... |
# F value - feature selection
# Load libraries
from sklearn.datasets import load_iris
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif
# Load iris data
iris = load_iris()
# Create features and target
X = iris.data
y = iris.target
# Create an SelectKBe... |
import random
random.seed() #Prepare random number generator
value = 0
score = 0
total = 0
print("Welcome to the Fishing Game! Would you like to head out to fish or stay on shore?")
print("1. Go Fish!")
print("2. Stay on shore!")
choice = int(input())
while choice < 1 or choice > 2:
print("Invalid i... |
class Complex:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __str__(self):
return str(self.real) + f'+{str(self.imaginary)}i'
def __add__(self, other):
real = self.real + other.real
imaginary = self.imaginary + other.imaginary... |
# Define the data
data = set()
count = int(input("Enter the number of data points: "))
for i in range(count):
x=float(input("X"+str(i+1)+": "))
y=float(input("Y"+str(i+1)+": "))
data.add((x,y))
# Find the average x and y
avgx = 0.0
avgy = 0.0
for i in data:
avgx += i[0]/len(data)
avgy += i[1]/len(d... |
class Calculator:
path_txt = 'calc_cache.txt'
path_csv = 'calc_cache.csv'
''' Advanced calculator '''
@staticmethod
def input_value():
''' Input value and check if it integer or float and not equal 0 '''
NULL = '0'
while True:
val = input()
if val.is... |
#Athuga hvar leikmaðurinn er staðsettur og hvert hann getur farið
#Taka við inputi sem segir í hvaða átt leikmaðurinn vill fara
#Ath hvort hægt er að fara í áttina sem leikmaðurinn setti inn
#Ef ekki er hægt að fara þá átt prenta: Not a valid direction!
#Annars færa staðsetningu leikmannsins í þá átt og breyta núverand... |
emails = ['sort@hotmail.com', 'you@hotmail.com', 'laz@gmail.com']
for item in emails:
if 'gmail' in item:
print(item)
A = ["Terribly Tricky"]
for word in A:
for letter in word[-6:]:
print(letter)
|
stack = []
def push(n):
stack.append(n)
def pop():
if len(stack)>0:
return stack.pop()
while True:
print("Stack Menu")
print("1. push")
print("2. pop")
print("0. exit")
choice = int(input("Enter your choice: "))
if choice == 1:
n = int(input("Enter a number t... |
import random
def repaso(nombre, num_preguntas):
aciertos = 0
operaciones = ["+", "-", "*", "/"]
for i in range(num_preguntas):
a = random.randint(1,9)
b = random.randint(1,9)
oper = random.randint(0,3)
resultado = input(f"{a}{oper}{b} = ")
if validar(a, b, opera... |
laptop = 12_000
print('Costo de laptop $', laptop)
sueldoPorSemana = 3_500
print('Sueldo por semana $', sueldoPorSemana)
semanas = 0
for i in range((laptop//sueldoPorSemana)+1):
semanas += 1
print('Semanas: ', semanas)
semanas = 0
ahorrado = 0
while (ahorrado < laptop):
semanas += 1
ahorrado += sueldoP... |
import time
from turtle import Screen, Turtle
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 600
start_position = (0, 0)
start_size = 3
snake_block_size = 20
snake_shape = "circle"
screen_color = "black"
snake_color = "white"
screen = Screen()
screen.setup(width=WINDOW_WIDTH,
height=WINDOW_HEIGHT)
screen.bgcolor(scr... |
from turtle import Turtle, Screen
import random
turtle = Turtle()
s = Screen()
s.colormode(255)
side_length = 20
left_or_right = 0
turtle.pensize(4)
directions = [0, 90, 180, 270]
for sides in range(1, 200):
red = random.randint(0, 255)
blue = random.randint(0, 255)
green = random.randint(0, 255)
turtl... |
class Node:
rChild,lChild,data =None,None,None
def __init__(self,key):
self.rChild = None
self.lChild = None
self.data = key
class MyBinaryTree:
root,size =None,0
def __init__(self):
self.root = None
self.size =0
def insert (self, node, data):
if node... |
def pairSum(n):
total = 0
for i in range(n):
total += i + i+1
return total
print(pairSum(12))
|
import psycopg2
#crete a new database named botdb
def createDatabase():
#establishing the connection
conn = psycopg2.connect(
database="postgres", user='postgres', password='admin', host='127.0.0.1', port= '5432'
)
conn.autocommit = True
#Creating a cursor object using the cursor() method... |
from cs50 import get_int,get_string
def main():
n = get_string("Number: ")
# a = check(n)
# print(a)
# print(n[0:2])
if check(n) and (len(n)==13 or len(n)==16) and int(n[0])==4:
print("VISA")
elif check(n) and len(n)==15 and (int(n[0:2])==34 or int(n[0:2])==37):
print("AMEX")
... |
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the makeAnagram function below.
def makeAnagram(a, b):
c1=Counter(a)
for i in b:
c1[i]-=1
val=c1.values()
s=sum(abs(i)for i in val)
return s
if __name__ == '__main__':
f... |
import queue
class MovingAvg(): # 클래스는 인자를 받을수도 있는듯
def __init__(self, size):
self.size = size
self.queue = queue.Queue() # 큐를 연결시키기위해서 self.queue를 만듦
# 변수를 연결시켜주기 위해서 다시 self.sum이라는 변수를 만듦. <- 처음풀때 이생각을 못함
self.sum = 0
def nextVal(self, num):
# self.num = num
... |
def solution(board, nums):
answer = 0
bingo = [0 for i in range(len(board))]
# print(bingo)
# 2차원 리스트에 값이 포함되어있는지 확인하는법?
# 2차원 배열안에 있는지는 확인을 한번에 못하는듯하다.
# 따라서 한줄의 배열을 받아와서 확인하는수 밖에 없는닷하다.
# <해설풀이>
# 순서를 고려얀하고 빙고수만 받기떄문에 nums를 set으로 바꾸면된다.
for num in nums:
for i ... |
# m,n = input().split()
# m, n = [int(x) for x in [m,n]]
matrix = [[" "]*3 for i in range(3) ]
dol = ['0','X']
turn = 0
def matrix_print() :
for i in range(3):
print("───┼───┼───┼───┤")
print(str(i+1)+" │ ", end="")
for j in range(3):
print(matrix[i][j]+" │ ", end="")
... |
# Problem statement - Addition of Two numbers
# problem expected Input - varibales a, b
# problem expected Output - a+b
# additional infomation
# start code here
def add(integer1, integer2):
return integer1+integer2
result = add(1, 2)
print(result)
|
import pandas as pd
import matplotlib.pyplot as plt
def bar(f):
plt.figure(figsize = (10,5))
plt.bar(f['Date'],f['No of Deaths'])
#set label
plt.ylabel('No of Deaths')
plt.xlabel('Date')
plt.title('Daily covid 19 deaths in '+ k, fontweight = 'bold')
plt.show()
print("Time... |
# Daily coding problem 1
# Source: Google
# Problem: Given a list of numbers and a number k, return whether any two numbers
# from the list add up to k
# Problem Solution should look like:
# Given array = [10,15,3,7] and k = 17
# return true since 10+7 = 17
###########################################... |
#!/usr/bin/env python
import sys
from math import log
"""
Experiment with IR (Information Retrival) technology, tf-idf
(Term Frequency, Inverse Document Frequency)
"""
# return a normalized "term frequency"
def tf(term, doc):
# split the document and clean up
words = [word.rstrip(',.') for word in doc.lower().split... |
class Cal24op():
# if all 3 params are given, l and r are objects
# if only 1 param is given, l is a number
def __init__(self, l, r=0, op="$"):
self.l = l
self.r = r
self.op = op
self.result = 0
self.print_result = " " + str(l) + " "
self.valid = True
... |
# Exemplo 1
'''resposta = input('Vamos sair hoje [s/n]? ')
while resposta != 's':
resposta = input('Vamos [s/n]? ')
print('Então, vamos!!')
'''
# Exemplo 2
resposta = input('Vamos sair hoje [s/n]? ')
n = 1
while resposta != 's':
resposta = input(f'Vamos{"s" * n} [s/n]? ')
n += 1 # [n += 1] é igual a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.