text stringlengths 37 1.41M |
|---|
## https://leetcode.com/problems/valid-palindrome
class Solution:
def isPalindrome(self, s: str) -> bool:
S = ""
for i in s:
if i.isalnum():
S += i
return S.lower() == S[::-1].lower() |
# https://leetcode.com/problems/sort-colors/submissions/
# Given an array nums with n objects colored red, white, or blue, sort them in-place
# so that objects of the same color are adjacent, with the colors in the order red,
# white, and blue.
# We will use the integers 0, 1, and 2 to represent the color red, white, a... |
#User function Template for python3
## https://practice.geeksforgeeks.org/problems/middle-of-three2926/1#
class Solution:
def middle(self,A,B,C):
# R = sorted([A,B,C])
# return R[1]
if((A-B)*(A-C)<0) :
return A
elif((B-A)*(B-C)<0):
return B
e... |
## Practice of Tree Traversals
class TreeNode(object):
def __init__(self,val = None,left = None, right = None):
self.val = val
self.left = left
self.right = right
class BinaryTree(object):
def __init__ (self,root = None):
self.root = TreeNode(root)
def TreeVisualizer(self,... |
## Fibonacci numbers using Bottom up DP
def Fib(n):
fib = [0]*10000
fib[0] = 1
fib[1] = 1
for i in range(2,n+1):
fib[i] = fib[i-1]+fib[i-2]
return fib[n]
if __name__ == "__main__":
print(Fib(250)) |
## https://leetcode.com/problems/number-of-1-bits/
class Solution:
def hammingWeight(self, n: int) -> int:
return bin(n).count("1")
####### Another approach ########
class Solution:
def hammingWeight(self, n: int) -> int:
bitcount = 0
while n > 0:
if n % 2 == 1:
bit... |
#!/bin/python3
import math
import os
import random
import re
import sys
# 3
# 11 2 4
# 4 5 6
# 10 8 -12
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference(arr):
# Write your cod... |
# Calculator
print(
"""
Hey, this is an Awesome calculator...
These are the operations supported by it.
1 for addition
2 for Multiplication
3 for Division
4 for Substraction
5 for power(x,y)
6 for exit
"""
)
while True:
X = float(... |
## https://leetcode.com/problems/can-place-flowers/
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
if n == 0:
return True
for i in range(len(flowerbed)):
left = (i == 0 or flowerbed[i - 1] == 0)
right = (i == len(flowerbed) - 1 ... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
## https://www.hackerrank.com/challenges/input/problem
x,k = map(int,input().split())
print(k==eval(input()))
|
###### INSERTION SORT -- Practice ######
def InsertionSort(arr):
for i in range(1,len(arr)):
key = arr[i]
j = i-1
while j >= 0 and key < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
if __name__ == "__main__":
arr = list(map(int,input("Enter t... |
## https://leetcode.com/problems/shuffle-the-array/
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
# nums1 = nums[:n]
# nums2 = nums[n:]
# res= []
# for i in range(len(nums1)):
# res.append(nums1[i])
# ... |
### Q: Write a program to insert, delete at beginning, end, middle of a linked list.
class node:
def __init__(self,data = None):
self.data = data
self.next = None
class Linked_list:
def __init__(self):
self.head = node()
def insert_at_end(self,data):
new_node = node(data... |
'''
Q. Given an array nums of n integers and an integer target, are there elements a, b, c,
and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array
which gives the sum of target.
Notice that the solution set must not contain duplicate quadruplets.
'''
def fourSum(nums,... |
### https://leetcode.com/problems/contains-duplicate/submissions/ ###
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
##### Method 1 #####
# return not len(nums) == len(list(set(nums)))
##### Method 2 #####
d = {}
for i in nums:
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
## https://www.hackerrank.com/challenges/30-review-loop
if __name__ == "__main__":
n = int(input())
for i in range(n):
odd = ""
even = ""
strng = input()
for j in range(len(strng)):
if j%2 == 1... |
### https://leetcode.com/problems/sort-array-by-parity-ii/submissions/
class Solution:
def sortArrayByParityII(self, A: List[int]) -> List[int]:
# """
# Dictionaries are a convenient way to store data for later retrieval by name (key).
# A defaultdict works exactly like a normal dict, but it is... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
def person(name,age,**kw):
if 'city' in kw:
pass
if 'job' in kw:
pass
print ('name:',name,'age:',age,'other:',kw)
person('Michael',30)
person('Bob',35,city='Beijing')
person('Jack',24,city='Beijing',addr='Chaoyang')
def f1(a,b,c=0,*args,**kw):
p... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import functools
def int2(x,base=2):
return int(x,base)
#functools中partial function 偏函数,把一个函数的某些参数固定住,返回一个新函数
if __name__=="__main__":
print (int2('120',8))
print (int2('10101'))
int8 = functools.partial(int,base=8)
print (int8('120'))
kw = {'base':8}
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
dict1 = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"}
print ("initial dict1: %s"%dict1)
dict2 = sorted(dict1.items(),key=lambda d:d[0])
print ("order by key: %s"%dict2)
dict3 = sorted(dict1.items(),key=lambda d:d[1])
print ("order by value: %s"%dict3)
ks = list... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
names = ["Michael","Bob","Tracy"]
scores = [95,75,85]
d = {}
for i in range(3):
d[names[i]] = scores[i]
print ("Initial Dict: ",d)
c = d.copy()
if 'Bob' in d:
print ("Scores of Bob",d['Bob'])
d['Ray'] = 100
print ("Updated Dict: ",d)
del(d["Tracy"])
print ("Updated Dict... |
import sqlite3 as sqlite
def connect_db(filename='app/db.sqlite'):
conn = sqlite.connect(database=filename)
init_tables(conn)
conn.row_factory = dict_factory # allows to call sql rows by their field name instead of by index
return conn
def init_tables(conn):
cur = conn.cursor()
cur.execute(... |
"""
The file that writes everything to a java file. This is the main
file which is going to be run.
Author: Utkarsh Dayal
"""
from docParser import *
from javaclass import *
def getMethodStub(methodName):
"""
Takes in a method name, and based on what the return type of
the method is, it returns a return ... |
# Crear un programa con tres clases Universidad, con atributos nombre
# (Donde se almacena el nombre de la Universidad). Otra llamada Carerra,
# con los atributos especialidad (En donde me guarda la especialidad de
# un estudiante). Una ultima llamada Estudiante, que tenga como atributos
# su nombre y edad. El prog... |
class Animales():
def __init__(self,descripcion,especie,hablar):
self.descripcion = descripcion
self.especie = especie
self.hablar = hablar
def habla(self):
print("Yo hago ",self.hablar)
def describir(self):
print("Soy de la especie ",self.especie)
class Perro(Anim... |
#escriba un script que sea capaz de calcular el índice de masa corporal de una persona en base a los datos ingresados por el usuario.
import math
from tabulate import tabulate
peso = float(input("Ingrese su peso en Kilogramos: "))
estatura = float(input("Ingrese su estatura en metros: "))
IMC = round(peso/math.pow(e... |
# clase
class Persona():
# atributos
nombre = "Carlos"
apellido = "Vergara"
sexo = "Masculino"
edad = 30
# metodos
def hablar(self, mensaje):
return mensaje
###########################
# objeto
persona = Persona()
print(persona.hablar("Hola soy"), "{} y mi apellido es {}, tengo... |
variable_uno = 5
variable_dos = 20
menor = variable_uno < variable_dos
mayor_igual = variable_uno >= variable_dos
menor_igual = variable_uno <= variable_dos
igual = variable_uno == variable_dos
diferente = variable_uno != variable_dos
mayor = variable_uno > variable_dos
print(mayor)
print(menor)
print(mayor_igual)
pr... |
import sqlite3
conexion=sqlite3.connect("AdministracionAlumnos3")
cursor = conexion.cursor()
elcodigo = int(input("Digite el código del curso que desea consultar: ")),
cursor.execute("SELECT * FROM CURSOS WHERE id_curso = ?",elcodigo)
loscursos=cursor.fetchall()
print(loscursos)
conexion.commit()
conexion.close() |
variable_uno = 5
variable_dos = 20
mayor = variable_uno > variable_dos
menor = variable_uno < variable_dos
mayor_igual = variable_uno >= variable_dos
menor_igual = variable_uno <= variable_dos
igual = variable_uno == variable_dos
diferente = variable_uno != variable_dos
resultado = True and True and diferente
resulta... |
"""
f=open("data.txt","r")
print(f.read(1)) # 한바이트만 읽어옴
print("")
f=open("data.txt","r")
print(f.read())
print("")
f=open("data.txt","r")
print(f.readlines())
print("")
f=open("data.txt","r")
r=f.readlines()
print(r[2])
f=open("data.txt","r")
r=f.readlines()
for x in range (0,4):
print(r[x])
f=open("data.txt"... |
#Linked list
#including the function:
#insertAtFront();
#insertAtBack()
#removeFromFront()
#removeFromBack()
class Node(object):
def __init__(self,data):
self.data=data
self.nextNode=None
def __str__(self):
return self.data
class linkedList(object):
... |
from abc import ABCMeta
class Vuelo(metaclass=ABCMeta):
'''Abstracción que representa a un vuelo'''
def __init__(self, codigo, avion, fecha_partida, horario_partida):
self.aeropuerto_origen = "Silvio Pettirossi"
self.pais_origen = "Paraguay"
self.codigo = codigo
self.avion = avi... |
from abc import ABCMeta, abstractmethod
class Cabina(metaclass=ABCMeta):
'''Abstracción que representa a una cabina'''
def __init__(self, precio, nombre):
self.precio = precio
self.nombre = nombre
def __str__(self):
return 'Precio: ' + str(self.precio) + ' US$' + '\n' + 'Cabina: ' ... |
threes = [value * 3 for value in range(3, 31)]
for three in threes:
print(three)
|
seats = input('How many people: ')
seats = int(seats)
if seats > 8:
print("You have to wait for table")
else:
print("Your table is ready")
|
guests = ['Katya', 'Kambar', 'Tanya']
print("I would like to invite you", guests[0], "for dinner")
print("I would like to invite you", guests[1], "for dinner")
print("I would like to invite you", guests[2], "for dinner")
|
def make_albums(artist, title, songs = None):
album = {'artist': '', 'title': ''}
album['artist'] = artist
album['title'] = title
if songs:
album['songs'] = songs
return album
fallout_boy_albums = make_albums('Fallout Boy', 'Centuries', 10)
for key, value in fallout_boy_albums.items():
print(key.title(), "and ... |
#! /usr/bin/env python3
#2020-07-22(Wes.) Note
"""
a.py 로 저장
class C:
# c = a.C() : class C 의 인스턴스가 생성
def __init__(self):
print("class C 의 인스턴스가 생성됨")
self.name = "ccc"
# print(c.name)
## ccc
self.age = 0
# print(c.age)
##출력: 0
def say_hi(self):
print("hi")
# c.say_hi()... |
#!/usr/bin/env python
"""Convert font PNGs from renderpng.sh into a header with an array of font
bitmap data.
"""
import os
from PIL import Image
def main():
print('#ifndef FONT_H')
print('#define FONT_H')
chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZdhms"
# Pixel data is in VFD format - column-major order, each by... |
# This is patterned after the [TensorFlow custom training tutorial]
# (https://www.tensorflow.org/tutorials/customization/custom_training_walkthrough#define_the_loss_and_gradient_function).
import matplotlib.pyplot as plt
def plot_training_experiment(train_loss_results, train_accuracy_results):
fig, axes = plt.subp... |
class Calculator:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def add(self):
return (self.num2 + self.num1)
def subtract(self):
if num1 > num2:
return (self.num1 - self.num2)
else:
return (self.num2 - self.num1)
def mul... |
import unittest
from hero import Hero
from spell import Spell
from weapon import Weapon
class TestHero(unittest.TestCase):
def setUp(self):
self.hero = Hero("Martin", "Manqk", 200, 300, 3)
def test_hero_init_(self):
self.assertEqual(self.hero.health, 200)
self.assertEqual(self.hero.mana, 300)
self.assertEq... |
import unittest
from bank_account import BankAccount
class TestBankAccount(unittest.TestCase):
def setUp(self):
self.acc = BankAccount("Sasho", 100, "dollars")
self.acc2 = BankAccount("Misho", 200, "dollars")
def test_init(self):
self.assertEqual(self.acc.get_name(), "Sasho")
... |
from unit import Unit
class Hero(Unit):
def __init__(self, name, title, health, mana, mana_regen):
self.name = name
self.title = title
self.mana_regen = mana_regen
Unit.__init__(self, health, mana, name)
self.phisical_damage = 0
self.magic_damage = 0
sel... |
def getFactorOf(number):
for i in range(2, int(number // 2)):
if number % i == 0:
return i
return None
def check(number):
factor = getFactorOf(number)
if factor:
print(number, 'has factor', factor)
else:
print(number, 'is prime')
if __name__ == '__main__':
... |
s = 'abcdefghjiklmnopqrstuvxyz'
# a
for char in s:
print(ord(char))
# b
codesSum = 0
for char in s:
codesSum += ord(char)
print('The sum is: {0}'.format(codesSum))
# c
charCodes = []
for char in s:
charCodes.append(ord(char))
print('Char codes are: {0}'.format(charCodes))
# c1
print('Char codes are: {... |
def addDict(*dicts):
result = {}
for d in dicts:
for k in d:
result[k] = d[k]
return result
if __name__ == '__main__':
d1 = {1: 2, 3: 4, 'c': 'e'}
d2 = {'a': 'b', 'c': 'd'}
print(d1, d2, addDict(d1, d2)) |
#fizzbuzz
for i in range(1,21):
if i%15==0:
print("Fizz Buzz")
continue
if i%3==0:
print("Fizz")
continue
if i%5==0:
print("Buzz")
continue
print(i)
|
# Use for, .split(), and if to create a Statement that will print out words that start with 's':
st = 'Print only the words that start with s in this sentence'
words = st.split()
for word in words:
if word[0] == 's' and len(word) > 1:
print(word)
# Use range() to print all the even numbers from 0 to 10.
... |
import math
import constants
def calc_alpha_probabilities(alpha):
"""
Calculate the normalized probabilities for each weight in the alpha distribution
:param: alpha: A float between (-2) to 3
:return: A dictionary with the probability for each weight
"""
constants.print_debug("\ncalculating ... |
class Bullet():
_instances = []
''' Bullet class should have only 1 instance '''
def __init__(self,Img):
self.Img = Img
self.bullet_state = False
if len(self._instances) == 0:
self._instances.append(self)
else:
raise Exception("This class is Singleton... |
## 1. Execute Method Placeholders ##
row_values = {
'identifier': 1,
'mail': 'adam.smith@dataquest.io',
'name': 'Adam Smith',
'address': '42 Fake Street'
}
import psycopg2
conn = psycopg2.connect("dbname=dq user=dq")
cur = conn.cursor()
cur.execute("INSERT INTO users VALUES( %(identifier)s, %(mai... |
## 1. Introduction ##
import pandas as pd
## 2. Read a CSV with Pandas ##
import pandas as pd
cars = pd.read_csv("cars.csv")
## 3. Dataframes ##
cars_shape = cars.shape
first_six_rows = cars.head(6)
last_four_rows = cars.tail(4)
## 4. Accessing Data With Indexes ##
cars_odd = cars.iloc[1::2, 0:3 ]
fifth_odd_... |
class Node:
def __init__(self, letter):
self.childleft = None
self.childright = None
self.Nodedata = letter
# create the nodes for the tree
root = Node('A')
root.childleft = Node('B')
root.childright = Node('C')
root.childleft.childleft = Node('D')
root.childleft.childright = Node('E') |
import RPi.GPIO as GPIO
import sys
import time
from datetime import datetime
from lib.relay import Relay
from lib.temp_sensor import TempSensor
relay_pin = 16
# After turning the relay on or maintaining current status, sleep this period before checking the temperature again
period = 30
# Set the GPIO mode to use the b... |
import unittest
import shoppingCart as sc
class TestShoppingCart(unittest.TestCase):
def test_addToCart(self):
tsc=sc.ShoppingCart()
#If any invalid Item is added to Cart which is not present in PriceList
self.assertRaises(KeyError,tsc.addToCart,['T-Shirt','Mukesh','Jacket'... |
import json
from difflib import get_close_matches
data=json.load(open("dat.json"))
def word_meaning(w):
w=w.upper()
if w in data:
return data[w]
elif len(get_close_matches(w,data.keys())) > 0:
print("Did you mean %s instead ?" %get_close_matches(w,data.keys())[0])
new_word=input("E... |
import tkinter as tk
# 第1步,实例化object,建立窗口window
window = tk.Tk()
window.title("番茄time")
window.geometry('400x400') # 长x宽
var = tk.StringVar()
e1 =tk.Entry(window,textvariable=var,font=("Microsoft Yahei",14))
e1.place(x=100,y=100)
# e1.focus_set()
a = e1.get()
#放置标签
#test.place()
window.mainloop()
# print(e... |
def car(s,many):
#排序
int_sort =sorted(many,reverse=True)
#计算车辆数量
count=0
#转化为文本列表
str_sort =[str(i) for i in int_sort]
while len(str_sort)>0:#str sort 列表未清空时:
all=[]#创建 all 并每次清空all 列表
m=len(str_sort)#判断当前 str sort 长度
# i=0
for l in range(1,m):
... |
import heapq
from collections import OrderedDict
from collections import deque
import math
# 平均值函数
def avg(data):
a = 0
for i in data:
a = a+i
return round(a/len(data), 1)
# 去头尾 求平均值
def dropFL(data):
_discard, *medi, _discard2 = data
return avg(medi)
'''
data = [1,4,3,8,10,9]
data.... |
#创建text文件 并逐行写入
import os
# ls =os.linesep#行的切换符号 适用于任何平台 Windows Unix
# print(ls)
class TextFlie:
def __init__(self):
self.fileName =input("please enter your file name:")
def makeTextFlie(self):
#检查filename 是否已存在
#os.path.exists 处理异常
# while True:
#... |
import io
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
#word_tokenize accepts a string as an input, not a file.
stop_words = set(stopwords.words('english'))
file1 = open("2015b.txt")
line = file1.read()# Use this to read file content as a stream:
words = line.split()
for r in words... |
celsius = 37
fahrenheit = (celsius * 1.8) + 32
print ("%.2f celsius = %.2f Fahrenheit" %(celsius,fahrenheit)) |
'''
Figuring out how to work with zip files in memory
'''
import io
from tempfile import TemporaryFile
from zipfile import ZipFile
import requests
import pandas as pd
# Typical CSV file content
df = pd.DataFrame({'a': (1, 2), 'b': (3, 4)})
fname = 'stata_out.dta'
# write file to disk
df.to_stata(fname)
# Write ... |
'''
iterable_cards.py
This script demonstrates core data structures and iterables in Python 3
using basic statistical concepts. Pay attention to what lazy evaluation
does for the program's memory usage.
In this simple card game each card has a value.
A player draws several cards without replacement and sums their val... |
'''
Chapter 9, Exercise 2 on page 146 of Wasserman's All of Statistics
Maximum likelihood estimators for parameters of uniform distribution.
Solving numerically as a constrained optimization problem.
Amazing what a difference it makes to use the log of the objective
function rather than the actual objective function.... |
import enum
class Direction(enum.Enum):
UP = 1
DOWN = -1
RIGHT = 2
LEFT = -2
def is_opposite(self, direction):
return self.value == -direction.value
if __name__ == "__main__":
"""should be TRUE"""
print(Direction.UP.is_opposite(Direction.DOWN))
"""should be FALSE"""
print(... |
# coding:utf-8
__author__ = 'sinlov'
# python 中含有一个类型是列表类型,列表是可变的序列,可以保存任何类型
book = ['python', 'Development', 8, 2008]
book.insert(1, 'web')
print("print book list", book)
print("print book list slicing ", book[:2])
# check object is in list
print("is python in book?", 'python' in book)
# remove object
my_list = ['q... |
#Initial conditions: choose v0 = 0, p = -1, timestep = choose
#d2s/dt2 = -Ps(t)
#s(tn) ~~ s(t0) + ds/dt * DeltaT
#v(tn) ~~ v(t0) + dv/dt * DeltaT
import numpy as np
import matplotlib.pyplot as plt
#P, t0, delta_t, s0, a0, v0, delta_v, delta_s
def acceleration(p,s,damp=0, v=0):
"""an expression for the acceler... |
"""
Project Euler Problem 5
=======================
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 number that is evenly divisible by all of the numbers
from 1 to 20?
"""
def smallest_common_multiple(limit):
num = 1
i = 1
step = 0
... |
# friends1 = ["Jim", 2, false]
friends = ["Jim", "Bob", "Fred", "Mary", "John", "Shaun"]
friends[1] = "changed from Bob"
print(friends[-1])
print(friends[1:])
print(friends[2:4])
print(friends[1]) |
class Vehicle(object):
def Move(self):
print ("Vehicle is moving")
def Transpot(self):
print ("Vehicle is transpoting")
class Car(Vehicle):
def __init__(self,weight,height):
self.weight = weight
self.height = height
def SpeedUp(self):
print ("Car is speeding up")
def SpeedDown(self):
print("Car is spe... |
from sys import exit
from random import randint
class Scene(object):
def enter(self):
print "You have found an unfinished scene. Woops."
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map=scene_map
def play(self):
#Get player name, boon, and bane... |
#!/usr/bin/env python
# coding: utf-8
# In[4]:
import json
import pandas as pd
import requests
# In[1]:
#Part III: Steam API
#In order to search for specific info about each game, we need to maintain a list of games and their corresponding steam app id
#to do so, we use the steam_app_id() which returns a list of... |
"""
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural
numbers and the square of the sum is 3025 − 385 = 2640.... |
#Find the sum of all the multiples of 3 or 5 below a limit defined by user
# % is the modulus operator
def sum_3_5(limit):
sum = 0
for x in range(1, limit):
if x % 3 == 0:
sum += x
elif x % 5 == 0:
sum += x
return sum
limit = input('What is the limit? ')
limit = i... |
import math
def is_square(n):
if n< 0:
return False
else:
if int(math.sqrt(n) + 0.5) ** 2 == n:
return True
else:
return False
'''
import math
def is_square(n):
if n < 0:
return False
sqrt = math.sqrt(n)
return sqrt.is_integer(... |
def parseData(self, data_s, numberOfArraySlots, separationChar = "."):
s_len = len(data_s) # Number of characters in the string
l = 0 # Index for the data array
entry = "" # The entry that we are pushing into the array
if numberOfArraySlots == 2:
data_arr = ["a", "b"] # Arra... |
import random, math, cards
from cards import Color
class Board():
def __init__(self, num_players):
"""
Constructs a new board
:param num_players: The number of players (Currently can only be 2-4)
:type num_players: int
"""
num_victory_cards = 4 + math.ceil(float(num_players) / 2) * 4
sel... |
num_1 = int(input())
num_2 = int(input())
print(num_1 + num_2)
print(num_1 - num_2)
print(num_1 * num_2)
|
#%% import necessary modules
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
import pdb
##Q1a
x_year= np.array([2005,2006,2007,2008,2009])
y_sales= np.array([12,19,29,37,45])
model = linear_model.LinearRegression()
model.fit(x_year.reshape(-1,1),y_sales.reshape(-1,1))
pri... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm
#%% Q1 Matrix multiplication
print("Question 1 **************************************")
A = np.array([
[2, 8, 4],
[5, 4, 2]])
B = np.array([
[4, 1],
[6, 4],
[5, 3]])
C = ... |
from stream import Stream
DITTO = "DITTO"
class Token(object):
def __init__(self, purpose, text, line, character):
self.purpose = purpose
self.text = text
self.line = line
self.character = character
def __repr__(self):
if self.text != "":
return "<%s:%s>" ... |
class Stream(object):
def __init__(self, string):
self.string = string
self.index = 0
self.line_stack = []
self.position_stack = []
def set_index(self, n):
while self.line_stack and self.line_stack[-1][0] > n:
self.line_stack.pop()
while self.positio... |
#subroutine to calculate number of stops between two stops on the victoria line
def victoria_line():
victoria = ["Brixton", "Stockwell", "Vauxhall", "Pimlico", "Victoria", "Green Park", "Oxford Circus","Warren Street", "Euston","King's Cross","Highbury & Islington", "Finsbury Park","Seven Sisters","Tottenham Hale", "... |
import pygame
import colors
class Tile:
"""A tile with x and y position"""
def __init__(self,x,y,z, color) -> None:
self.x = x
self.y = y
self.z = z
self.color = color
def allow_fall(self,snake):
return False
def allow_through(self,snake):
return False
... |
from random import choice
# Implements strategies the bot player might choose
def random_strategy(state):
"Returns a random card from the hand"
return choice(hand(state))
def near_treasure_strategy(state):
"Returns one of the three cards nearest the treasure"
treasure = state['turns'][0]['treasure']
... |
# EP-de-soft-eduardo-e-theo
Lista_de_produtos = {}
Escolha = int(input('''0 - Sair
1 - Adicionar item
2 - Remover item
3 - Alterar item
4 - Imprimir estoque
Faça sua escolha:'''))
while Escolha != 0:
if Escolha == 1:
Produto = input(... |
from Livro import Livro
from Autor import Autor
from Pilha import Pilha
linha = "---------------------------"
autor1 = Autor(1, "Fernando")
autor2 = Autor(2, "Pittacus")
autor3 = Autor(3, "Jay")
autor1.print()
autor2.print()
autor3.print()
print(linha)
book1 = Livro(1, "O caçador", autor1)
book2 = Livro(2, "Unidos... |
#!/usr/bin/env python3
from planegeometry.structures.points import Point
from planegeometry.algorithms.geomtools import orientation
class GrahamScan1:
"""Graham's scan algorithm for finding the convex hull of points.
https://en.wikipedia.org/wiki/Graham_scan
"""
def __init__(self, point_list):
... |
class Zaman:
def __init__(self, tarih):
self.gun, self.ay, self.yil = map(int, tarih.split('/'))
def __str__(self):
return "{gun} / {ay} / {yil} ".format(**self.__dict__)
def __sub__(self, other):
return self.yil-other.yil
def kalan_zaman(self,other):
pass
if __n... |
# def carpma(say,say2):
# return say *say2
#
#
#
# a = lambda say,say2:say*say2 #Yukarıdaki kod ile aynı işlevi görür.
# print(a(10,15))
#
# b = lambda deger:deger #Fonksiyon kullanmak yerine lambda kullanmak bazen daha cazip gelebilir.
# print(b("Örnek"))
#
# def sayi_dondur():
# for say in range(1,10):
# ... |
test_degiskeni = "Bu bir test değişkenidir"
print(test_degiskeni.upper()) #String değerlerini büyük harf yapar.
print(test_degiskeni.lower()) #String değerlerini küçük harf yapar.
print(test_degiskeni.capitalize()) #String değerinin ilk karakterini büyük harf yapar.
print(test_degiskeni.split()) #String değerindeki bo... |
minutes = 42
seconds = 42
seconds_in_a_minute = 60
total_seconds = (minutes * seconds_in_a_minute) + seconds
print(total_seconds)
|
data = """
INDIA
Runs:231, Wickets:3, Overs:50
ENGLAND
Runs:187, Wickets:10, Overs:50
BANGLADESH
Runs:220, Wickets:8,Overs:50
AUSTRALIA
Runs:250,Wickets:9, Overs:50
"""
COUNTRY_NAME : {"Runs":int, "Wickets":int,"Overs":int}
d1 = {"Runs": 231, "Wickets": 3, "Overs": 50}
d2 = {"Runs": 187, "Wickets": 10, "Ove... |
'''
题目:暂停一秒输出。
程序分析:使用 time 模块的 sleep() 函数。
'''
import time
a = {1: 1, 'a': 'fff', 'd': '2'}
for key in a:
print(a[key])
time.sleep(1)
print('bye') |
import difflib
import csv as csv
INPUT_PATH = "C:/Users/Divya moorjaney/Documents/FIS ADA/CompareCSV/"
def comparecsv(sqlfile, scalafile, split):
d = difflib.Differ()
sql_open = open(INPUT_PATH + sqlfile, 'r') # open file
sql_colcount = len(sql_open.readline().strip().split(split)) # get col counts ##... |
while True:
x = input("수를 입력하세요:")
try:
x = int(x)
sum = 0
for i in range(1, x + 1):
if i % 3 == 0:
sum += i
print("1부터 ", i, "까지 3의 배수의 합 : ", sum)
break
except Exception as e:
print("정수가 아닙니다. 다시 입력하세요.")
|
# 함수의 정의
def dummy(): # 구현부가 없을때
pass
def none(): # return만 하면 None이 반환
return
def times(a, b):
return a * b
dummy()
print(none()) # None
print(times(10, 20))
# 함수 자체도 객체
fun = times # 심볼로 할당
print(type(fun))
print(callable(fun))
if callable(fun): print(fun(10, 20))
# 함수의 return
def bigger(a, b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.