text stringlengths 37 1.41M |
|---|
class Player(object):
def __init__(self, name):
self.name = name
self._lives = 3
self._level = 1
self._score = 0
def _getLives(self):
return self._lives
def _setLives(self, lives):
if lives >= 0:
self._lives = lives
else:
pri... |
print('BMI換算')
H = input('請輸入身高:')
W = input('請輸入體重:')
H = float(H)
W = float(W)
H1 = H / 100
H1 = H1 * H1
BMI = W / H1
if BMI < 18.5:
print('BMI值:', BMI, '體重過輕')
elif 18.5 <= BMI < 24:
print('BMI值:', BMI, '體重正常')
elif 24 <= BMI < 27:
print('BMI值:', BMI, '體重過重')
elif 27 <= BMI < 30:
print('BMI值:', BMI... |
### INICIO REPRESENTACION DE DATOS ###
# El laberinto es representado en este programa como una lista de strings
# Los puntos son representados como tuplas (y,x)
# Un camino es una lista de tuplas
# Tambien se utiliza un diccionario que tiene como keys a las tuplas y guarda dentro de cada key al 'padre' de cada key... |
# 集合
print('-----------------集合的创建---------------------------')
# 方式一:直接{}
s = {2, 3, 4, 5, 5, 6, 7, 7}
print(s, type(3))
# 方式二:使用内置函数set()
s2 = set(range(6))
print(s2, type(s2))
# 将列表转化为集合
s3 = set([1, 2, 3, 4, 5, 5, 5, 6, 6])
print(s3, type(s3))
# 将元组转化为集合
s4 = set((1, 2, 4, 4, 5, 65))
print(s4, type(s4))
# 将字符串序列转化... |
for item in 'Python':
print(item)
for i in range(10):
print(i)
# 如果在循环体中不需要使用到自定义变量,可将自定义变量写为_
for _ in range(5):
print('人生苦短,我用Python')
sum = 0
for item in range(1, 101):
if sum % 2 == 0:
sum += item
print('1到100之间的偶数和为:', sum)
for i in range(1, 10):
for j in range(1, i + 1):
pr... |
# 继承
# python支持多重继承
# 默认继承object类
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print('姓名:{0},年龄:{1}'.format(self.name, self.age))
# 定义子类
class Student(Person):
def __init__(self, name, age, stu_no):
super().__init__(... |
# with语句可以自动管理上下文资源,
# 不论什么原因跳出with块,都能保证文件正确的关闭,以此来达到释放资源的目的
"""
MyContentMgr实现了特殊方法__enter__、__exit__,
则称该类对象遵守了上下文管理器
"""
class MyContentMgr(object):
def __enter__(self):
print('enter方法被调用执行了')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('exit方法被调用执行了')
d... |
class Node:
def __init__(self):
self.left=None
self.right=None
self.val=None
def add_to_stack(Stack,i,value):
Stack[i].val=value
while (i//2)>0:
if Stack[i//2].val>Stack[i].val:
Stack[i//2],Stack[i]=Stack[i],Stack[i//2]
else:
break
i//... |
from random import randrange
def merge(tabA,tabB):
tabC=[0]*(len(tabA)+len(tabB))
a=0;b=0;c=0
while a<len(tabA) or b<len(tabB):
if(a<len(tabA) and b<len(tabB)):
if(tabA[a]<=tabB[b]):
tabC[c]=tabA[a]
c+=1
a+=1
else:
... |
import argparse
from random import randrange
def quickSort(tab,left,right):
if (right-left)>0:
middle_l,middle_r = partition(tab,left,right)
quickSort(tab,left,middle_r)
quickSort(tab,middle_l,right)
def partition(tab, left, right):
pivot=tab[randrange(right-left)+left]
while left<=... |
string1= "E=M*C^2"
string2= "e=m*c^2"
alphabet= ['A', 'B', 'C', 'D', 'E', 'F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
string1 = string1.upper()
string2 = string2.upper()
decode_str1= []
decode_str2= []
for i in range(len(string1) - 1):
if string1[i] in alphabet and string1[... |
from tkinter import *
from tkinter import ttk
from main import generate_password
def copy2clipboard():
root.clipboard_clear()
root.clipboard_append(new_pass_label['text'])
copy_button['text'] = 'Copied !'
root.update()
return
def display_password():
try:
pass_len = int... |
student = {
"name":"Mark",
"student_id":15163,
"feedback":None
}
try:
lastName = student["last_name"]
except KeyError:
print("Key not found")
try:
con = 3 + "x"
except TypeError as error:
print("Cannot add int to string")
print(error)
except Exception:
print("Unknown error")
print(... |
from student import Student
class HighSchool(Student):
student_name = "SpringField HighSchool"
def get_name_capitalize(self):
original_value = super().get_name_capitalize()
return original_value + "-HF"
|
sunday = [20, 22, 25, 28]
monday = [15, 20, 16, 18]
tuesday = [25, 28, 12]
for item in zip(sunday, monday, tuesday):
print(item)
daily = [sunday, monday, tuesday]
for item in zip(daily[0], daily[1], daily[2]):
print(item)
for item in zip(*daily):
print(item)
transposed = list(zip(*daily))
print(transp... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
# Para cada línea que nos llegue de la entrada estándar...
for line in sys.stdin:
# Para cada elemento de una línea separado por espacios = palabra
for word in line.split(' '):
word = word.strip(',;.:-?¿!¡[]()"\'').lower()
# Imprimimos la palabra, un ta... |
def numprimo(numero):
i = 1
somaresto = 0
while(i<=numero):
calculo = numero/i
resto = int(numero%i)
if(resto >= 1):
resto=1
somaresto = somaresto + 1
i += 1
if numero-somaresto==2:
print('O número', numero, 'é primo')
else:... |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: 16cse012
#
# Created: 20/10/2017
# Copyright: (c) 16cse012 2017
# Licence: <your licence>
def main():
print ("hello world")
float num1 = 1.5
float = 6.3
sum... |
def create_fibonacci():
nums = [1,2]
i = 0
num = 0
while num < 4000000:
num = nums[i] + nums[i+1]
nums.append(num)
i += 1
return nums
def sum(nums):
result = 0
for i in nums:
if i % 2 == 0:
result += i
return result
print sum... |
def reverse(array, start, end):
while (start < end):
array[start], array[end] = array[end], array[start]
start = start + 1
end = end - 1
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
len = len(array)
k = 3
reverse(array, 0, len-1)
reverse(array, 0, k-1)
reverse(array, k, len-1)
print(array)
|
#fname = input("Enter file name: ")
fh = open("files/mbox-short.txt")
email = dict()
largest_till_now_count = 0
largest_till_now_key = 0
for line in fh:
if not line.startswith('From '): continue
words = line.split()
email[words[1]] = email.get(words[1], 0) + 1
if email[key] > largest_till_n... |
# 导入函数 (类似与Java的导Jar包)
import random
# 随机生成数字
computer = random.randint(1, 3)
# 用户输入数字
fist = int(input("请出拳 石头(1) 剪刀(2) 布(3)"))
if ((fist == 1 and computer == 2)
or (fist == 2 and computer == 3)
or (fist == 3 and computer == 1)):
print("玩家赢了")
elif fist == computer:
print("平局")
else:
prin... |
a = 21
b = 10
c = 0
c = a + b
print("1 - c 的值为:", c)
c = a - b
print("2 - c 的值为:", c)
c = a * b
print("3 - c 的值为:", c)
c = a / b
print("4 - c 的值为:", c)
c = a % b
print("5 - c 的值为:", c)
# 修改变量 a 、b 、c
a = 2
b = 3
c = a**b
print("6 - c 的值为:", c)
a = 10
b = 5
c = a//b
print("7 - c 的值为:", c)
f = "-"*10
print(f)
... |
class Cat:
def __init__(self,new_name):
print("初始化方法")
# self.name="Tom"
self.name=new_name
def __del__(self):
print("%s 走了" %self.name)
def __str__(self):
# 必须要return 类似于Java里面的田toString方法
return "我是小猫"
cat=Cat("Tom")
print(cat)
|
# 元祖 定义后不能修改
info_tuple = ("zhangsan", 18, 1.75)
print(type(info_tuple)) # <class 'tuple'>
single_tuple=(5)
print(type(single_tuple)) # <class 'int'>
# 定义一个只包含一个元素的元组
single_tuple=(5,)
print(type(single_tuple)) # <class 'tuple'>
# 常用方法
# 统计
print(info_tuple.count("zhangsan"))
# 取取索引
print(info_tuple.index("zh... |
# 列表常用操作 增删改查
""""
int[] arr =new int[10]; Java里面的数组操作
"""
name_lists = ["张三", "李四", "王五"]
temp_lists = ["1", "2", "3"]
# 取值 取索引 (类似于Java中的下标)
print(name_lists[2])
# 知道数据内容,取出索引
print(name_lists.index("李四"))
# 修改
name_lists[0] = "zhangs"
# list assignment index out of range 超出范围程序会报错
name_lists[2] = "lishi"
... |
# 格式化输出
"""
格式符号 转换
%c 字符
%s 通过str() 字符串转换来格式化
%i 有符号十进制整数
%d 有符号十进制整数
%u 无符号十进制整数
%o 八进制整数
%x 十六进制整数(小写字母)
%X 十六进制整数(大写字母)
%e 索引符号(小写'e')
%E 索引符号(大写“E”)
%f 浮点实
%g %f和%e 的简写
%G %f和%E的简写
"""
name = "小明"
print("我的名字叫%s" % name)
student_no = 1
# 我的学号是:001
print("我的学号是:%03d" % student_no)
price = 805
weigh... |
def show_function():
print("*************************************************")
print("欢迎使用【名片管理系统】 v1.0")
print()
print("1.新建名片")
print("2.显示全部")
print("3.查询名片")
print()
print("0.退出系统")
print("*************************************************")
def add():
name_str = str(input(... |
import sys
class WordCounter:
def __init__(self, filename):
self.filename = filename
def wordcounter(self):
try:
file = open(f'{self.filename}.txt')
except FileNotFoundError:
print('Ingresa un archivo valido, o en su caso una ruta valida hacia el archivo')
... |
#!/usr/bin/env python3
from itertools import product, permutations, combinations
from bisect import bisect_right,bisect_left
X=input()
choku = ['c', 'h', 'o', 'k', 'u']
is_c = False
for s in X:
if s in choku:
if s == 'h':
if not is_c:
print('NO')
exit()
... |
#!/usr/bin/env python3
from itertools import product
field = [list(input()) for i in range(10)]
H,W=10,10
def walk(x, y, fp):
"""
探索関数
Parameters:
x : int
x座標
y : int
y座標
fp: list
探索済座標記憶配列
Returns:
fp : list
更新したfp
... |
from typing import Tuple
from PIL import Image, ImageEnhance, ImageOps
'''
Author: Grant Garcelon
Date: October 2021
'''
class Ascii_art():
def __init__(
self,
image_path: str, # Path the the image
contrast: float, # Value to adjust the contrast
brightness: float, #... |
def part1():
groups = 0
with open('Inputs/Day6.txt','r') as file:
lines = file.readlines()
answered_yes = list()
for line in lines:
line = line.strip()
if len(line) > 0:
answered_yes.extend(list(line))
else:
groups += le... |
#!/usr/bin/python
import time
import sys
# YOUR FUNCTIONS GO HERE -------------------------------------
def scoring(seq1,seq2):
#Scoring algorith, takes 2 sequences and returns their alignment score
score = 0
firstSeq = seq1
secondSeq = seq2
#For each item in the alignment, add to the score
fo... |
import numpy as np
def svm_loss_naive(W, X, y, reg):
"""
Structured SVM loss function, naive implementation (with loops).
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy... |
x = 3
x += x - x
print(x)
"""
1. x references int [3]
2. x - x is calculated to be 0, this value is put into memory
3. x is set to reference the former value's memory address
""" |
width = 7
x = 1
while x < (width+1):
y = 1
while y < (x+1):
print('T', end='')
y += 1
print()
x += 1
x = 1
while x < (width+1):
y = width-x+1
while y > 1:
print(' ', end='')
y -= 1
print('T'*x)
x += 1 |
import tkinter
import tkinter.filedialog as dialog
class Editor:
""" a gui text editor """
def __init__(self, root):
text = tkinter.Text(root)
text.pack()
menubar = tkinter.Menu(root)
filemenu = tkinter.Menu(menubar)
filemenu.add_command(label='Save', command=lambda :... |
population = 500000000000
land_area = 1000000
if population < 10000000:
print(population)
if (population > 10000000) and (population < 35000000):
print(population)
if (population / land_area > 100):
print("Densely populated")
if (population / land_area > 100):
print("Densely populated")
else:
pr... |
from io import StringIO
from typing import TextIO
def hopedale_average(reader: TextIO) -> int:
'''a. Write an outline in English of the algorithm you would use to read
the values from this data set to compute the average number of pelts
produced per year.
b. Translate your algorithm into Python by writ... |
fruit = 'pineapple'
#order of methods:
fruit.find('p', fruit.count('p'))
# count; find
fruit.count(fruit.upper().swapcase())
# upper; swapcase; count
fruit.replace(fruit.swapcase(), fruit.lower())
#swapcase, lower, replace |
from typing import Any
def linear_search_while(lst: list, value: Any) -> int:
"""Return the index of the first occurrence of value in lst, or return
-1 if value is not in lst.
>>> linear_search_while([2, 5, 1, -3], 5)
1
>>> linear_search_while([2, 4, 2], 2)
0
>>> linear_search_while([2, 5, ... |
user_input = ""
while user_input.upper() != 'QUIT':
print('Program running. Type quit, Quit, QUIT or any other capitalization to quit.')
user_input = input('> ') |
from math import sqrt
class Point:
""" A Point in (x,y) coordinates
"""
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
class LineSegment:
""" A line segment
>>> segment = LineSegment(Point(1, 1), Point(3, 2))
>>> segment.slope()
0.5
>>> segment.l... |
from typing import TextIO
from io import StringIO
def skip_header(reader: TextIO) -> str:
"""Skip the header in reader and return the first real piece of data.
>>> infile = StringIO('Example\\n# Comment\\n# Comment\\nData line\\n')
>>> skip_header(infile)
'Data line\\n'
"""
... |
rat_1 = [1,2,3,4,5,6,7,8,9,10]
rat_2 = [11,12,13,14,15,16,17,18,19,20]
if rat_1[0] > rat_2[0]:
print("Rat 1 weighed more than rat 2 on day 1.")
else:
print("Rat 1 weighed less than rat 2 on day 1.")
if (rat_1[0] > rat_2[0]) and (rat_1[9] > rat_2[9]):
print("Rat 1 remained heavier than Rat 2.")
elif (rat_1... |
vowels = {'a', 'e', 'i', 'o', 'u'}
print(vowels)
print(set(vowels))
print(set({5, 3, 1}))
print(set(range(5)))
vowels.add('y')
print(vowels)
|
"""
Joshua Arribere May 7, 2017
Script to go through pixels of a tif file. For each pixel, will calculate an
average pixel intensity for some radius around that pixel. If that avg
is above some threshold (in red, green channels), it will call that pixel
a signal-containing pixel. Otherwise the pixel is bg.... |
import datetime
def speak(str):
from win32com.client import Dispatch
speak = Dispatch("SAPI.spVoice")
speak.speak(str)
year = input("Enter the age\n OR \nEnter the birth year\n")
loen=len(year)
current_year = datetime.datetime.now().strftime("%Y")
try:
if loen ==4:
print("you have entered... |
from sqlalchemy.sql import text
# Database utility functions
def insert(session, table, parameters):
"""
Inserts a new record into a table
Args:
session: Database session
table: Table to insert the new record in
parameters: A list of tuples where each tuple defines the field
... |
def dayOfProgrammer(year):
if year == 1918:
return '26.09.1918'
elif ((year <= 1917) & (year % 4 == 0)) or ((year % 400 == 0) or ((year % 4 == 0) & (year % 100 != 0))):
return '12.09.%s' %year
else:
return '13.09.%s' %year
x = dayOfProgrammer(int(inp... |
n = int(input())
nums = list(map(int, input().split()))
sum = 0
for num in nums:
sum += num
print(sum)
|
import time
import datetime
"""
Timer function meant to be used as a decorator
"""
def timer(func):
def wrapper(*args,**kwargs):
before = time.time()
val = func(*args,**kwargs)
total_time = str(datetime.timedelta(seconds=time.time()-before))
list_time = total_time.split(':')
... |
from typing import List
from .card import Card
def hand(s: str, sort: bool = True) -> List[Card]:
num_cards = len(s) // 2
cards = []
for i in range(num_cards):
cards.append(Card(s[2*i:2*i + 2]))
if sort:
return sorted(cards, reverse=True)
return cards
|
# Note - this code must run in Python 2.x and you must download
# http://www.pythonlearn.com/code/BeautifulSoup.py
# Into the same folder as this program
import re
import urllib
from BeautifulSoup import *
i=5;
url = raw_input('Enter URL:')
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
sum=0
# Retri... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def showAll(node):
print('showAll:')
while(node!=None):
print(node.val)
node = node.next
class Solution:
def reverseList(self, head):
"""
:type hea... |
# -*- coding: utf-8 -*-
import time
# 函数名称:fibonacciSequence
# 函数功能:自底向上 -- 产生斐波切纳数列中的某一位
# 输入参数:int
# 返回参数:int
def fibonacciSequence(n):
if n<=2: return 1
seq = [1, 1]
for i in range(2, n):
seq.append(seq[-1] + seq[-2])
return seq[-1]
# 函数名称:fibonacciSequence_up_to_buttom
# 函数功能:自顶向下 -- 产生... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
if t==None:
return ''
if t!= None:
if t.left==Non... |
# vim: fdm=indent
'''
author: Fabio Zanini
date: 09/05/16
content: Utility functions
'''
# Functions
def mkdirs(newdir):
""" Create a directory and all parent folders.
Features:
- parent directories will be created
- if directory already exists, then do nothing
- if ther... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: Swking
@File : DList.py
@Date : 2018/11/25
@Desc : 双向链表
"""
class Node:
def __init__(self, value=None):
self.value = value
self.prev = None
self.next = None
class DLinkList:
def __init__(self):
self.head = Node(None) # 初始化一个头结点
self.end = sel... |
# Exercise 3-1. Names:
names = ['sara', 'anam' , 'faiza' , 'zainab']
print(names[2].title())
print(names[-1].title())
print(names[0].title())
print(names[-3].title())
# Exercise 3-2. Greetings:
message_1 = "Hello " + str(names[0]) +" !" +" welcome to python class. "
message_2 = "Hello " + str(names[1]) +"... |
"""pedirle una cancion y a través del id volver a llamar a la api y mirar si esta en available_countries"""
import json
from pprint import pprint
import requests
#busqueda de artista
buscar=str(input("Nombre artista: "))
response = requests.get("https://deezerdevs-deezer.p.mashape.com/search?q="+buscar,
headers={
... |
i = 4
d = 4.0
s = 'HackerRank '
# Declare second integer, double, and String variables.
i2= int(input())
d2= float(input())
s2= str(input())
# Print the sum of both integer variables on a new line.
print(i+i2)
# Print the sum of the double variables on a new line.
print(float(d+d2))
# Concatenate and print t... |
# libraries
from matplotlib import pyplot as plt
from matplotlib_venn import venn3, venn3_circles
import numpy as np
#initialisation tableau
tab=[]
#verifie le nombre
def verifNombre():
while True:
try:
value = abs(int(input('Entre un nombre positif : ')))
if 0<value:
... |
pizzas = ['pepperoni', 'classic trio', 'hawaian']
for pizza in pizzas:
print("I like to eat {} pizza!".format(pizza.title()) )
|
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(sorted(cars)) # This will sort the list but not modify it
cars.reverse() # This will revers the order of the list in-place
print(cars)
cars.sort() # This will sort the list in-place (modify it)
print(cars)
cars.sort(reverse=True) #This will sort the list in reverse
... |
__author__ = 'GCassani'
"""Function to create balanced, smaller test sets from a list of words"""
import os
import random
from collections import defaultdict
def organize_words_by_pos_tag(test_set, target_tags):
"""
:param test_set: the path to a .txt file containing two strings per line. The first ... |
p = 23
# what is inefficient?
# everytime i am calculating the ord of the strings unnecesaarily
# can use numbers to speed it up
def calculate_hash(sentence):
nums = [str(ord(c)) for c in sentence]
number = int("".join(nums))
hash_num = number % p
return hash_num
# print("hash is ",calculate_hash("abc"... |
arr = [5,2,4,6,1,3]
# insert sort
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
# the idea is to keep pushing the key inside the sorted array till it finds it proper place
while j >=0 and arr[j] > key:
arr[j], arr[j+1] = key, arr[j]
j -= 1
print(arr)
# optimised insertio... |
#!/usr/bin/env python
#Check your powerball numbers!
#created by Brandon I.
import sys
input_winning_numbers = open("winningnumbers.txt", "r") #opens winning numbers text file in same directory as script file.
#format the file with a comma delimeter, for example: 19,25,29,36,48,12
#the first five should be the white... |
import re
def complex_root(a, b):
s = root([[1,a],[1,a]])[0]
s[-1] += float(b)**2
return s
def root(r):
if len(r) == 1:
return r
dev = [0 for i in range(len(r[0]) + len(r[1]) - 1)]
for i in range(len(r[0])):
for j in range(len(r[1])):
dev[i + j] += r[0][i] * r[1][j... |
def main():
start = int(input("Enter the start limit: "))
end = int(input("Enter the end limit: "))
divisors = []
for i in range(start, end):
if i % 3 == 0 or i % 5 == 0:
divisors.append(i)
print("The divisors are: " + str(divisors))
print("The sum is " + str(sum(divisors)))
... |
# Programming for the Puzzled -- Srini Devadas
# A Weekend to Remember
# This puzzle deals with the problem of inviting friends to dinner over two days
# such that no two of your friends who dislike each other are invited on the same
# day. This can be done if the graph is a bipartite graph.
# The code determin... |
def is_palindrome(word):
first_letter = word[0].lower()
last_letter = word[-1].lower()
if len(word) < 2:
return True
elif first_letter == last_letter:
return is_palindrome(word[1:-1])
else:
return False
def test_palindrome():
assert is_palindrome("kayaK") is True
a... |
import numpy as np
from .utils import load_data, load_weights, load_own_image, display_data, predict_nn
def ex3_nn():
"""
Machine Learning Class - Exercise 3 | Part 2: Neural Networks
Instructions
------------
This file contains code that helps you get started on the
linear exercise. You will... |
for i in range(3):
print("a")
for j in range(3):
print("b")
|
import math
import random
import pygame
def colors():
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
return black, white, red, green, blue
def main():
pygame.init()
black, white, red, green, blue = colors()
size = [700, 500]
screen = pygame.display.set... |
list=['a','e','i','o','u']
r=raw_input("value is:")
print(r)
if(r in list):
print"vowel"
else:
print"Constant"
|
def ehInteiro(texto):
try:
int(texto)
return True
except ValueError:
return False
def getTrecho(texto):
trecho = ""
if str.isalpha(texto[0]):
i = 0
while (str.isalpha(c[i])):
trecho += c[i]
i += 1
return trecho
else:
i... |
class Heap:
def __init__(self):
self.heap_array = []
self.heap_array.append(None)
def move_up(self, index_id):
if index_id == 1:
return False
parent_id = index_id // 2
if self.heap_array[parent_id] > self.heap_array[index_id]:
return... |
# Character Classes
# Character classes are nice for shortening regular expressions
import re
# Shorthand character class Represents
# \d Any numeric digit from 0 to 9.
# \D Any character that is not a numeric digit from 0 to 9
# \w Any letter, numeric digit, or the underscore characte(Think of... |
#! python3
# bulletPointAdder - Adds wiki bullet points to the start of each line
# of text on the clipboard
import pyperclip
text = pyperclip.paste()
# TODO: Separate lines and add stars
lines = text.split('\n')
for i in range(len(lines)): # loop through all indexes in the "lines" lis
lines[i] = '* ' + lines[... |
from abc import ABCMeta, abstractmethod
import MySQLdb
class DbManager:
__metaclass__ = ABCMeta
def __init__(self):
self.hostname = 'localhost'
self.username = 'jose'
self.password = 'josepass'
self.database = 'viernes'
self.connection = None
def connectToDB(self):
self.connection = MySQLdb.connec... |
# q02_triangle.py
#validates triangle and compute perimeter
#input variables
side1 = float(input("Enter side 1: "))
side2 = float(input("Enter side 2: "))
side3 = float(input("Enter side 3: "))
#compute perimeter
def compute_perimeter(a,b,c):
print(a + b + c)
#validate triangle
if (side1 + side2) > side3 and ... |
#q07_miles_to_kilometres.py
#variables
miles1 = int(1)
kilometres1 = float(miles1 * 1.609)
kilometres2 = int(20)
miles2 = float(kilometres2 / 1.609)
#print headers
print("{1:^7}{0:^11}{0:^11}{1:^7}".format("Kilometres","Miles"))
#print values
for miles1 in range(1,11):
print("{0:^7}{1:^11.3f}{2:^11}{3:^7.3f}".f... |
count = int(input("How many numbers?: "))
nums = [int(input(f"Enter Number {num + 1}: ")) for num in range(count)]
even_nums = [num for num in nums if num % 2 == 0]
even_sum = sum(even_nums)
print(f"The sum of all the even numbers is: {even_sum}") |
""" DO IT NOW class examples from CP1404"""
"""
DO IT NOW #1
Write code that asks a user for their age and tells them if they are an adult or child
"""
# user_age = int(input("What is your age: "))
# if user_age >= 18:
# print("You are an adult")
# else:
# print("You are a child")
"""
DO IT NOW #2
Write cod... |
import nbformat
def word_count(notebook):
"""Prints the word count in Markdown cells of the file named notebook."""
with open(notebook, 'r', encoding='utf-8') as f:
nb = nbformat.read(f, as_version=4)
word_count = 0
total_word_count = 0
for cell in nb['cells']:
if cell['cell_type'] =... |
numero = int(input('Digite um número e vou adivinhar se é par ou ímpar: '))
resto = (numero % 2)
if resto == 0:
print('O número {} é par'.format(numero))
else:
print('O número {} é ímpar'.format(numero))
|
salario = float(input('Digite o valor do salário do funcionário R$ '))
if salario <= 1250.00:
print('O valor do salário, após o aumento, será de R${}'.format((salario * 0.15) + salario))
else:
print('O valor do salário, após o aumento, será de R${}'.format((salario * 0.10) + salario)) |
#isnumeric
#isalpha
#isalnum
#print(variavel.isalgo())
#isupper
algo = input('Digite algo: ')
print('O tipo deste dado é ', type(algo))
print('Só tem espaço? ', algo.isspace())
print('Só tem letras? ', algo.isalpha())
print('É alfanumérico? ', algo.isalnum())
print('É numérico? ', algo.isnumeric())
print('Está escrito... |
x = 2
y = 3
#x = y
print(x == y)
#são os operadores: <, >, >=, <= |
import math
angulo = float(input('Digite o ângulo desjado: '))
print('Para o ângulo {:.2f} o seno é {:.2f}'.format(angulo, math.sin(math.radians(angulo))))
print('O cosseno é {:.2f}'.format(math.cos(math.radians(angulo))))
print('E a tangente é {:.2f}'.format(math.tan(math.radians(angulo))))
|
"""Escribe un programa que pida un número (límite) y luego te pida números
hasta que la suma de los números introducidos supere el límite inicial.
El programa termina escribiendo la lista de números."""
#Francisco Llamas
lista=[]
limite=int(input("introduzca el limite"))
suma=0
while suma<limite:
numero=int(input(... |
#Práctica 5 ejercicio 12
#Francisco Llamas
numero=int(input("por favor introduzca un numero"))
a=0
for i in range(1, numero+1):
if numero%i==0:
a=a+1
if a==2:
print("El numero", numero,"es primo")
else:
print("El numero", numero,"no es primo")
|
#Ejercicio 1 práctica 5
#Francisco Llamas
print("lista de números del 1 al 10")
for i in range(10):
print (i+1)
print("lista de números del 10 al 20, ascendiendo de 2 en 2")
for i in range(10):
print (i*2+2)
print("lista de números del 20 al 38, ascendiendo de 2 en 2")
for i in range(10):
print (i*2+20)
pri... |
"""Escribe un programa que pida notas y los guarde en una lista.
Para terminar de introducir notas, escribe una nota que no esté entre 0 y 10.
El programa termina escribiendo la lista de notas."""
#Francisco Llamas
notas=[]
entrada=float(input("introduzca las notas"))
while entrada in range(11):
notas.append(float(... |
palabras=["uno","dos","tres"]
diccionario=[]
palabra2=["cuatro","cinco","seis"]
diccionario.append(palabras)
diccionario.append(palabra2)
for i in range(len(diccionario)):
for j in range(len(diccionario[i])):
print(diccionario[i][j])
|
"""Escribe un programa que te pida números
cada vez más grandes y que se guarden en una lista.
Para acabar de escribir los números,
escribe un número que no sea mayor que el anterior.
El programa termina escribiendo la lista de números:"""
#Francisco Llamas
lista=[]
entrada=int(input("introduzca un numero"))
entrada2=i... |
import requests
class WikiInfo():
"""
Get the summary of the related place.
"""
def __init__(self, address, latitude, longitude):
self.address = address
self.latitude = latitude
self.longitude = longitude
self.get_pages_url = "https://fr.wikipedia.org/w/api.php"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.