text stringlengths 37 1.41M |
|---|
#writes False if any one of them is greater than or equal to the sum of the other two and True
#otherwise.
# (Note: This computation tests whether the three numbers could be the lengths of the sides of
# some triangle.)
#--------------------------------------------------------------------------------------------------... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 19 09:23:33 2018
@author: joykumardas
program.py
"""
def main():
folder = get_folder_from_user()
if not folder:
print("Sorry we cant search that location.")
return
text = get_search_text_from_user()
if not text:... |
import tkinter as tk
import requests
from bs4 import BeautifulSoup
url = 'https://weather.com/en-IN/weather/today/l/32355ced66b7ce3ab7ccafb0a4f45f12e7c915bcf8454f712efa57474ba8d6c8'
root = tk.Tk()
root.title("Weather")
root.config(bg = 'white')
def getWeather():
page = requests.get(url)
soup = Be... |
num=int(input("enter any Number"))
rev =0
while num>0 :
Rem = num% 10
num = num//10
rev=rev*10+Rem
print("The Reverse of the number",rev)
|
#this code gives the numbers of integers, floats, and strings present in the list
a= ['Hello',35,'b',45.5,'world',60]
i=f=s=0
for j in a:
if isinstance(j,int):
i=i+1
elif isinstance(j,float):
f=f+1
else:
s=s+1
print('Number of integers are:',i)
print('Number of Floats are:',f)
prin... |
# Decision Tree Regression tutorial from Machine Learning A-Z - SuperDataScience
# Input by Ryan L Buchanan 23SEP20
# Import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:-1].values
y = dataset.ilo... |
import pygame
from pygame.locals import *
WIDTH = 600
HEIGHT = 300
WINDOW_DIMENSIONS = (WIDTH, HEIGHT)
WHITE = pygame.Color('white')
BLACK = pygame.Color('black')
# some variables to define an oscillating circle
RADIUS = 50 # circle radius, pixels
LINEWIDTH = 1 ... |
#! /usr/bin/python
#
# Simple Roman Merels engine (to be used in a pygame application)
# http://gwydir.demon.co.uk/jo/games/romgame/index.htm
#
__author__ = 'ericdennison'
import random
import re
from consoletictactoe import TTTPosition
class MerelsPosition(TTTPosition):
"""
Representation of a Merels board... |
import pygame
from pygame.locals import *
from pygameapp import PygameApp
from circle import Circle
class MyApp(PygameApp):
"""
Custom version of PygameApp, to display moving circle
"""
def __init__(self, screensize = (400,400)):
"""
Application initialization is executed only ONCE!
... |
def ContientE(mot):
if "e" in mot : return True
return False
def NbE(mot):
nbE=0
for i in mot:
if i=="e": nbE+=1
return nbE
def ContientLettre(mot, lettre):
for i in range(len(mot)) :
if mot[i]==lettre:
print("La lettre",lettre,"se trouve la position",str(i+1))
... |
# Name: Ryan Menow
# Date: 12/06/2020
# Course: CSCI 330 - Programming Languages
# Professor: William Killian
# Assignment: MU Calculator
# Description: Implement a calculator using Python!
# This includes implementing the lexical analyszer, expression parser and evalutor.
import ply.lex as lex
import ply... |
string = input("Enter sentence to encrypt: ")
shift = int(input("Enter value to shift characters by: "))
stringl = string.split()
wordList = []
i = 0
for word in stringl:
wordList.append([])
for letter in word:
x = ord(letter)
if x in range(97, 123):
x += shift
if x > 122:
x = 96 + (x - 12... |
bDay = input("Enter your birthdate (dd/mm/yyyy): ").split("/")
b = int(bDay[0])
a = int(bDay[1])
c = int(bDay[2]) % 100
d = int(bDay[2]) // 100
if a <= 10:
a -= 2
else:
a += 10
c -= 1
w = (13 * a - 1)//5
x = c // 4
y = d // 4
z = w + x + y + b + c - 2 * d
r = z % 7
dayList = ["Sunday", "Monday... |
n = int(input("Enter your number: "));
a = 1;
x = 0;
y = 1;
def getFibo(x, y, a, n):
z = 0
if a <= n:
z = x + y;
a += 1;
return getFibo(y, z, a, n);
else:
return x;
print(getFibo(x, y, a, n)); |
while True:
num = int(input("Enter your integer: "))
if num **0.5 > 998537:
print("Number entered is out of range (max is 9900000000000)") #Actually limit can be higher but eh...
else:
break
f = open("primes1000000.txt", "r")
primes = f.read().split()
f.close()
def checkPrime(num, primes):
if s... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 10:13:21 2019
@author: Administrator
"""
## CODE FOR MINES IMPLEMENTATION
def dump(game):
"""Print a human-readable representation of game.
Arguments:
game (dict): Game state
>>> dump({'dimensions': [1, 2], 'mask': [[False, False]], 'board': [['... |
from typing import ByteString, Dict, Iterable, Mapping, Text
def decode_dict(data: Dict[bytes, bytes]) -> Dict[str, str]:
"""
Recursively decode all byte-strings found in a dictionary
"""
ret = {}
for key, value in data.items():
if isinstance(key, ByteString):
key = key.decode(... |
#!/usr/bin/python
import Tkinter as tki
import os
import tkMessageBox
# http://stackoverflow.com/questions/14771380/how-do-i-make-the-program-wait-for-an-input-using-an-entry-box-in-python-gui
# Frame for displaying abstract and evaluation
class Questionnarie(tki.Frame):
def __init__(self, parent, readings, rati... |
def solution(expression):
answer = 0
# 연산자 우선 순위 모든 경우의 수
operators_all = [
('+','-','*'),('+','*','-'),
('-','+','*'),('-','*','+'),
('*','+','-'),('*','-','+')
]
# 배열로 변환
expression = expression.replace("*",',*,')
expression = expression.replace("+",',+,')
expre... |
from DB.connection import DataBase
import funtions
def menu():
print('-' * 20 + ' MENU ' + '-' * 20)
print('1 - Registrar nueva tienda')
print('2 - Crear nueva categoría')
print('3 - Agregar producto')
print('4 - Mostrar todos los productos por país')
print('5 - Mostrar el valor total de los pr... |
# Ανάδραση σε επιλογή κύκλου
'''
Να ζωγραφήσετε 100 τυχαίους κόκκινους κύκλους ακτίνας 10 pixel. Όταν επιλέγεται ένας από
τους κύκους να αντιδρά αλλάζοντας χρώμα.
'''
import tkinter as tk
import random
class App():
def __init__(self, root):
self.root = root
self.root.title('canvas_1')
sel... |
# εφαρμογή contacts v.0 χωρίς μόνιμη αποθήκευση
import os
import random
class Contact():
''' κλάση επαφών με όνομα και τηλέφωνο
μια μεταβλητή κλάσης theContacts'''
theContacts = {}
def list_contacts(term = ''):
for c in sorted(Contact.theContacts, key=lambda x : x.split()[-1]):
... |
# Animation show 1
import tkinter as tk
import time
import random
class ball(object):
def __init__(self, canvas, *args, **kwargs):
self.canvas = canvas
self.id = canvas.create_oval(*args, **kwargs)
self.vx = random.randint(1,5)
self.vy = random.randint(1,5)
def move(self):
... |
'''Find the largest palindrome made from the product of two 3-digit
numbers. '''
numlist = []
# want the largest just go the other way to find the largest
def checkPalindrome(word): ##checks if its palindrome
word = str(word)
word = list(word)
length=len(word)
half = length//2
for k in range(half):
if... |
"""
Example demonstrating lazy evaluation.
"""
import time
from flexx import react
class DataProcessor(react.HasSignals):
@react.input
def raw1(n=0):
return float(n)
@react.input
def raw2(n=0):
return float(n)
@react.lazy('raw1')
def processed1(data):
pr... |
import os
import math
os.system('cls')
def get_average(data_list):
total_sum = 0
size = len(data_list)
for i in range(size):
total_sum += data_list[i]
return total_sum / size
def get_min(data_list):
return min(data_list)
def get_max(data_list):
return max(data_list)
def get_deviation(data_list):
average ... |
import os
os.system('cls')
#Python doesn't have a switch-case so a solution is to use a dict either in a function or class
def month(i):
switcher = {
1:"January",
2:"February",
3:"March",
4:"April",
5:"May",
6:"June",
7:"July",
8:"August",
9:"September",
10:"October",
11:"November",
12:"Decemb... |
import os
os.system('cls')
quote = input("What is the quote?")
person = input("Who said it?")
print(f"{person} says, \"{quote} \"") |
import os
from sys import argv
os.system('cls')
script, filename = argv
def read_datafile(filename):
txt = open(filename)
names_list = []
names_list = txt.read().split("\n")
names_sorted = sorted(names_list)
print(f"Last First Salary")
print("--------------------------------------")
#Splits... |
import os
import json
from urllib.request import urlopen
os.system('cls')
city = input("Where city are you in? ")
with urlopen(f"http://api.openweathermap.org/data/2.5/weather?q={city}&APPID=a7c64bcd3a79ce72e2f62695d35b7eed") as response:
source = response.read()
data = json.loads(source)
#JSON data is in Kelvin
... |
import math
import os
os.system('cls')
length = int(input("What is the length of the room in feet?"))
width = int(input("What is the width of the room in feet?"))
print(f"You entered dimensions of {length} feet by {width} feet")
area = length * width
print(f"The area is {area} square feet")
conversion_factor = 0.0929... |
#%%
import datetime
import math
#%%
class Pessoa:
def __init__(self, nome:str, sobrenome:str, data_de_nascimento:datetime.date):
self.nome = nome
self.sobrenome = sobrenome
self.data_de_nascimento = data_de_nascimento
@property
def idade(self) -> int:
return math.floor((dat... |
#%%
import datetime
import math
from typing import List
#%%
class Pessoa:
def __init__(self, nome:str, sobrenome:str, data_de_nascimento:datetime.date):
self.nome = nome
self.sobrenome = sobrenome
self.data_de_nascimento = data_de_nascimento
@property
def idade(self) -> int:
... |
# 17) Definir una clase padre llamada Vehiculo y dos clases hijas llamadas Coche y Bicicleta,
# las cuales heredan de la clase Padre Vehiculo.
# La clase padre debe tener los siguientes atributos y métodos
# Vehiculo (Clase Padre):
# -Atributos (color, ruedas)
# -Métodos ( __init__() y __str__ )
# Coche (Clase Hija ... |
# 10) Tarea: Iterar un rango de 0 a 10 e imprimir números divisibles entre 3
for i in range(10):
if i % 3 == 0:
print(f'Número divisible por 3: {i}') |
def count_distance(start, end, speed):
#semua perhitungan diubah kedetik
start = ((start[1] + (start[0] * 60)) * 60) + start[2]
end = ((end[1] + (end[0] * 60)) * 60) + end[2]
time = end - start
#10 menit pertama
distance = (10*60) * speed
time -= (10*60)
speed += 1
while time != 0:
#setiap 7 me... |
money = input("请输入红包金额")
num = money.count(".")
if num <= 1:
for i in money:
if i not in "1234567890.":
print("请输入数字!!")
exit()
if num == 1:
xsws = len(money) - (money.index(".")+1)
if xsws <=2:
money = float(money)
if money >= 0.01 and mo... |
import random
item_list = ['Rock', 'Paper', 'Scissor']
com_point = 0
player_point = 0
while True:
com_player = random.choice(item_list).lower()
player = input(' \n enter your choice: Rock, Paper, Scissor, Quit: ').lower()
if player == com_player:
print(' Tie')
print(' Point table: \n Co... |
#!/usr/bin/python3
import struct
import sys
def main():
if len(sys.argv) != 2:
print("error: missing argument", file=sys.stderr)
return 1
with open(sys.argv[1]) as file:
addr = 0
for line in file:
line = line.strip()
if line.startswith('//'):
... |
import pygame
class Snake:
def __init__(self, width, height, display, difficulty):
self.w = 12
self.h = 12
self.x = width / 2
self.y = height / 2
self.name = 'Hossein'
self.color = (0, 255, 255)
self.speed = 1.5 * difficulty
self.score = 0
s... |
#from items import *
from map import rooms
from gameparser import *
current_room = rooms["lobby"]
def age_verification(name):
while True:
try:
print("How old are you?")
player_age = int(input("..."))
if player_age < 0 or player_age > 100:
print("Pleas... |
import turtle
import os
BORDER_RIGHT = 600
BORDER_LEFT = 90
def setup_screen():
"""Create a main screen."""
window = turtle.Screen()
window.bgcolor("black")
window.title("Space Invaders")
_draw_border()
def _draw_border():
"""Draw border on the main window."""
border_pen = turtle.Turtle(... |
# 3.3 Organizing Lists
#3.3.1 Using sort() to sorting the list permenantly 使用方法sort() 对列表进行永久性排序
cars = ["bmw", "audi", "toyota", "subaru"]
cars.sort()
print(cars)
# 你还可以按与字母顺序相反的顺序排列列表元素,为此,只需向sort() 方法传递参数reverse=True
cars = ["bmw", "audi", "toyota", "subaru"]
cars.sort(reverse = True)
print(cars)
# 3.3.2 Using sor... |
python2.7
print "Hello Python 2.7 world!"
Hello Python 2.7 world!
# 在Python 2中,无需将要打印的内容放在括号内。从技术上说,Python 3中的print 是一个函数,因此括号必不可少。有些Python 2 print 语句也包含括号,但其行为与Python 3中
稍有不同。简单地说,在Python 2代码中,有些print 语句包含括号,有些不包含。
python2.7
>>> 3 / 2
1
# 在Python 2中,整数除法的结果只包含整数部分,小数部分被删除。请注意,计算整数结果时,采取的方式不是四舍五入,而是将小数部分直接删除。
在Pytho... |
#5.2 Condition test
#5.2.1
car = 'bmw'
car == 'bmw'
#5.2.2
car = 'Audi'
car == 'audi'
car = 'Audi'
car.lower() == 'audi'
#5.2.3
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
#5.2.4
age = 18
age == 18
answer = 17
if answer != 42:
print("That is not the ... |
#5-3 practice
#5-3 alien color #1
alien_color = 'green'
if alien_color == 'green':
print("You just received 5 points!")
alien_color = 'red'
if alien_color == 'green':
print("You just received 5 points!")
#5-4 alien color #2
alien_color = 'green'
if alien_color == 'green':
print("You just received 5 point... |
import re
'''Step 1: create the big occurences list'''
def occurenceslist_creator():
alfabet = 'abcdefghijklmnopqrstuvwxyz $'
occurenceslist = dict([(letter, []) for letter in alfabet]) #to create a dictionary with empty values with first letters as keys
for firstletter in occurenceslist.keys():
oc... |
"""
Module utility to define some utilities functions, like read data,
divide data in training and test set and so on.
"""
import csv
import numpy as np
def read_monk_data(file_path, train_dim=1.0, shuffle=False):
"""
Read data from Monk dataset to put as input in ML algorithms
Param:
... |
"""
Layer Module used to represent a layer of a NN
"""
import numpy as np
from activation_function import ActivationFunction
from learning_rate import LearningRate
import copy
class Layer:
"""
Layer class represent a layer in a NN
"""
def __init__(self, weights, learning_rates, ac... |
import random
HANGMAN_PICS = ['''
+---+
|
|
|
===''', '''
+---+
O |
|
|
===''', '''
+---+
O |
| |
|
===''', '''
+---+
O |
/| |
|
===''', '''
+---+
O |
/|\ |
|
===... |
import turtle
def draw_anyshape():
window = turtle.Screen()
window.bgcolor("red")
draw_square()
# draw_circle()
# draw_triangle()
window.exitonclick()
def draw_square():
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("green")
brad.speed(2)
count = 0
while count... |
import math
import pandas as pd
# x is defined as a list of data points or the mean depending on the defenition it's provided.
# z is the z-score primarly they z-score for the 95 or 98% (CI)
# x_bar is a sample mean withint the normal distribution
# n is the sample size for the normal distribution, excpet in the mid... |
class planet:
planets = dict()
def __init__(self, name, orbiter):
self.orbiters = []
self.orbits = None
if orbiter != None:
self.orbiters.append(orbiter)
orbiter.addOrbits(self)
self.planets[name] = self
self.name = name
def addOrbiter(self,... |
#!/usr/bin/env python3
import sys
import ast
import re
#input_file = "test.txt"
#input_file = "test2.txt"
input_file = "input.txt"
with open(input_file) as f:
data = f.read()
kws = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid"]
ecls = ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
def checkInput(... |
#!/usr/bin/env python3
import sys
input_file = 'test_input.txt'
input_file = 'input.txt'
#input_file = "test2.txt"
if len(sys.argv) > 1 :
input_file = sys.argv[1]
with open(input_file) as f:
data = f.readlines()
data = [d.strip() for d in data]
data = [d.split("->") for d in data]
cave = {}
def addCoord(... |
#!/usr/bin/env python3
import sys
input_file = 'test_input.txt'
input_file = 'input.txt'
if len(sys.argv) > 1 :
input_file = sys.argv[1]
with open(input_file) as f:
data = f.readlines()
data = [d.strip() for d in data]
var='a'
alphabets=[]
# starting from the ASCII value of 'a' and keep increasing the
# v... |
#!/usr/bin/env python3
import sys
input_file = 'test_input.txt'
input_file = 'input.txt'
if len(sys.argv) > 1 :
input_file = sys.argv[1]
with open(input_file) as f:
data = f.readlines()
data = [d.strip() for d in data]
# PART one
pointsDict = {
"A X": 4,
"A Y": 8,
"A Z": 3,
"B X": 1,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019/11/4 15:52
# @Author : YangYusheng
# @File : 前馈神经网络.py
# @Software: PyCharm
# coding:utf-8
import numpy as np
import pandas as pd
class NeuralNetwork():
# 随机初始化权重
def __init__(self):
np.random.seed(1)
self.synaptic_weights = 2... |
class cell():
"""A cell is a single unit of a sudoku puzzle. A sudoku puzzle is composed of 81 cells.
Initialize a cell with a list of possible answers that can be put in
an answer (if one exists), position in the sudoku puzzle, and whether or not
the answer has been selected for the box"""
def... |
#!/usr/bin/env python
import math
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-n", type=int, help = "total number of items to choose from")
parser.add_argument("-k", type=int, help = "number of items to choose")
parser.add_argument("-l", "--log", action="store_true", help = "returns the lo... |
import json
import os
import time
import random
def main():
# TODO: allow them to choose from multiple JSON files?
for file in os.listdir():
if file.endswith(".json"):
print (file)
json_file = input("Which file will you open? ")
with open("theGlassHouse1.json") as fp:
... |
/**
Plays song when it's time to wake up. Input required hour and minute from user and keeps the loop running until its time for alaram.
It requires path to any song or music file in computer system in order to play music.
**/
import time
import os
not_executed = 1
try:
hour = int(input("At what hour? "))
... |
'''
Matteo Gisondi, 1730913, Samuel Park, 1732027, Ali Tahmasebi, 1730131
Friday, May 24
R. Vincent, instructor
Final Project
'''
from Piece import Piece
import numpy as np
class Player():
'''keep track of piece positions and color of pieces'''
DIM = 8 # dimensions of a standard board
def __init__(self,... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Date 2015/10/31
# By Charlotte.HonG
# unix_mid_test_05
import random
# 演算法
# def insertion_sort(lst, start, end):
# if len(lst) == 1:
# return
# for i in xrange(start + 1, end + 1):
# temp = lst[i]
# j = i - 1
# whi... |
# 0 - 4
for i in range(5):
print("i = ", i)
# 2 - 4
for i in range(2, 5):
print("i = ", i)
|
# > : Greater than
# > : Less than
# >= : Greater than or equal to
# <= : Less than or equal to
# == : Equal to
# != : Not equal to
drink = input("Pick one (Coke or Pepsi) : ")
if drink == "Coke":
print("Here is your Coke")
elif drink == "Pepsi":
print("Here is your Pepsi")
else:
print("Here is your water... |
# print(type("3"))
# print(type('3'))
# print(type('''3'''))
samp_string = "This is a very important string"
print("Length: ", len(samp_string))
print(samp_string[0])
print(samp_string[-1])
print(samp_string[0:4]) #till 4th non inclusive
print(samp_string[8:])
print("Every other", samp_string[0:-1:2]) # Start from th... |
# Import the os and reading CSV modules
import os
import csv
# Path to CSV file
csvpath = os.path.join('Resources', 'budget_data.csv')
# Reading using CSV module
with open(csvpath, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
# Skip the header
header = next(csvreader)
# Ini... |
import csv
import os
raw_data = open('budget_data.csv')
csv_reader = csv.reader(raw_data, delimiter=',')
file_heders = next(csv_reader)
print(F"Hearder: {file_heders} ")
count_months = 0
total = 0
previousvalue = 867884
total_changes = 0
G_increase = 0
G_decrease = 0
for row in csv_reader:
count_months += ... |
########################################################################
# USER STORY:
# When you take a pic of your signature
# but the background is not entirely white
# you can "python Set_Background_White YOUR_SIGNATURE_FILE" to turn the background white
# GIVEN that your signature is somewhat black or dark color
#... |
"""
简易计算器
"""
class Count:
result_msg = ''
'''
加法运算
'''
def add(self, value: int):
self.result_msg += '+' + value.__str__()
'''
减法运算
'''
def subtract(self, value: int):
self.result_msg += '-' + value.__str__()
'''
乘法运算
'''
def multip... |
def mas_repetido(matriz):
pass
def condensa(cadena):
if cadena:
ocurrencias = 0
i = 0
lista = []
while len(cadena) > 0:
ocurrencias += 1
while i + 1 < len(cadena) and cadena[i + 1] == cadena[i]:
ocurrencias += 1
i += 1
i = 0
lista.append((cadena[0], ocurrencias))
cadena = cadena.replac... |
#imports everything from the random module. This allows program to select random integers.
from random import *
#Creates min and max variables. Min variable will be between 0 and 10 (not including 10). Max variable will be between 11 and 21 (not including 21).
min = randrange(10)
max = randrange(11,21)
#Creates a ran... |
#!/usr/bin/python
from random import *
x = 0
i = 0
while True:
x = randint (1, 6)
print (x)
i = i+1
if x == 3:
print ('salio 3! en el intento', i)
break
|
if __name__ == '__main__':
T = int(input())
alphabet_dict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10, 'k':11, 'l':12,
'm':13, 'n':14, 'o':15, 'p':16, 'q':17, 'r':18, 's':19, 't':20, 'u':21, 'v':22, 'w':23,
'x':24, 'y':25, 'z':26}
for _ ... |
if __name__ == '__main__':
N = int(input())
S = str(input())
count_a, count_e, count_h, count_r = S.count('a'), S.count('e'), S.count('h'), S.count('r')
count_c, count_k, count_t = S.count('c'), S.count('k'), S.count('t')
min2x = min(count_a, count_e, count_h, count_r)
minx = min(count_c, coun... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 5 18:15:36 2020
@author: huybv1998
"""
n = int(input("nhap 1 so n : "))
sum1 = 0
for i in range(1, n):
if (n % i == 0):
sum1 += i
if (sum1 == n):
print("so n la so hoan hao")
else:
print("so n la so ko hoan hao")
|
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 22 23:22:39 2020
@author: huy
"""
A = []
B = []
n = int(input("Nhập 1 số n: "))
for i in range(0, n):
if (i % 2 == 0):
A.append(i)
if (i%2):
B.append(i)
print(A)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 28 23:59:37 2020
@author: huybv1998
"""
import random
N = int(input("Nhập số N: "))
A = list(range(N))
random.shuffle(A)
print(A)
|
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 31 01:22:37 2020
@author: huybv1998
"""
import math
def calculateArea(a, b, c):
p = (a + b + c)/2
S = math.sqrt(p*(p-a)*(p-b)*(p-c))
ha = S/(0.5*a) #Chỗ này đề bài bị sai
hb = S/(0.5*b) #Không phải là 2*a mà là 0.5*a
hc = S/(0.5*... |
import sys
from math import sin, cos, sqrt, atan2, radians
def Distance(lat1, lon1, lat2, lon2):
R = 6371.0
lat1 = radians(lat1)
lon1 = radians(lon1)
lat2 = radians(lat2)
lon2 = radians(lon2)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = abs(sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(... |
import sys
for row_column in sys.stdin:
row, column = row_column.split()
row = int(row)
column = int(column)
element = [[None]*column for i in range(row)]
answer = [[None]*row for i in range(column)]
# print(element)
for row_number in range(0, row):
element[row_number] = sys.stdin.r... |
#!/usr/bin/env python
# coding: utf-8
# <H1>WATER JUG PROBLEM USING BFS & DFS<H1>
# Given Problem: You are given a m liter jug and a n liter jug where $0 < m < n$. Both the jugs are initially empty. The jugs don't have markings to allow measuring smaller quantities. You have to use the jugs to measure $d$ liters of w... |
### neural network model for predicting handwritten digits
### using MNIST datasets
### tutorials from tensorflow.org
# load the datasets
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('../data/', one_hot=True)
# import tensorflow library
import tensorflow as tf
# graph ... |
"""
This module contains helper functions
for text processing
"""
import sys
import re
def preprocess_human(text):
"""
Adds new lines before all headers
in order to make the text more readable
"""
text = re.sub('\n', '', text) # Get rid of the old new lines that I'd put in
header_patterns = [r'... |
#Nand gate
class Gate(object):
""" class representing a gate. It can be any gate. """
def __init__(self, *args):
""" initialise the class """
self.input = args
self.output = None
def logic(self):
""" the intelligence to be performed """
raise NotImplemen... |
phone = input('Phone: ')
numbers = { #defining dictionary
'1': 'one', #dont forget the commas at the end
'2': 'two',
'3': 'three',
'4': 'four',
'5': 'five',
}
phone_number = ''
for x in phone:
numbers.get(x)
phone_number = phone_number + ' ' + numbers.get(x, '!!') # added '!' value not to have 'NONE error'
prin... |
my_name = 'Python' #문자열 (사람을 위한 텍스트를 프로그래머가 부르는 방법)
my_age = 2019 - 1994 #숫자
print(my_name, '응 어제', my_age, '살')
my_next_age = my_age + 1
print('내년에는', my_next_age, '살')
multiply = 9 * 9 # = 81
divide = 30 / 5 # = 6
power = 2 ** 10 # = 1024
reminder = 15 % 4 # = 3
print(multiply, divide, power, reminder)
text = ... |
# Get Starbucks from cities
'''
This file retrieves latitude/longitude pairs for all Starbucks in each of the
cities available in the data, and saves to a csv. This data is used to construct
the "Starbucks index" of average minimum distance necessary to find another Starbucks
in each city.
Usage: Call get_all_starbuc... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 27 09:53:12 2017
@author: pesu
"""
'''
Python program that outputs a list of n-grams represented as string and a
dictionary containing n-gram and its count as key-value pairs.
'''
from nltk import word_tokenize
file_content = open("in1.txt").re... |
# Programming Exercise 15
# 15 Find a sudoku puzzle. Write a program to solve it.
class Block:
def __init__(self, data):
self.block = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
def getPos(self, num):
return self.block[num]
class Board:
def __init__(s... |
import Rental
import Movie
class Customer:
def __init__(self, name):
self.Name = name
self.Rentals = []
def addRental(self, arg):
self.Rentals.append(arg)
def getName(self):
return self.Name
def statement(self):
totalAmount = 0
frequentRenterPoints = 0... |
#!/usr/bin/env python3
"""
Author: Wing Yu Chung
Given: A positive integer n≤7.
Return: The total number of permutations of length n, followed by a list of all such permutations (in any order).
"""
#Import statements
from sys import argv
from itertools import permutations
def read_file(filetxt):
... |
#!/usr/bin/env python3
"""
Author: Wing Yu Chung
Given: A DNA string s (of length at most 1 kbp) and a collection of substrings of s acting as introns.
All strings are given in FASTA format.
Return: A protein string resulting from transcribing and translating the exons of s.
(Note: Only one solution will exist fo... |
'''
#Bài 1
name = input("Nhap vao ho va ten: ")
print("Ten cua ban la: " + name[0:])
print("In nguoc ten cua ban: " + name[::-1])
print("-----------------------------------------")
#Bài 2
long = input("Nhập vào tên của Long :")
tuyen = input("Nhập vào tên của Tuyến :")
if len(long) < len(tuyen):
print(tuyen +" là b... |
import sys
import random
def generate_markov(input):
out = dict()
for line in input:
line = line.lower()
words = line.replace("\n", "").split(" ")
for i in range(len(words)-2):
key = words[i]+" "+words[i+1]
val = words[i+2]
if key in out.keys():
out[key].append(val)
else:
out[key] = [val]
... |
def preOrder(root):
preorder_list = []
# VISIT NODE THEN LEFT THEN RIGHT
def traverse(node):
preorder_list.append(node.info)
if node.left is not None:
traverse(node.left)
if node.right is not None:
traverse(node.right)
traverse(root)
for num in preord... |
def cube(x): return x ** 3
def fibonacci(n):
list = []
for i in range(0, n):
if i == 0:
list.append(0)
elif i == 1:
list.append(1)
else:
list.append(list[i-1] + list[i-2])
return list
if __name__ == '__main__':
n = int(input())
print(l... |
import math
class Points(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __sub__(self, O):
x = self.x - O.x
y = self.y - O.y
z = self.z - O.z
return Points(x, y, z)
def dot(self, O):
x = self.x * O.x
y = s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.