text stringlengths 37 1.41M |
|---|
import datetime
name = input('ENTER YOUR NAME HERE:- ')
hour = int(datetime.datetime.now().hour)
if hour>=0 and hour<12:
print(f'GOOD MORNING {name}')
elif hour>=12 and hour<17:
print(f'GOOD AFTERNOON {name}')
else:
print(f'GOOD EVENING {name}')
passward = int(input('ENTER THE PASSWARD TO ACCESS THE SYSTEM:-' ))... |
# Take Inputs:
a = int(input('Enter the value of a: '))
b = int(input('Enter the value of b: '))
c = int(input('Enter the value of c: '))
#get the roots
d = (b*b - 4*a*c)**0.5
x1 = (-b + d)/(2*a)
x2 = (-b - d)/(2*a)
print('\r\nthe root of a quadratic equation ARE:')
print('x1: {0}'.format(x1))
print('x2: {0}'.format(... |
from random import *
class PlayerController:
def __init__(self):
self._currentPlayer = 1
self._currentPlayerType = "human"
self._playerIdentity = 0
self.mode = "human"
# generate random player number
def chooseFirst(self):
se... |
print("주문 가능한 메뉴:")
menu_list=['햄버거','샌드위치','콜라','사이다']
print(menu_list)
a=int(input("메뉴번호(0-3):"))
b=int(input("개수:"))
print("선택된 메뉴:",menu_list[a])
if a==0:
price=3000
elif a==1:
price=2000
elif a==2:
price=1000
elif a==3:
price=1000
print("총가격:%d"%(price*b))
|
"""
문제: 정수의 각 자리수의 합을 출력하라
입력 예)
정수:546
출력 예)
자리수의 합: 15
"""
a=int(input("정수:"))
b=0
while a>0:
c=a%10
b=b+c
a=a//10
print("자리수의 합:%d" %b)
a=int(input("정수:"))
sum=0
while a>0:
b=a%10
a=a//10
sum=sum+b
sum=sum+a
print(sum) |
import operator
from time import sleep
from typing import Any, List
def wait_for_assert(expected_data: Any,
function: (),
message: str='',
retries: int=5,
delay_sec: int=1,
oper=operator.eq,
excepti... |
from helpers import get_data
from typing import List
def unique_letters_in_strings(strings: List[str]) -> int:
return len(set("".join(strings)))
def all_shared_letters_in_strings(strings: List[str]) -> int:
if not strings:
return 0
start_set = set(strings[0])
return len(start_set.intersectio... |
from collections import namedtuple
from typing import Iterable
from itertools import tee
InputLine = namedtuple("InputLine", ("low", "high", "letter", "password"))
def is_password_valid(low: int, high: int, letter: str, password: str) -> bool:
return low <= password.count(letter) <= high
def is_password_valid_... |
def chooseoption():
hotelsize = input("""
please select your hotel size by choosing a number
1 small
2 medium
3 big
or if you would like to continue your last hotel type 'start'
""")
print(hotelsize)
if hotelsize == 'start':
hotelsize = input("""
plea... |
def lastfirst(lst):
fname = list()
lname = list()
for name in lst:
nameV = name.split(',')
fname.append(nameV[1])
lname.append(nameV[0])
print('First name: ' , fname)
print('Last name: ', lname)
allnames = list()
allnames.append(fname)
allnames.append(lname)
... |
# -*- coding: utf-8 -*-
"""
Herman Sanghera
October 26, 2019
CodingBat Solutions (Python)
This is a python file containing my own solutions to the
different Python Warmup-2 exercises on codingbat.com
"""
"""
Warmup-2 > string_times:
Given a string and a non-negative int n, return a larger string
that i... |
lista=["Luis","Maria","Cecy","Beto"]
print(lista[:])
#añadir elementos a la lista
lista.append("Isma")
print(lista[:])
lista.extend(["Gordo","Eve"])
print(lista[:])
print(lista.index("Luis"))
print("Luis" in lista)
lista.extend(["Luis","Pedro"])
print(lista[:]) |
import itertools
my_list = ['a','b','c']
combinations = itertools.combinations(my_list, 3)
for c in combinations:
print(c)
# permutations = itertools.permutations(my_list, 3)
# for p in permutations:
# print(p) |
def permutations(word):
if len(word) == 1:
return [word]
else:
# get all permutations
perms = permutations(word[1:])
char=word[0]
result=[]
for perm in perms:
for i in range(len(perm) + 1):
p = perm[:i]+char+perm[i:]
if p not in result:
result.append(p)
return result
print(permutations(... |
age =int(input('请输入你的年龄:'))
subject =input('请输入你的专业:')
college =input('是否是重点大学:')
if age > 25 and subject == '电子工程专业':
print('面试成功')
elif college == '是' and subject == '电子信息工程专业':
print('面试成功')
elif age < 28 and subject == '计算机':
print('面试成功')
else:
print('不符合面试要求')
|
print('请输入(中心,音乐模块,微信支付模块)')
while True:
a = input('输入:')
if a == '中心':
print('您的分数为:35')
elif a == '音乐模块':
print('您的分数为:30')
elif a == '微信支付模块':
print('您的分数为: 40')
else:
print('输入有误')
break
|
a = int(input('请您输入一个年份'))
if (a%4==0 and a%100!=0) or a%400==0:
print('这个年份是闰年')
else:
print('这个年份是平年')
|
a = int(input('输出花的朵数'))
if a == 1:
print('你是我的唯一')
elif a == 3:
print('I Love You')
elif a == 10:
print('十全十美')
elif a == 99:
print('天长地久')
elif a == 108:
print('求婚')
elif a == 999:
print('土豪')
else:
print('掏钱吧')
|
import random
class Die:
# constructor
def __init__(self, sides=2, value=0):
# can't have a 1 sided die...
if not sides >= 2:
raise ValueError("Must have at least 2 sides")
# can't have letters either...
if not isinstance(sides, int):
raise ValueError("S... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#===============================================================
l = list(range(2000,3200+1))
#print(l)
for number in l :
#print(number)
isDivided = (number%7)
fiveDivided = number%5
if isDivided == 0 and fiveDivided != 0:
print(number)
# In[ ]:... |
months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
]
num_of_month = int(input('Enter number of month (1-12): '))
print('Name of month: ' + str(months[num_of_month - 1]))
|
firstName = input('Enter first name: ')
lastName = input('Enter last name: ')
print('------------------------------------------------')
print('Greetings! Hello Mr. ' + firstName + ' ' + lastName)
print('------------------------------------------------')
|
# program to replace {} with user provided input.
# Ex:
# Today is {} and it is a happy day! <- Monday, Tuesday, wednesday etc.
inp_str = input('Enter a string with {}: ')
inp_repl = input('Enter a replacement variable: ' )
index = inp_str.find('{}')
if index >= 0:
ret_str = inp_str[:index] + inp_repl + inp_s... |
class Solution:
def Fibonacci(self, n):
# write code here
if n == 0:
return 0
elif n == 1:
return 1
else:
return self.Fibonacci(n - 1) + self.Fibonacci(n - 2)
if __name__ == '__main__':
n = 10
s = Solution()
print(s.Fibonacci(n)) |
# Tuple is similar to list, but it is immutible.
fruits = ('Apple', 'Banana', 'Grapes', 'orange')
# fruits[1] = 'Mango' // Not Possible will get TypeError: 'tuple' object does not support item assignment
print(fruits[1])
print(fruits[2:10])
print(fruits[:2])
print(fruits[3:])
# Tuple/list slicing
numbers = [1, 4, 6, ... |
w = float(input('Enter your Weight in Kg: '))
h = float(input('Enter your height in meter: '))
def getBMIVal(weight, height):
return weight/height**2
print('Your BMI value is : ', getBMIVal(w, h)) |
# CMPM146 - Game AI
# P1 - Dijkstra's in a Dungeon
# By: Sean Song and Hana Cho
from p1_support import load_level, show_level, save_level_costs
from math import inf, sqrt
from heapq import heappop, heappush
def dijkstras_shortest_path(initial_position, destination, graph, adj):
""" Searches for a minimal cost pa... |
import random
choices = ['rock', 'scissors', 'paper','0']
exitGame = False
while(exitGame == False):
computer_choice = random.choice(choices)
user_choice = None
while user_choice == None:
print("\n############# ROCK PAPER SCISSORS ###########")
print("## TYPE 'rock', 'paper', 'scissors' OR '0' TO EXIT ##########... |
def get_surface_radius() -> float:
""" Function for input from user radius of surface """
print(" Введите радиус поверхности( дробная часть отделяется точкой")
print(" Пример: 1.001")
radius = input(" ")
try:
res = float(radius)
except:
print(" Введите правильные данные")
... |
from PIL import Image #@UnresolvedImport
import pdb
import numpy as np
from roslib.msgs import EXT
'''
im.transform(size, AFFINE, data, filter) ⇒ image
Applies an affine transform to the image, and places the result in a new image with the given size.
Data is a 6-tuple (a, b, c, d, e, f) which contain the first tw... |
import sys
def replace_quotes(text):
flag = False
new_text = ''
for char in text:
if char == '\"':
if flag:
char = "''"
flag = False
else:
char = '``'
flag = True
new_text += char
return new_text
def... |
introduction=input("Enter something about yourself: ")
charCount=0
wordCount = 1
for x in introduction:
charCount+=1
if x ==" ":
wordCount+=1
print("Number of characters in the entered string: ",charCount)
print("Number of words in the entered string: ",wordCount) |
"""
Straws [dicebox 1.0]
Draw straws.
Author(s): Jason C. McDonald
"""
import random
class StrawBundle:
"""
A bundle of straws, one of which is short.
"""
def __init__(self, count=1, short=1, draws=0):
"""
Initialize a bundle of straws.
"""
# The number of straws in ... |
"""
class Person:
def __init__(self, name, height, weight):
self.name = name
self.height = height
self.weight = weight
def male(self):
print(f"{self.name} you are male!")
def female(self):
print(f"{self.name}you are female!")
ramesh = Person("Ramesh"... |
types_of_people = 10
binaries = 1
print("There is {} types of peoples out there , one who understand the binaries and another who can't".format(types_of_people))
print(f"binaries have two digits one is {binaries} and another is 0") |
import math
co = float(input('cateto oposto:'))
ca = float(input('cateto adjacente:'))
h = math.hypot(co, ca)
print('o comprimento da hipotenusa é {:.2f}'.format(h))
|
peso = float(input('Qual o seu peso? (KG)'))
alt = float(input('Qual a sua altura? (M)'))
imc = peso / (alt ** 2)
print(imc)
if imc < 18.5:
print('Voce está abaixo do peso')
elif 18.5 <= imc < 25:
print('voce eta no peso ideal')
elif 25 <= imc < 30:
print('voce esta com sobrepeso')
elif 30 <= imc < 40:
... |
velo = int(input('qual a velocidade do veículo em km/h:'))
if velo > 80:
print('VOCE FOI MULTADO !!!')
print('Multa no valor de R${}'.format((velo-80)*7))
else:
print('Situaçao normal') |
import csv
def numbers(s):
return any(i.isdigit() for i in s)
with open('ways_tags.csv') as f:
reader = csv.DictReader(f)
new_set = set()
for row in reader:
if row['key'] == 'street' and numbers(row['value']):
new_set.add(row['value'])
# The set cannot simply be printed, as the... |
sandwich = [["rye", "sourdough", "baguette"],
[["ham", "salami", "turkey"],
["swiss", "munster", "cheddar"]],
["mayo", "mustard", "tabasco"]]
print sandwich[0][1]
print sandwich[1]
print sandwich[1][0][0]
print sandwich[2]
print sandwich[1][1][2]
print sandwich[0][1]
city_info = {... |
import string
import random
s1 = string.ascii_lowercase
s2 = string.ascii_uppercase
s3 = string.digits
s4 = string.punctuation
length = input("Enter the length of the password: ")
if(not length.isnumeric()):
print("Please enter the valid length of the password")
else:
password = []
password.extend(s1)
... |
"""
This script looks in specified folder for files with either .prt.x or .asm.x extension, where x is an integer.
These file will be renamed by removing the .x parts.
- If multiple files map to the same name - the highest integer is used.
- If a file without the .x part already exists - it will be overwritten.
"""
... |
def reverseList(l):
l.reverse()
for i in l:
if type(i) == list:
reverseList(i)
return l
m = eval(input("Enter a list"))
print(reverseList(m)) |
h=int(input("Cuantos hombres estan inscritos"))
m=int(input("Cuantas mujeres hay inscritas"))
total=m+h
ph=(h*100)/total
pm=(m*100)/total
print("El total de alumnos inscritos son ",total)
print("EL porcenaje de hombre es de %.1f"%ph,"%")
print("EL porcenaje de mujeres es de %.1f"%pm,"%") |
from chromosome import Chromosome
from queue import PriorityQueue
import random
import math
class Population:
# Initializer for a population of different backpack
# configurations (Chromosomes)
def __init__(self, n):
# Desired population size is inputted by the user
... |
import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101) #to get same random number
df = pd.DataFrame(randn(5,4),['A','B', 'C','D','E'],['W','X','Y','Z'])
print(df)
print(df['W']) #Indexing DataFrame
print(type(df['W']))# type of Series
print(df.W) #avoid this but it work
print(d... |
#!/usr/bin/python2.7
'''
------# ! / usr /bin/env python
'''
#Validate valid order or non-order(reject) & Identify message type
import time
from six.moves import input
import os
clear = lambda: os.system('clear')
from threading import Timer
#Figure out how to make this do various things after time, not just print.
ti... |
#Sorteo para 5 personas, hay 3 premios
#OJO: una persona no puede ganar dos veces
from random import randint
pipol = ["Pepito", "Shitz", "Luis", "RoDi", "Filomeno"]
for sorteo in range(3):
ganador = pipol[randint(0,len(pipol)-1)]
print("Ganador", sorteo + 1,":", ganador)
pipol.remove(ganador)
|
""" 02 - Utilizando estruturas de repetição com variável de controle,
faça um programa que receba uma string com uma frase informada pelo usuário e
onte quantas vezes aparece as vogais a,e,i,o,u e mostre na tela,
depois mostre na tela essa mesma frase sem nenhuma vogal.
"""
from unidecode import unidecode #FUNÇÃO R... |
import random
def determine(num, guess):
cowbull = [0, 0]
#num = str(num)
#guess = str(guess)
for i in range(4):
if num[i] == guess[i]:
cowbull[0] += 1 #cow++
else:
for k in range(4):
if guess[i] == num[k] and k != i:
... |
for i in range(10):
if i % 2 == 0:
print("Aren't people who use tabs instead of spaces utterly loathsome?")
if i % 2 == 1:
print("I'd hate to be the sucker who has to fix this file's whitespace.")
#In some spots I've used 8 spaces, and in other spots I've used a tab
#If we want to change ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 21 11:36:26 2020
@author: Administrator
"""
length=float(input("Enter the length of Rectangle"))
breadth=float(input("Enter the breadth of Rectangle"))
area_of_rectangle=length*breadth
if length>breadth:
print("the area of rectangle is: ",area_of_rectangle)... |
from random import randint
class Gladiator:
def __init__(self, health, rage, damage_low, damage_high, name):
""" (int, int, int, int, str, int) -> Gladiator
Represents a Gladiator with the health, rage, the lowest
damage possible, and the highest damage possible"""
self.health = he... |
#Using ordered list of items, by starting the search at halfway, can discard greater/smaller set of values if item not found using pivot.
#Keep track of first and last points of the list to find mid point of list
#Divide and conqueror implementation
def binary_search(ordered_list, item):
first = 0
last = len(o... |
class HashTable:
def __init__(self):
self.size = 11 #arbitrary but use prime number to have easier time resolving collisions
self.keys = [None] * self.size #initialise list of keys of length size and using None values
self.values = [None] * self.size #initialise list of values corresponding... |
from random import randint
name = raw_input('enter your name:')
try:
f = open('game.txt','r')
except:
f = file('game.txt','w')
f = open('game.txt','w')
f.write('0 0 0')
f = open('game.txt','r')
#score = f.read().split()
#game_times = int(score[0])
#min_times = int(score[1])
#total_times = int... |
import json
with open('config.json') as json_data_file:
data = json.load(json_data_file)
#Gets compass bearing
def getCompassBearing():
destination = raw_input('destination = ')
return destination
#Returns the offset in between two cardinal points
def getDifference (cardinal1, cardinal2):
differenc... |
prenotazioni=[]
lettera_sì=[]
lettera_no=[]
while True:
dati_pren=input("Scrivi nome e cognome del partecipante: (Scrivi STOP per interrompere la lista) ")
if dati_pren=="STOP":
break
else:
prenotazioni.append(dati_pren)
richesta_lettera=input("Il partecipante deve ricever... |
#! /usr/bin/env python3
"""--- Advent of Code Day 22: Crab Combat ---"""
from typing import List, Deque, Tuple
from collections import deque
from itertools import islice
FILENAME = "day_22.txt"
def calculate_score(cards: Deque[int]) -> int:
score = 0
for i, n in enumerate(reversed(cards), 1):
score ... |
#lambda fn that multiply argument x with argument y
a=lambda x,y:x*y
print(a(4,2))
#fibonacci series to n
def fib(n):
b=[0,1]
any(map(lambda _:b.append(b[-1]+b[-2]),range(2,n)))
print(b)
n=int(input("Number"))
fib(n)
#multiply each number of list with a no
l=list(range(20))
l=list(map(lambda... |
import copy, itertools
def get_all_pairs(lst):
""" Get pairs of elements in the
list in all possible ways.
INPUT: list of N elements
OUTPUT: list of list of lists containing the pairs
Example: lst [0,1,2,3]
res = [ [[0,1], [2,3]],
[[0,2], [1,3]],... |
print("The area of CIRCLE is :",3.14*float(input())**2)
|
class F:
def __init__(self):
self.item = 0
G = F()
l = [1, 2, 3, G, 'h']
l.remove(G)
print(l)
|
import random
class RandomizedSet(object):
def __init__(self):
self.dic={}
self.nums=[]
def insert(self, val):
if val not in self.dic:
self.dic[val]=len(self.nums)
self.nums.append(val)
return True
return False
def remove(sel... |
def DisplayName(_name):
print(f"Votre nom est {_name}")
def DisplayFirstName(_firstname):
print(f"Votre nom est {_firstname}")
def DisplayFullName(_name,_firstname):
print(f"Vous vous appelez {_firstname} {_name}") if _name != "Bakashika" and _firstname !="Jessie" else print(f"Bonjour votre majesté {_firstname} {_... |
person_count = int(input("Please enter the number of people: "))
cake_count = int(input("Please enter the number of cake: "))
matrix = []
for i in range(0, person_count):
sub_matrix = []
str_row = input('Please enter row %d: ' % i)
str_row_item = str_row.split(' ')
for item in str_row_item:
sub_... |
import threading
class CoreNodeList:
def __init__(self):
self.lock = threading.Lock()
self.list = set()
def add(self,peer):
"""
Coreノードをリストに追加
"""
with self.lock:
self.list.add((peer))
print('Current Core List: ', self.list)
def remove(self, peer):
"""
離脱したと判断されるCoreノードをリストから削除
"""
with ... |
values = [[10000, 500], [9000, 600], [5000, 1000], [3000, 1200], [0, 1500]]
i = float(input("Enter an interest rate "))
def prv(ar, r, n):
return ar * ((1-(1+r)**-n)/r)
def pv(fv, r, n):
return fv / ((1+r) ** n)
def start(values, r):
output = []
num = 0
while num < len(values):
output.append(prv(v... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Auteur(s) : Dylan DE MIRANDA (dylandemiranda@gmail.com) & Alexy DA CRUZ (adacruz@geomtech.fr)
# Version : 0.1
# Date : 07/01/2021
# Thème du script : Losange vide : création d'un losange vide affiché à l'écran.
def auRevoir():
"""
affiche 3 sauts de ligne et Fin... |
from remaining_integer import RemainingInteger
def test_simple():
rem = RemainingInteger()
arr = [6, 1, 3, 3, 3, 6, 6]
assert rem.find_remaining_integer(arr) == 1
def test_middle_number():
rem = RemainingInteger()
arr = [1, 2, 3, 1, 3, 1, 3]
assert rem.find_remaining_integer(arr) == 2
def tes... |
import collections
def number_to_snapshot(number):
return ''.join(sorted(str(number)))
snapshot_to_count = collections.defaultdict(int)
n = 1
while True:
cube = n * n * n
snapshot = number_to_snapshot(cube)
snapshot_to_count[snapshot] += 1
if snapshot_to_count[snapshot] == 5:
target_snap... |
# name = "bilal"
# age = '23'
# is_new = True
# print(name,age,is_new)
# name = input('What is your name? ')
# color = input('What is your favourite color? ')
# print(name + 'Likes' + color)
# birth_year = input('birth year: ')
# print(type(birth_year))
# age = 2019 - int(birth_year)
# print(age)
# print... |
line = raw_input().split(" ")
n1 = float(line[0])
n2 = float(line[1])
n3 = float(line[2])
n4 = float(line[3])
average = (n1*2 + n2*3 + n3*4 + n4)/10;
print "Media: %.1f" % average
if (average >= 7.0):
print "Aluno aprovado."
elif(average < 5.0):
print "Aluno reprovado."
elif (average >= 5 and average < 7):
... |
even_numbers = 0
odd_numbers = 0
positive_numbers = 0
negative_numbers = 0
for i in range(0, 5):
number = float(raw_input())
if number % 2 == 0:
even_numbers += 1
else:
odd_numbers += 1
if number < 0:
negative_numbers += 1
if number > 0:
positive_numbers += 1
print ... |
a = int(raw_input())
b = int(raw_input())
if (b < a):
b, a = a, b
odd_sum = 0
for i in range(a+1, b):
if i % 2 == 1:
odd_sum += i
print odd_sum
|
values = raw_input().split(" ")
v1 = float(values[0])
v2 = float(values[1])
v3 = float(values[2])
print "TRIANGULO: %.3f" % ((v1 * v3)/2)
print "CIRCULO: %.3f" % (3.14159 * v3**2)
print "TRAPEZIO: %.3f" % ((v1+v2)*v3/2)
print "QUADRADO: %.3f" % (v2**2)
print "RETANGULO: %.3f" % (v1*v2)
|
salary = float(raw_input())
if salary >= 0 and salary <= 400:
money_earned = (salary * .15)
new_salary = salary + money_earned
percentual_increase = 15
elif salary > 400 and salary <= 800:
money_earned = (salary * .12)
new_salary = salary + money_earned
percentual_increase = 12
elif salary > 80... |
# Random password generator
# atleast 8 characters,
# atleast 1 uppercase letters
# atleast 1 lowercase
# atleast 1 numeric number
# atleast 1 special characters
import random
upper_char_A = ["A","B","C","D","E","F","G","H"]
lower_char_a = ["a", "b", "c", "d", "e", "f", "g", "h"]
special_char = ["!", "@", "... |
"""
Note generators
Copyright (C) 2012 Alfred Farrugia
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hop... |
a = [1,2]
# b = {a:1}
# # TypeError: unhashable type: 'list'
# print(b)
print(a.__hash__) # None
# print(hash(a))
'''
Traceback (most recent call last):
File "hashable_objects.py", line 7, in <module>
print(hash(a))
TypeError: unhashable type: 'list
'''
a = (1,2)
b = {a:1}
print(b)
print(a.__hash__) # None
pr... |
x = 0
while x < 10:
print('x is currently :', x)
x += 1
else:
print('All done!')
# Break continue and pass
x = 0
while x < 10:
print('x is currently :', x)
print('x is still less than 10 , adding 1 to x')
x += 1
if (x == 3):
print(' Hey x is equals 3!')
pass ## pass does... |
#1
def fun(name,age):
print(f'{name}在{2018+100-age}年为100岁')
fun('xuzhiqian',17)
#2
def fun():
n = int(input("请输入整数"))
if n%2 == 0:
print('偶数')
elif n%2 ==1:
print('奇数')
else:
print('请输入整数')
fun()
#3
def fun(ls):
flag = 0
for i in ls:
if i=='':
f... |
# -*- coding:utf-8 -*-
# &Author AnFany
# 计算自定义精度的任意正实数的算数平方根:直接法,二分法,牛顿迭代法,数对比值法(未实现),
import big_number_product as b_p # 大数乘法
import big_number_division as b_d # 大数除法
import big_number_sub_add as b_s_a # 大数加减法
class SQRT():
def __init__(self, number, decimal, sign='s', method='s_direct'):
... |
# code to build, compile and fit a convolutional neural network (CNN) model to the MNIST dataset of images of
# handwritten digits.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Run this cell first to import all required packages. Do not make any imports elsewhere in the notebook
import tens... |
#!/bin/python3
# IT101 - RPG dungeon game project
# Jordan Golden
def showInstructions():
#print a main menu and the commands
print('''
RPG Game
========
Navigate your way through the Deadmines and
thwart the Defias Brotherhood. Defeat the
bosses and get to the exit with their loot.
Commands:
go [direction]
... |
from datetime import datetime
import pandas
import random
import smtplib
today = datetime.now()
today_tuple = (datetime.now().month, datetime.now().day) # We create the tuple with today's month and day, like (12,30)
# Use pandas to read the birthdays.csv
data = pandas.read_csv("birthdays.csv")
# Use dictionary com... |
from turtle import Turtle, Screen
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time
# Create the screen and give it size, color and title.
screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("My Pong Game")
screen.tracer(0) # --> Turn ... |
from tkinter import *
THEME_COLOR = "#375362"
class QuizInterface:
# In the class init we will create the user interface.
def __init__(self): # Everytime we create a new object from the class QuizInterface, a window will be created
self.window = Tk() # We create the window as the property of the class.
... |
from tkinter import *
def button_clicked():
print("I got clicked")
new_text = input.get() # Get hold of what you are typing
my_label.config(text=new_text) # When we click the button the text of the label will change
window = Tk()
window.title("My First GUI Program")
window.minsize(width=500, height=300)
w... |
MY_LAT = 55.953251 # Your latitude
MY_LONG = -3.188267 # Your longitude
iss_latitude = 51.54
iss_longitude = 1
if int(iss_latitude) in range(50, 60) and int(iss_longitude) in range(2, -9, -1):
sunrise = 4
sunset = 19
hour = 21
if hour >= sunset or hour <= sunrise:
print("Ullet")
e... |
# This is a simple hangman game and there are 10 questions.
"""
After each question, in brackets, there is a hint that let's player the expected output
The game records the number of questions you have answered wrong.
If you fail a question, the program responds with "You are hanging the man\n"
After six mistakes game... |
import tensorflow as tf
x_data = [1,2,3]
y_data = [1,2,3]
W = tf.Variable(tf.random_normal([1]), name='weight')
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
hypothesis = X * W
cost = tf.reduce_sum(tf.square(hypothesis - Y))
learning_rate = 0.1
gradient = tf.reduce_mean((W*X-Y) * X)
descent = W - l... |
def inSquare(x, y):
return abs(x) + abs(y) <= 1
x = float(input())
y = float(input())
if inSquare(x, y):
print("YES")
else:
print("NO")
|
# Decorators are used to modify functionality of function
# Here we change normal add frunction to add 2 tuples
import functools
def point_add_decorator(func):
@functools.wraps(func)
def point_add(*args, **kwargs):
# print(type(args[0]))
if type(args[0]) == type((1, 2)):
x = func(... |
import webbrowser
class Video:
"""This class contains basic properties of a video.
Attributes:
title (str): Title of video
duration (number): Number of minutes
"""
def __init__(self, title, duration=0):
self.title = title
self.duration = duration
class Movie(Video):... |
import hashlib
import random
import string
import hmac
SECRETE_KEY = "129jcn299jcji"
# SECURE COOKIES
# For speed up, we don't need to use SHA-256 to encrypt cookies.
# md5 and a SECRETE KEY is good enough
def make_hmac(value):
"""
Generate a hash-based message authentication code
:param value: cookie's ... |
print("Hola Mundo")
variable1 = "Gato"
variable2 = 100
variable3 = 45.23
print(variable1)
print(variable2)
print(variable3)
variable1 = "Perro"
print("El valor de la variable variable1 es: ", variable1)
print("El valor de la variable variable1 es {} y el valor de la variable variable2 es {}".format(variable1, varia... |
'''
A estas alturas hemos visto lo basico de un curso de python1, en este ejemplo, trabajaremos
con lectura y escritura de archivos de texto. Para ello, tomaremos un archivo, leeremos los
nombres existentes en el y obtendremos las iniciales de ellos, armando un diccionario el cual
se exportara a un archivo de salida
'... |
'''
previamente trabajamos con listas y ya sabemos como funcionan, a continuacion trabajaremos con un
nuevo tipo de listas que se llama Diccionario.
Practicamente los diccionarios son estructuras que permiten asociar una palabra clave a un valor,
este valor puede ser de cualquier tipo.
'''
#un diccionario se define e... |
'''
Las condiciones o decisiones son segmentos de codigo que se ejecutan dependiendo de un
valor o una condicion que nosotros declaremos. Al igual que en la vida, las condiciones permiten ejecutar
codigo, si queremos darnos un lujo, comprar un regalo a su novia, salir a vacacionar, etc.
Para trabajar con condiciones ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.