text stringlengths 37 1.41M |
|---|
from underline_var import *
import underline_var
# 注意在该程序中underline_var和underline需要在一个路径下
class MyClass(object):
def __init__(self):
self.__superprivate = "Hello"
self._semiprivate = "world!"
# print(_a) #NameError: name '_a' is not defined
print(underline_var._a)
print(b)
a = MyClass()
print(a._... |
#print ("Hello World!")
name = input ("Enter temperature in celsius: " )
F= (float (name)*9/5)+32;
print(str(float(name))+ "° in Celsius is equivalent to " + str(F) + "° Fahrenheit.")
|
def isPrime(n):
prime = True
if n < 2:
prime = False
elif n == 2:
prime = True
else:
i = 2
while i < n/2 + 1:
if n%i == 0:
prime = False
break
else:
i += 1
return prime
print(isPrime(5))
print(is... |
name = input("Hello, what is your name?")
age = input("How old are you?")
year = 100 - int(age) + 2017
print("Nice to meet you " + name + ". On " + str(year) + ", you will be 100 years old. Hope you'll live that long. :)")
|
def palindrome(a):
if a == a[::-1]:
print(a + " is palindrome")
else:
print(a + " is not palindrome")
a = "madam"
b = "mertkan"
palindrome(a)
palindrome(b)
|
import random
def intersect(a, b):
result = []
init_result = [i for i in a if i in b]
for i in init_result:
if i not in result:
result.append(i)
return result
a = [random.randrange(1, 10) for i in range(20)]
b = [random.randrange(1, 10) for i in range(20)]
print(a)
print(b)
print(i... |
#!/usr/bin/python3
"""
this is the code to accompany the Lesson 2 (SVM) mini-project
use an SVM to identify emails from the Enron corpus by their authors
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import prepro... |
# To pass the test, your code should output "Passed All Dictionary Tests!"
# If you get any other error other than the one printed below, google to figure out what you did. Most likely error to encounter is a Key Error (means key doesn't exist in dictionary).
def test(value, answer):
if value != answer:
pri... |
def get_choice_from_cli(options,
repeat_until_correct=True,
return_key=False,
title="Select one option from the list:",
prompt="Selection > ",
redo_text="Not a valid selection, try again."):
"""... |
# -*- coding: utf-8 -*-
"""This module implements Future base class and its subclasses.
Future objects are the result of asynchronous functions execution. Their
value is unknown at construction, so they offer an interface for gathering
this value when it is computed, or wait until it is available."""
import operator
... |
def canSum(targetSum, numbers):
tab = [False for _ in range(targetSum+1)]
# seed
tab[0] = True
for i in range(targetSum+1):
if tab[i] is False:
continue
for num in numbers:
if (i+num <= targetSum): tab[i+num] = True
return tab[targetSum]
print(canSum(7, [2,3]))
print(canSum(7, [5,3,4,7]))
print(can... |
def bestSum(t, arr, memo=None):
"""
m: target sum, t
n: len(arr)
time = O(n^m*m)
space = O(m*m) [in each stack frame, I am storing an array, which in worst case would be m]
// Memoized complexity
time = O(n*m*m)
space = O(m*m)
"""
if memo is None:
memo = {}
if t in memo:
return memo[t]
if t == 0:
r... |
# 元组
import random
t1 = ()
'''
1.定义符号()
2.元组中的内容不可修改
3.关键字 tuple
'''
print(type(t1))
# 注意要加,号
t2 = ('hello',)
print(type(t2))
t3 = ('hello','world')
print(type(t3))
t4 = (2,3,4,5,6)
list1 = []
for i in range(10):
ran = random.randint(1,20)
list1.append(ran)
print(list1)
t5 = tuple(list1)
print(t5)
# 查询... |
# -*- coding: utf-8 -*-
name = 'Steven J. Moxley'
age = 28
height = 72 #inches
weight = 185 #lbs
eyes = 'Hazel'
teeth = 'White'
hair = 'Dirty Blonde'
#conversion for inches to centimeters
inches = 72
centimeters = inches * 2.54
#conversion for lbs to kg
pounds = 180
kilos = pounds / 2.2046226218
print "Let's talk a... |
import pandas as pd
import numpy as np
import xlrd
df = pd.read_excel('Ey2.xlsx')
df.rename(columns={'Unnamed: 0':'Airport','Unnamed: 1':'City','Unnamed: 2':'Month', 'Unnamed: 3':'CarrierID','Unnamed: 4':'Non_of_Flights' })
df1 = df.dropna()
df1
# Example on how to read data from excel file
#The data in the excel fi... |
#Question:
'''Write a program which can compute the factorial of a given numbers.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program:
'''
x=int(input("Enter a number:"))
i=1
y=1
if x==0:
y=1
else:
while i<=x:
y=y*i
... |
'''
Question:
Write a program that accepts a sequence of whitespace separated words as input and
prints the words after removing all duplicate words and sorting them alphanumerically.
Suppose the following input is supplied to the program:
hello world and practice makes perfect and hello world again
Then, the output s... |
#1. 데이터 구성
import numpy as np
x = np.array([1,2,3])
y = np.array([1,2,3])
x2 = np.array([4,5,6])
#2. 모델구성
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(100, input_dim = 1, activation = 'relu')) #input_dim(차원) : 1 (input layer)
model.add(Dense(28)) # out-put... |
name = "sam"
last_letters = name[::]
l = last_letters
print (l)
l = 'p' + l
print (l)
x = 'hello world'
x = x + "it is bala!"
print (x)
x1 = "bala is beautiful"
x1= x1. split('b')
print (x1)
|
class Rect(object):
def __init__(self, x0, y0, x1, y1):
if (x0 > x1):
t = x0
x0 = x1
x1 = t
if (y0 > y1):
t = y0
y0 = y1
y1 = t
self.value = (x0, y0, x1, y1)
def __getitem__(self, key):
return self... |
from abc import ABCMeta, abstractmethod
#иппортируем из модуля abc, то что нам нужно для создания абстрактного базавого класса
class IOperator(object):
"""
Интерфейс, который должны реализовать как декоратор,
так и оборачиваемый объект.
"""
__metaclass__ = ABCMeta
"""
Используем абстрактный ме... |
"""
UNIT 2: Logic Puzzle
You will write code to solve the following logic puzzle:
1. The person who arrived on Wednesday bought the laptop.
2. The programmer is not Wilkes.
3. Of the programmer and the person who bought the droid,
one is Wilkes and the other is Hamming.
4. The writer is not Minsky.
5. Neither Knu... |
# Unit 5: Probability in the game of Darts
"""
In the game of darts, players throw darts at a board to score points.
The circular board has a 'bulls-eye' in the center and 20 slices
called sections, numbered 1 to 20, radiating out from the bulls-eye.
The board is also divided into concentric rings. The bulls-eye has
... |
class Person:
name = 'default name'
def __init__(self):
print('__init__' )
def print(self):
print(self.name)
def __del__(self):
print('__del__')
p1 = Person()
p1.print()
p1.name = 'wellstone'
p1.print()
|
import unittest
def solution(n):
answer = ''
nums = ['1', '2', '4']
quotient = -1
while quotient != 0:
quotient = int((n - 1) / 3)
remainder = (n - 1) % 3
answer = nums[remainder] + answer
n = quotient
return int(answer)
class Module1Test(unittest.TestCase):
... |
# Zeller's Algorithm
#
# Zeller's algorithm computes the day of the week on which a given date will
# fall (or fell). In this exercise, you will write a program to run Zeller's
# algorithm on a specific date. The program should use the algorithm outlined
# below to compute the day of the week on which the user's bir... |
def get_bounds(points):
"""
return bounding box of a list of gpxpy points
"""
min_lat = None
max_lat = None
min_lon = None
max_lon = None
min_ele = None
max_ele = None
for point in points:
if min_lat is None or point.latitude < min_lat:
min_lat = point.latit... |
# This script calculates the walking distance from origin point to destination point included in the dataset using coordinates
import pandas as pd
import googlemaps
# Inserting the API key
gmaps = googlemaps.Client(key='XXXXXXXXXXXXXXXXXX')
def distance_function(data):
df = pd.DataFrame(data)
# Setting... |
from fractions import Fraction, gcd
import functools
# Given numpy is not a standard library to invert a matrix the following functions
# are taken from link; transposeMatrix, getMatrixMinor, getMatrixDeternminant, getMatrixInverse
# https://stackoverflow.com/questions/32114054/matrix-inversion-without-numpy
def tra... |
"""level 10
Find len(sequence[30])
Given the sequence = [1, 11, 21, 1211, 111221, ...]
This is the 'Look and Say' sequence:
https://en.wikipedia.org/wiki/Look-and-say_sequence
"""
def level_10(num):
"""Return the next number in the 'see-and-say' sequence, given a number.
The next number in t... |
print("Bem vindo à melhor calculadora de sempre.")
print("Por favor insere o primeiro número, a operação a realizar, e depois o segundo número.")
print("Sou capaz de fazer somas (+), subtrações (-), multiplicações (*) e divisões (/)")
#input de variaveis
num1 = float(input("Primeiro número: "))
sinal = input("Operação... |
# coding=utf-8
# -*- coding:utf-8 -*-
'''
Author: Solarzhou
Email: t-zhou@foxmail.com
date: 2019/11/12 22:00
desc:
'''
# 方法1:动态规划
# 一般可以使用动态规划求解的问题有如下四个特点:
# 1)求一个问题的最优解(可以是最大值或者时最小值)
# 2)整体entity的最优解是依赖于各个子问题的最优解
# 3)这些小问题还有相互重叠的更小的问题;
# 4)从上往下分析,从下往上求解;即:
# 由于子问题在分解大问题的过程中重复出现,为了避免重复求解子问题,
# 我们可以用从下往上的顺序先求解子问题... |
# 解题思路:
# 对于两棵二叉树来说,要判断B是不是A的子结构,首先第一步在树A中查找与B根节点的值一样的节点。
# 通常对于查找树中某一个节点,我们都是采用递归的方法来遍历整棵树。
# 第二步就是判断树A中以R为根节点的子树是不是和树B具有相同的结构。
# 这里同样利用到了递归的方法,如果节点R的值和树的根节点不相同,则以R为根节点的子树和树B肯定不具有相同的节点;
# 如果它们值是相同的,则递归的判断各自的左右节点的值是不是相同。
# 递归的终止条件是我们达到了树A或者树B的叶节点。
# 有地方要重点注意,is_subTree()函数中的两个 if 判断语句 不能颠倒顺序 。
# 因为如果颠倒了顺序,会先判断pRoot1 是... |
# coding=utf-8
# -*- coding:utf-8 -*-
'''
Author: Solarzhou
Email: t-zhou@foxmail.com
date: 2020/1/10 14:45
desc:
'''
# 思路: 使用“”“”“"二分法"解决问题
class Solution(object):
def getNumberSameAsIndex(self, nums):
high = len(nums) - 1
low = 0
while low < high:
mid = (low + high) // 2
... |
# solutions 1
# 使用python内置函数
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(' ', '%20')
# solution 2
# 正则表达式
import re
class Solution1:
# s 源字符串
def replaceSpace(self, s):
# write code here
# ret = re.compile(' ')
# retu... |
# -*- coding:utf-8 -*-
# 方法 1
# 思路:将所给字符串s当做列表进行处理,很容易就能得到左移、右移效果,
# 将转换后的字符串存储到列表result中,之后对result中的元素进行拼接。
class Solution:
def LeftRotateString(self, s, n):
# write code here
if not s:
return ""
lenS = len(s)
result = []
if lenS < n:
return ''
... |
# coding=utf-8
# -*- coding:utf-8 -*-
'''
Author: Solarzhou
Email: t-zhou@foxmail.com
date: 2019/11/7 22:43
desc:
'''
# 思路:
# 通过两层循环找出符合要求的最大数;
# 1)外层循环从第一个数字,依次遍历;
# 2)内层循环依次许多size个数,即range(i, i+size),将最大的数字取出来追加到result中。
class Solution:
def maxInWindows(self, num, size):
# write code here
if n... |
# 解题思路
# 1. 把复制的结点链接在原始链表的每一对应结点后面
# 2. 把复制的结点的random指针指向当前节点random指针的下一个结点
# 3. 拆分成两个链表,奇数位置为原链表,偶数位置为复制链表,
# 注意复制链表的最后一个结点的next指针不能跟原链表指向同一个空结点None,
# next指针要重新赋值None(判定程序会认定你没有完成复制)
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solut... |
import MapReduce
import collections
import sys
"""
Count asymmetric friendships
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
person = record[0]
friend = record[1]
mr.emit_intermediate(person, friend)
mr.emit_intermediate(friend,... |
def numb_input():
input1 = input("give me a number ")
input2 = input("give me another number ")
input3 = input("third number please ")
return int(input1), int(input2), int(input3)
def addup():
num1, num2, num3 = numb_input()
sum = num1 + num2 + num3
print(sum)
def main():
addup()
p... |
'''
print('第一题')
l = []
def input_number():
while True:
i = int(input('输入数字(-1结束):'))
if i < 0:
break
l.append(i)
return l
input_number()
print('刚才输入的整数是:',l)
'''
print('第二题')
def isprime(x):
if x <= 1: #排除小于2的情况
return False
if x == 2:
return Tru... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import functools
def f1(x, y):
print('f1:', x, y)
return x + y
a = [1, 2, 3]
print(a)
b = sum(a)
print(b)
#c = functools.reduce(f1, a)
c = functools.reduce(lambda x, y: x + y, a)
print(c)
|
class FileManage:
'''定义一个文件管理员类'''
def __init__(self,filename='a.txt'):
self.file = open(filename,'w')
def writeline(self,string):
self.file.write(string)
self.file.write('\n')
def __del__(self):
'''析构方法会在对象销毁前自动调用'''
self.file.close()
print('文件已关闭')
... |
#class_varible.py
#此示例示意类变量的用途和使用方法
class Human:
total_count = 0
def __init__(self,name):
self.name = name
self.__class__.total_count += 1 #人数加1
print(name,'对象创建')
def __del__(self):
self.__class__.total_count -= 1 #总人数减1
print('当前对象的个数是:',Human.total_count)
h1 = Human... |
#mynumber.py
#此程序示意运算符重载
class Mynumber:
def __init__(self,v):
self.data = v
def __repr__(self):
return 'Mynumber(%d)' %self.data
def __add__(self,other):
print('__add__方法被调用')
obj = Mynumber(self.data + other.data)
return obj
def __sub__(self,other):
obj... |
n=int(input('输入一个数:'))
#方法一
if n > 0:
print(n)
else:
print(-n)
#方法二
if n < 0:
n = -n
print(n)
#方法三
print(n if n>0 else -n)
|
#打印'AaBbCcDd.....YyZz'
for i in range(ord('A'),ord('Z')+1):
print(chr(i)+chr(i).lower(),end='')
print()
n = int(input('输入整数:'))
for i in range(1,n+1):
for j in range(i,i+n):
print('%2d' %j,end=' ')
print()
|
'''
print('第一题')
def mysum(*args):
return sum(args)
print(mysum(1,3,36,3))
'''
print('第二题')
#方法一
def mymax(*args):
if len(args) == 1:
l = list(*args)
l.sort()
return l[-1]
#return max(args[0])
return max(args)
#方法二
def mymax2(a,*args):
if len(args) == 0:
m =... |
class Biology:
def fun(self):
self.fun_self()
class Animal(Biology):
def fun_self(self):
print("一类动物")
class Dog(Animal):
def fun_self(self):
print("一条狗")
def myfun(s):
s.fun_self()
s1 = Animal()
myfun(s1) # 输出结果:
s1 = Dog()
myfun (s1) #输出结果:
def decdsso(fn):
print("d... |
s1 = input('请输入第一行字符串:')
s2 = input('请输入第二行字符串:')
s3 = input('请输入第三行字符串:')
l = (max(len(s1),len(s2),len(s3)) + 2)
l1 = (l-len(s1))//2
l2 = (l-len(s2))//2
l3 = (l-len(s3))//2
print('+'+'-'*l+'+')
print('|'+' '*l1+s1+' '*((l-len(s1))-l1)+'|')
print('|'+' '*l2+s2+' '*((l-len(s2))-l2)+'|')
print('|'+' '*l3+s3+' '*((l-len(s... |
#此示例示意for语句的用法:
s = 'abcde'
for x in s:
print('---->',x)
else:
print('for循环因迭代对象结束而终止')
|
class Human:
count = 0 #类变量
def __init__(self,n,a,addr):
self.name = n
self.age = a
self.id = addr
self.__class__.count += 1 #修改类变量
def __del__(self):
self.__class__.count -= 1
@classmethod
def get_human_count(cls):
return cls.count
def show_... |
import time,sys
while True:
#print('\r %2d:%2d:%2d' %time.localtime()[3:6],end='')
print('\r%02d:%02d:%02d' %time.localtime()[3:6],end='')
#在cmd内可以看出效果,在IDLE内无法看出效果
time.sleep(1)
'''
y=int(input('年:'))
m=int(input('月:'))
d=int(input('日:'))
t=time.mktime((y,m,d,0,0,0,0,0,0))
print(t)
time_tuple = ti... |
import numpy as np
import csv
f=open('winequality-red.csv', 'r')
wines=list(csv.reader(f, delimiter=";"))
#print(wines[:3])
qualities = [float(item[-1]) for item in wines[1:]]
#print(sum(qualities) / len(qualities))
a=np.array(wines)
#print(a.shape)
wines = np.genfromtxt("winequality-red.csv", delimiter=";", skip_he... |
def outer(a):
def inner(b):
return a*b
return inner
d=outer(9)
print(d(3))
#ax^2+bx+c
def outer(x):
def inner(a,b,c):
return a*x**2+b*x+c
return inner
p=outer(3)
print(p(2,-3,6))
|
import requests
from bs4 import BeautifulSoup
page = requests.get("http://dataquestio.github.io/web-scraping-pages/simple.html")
'''
Sends a GET request.
'''
#print(page)
#print(page.status_code)
#print(page.content)
'''content
Content of the response, in bytes.
'''
soup = BeautifulSoup(page.content, 'html.parser... |
p=[[]]*3
print(p)
p[0].append(5)
print(p)
q=[[] for i in range(3)]
print(q)
q[0].append(9)
print(q)
|
#Project Euler Problem 27
biggest = 0
product = 0
hold = []
primes1 = []
primes2 = []
def f(n, a, b):
return n*n + a*n + b
def isPrime(n):
mid = n+1 // 2
if n < 0:
return False
else:
for i in range(2, mid):
if n % i == 0:
return False
r... |
#ac 辗转相除法 a,b的最大公约数 == a-b,b的最大公约数
def common(a,b):
if a % b == 0:
return b
elif b == 1:
return 1
else:
return common(b,a%b)
while True:
try:
line = input()
except EOFError:
break
line = line.strip().split()
x = int(line[0])
y = int(line[1])
... |
movies =["Holy Grail", "life of brian", "The meaning of life"]
count=0
while count < len(movies):
print(movies[count])
count=count+1
#this is my first python program
import sys
print(sys.platform)
x=2**10
print x
z='SEro'
print(z*20)
#a=input()
#a= input()
#b=raw_input() |
#Program to print out the grade
marks = int(input("ENter Student Marks\n"))
if marks>=100 or marks<0:
print("Invalid mark, Marks should be between 0-100")
else:
if marks >=80:
print("D1")
elif marks >=75:
print("D2")
elif marks >=65:
print("C3")
elif marks >=60:
pr... |
# Authors: Samwel, Josephine, Modester
# GitHub handles: @Sammyiel, @Josephine-uwizeye, @Modester-mw
# Question: Implement a basic measure of tracking the time taken to run an algorithm.
# Importing modules
import time
# Identify the starting time
start = time.time()
# The actual program
x = 0
while x < 5000:
... |
'''
Ejercicio 2
Escribir un programa que almacene la cadena de caracteres contraseña en una variable, pregunte al usuario por la contraseña e imprima por pantalla si la contraseña introducida por el usuario coincide con la guardada en la variable sin tener en cuenta mayúsculas y minúsculas.
'''
def run():
contraseña_... |
'''
Ejercicio 8
Escribir un programa que lea un entero positivo, n, introducido por el usuario y después
muestre en pantalla la suma de todos los enteros desde 1 hasta n.
La suma de los n primeros enteros positivos puede ser calculada de la siguiente forma:
'''
def suma_de_numero(numero):
suma_total = 0
for i... |
'''
Ejercicio 2
Escribir un programa que pregunte al usuario su edad y muestre por pantalla todos los años que ha cumplido (desde 1 hasta su edad).
'''
def run():
edad = int(input('digite su edad: '))
print('usted a cumplido todas estas edades')
for i in range(0,edad - 1):
print(i + 1)
if __name__ == '__main... |
'''
Ejercicio 7
Escribir un programa que muestre por pantalla la tabla de multiplicar del 1 al 10.
'''
def tabla(numero):
print(f'tabla de multiplicar de el numero {numero})
for i in range(1,10):
print(i * numero '\n')
def run():
for i in range(1,10):
tabla(i)
print()
if __name__ == '__ main__':
r... |
'''Ejercicio 4.
Escribir un programa que pregunte una fecha en formato dd/mm/aaaa y muestre por pantalla la misma fecha en formato dd de <mes> de aaaa donde <mes> es el nombre del mes.'''
def run():
meses = {1:'enero', 2:'febrero', 3:'marzo', 4:'abril', 5:'mayo', 6:'junio', 7:'julio', 8:'agosto', 9:'septiembre', 10... |
'''
Ejercicio 10
La pizzería Bella Napoli ofrece pizzas vegetarianas y no vegetarianas a sus clientes. Los ingredientes para cada tipo de pizza aparecen a continuación.
Ingredientes vegetarianos: Pimiento y tofu.
Ingredientes no vegetarianos: Peperoni, Jamón y Salmón.
Escribir un programa que pregunte al usuario si qu... |
'''
Ejercicio 8
En una determinada empresa, sus empleados son evaluados al final de cada año. Los puntos que pueden obtener en la evaluación comienzan en 0.0 y pueden ir aumentando, traduciéndose en mejores beneficios. Los puntos que pueden conseguir los empleados pueden ser 0.0, 0.4, 0.6 o más, pero no valores interme... |
nos = [4, 5, 10, 3, 5, 10, 1, 6, 8]
# get a new list of only the pointers greater than 5 from the nos list (filtering)
'''def greater_than_5(element):
return element > 5
iterable = filter(greater_than_5, nos)
print(list(iterable))'''
iterable = filter(lambda element: element > 5, nos)
print(list(iterable))
# get ... |
'''
>= 70 - A
>= 60 - B
>= 40 - C
< 40 - F
> 100 or < 0 - I
'''
marks = float(input('Enter marks : ')) # module (entire file) - Access the variable (get the value)
def get_grade():
# if-elif-elif-elif-else
# marks = 90 # get_grade()
'''global marks
marks = 90 # module (entire file)'''
if marks > 100 o... |
# enforce protocol on its sub classes
# 1. It should mark itself as an Abstract class
# 2. Along with that, mark the methods that need to be followed as part of the protocol, as abstract methods
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
de... |
class Book:
def __init__(self, title, price, pages):
self.title = title
# self.__price = price # private attribute (two underscores prefixed)
self.set_price(price)
self.pages = pages # @pages.setter
def __str__(self):
return 'Title: {0}\nPrice: {1}\nPages: {2}'.format(self.title, self.__price,... |
import cv2
import argparse
#This file contains the code to detect faces in an image using OpenCV.
#Before we get started, we need to know which file we are looking at.
parser = argparse.ArgumentParser(description='Detects faces in an image and reports how many were found.')
parser.add_argument('filename', metavar='fn... |
"""Builds an image classifier for fashion MNIST dataset using a simple sequential network
Model (sequential):
- flatten (28 x 28 -> 784)
- dense (784 -> 300, relu)
- dense (300 -> 100, relu)
- dense (100 -> 10, softmax)
"""
from tensorflow import keras
if __name__ == "__main__":
... |
# 1. TAREA: imprimir "Hola mundo"
print( "Hola mundo" )
# 2. imprimir "Hola Noelle!" con el nombre en una variable
name = "Noelle"
print( "Hola", name ) # con una coma
print( "Hola "+ name ) # con un +
# 3. imprimir "Hola 42!" con un numero en una variable
name = 42
print( "Hola",name ) # con una coma
print( "Hola "+s... |
from datetime import datetime
import random
class Caixa:
def __init__(self, nome, conta, saldo=0):
self.nome = nome
self.conta = conta
self.saldo = saldo
self.operacao = []
def saque(self, valor):
if valor <= self.saldo:
self.saldo -= valor
data =... |
a=float(input("First number:"))
b=float(input("Second number:"))
operation=(input("Your operatoin:"))
result= None
if operation == "+":
result=a+b
elif operation == "-":
result = a-b
elif operation=="*":
result = a*b
elif operation=="/":
if b == 0:
print("you can't do it")
else:... |
def menu():
while True:
print("**Carnet de contact v1**")
print("Que souhaiter vous faire ? ")
print("A - rechercher")
print("B - ajouter")
print("C - supprimer")
print("D - Quitter")
choix = input("Lettre: ").upper()
if (choix == "A"):
rechercher()
elif (choix == "B"):
getuserinfo(... |
#*******************************************************************
#
# Program: Project 3 -- 4x4 Tic-Tac-Toe
#
# Author: Caleb Myers
# Email: cm346613@ohio.edu
#
# Class: CS 3560 (Chelberg)
#
# Description: This is the Player class file for prog3.
#
# Date: February 26, 2017
#
#*****... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 3 12:32:57 2021
@author: anjal
"""
import datetime
import sqlite3
example_db = '/var/jail/home/team13/final_project/scores.db'
def request_handler(request):
if (request['method'] == 'POST'):
# this is a post request
if('user' in request['form']):... |
''' Address class '''
class Address():
''' Address class '''
def __init__(self,
street='UNDEFINED',
city='UNDEFINED',
state='UNDEFINED',
zipcode='UNDEFINED'):
self.street = street
self.city = city
self.state = state
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
''' Solution bitch '''
def mergeTwoLists(self, l1: ListNode, l2: ListNode):
l1_ptr = l1
l2_ptr = l2
merge_list = ListNode()
... |
from .Utility import guess_types
def outlier_count(data, numericals=None, threshold_sigma=2):
"""
Prints a dictionary which gives a report on outliers per numerical column in format (no:outliers, % outliers)
Outliers are defined as the values that fall outside the range of |X-mean|<= threshold*stdev
I... |
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder
def create_top_medalist():
'''
This function is used to create a dataframe of athletes that received medals for countries that
received more than 90 medals.
'''
df = pd.read_csv... |
import numpy as np
from polygon import Polygon
# this function was given in the exercise
def euclidean_distance(a, b):
array_a = np.array(a)
array_b = np.array(b)
return np.linalg.norm(array_a - array_b)
# Step 3
class Square(Polygon):
def area(self):
side = euclidean_distance(self.points[0... |
# 导包
import unittest
import requests
# 定义测试类
class TestLogin(unittest.TestCase):
def setUp(self):
# 创建Session对象
self.session = requests.Session()
self.verify_url = "http://localhost/index.php?m=Home&c=User&a=verify"
self.login_url = "http://localhost/index.php?m=Home&c=User&a=do_l... |
"""Python Database API
Django DB Models can be used to create schemas for database entities
which will then be used to create the physical database.
Models:
-------
Survey:
Survey entity encapsulates basic attributes of a survey including
name(survey name) and published_on(date time when the survey is published.
Meth... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
:program name: fwlc
:module author: Nicolas Osborne <nicolas.osborne@etudiant.univ-lille1.fr>
:date: 2018, Mars
:synopsis: REPL for Fun With Lambda Calculus
"""
import lib.lexpr
import lib.lread
from string import ascii_uppercase
PROMPT = "<°λ°> "
DIC = dict()
d... |
#https://leetcode.com/problems/1-bit-and-2-bit-characters/submissions/
class Solution(object):
def isOneBitCharacter(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
if 1 in bits:
first_one_index = bits.index(1)
del bits[:first_one_index]
... |
# 1
# numero= 1
# cantidad = 0
# suma= 0
# while numero != 0:
# numero= int(input("ingrese un numero: "))
# if numero != 0:
# suma= suma + numero
# cantidad= cantidad + 1
# print(f"usted ingreso {cantidad} y la suma es:{suma} ")
#2
# def menu ():
# print ("bienvenido al mneú: 1. ... |
# title = 'Book entitled \"The cat in the boots\"'
# number = 1
# print(f'Enter a number:{number}')
# l = list((range(2,200,-7,))
# print(l)
# x = input('Enter removable list item')
# ex_1 = ['Cherry', 'Grass', 'Apartment', 'Dog', 'The_Chosen_One']
# if x in list(ex_1):
# ex_1.remove(x)
# print('Item has been rem... |
num = input('Enter your number')
if int(num)== 0:
print('You are not allowed to divide by 0')
elif int(num)%3 == 0 or int(num)%5 == 0 or int(num)%7 == 0:
print('Your number can be divided by 3,5 or 7')
else:
print("Your number can't be divided by 3, 5 or 7")
|
# class Animal(object):
# def __init__(self, name, sex):
# self.name = name
# self.sex = sex
# dog = Animal('Rex', 'male')
# print(dog)
#
#
# class Animal(object):
# pass
#
#
# class Human(Animal):
# pass
#
#
# class Student(Human):
# pass
class Book(object):
def __init__(self, title, aut... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 19 21:39:50 2018
@author: MariusD
"""
#%%
available_products={"Guitar":"1000",
"Pick box":"5",
"Guitar Strings":"10"}
def checkout(cart):
cost=0
if cart==[]:
return "Please selec... |
# Az alábbi mintát jelenítsd meg for ciklus segítségével!
# Minta:
# 5 4 3 2 1
# 4 3 2 1
# 3 2 1
# 2 1
# 1
list = [1, 2, 3, 4, 5]
list_rev = list[::-1]
for j in range(5):
for i in list_rev[j:]:
print(i, end='')
print()
# oszlop - ez nem megy
# fx = [5, 4, 3, 2, 1]
# y = []
# for j in range(5):
# ... |
graph = {"S": ["A","D"],
#Cola sale el primero que ingresamos
#Cola: [ S ] → procesar nodo S y desencolarlo.
#Cola: [ ] → nodo A desencolado. Visitar todos sus hijos y encolarlos
"D": ["S","A","E"],
#Cola: [ D ] → nodo D no es visitado. Lo agregamos a la cola.
"A": ["S","D", "B"],
#Cola: [ ] → n... |
from room import Room
from player import Player
from item import Item
import textwrap
# Declare all the rooms
room = {
'outside': Room("Outside Cave Entrance",
"North of you, the cave mount beckons"),
'foyer': Room("Foyer", """Dim light filters in from the south. Dusty
passages run no... |
dicts={'a':'apple','c':'cat','b':'ball'}
val=lambda x:sorted(x)#sorting keys and then values
ok=val(dicts)
sortdict={}
for j in ok:
sortdict[j]=dicts[j]
print(sortdict)
|
input2=int(input("Enter a length of list : "))
ls=[]
for i in range(input2):
ls.append(int(input()))
def largest(val):
res=val[0]
for j in val:
if(j>res):
res=j
return res
print(largest(ls))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.